Finalizing the Integration of Cobra into Multi-git

Refactor the main.go file to take advantage of our Cobra root command, then test multi-git to ensure our refactoring didn't break anything. At the end of the lesson, multi-git will be a full-fledged Cobra application.

Refactor the main.go file

With the root command fully implemented, we need to refactor the main.go file, so it executes the Cobra root command instead of all the work it’s currently doing.

The location of main.go should also change. At the moment, it is in cmd/mg/main.go, but Cobra applications have a main.go file at the top-level directory of the project.

The main.go is very simple, and it just executes the root command:

package main

import "github.com/the-gigi/multi-git/cmd"

func main() {
	cmd.Execute()
}

The only unique thing about main.go is that it uses the Go module name to import the cmd package where the root command exposes the Execute() function.

Let’s give it a quick try with no arguments. Heads up, it should fail.

$ go build
$ ./multi-git
Error: accepts 1 arg(s), received 0
Usage:
  multi-git [flags]

Flags:
  -h, --help           help for multi-git
      --ignoreErrors   ignoreErrors will continue executing th command for all repos if true
                                       otherwise it will stop execution when an error occurs

accepts 1 arg(s), received 0

Try running the final multi-git with cobra integrated.

Get hands-on with 1400+ tech skills courses.