Use a copy of root flagset in `HandleGlobalFlags`

This makes things more idempotent, rather than relying on undoing the
interspersed settings.

Note that the underlying `Flag`s remain shared, it's just the `FlagSet` which
is duplicated.

Signed-off-by: Ian Campbell <ijc@docker.com>
This commit is contained in:
Ian Campbell 2019-03-12 11:13:50 +00:00
parent 2c624e8984
commit e824bc86f3
1 changed files with 5 additions and 3 deletions

View File

@ -124,8 +124,10 @@ func (tcmd *TopLevelCommand) HandleGlobalFlags() (*cobra.Command, []string, erro
// We manually parse the global arguments and find the // We manually parse the global arguments and find the
// subcommand in order to properly deal with plugins. We rely // subcommand in order to properly deal with plugins. We rely
// on the root command never having any non-flag arguments. // on the root command never having any non-flag arguments. We
flags := cmd.Flags() // create our own FlagSet so that we can configure it
// (e.g. `SetInterspersed` below) in an idempotent way.
flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError)
// We need !interspersed to ensure we stop at the first // We need !interspersed to ensure we stop at the first
// potential command instead of accumulating it into // potential command instead of accumulating it into
@ -133,9 +135,9 @@ func (tcmd *TopLevelCommand) HandleGlobalFlags() (*cobra.Command, []string, erro
// arguments which we try and treat as globals (when they are // arguments which we try and treat as globals (when they are
// actually arguments to the subcommand). // actually arguments to the subcommand).
flags.SetInterspersed(false) flags.SetInterspersed(false)
defer flags.SetInterspersed(true) // Undo, any subsequent cmd.Execute() in the caller expects this.
// We need the single parse to see both sets of flags. // We need the single parse to see both sets of flags.
flags.AddFlagSet(cmd.Flags())
flags.AddFlagSet(cmd.PersistentFlags()) flags.AddFlagSet(cmd.PersistentFlags())
// Now parse the global flags, up to (but not including) the // Now parse the global flags, up to (but not including) the
// first command. The result will be that all the remaining // first command. The result will be that all the remaining