myapp ├── cmd │ ├── foo.go │ └── bar.go └── main.go
package main import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/cobra/doc" ) func main() { rootCmd := &cobra.Command{ Use: "myapp", Short: "My command-line application", } fooCmd := &cobra.Command{ Use: "foo", Short: "A foo sub-command", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello from foo") }, } barCmd := &cobra.Command{ Use: "bar", Short: "A bar sub-command", Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello from bar") }, } rootCmd.AddCommand(fooCmd, barCmd) // Get the full path of the `myapp` command fmt.Println(rootCmd.CommandPath()) // Get the full path of the `myapp foo` command fmt.Println(fooCmd.CommandPath()) // Get the full path of the `myapp bar` command fmt.Println(barCmd.CommandPath()) }In this example, we create a `rootCmd` object with two sub-commands: `fooCmd` and `barCmd`. We then use the `CommandPath` function to get the full path of each command. This allows us to clearly identify each command when printing output, logging, or debugging. Overall, `github.com/spf13/cobra` is a powerful and flexible package for building command-line applications in Go. The `CommandPath` function is just one of many features that make this package a great choice for any Go developer looking to build command-line tools.