What is the difference between go-Cobra PersistentFlags and Flags?
Asked Answered
S

2

22

I'm trying to figure out whats is the difference between PersistentFlags and Flags in go-Cobra, and when should we use each of them. I've read this but I didn't understand it.

Seduce answered 19/8, 2020 at 22:51 Comment(0)
K
58

When using Cobra you define a top level command:

prog

This top level command has sub-commands. For instance, suppose we have three sub-commands, init, start, and stop.

prog init [-i]         # initialize, but don't start anything: -i means ignore
prog start [-f] [-q]   # after init, start: -f=fast, -q=quiet
prog stop [-f]         # stop: -f=force

The -i flag is only for init, so we add a -i flag to the init subcommand.

The -q flag is only for start, so we add a -q flag to the start subcommand, and so on.

Now we'd like to add a debug mode to every command. We could go into each command and add a --debug flag ... but we can also just set a persistent flag for the root command. This persistent flag will now be available in every sub-command.

If you have a sub-command that has sub-sub-commands, you can set a persistent flag in the sub-command to make that flag appear in every sub-sub-command, and so on.

Klaxon answered 20/8, 2020 at 4:48 Comment(0)
M
-4

Flags returns the complete FlagSet that applies to this command (local and persistent declared here and by all parents).

PersistentFlags returns the persistent FlagSet specifically set in the current command.

Millicentmillie answered 24/6, 2022 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.