15

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.

Vahid
  • 1,265
  • 10
  • 20

2 Answers2

44

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.

Teocci
  • 7,189
  • 1
  • 50
  • 48
torek
  • 448,244
  • 59
  • 642
  • 775
-1

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.