Reputation: 19352
I want to have the option of the following cmd invocations in a cli tool I am building in go
using cobra
:
$ mytool envs apps compare
$ mytool envs vars compare
So am creating the commands and performing the bindings as follows:
rootCmd.AddCommand(envsCmd)
envsCmd.AddCommand(appsCmd)
envsCmd.AddCommand(varsCmd)
varsCmd.AddCommand(compareCmd)
appsCmd.AddCommand(compareCmd)
However, when checking the parent of the compare
subcommand, it always turns out to be apps
var compareCmd = &cobra.Command{
Hidden: false,
Use: "compare",
Short: "",
Long: ``,
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println(cmd.Parent().Use)
The above always prints apps
no matter if I invoke
$ mytool envs apps compare
or
$ mytool envs vars compare
Should I assume what I want to achieve is not possible at least using cobra
?
Upvotes: 0
Views: 1274
Reputation: 51542
The commands are linked using pointers, so the last one you add becomes the parent command. Try two copies of the same command instead:
var baseCompareCmd = cobra.Command{...}
var varCompareCmd = baseCompareCmd
var appsCompareCmd = baseCompareCmd
varsCmd.AddCommand(&varCompareCmd)
appsCmd.AddCommand(&appsCompareCmd)
Upvotes: 1