Skip to content

How to retrieve parent command flag value? #1991

@alebedev80

Description

@alebedev80

There are two commands: main and sub-command. In the main command there is PersistentFlag name.

As i understand there are three options:

  • define flag name in the sub-command. But if there are dozen sub-command with same logic which requires a name then code smell
  • call parent()... i'm implementing command in a way when it doesn't 'know' anything about parents
  • use viper. that's anti-pattern "God object". (btw, please help me integrate viper to a sub-command as dependency but not global object)

From my point of view the method PersistentFlags.Lookup() should recursively search for the value of the flag starting from the current subcommand and moving up through the ancestors until it finds the value or reaches the root.

func recursiveFlagLookup(cmd *cobra.Command, flagName string) (string, error) {
	flag := cmd.PersistentFlags().Lookup(flagName)

	if flag != nil && flag.Value != nil {
		return flag.Value.String(), nil
	}

	if cmd.Parent() != nil {
		return recursiveFlagLookup(cmd.Parent(), flagName)
	}

	return "", fmt.Errorf("flag '%s' not found", flagName)
}

But i'm new in Go and Cobra and maybe already exists nice solution. Please help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions