Search code examples
gogo-cobra

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


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.


Solution

  • 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.