Skip to content

Commit

Permalink
Use a copy of root flagset in HandleGlobalFlags
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
Ian Campbell committed Mar 12, 2019
1 parent 26113ac commit 73f5adb
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions cli/cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,20 @@ func (tcmd *TopLevelCommand) HandleGlobalFlags() (*cobra.Command, []string, erro

// We manually parse the global arguments and find the
// subcommand in order to properly deal with plugins. We rely
// on the root command never having any non-flag arguments.
flags := cmd.Flags()
// on the root command never having any non-flag arguments. We
// 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
// potential command instead of accumulating it into
// flags.Args() and then continuing on and finding other
// arguments which we try and treat as globals (when they are
// actually arguments to the subcommand).
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.
flags.AddFlagSet(cmd.Flags())
flags.AddFlagSet(cmd.PersistentFlags())
// Now parse the global flags, up to (but not including) the
// first command. The result will be that all the remaining
Expand Down

0 comments on commit 73f5adb

Please sign in to comment.