← Back to Blog
🌟
2025-09-118 min

Building a CLI Tool with Go and Cobra: A Git Commit Message Fetcher

Learn how to build a clean and powerful command-line interface (CLI) application in Go using the Cobra library.

# Building a CLI Tool with Go and Cobra: A Git Commit Message Fetcher Command Line Interfaces (CLIs) are powerful tools that help developers automate tasks and streamline workflows. In this tutorial, we'll build a simple yet practical CLI tool using Go and the Cobra library to fetch the most recent git commit message from a repository. ## Why Go and Cobra? Go is an excellent choice for building CLI tools due to: - **Single binary distribution** - no dependencies needed - **Fast compilation** and execution - **Strong typing** and excellent standard library Cobra is a popular Go library that provides: - Easy command structure with subcommands - Automatic help generation - Flag parsing and validation - Smart suggestions for mistyped commands ## Project Structure Let's start by looking at our project structure: ``` git-commit-tool/ ā”œā”€ā”€ cmd/ │ └── root.go ā”œā”€ā”€ main.go ā”œā”€ā”€ go.mod └── README.md ``` ## Setting Up the Project First, initialize your Go module: ```bash mkdir git-commit-tool cd git-commit-tool go mod init github.com/yourusername/git-commit-tool ``` Install Cobra: ```bash go get -u github.com/spf13/cobra@latest ``` ## The Code ### main.go ```go package main import "github.com/yourusername/git-commit-tool/cmd" func main() { cmd.Execute() } ``` ### cmd/root.go ```go package cmd import ( "fmt" "os" "os/exec" "strings" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "git-commit-tool", Short: "A tool to fetch the most recent git commit message", Long: `git-commit-tool is a CLI application that retrieves the most recent commit message from the current git repository.`, Run: func(cmd *cobra.Command, args []string) { getLatestCommit() }, } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func getLatestCommit() { // Check if we're in a git repository if _, err := exec.Command("git", "rev-parse", "--git-dir").Output(); err != nil { fmt.Println("Error: Not a git repository or git is not installed") os.Exit(1) } // Get the latest commit message out, err := exec.Command("git", "log", "-1", "--pretty=%B").Output() if err != nil { fmt.Printf("Error getting commit message: %v\n", err) os.Exit(1) } commitMessage := strings.TrimSpace(string(out)) fmt.Println("Latest commit message:") fmt.Println(commitMessage) } ``` ## Building and Using the Tool Build the binary: ```bash go build -o git-commit-tool ``` Make it executable and test it: ```bash chmod +x git-commit-tool ./git-commit-tool ``` You should see output similar to: ``` Latest commit message: Add new feature for user authentication ``` ## Adding Features with Cobra One of Cobra's strengths is its support for subcommands and flags. Let's enhance our tool: ```go // Add this to your root.go before the Execute function var ( shortMode bool ) func init() { rootCmd.PersistentFlags().BoolVarP(&shortMode, "short", "s", false, "Show shortened commit message") } // Modify the getLatestCommit function func getLatestCommit() { // [previous git check code remains the same] format := "--pretty=%B" if shortMode { format = "--pretty=%s" // subject only } out, err := exec.Command("git", "log", "-1", format).Output() // [rest remains the same] } ``` Now you can use: ```bash ./git-commit-tool --short # or ./git-commit-tool -s ``` ## Error Handling and Validation Our tool includes basic error handling, but you could extend it with: - Better git command validation - Support for specific git directories - JSON output format option - Custom commit range support ## Conclusion Building CLI tools with Go and Cobra is straightforward and powerful. This simple git commit message fetcher demonstrates how quickly you can create useful utilities. Cobra's structure makes it easy to extend functionality with subcommands, flags, and validation. The complete code is available on [GitHub](https://github.com/yourusername/git-commit-tool). Feel free to extend it with more features like commit statistics, author information, or multi-repository support! **Next steps:** - Add support for remote repositories - Implement colorized output - Add JSON/XML output formats - Create installation script Happy coding! šŸš€ --- *Have questions or suggestions? Leave a comment below! Don't forget to check out the [Cobra library documentation](https://github.com/spf13/cobra) for more advanced features.*
#Golang CLI#Cobra framework#Build CLI with Go#Git commit message#Go command-line tool#Cobra tutorial

Written by Seyed Ali

← Back to all articles