Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd.Parent() returns the LAST parent added in code, regardless of the actual command's parent. #1206

Closed
rfinner opened this issue Aug 26, 2020 · 2 comments

Comments

@rfinner
Copy link

rfinner commented Aug 26, 2020

app get schedule

  • returns: schedule parent is get

** AND **

app create schedule

  • returns: schedule parent is get

for the following code:

var scheduleCmd = &cobra.Command{
Use: "schedule",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("schedule parent is ", cmd.Parent().Use)
},
}

func init() {
createCmd.AddCommand(scheduleCmd)
getCmd.AddCommand(scheduleCmd)
}

The reverse is also true if I reverse the order AddCommand. cmd.Parent() returns the LAST parent added, regardless of the actual command's parent.

@Luap99
Copy link
Contributor

Luap99 commented Aug 26, 2020

You cannot do this. Each command can only have one parent. For your use case you would need to generate the command with a function and invoke it for each addcommand call. Like #1015 (comment)

@rfinner
Copy link
Author

rfinner commented Aug 26, 2020

Thanks!

Luap99 explained why answer in #1005 solves my use case:

Here is the code that works (I think it this right but beware that I am a newbie to cobra):

func newScheduleCmd() *cobra.Command {
return &cobra.Command{
Use: "schedule",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("schedule parent is ", cmd.Parent().Name())
fmt.Println("schedule full path: ", cmd.CommandPath())
},
}
}
func init() {
createCmd.AddCommand(newScheduleCmd())
getCmd.AddCommand(newScheduleCmd())
}

@rfinner rfinner closed this as completed Aug 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants