cli icon indicating copy to clipboard operation
cli copied to clipboard

Global flags on simple go CLI

Open ShadowScorpion opened this issue 5 years ago • 4 comments

How I can able to make the flags to be available across whole my script with possibility to use them on any place when running script?

Example :

func main() {
	app := cli.NewApp()
	app.Name = "CLI"

	globalFlags := []cli.Flag{
		&cli.StringFlag{
			Name:    "config",
			Usage:   "path to config file",
			Value:   "~/.aws/credentials",
		},
	}

	app.Flags = globalFlags

	app.Commands = []*cli.Command{
		{
			Name:    "credentials",
			Usage:   "manage CLI credentials",
			Subcommands: []*cli.Command{
				{
					Name:  "set",
					Usage: "set CLI credentials",
					Flags: globalFlags,
					Action: func(c *cli.Context) error {
						fmt.Println(c.String("config"))
						return nil
					},
				},
			},
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}

And from here I get correct response:

go run ./test.go credentials set --config /tmp/test 
/tmp/test

And now how I can able to specify it before subcomand?

go run ./test.go --config /tmp/test credentials set
~/.aws/credentials

Tried to do via setting global vars, via function like this, but also no luck :

func CheckGlobalParameters(c *cli.Context) error {
	if c.GlobalIsSet("config") {
		configPath = c.String("config")
	}
}

ShadowScorpion avatar Nov 19 '20 20:11 ShadowScorpion

Has anyone solved it?

frederikhors avatar Feb 03 '21 19:02 frederikhors

Good question! I'm not sure offhand ~how to do this~ why it doesn't work the way you want here 🤷🏼‍♀️ It definitely seems like something you should be able to do, though!

coilysiren avatar Feb 10 '21 07:02 coilysiren

There are two schools for this. The git command line, or for example, p4, separates gloval and command-local flags. Cobra, which is used in a lot of go CLIs, however, allows mixing global and local flags.

I believe the best way to do this latter is to put “common” flags into a func, and group them as such, before appending them into local flags.

julian7 avatar Feb 17 '21 06:02 julian7

This will be fixed by PR #1245

dearchap avatar Apr 02 '21 23:04 dearchap

Duplicate of #1113

dearchap avatar Oct 21 '22 19:10 dearchap