Skip to content

Commit 33fc528

Browse files
author
Ian Campbell
committed
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 <[email protected]>
1 parent 60c5db5 commit 33fc528

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

cli/cobra.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,18 +124,20 @@ func (tcmd *TopLevelCommand) HandleGlobalFlags() (*cobra.Command, []string, erro
124124

125125
// We manually parse the global arguments and find the
126126
// subcommand in order to properly deal with plugins. We rely
127-
// on the root command never having any non-flag arguments.
128-
flags := cmd.Flags()
127+
// on the root command never having any non-flag arguments. We
128+
// create our own FlagSet so that we can configure it
129+
// (e.g. `SetInterspersed` below) in an idempotent way.
130+
flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError)
129131

130132
// We need !interspersed to ensure we stop at the first
131133
// potential command instead of accumulating it into
132134
// flags.Args() and then continuing on and finding other
133135
// arguments which we try and treat as globals (when they are
134136
// actually arguments to the subcommand).
135137
flags.SetInterspersed(false)
136-
defer flags.SetInterspersed(true) // Undo, any subsequent cmd.Execute() in the caller expects this.
137138

138139
// We need the single parse to see both sets of flags.
140+
flags.AddFlagSet(cmd.Flags())
139141
flags.AddFlagSet(cmd.PersistentFlags())
140142
// Now parse the global flags, up to (but not including) the
141143
// first command. The result will be that all the remaining

0 commit comments

Comments
 (0)