Skip to content

Adding global flags to all subcommands is not simple #2

@boreq

Description

@boreq

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)
	}
}

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