Skip to Content
Course content

57: Building a CLI Tool with Cobra

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I actually get a project started without wiring every command by hand?

If you've tried building a CLI using just the standard flag package, you know it gets messy fast once you have subcommands. That's why we use Cobra. I usually start by installing the cobra-cli tool; it handles the boilerplate so you don't have to spend an hour creating folders and initializing root commands.

For this lesson, let's imagine we're building taskmaster, a tool to manage a local JSON-based todo list. After installing the CLI tool, I'd run cobra-cli init. This generates a cmd/root.go file. This is your entry point. It defines the base command that every other command will hang off of.

// cmd/root.go
var rootCmd = &cobra.Command{
	Use:   "taskmaster",
	Short: "Taskmaster manages your daily grind",
	Long:  `A simple CLI tool to track tasks in a local JSON file.`,
	Run: func(cmd *cobra.Command, args []string) {
		// This runs if no subcommand is provided
		fmt.Println("Welcome to Taskmaster! Use 'taskmaster add' to get started.")
	},
}

Once that's set, adding a new action is as simple as cobra-cli add add. This creates cmd/add.go, which is automatically registered to the root command. It's a much cleaner way to scale your tool as you add more features.

What's the deal with Persistent Flags versus Local Flags?

This is where people usually get tripped up. In Cobra, a Persistent Flag is available to the command it's assigned to AND every subcommand under it. A Local Flag only works for that specific command.

Think about our taskmaster tool. You might want to specify the path to your JSON database file. Since every single command (add, list, delete) needs to know where that file is, that should be a persistent flag on the root command. However, a --priority flag only makes sense when you're adding a task, so that's a local flag.

// In cmd/root.go
var cfgFile string

func init() {
	// Every subcommand can now access --config
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "tasks.json", "config file for tasks")
}

// In cmd/add.go
var priority string

func init() {
	// Only 'taskmaster add' can use --priority
	addCmd.Flags().StringVarP(&priority, "priority", "p", "medium", "priority level (low, medium, high)")
}

I personally prefer using StringVarP (the 'P' version) because it lets you define both a long flag (--priority) and a short shorthand (-p), which makes the tool feel way more professional for the end user.

How do I keep my cmd folder from becoming a giant mess of spaghetti?

I've seen too many Go projects where the entire business logic is crammed inside the Run function of the Cobra command. Please, don't do that. The cmd package should be a thin wrapper. Its only jobs are to parse flags, validate the input, and call a function in another package.

If you put your JSON parsing and file writing logic directly in add.go, you'll find it impossible to write unit tests for that logic without simulating a full CLI execution. Instead, create a internal/tasks package to handle the actual data work.

// cmd/add.go
var addCmd = &cobra.Command{
	Use:   "add [task]",
	Short: "Add a new task to the list",
	Args:  cobra.MinimumNArgs(1), // Validates that the user actually provided a task name
	Run: func(cmd *cobra.Command, args []string) {
		taskName := args[0]
		
		// Delegate the actual work to a separate package
		err := tasks.AddTask(cfgFile, taskName, priority)
		if err != nil {
			log.Fatalf("could not add task: %v", err)
		}
		fmt.Printf("Added task: %s [%s]\n", taskName, priority)
	},
}

By keeping the Run function lean, your CLI becomes a delivery mechanism, not the application itself. This makes your code modular and actually maintainable.




📋 Practical Task

Exercise: Implement Task Filtering for Taskmaster

Now it's your turn to extend the taskmaster tool. You need to create a list command that allows users to view their tasks, but with a twist: they should be able to filter the list by priority using a flag.

  • Use cobra-cli add list to generate the command.
  • Add a local flag --filter (with a shorthand -f) to the list command.
  • Ensure the command validates that no positional arguments are passed (use cobra.NoArgs).
  • In the Run function, print a message indicating which priority is being filtered (e.g., "Filtering tasks by priority: high"). If no filter is provided, it should say "Showing all tasks".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.