Global flags on simple go CLI
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")
}
}
Has anyone solved it?
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!
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.
This will be fixed by PR #1245
Duplicate of #1113