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

Adding global flags to all subcommands is not simple #2

Open
boreq opened this issue Aug 8, 2018 · 1 comment
Open

Adding global flags to all subcommands is not simple #2

boreq opened this issue Aug 8, 2018 · 1 comment

Comments

@boreq
Copy link
Owner

boreq commented Aug 8, 2018

Example: a --verbosity flag which can be added to all subcommands.

It would obviously be annoying and wrong to add this flag to every subcommand and modify their run methods. Either a better way of doing this has to be devised or an automated way of doing this should be documented in the godoc.

This is how this can be solved right now:

func main() {
	injectGlobalBehaviour(&commands.MainCmd)
	err := guinea.Run(&commands.MainCmd)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func injectGlobalBehaviour(cmd *guinea.Command) {
	cmd.Options = append(cmd.Options, guinea.Option{
		Name:        "verbosity",
		Type:        guinea.String,
		Default:     "info",
		Description: "One of: debug, info, warn, error or crit. Default: info",
	})
	oldRun := cmd.Run
	cmd.Run = func(c guinea.Context) error {
		level, err := logging.LevelFromString(c.Options["verbosity"].Str())
		if err != nil {
			return err
		}
		logging.SetLoggingLevel(level)
		if oldRun != nil {
			return oldRun(c)
		}
		return nil
	}
	for _, subCmd := range cmd.Subcommands {
		injectGlobalBehaviour(subCmd)
	}
}
@boreq
Copy link
Owner Author

boreq commented Jul 8, 2019

This is a different approach which can be used:

var globalOpt = []guinea.Option{
	guinea.Option{
		Name:        "help",
		Type:        guinea.Bool,
		Default:     false,
		Description: "Display help",
	},
}

func main() {
	cmd, cmdName, cmdArgs := guinea.FindCommand(&commands.MainCmd, os.Args)
	cmd.Options = append(cmd.Options, globalOpt...)
	if err := cmd.Execute(cmdName, cmdArgs); err != nil {
		fmt.Fprintln(os.Stderr, err)
                os.Exit(1)
	}
}

@boreq boreq pinned this issue Feb 8, 2023
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

1 participant