HandleGlobalFlags takes care of parsing global flags defined on the command, it returns the underlying cobra command and the args it will be called with (or an error). On success the caller is responsible for calling Initialize() before calling `Execute` on the returned command.
()
| 127 | // On success the caller is responsible for calling Initialize() |
| 128 | // before calling `Execute` on the returned command. |
| 129 | func (tcmd *TopLevelCommand) HandleGlobalFlags() (*cobra.Command, []string, error) { |
| 130 | cmd := tcmd.cmd |
| 131 | |
| 132 | // We manually parse the global arguments and find the |
| 133 | // subcommand in order to properly deal with plugins. We rely |
| 134 | // on the root command never having any non-flag arguments. We |
| 135 | // create our own FlagSet so that we can configure it |
| 136 | // (e.g. `SetInterspersed` below) in an idempotent way. |
| 137 | flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) |
| 138 | |
| 139 | // We need !interspersed to ensure we stop at the first |
| 140 | // potential command instead of accumulating it into |
| 141 | // flags.Args() and then continuing on and finding other |
| 142 | // arguments which we try and treat as globals (when they are |
| 143 | // actually arguments to the subcommand). |
| 144 | flags.SetInterspersed(false) |
| 145 | |
| 146 | // We need the single parse to see both sets of flags. |
| 147 | flags.AddFlagSet(cmd.Flags()) |
| 148 | flags.AddFlagSet(cmd.PersistentFlags()) |
| 149 | // Now parse the global flags, up to (but not including) the |
| 150 | // first command. The result will be that all the remaining |
| 151 | // arguments are in `flags.Args()`. |
| 152 | if err := flags.Parse(tcmd.args); err != nil { |
| 153 | // Our FlagErrorFunc uses the cli, make sure it is initialized |
| 154 | if err := tcmd.Initialize(); err != nil { |
| 155 | return nil, nil, err |
| 156 | } |
| 157 | return nil, nil, cmd.FlagErrorFunc()(cmd, err) |
| 158 | } |
| 159 | |
| 160 | return cmd, flags.Args(), nil |
| 161 | } |
| 162 | |
| 163 | // Initialize finalises global option parsing and initializes the docker client. |
| 164 | func (tcmd *TopLevelCommand) Initialize(ops ...command.CLIOption) error { |