2023-03-06 02:28:31 +00:00
|
|
|
// Copyright 2013-2023 The Cobra Authors
|
2013-09-24 16:47:29 +00:00
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
2022-09-16 11:55:56 +00:00
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
2013-09-24 16:47:29 +00:00
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2017-05-05 06:08:38 +00:00
|
|
|
// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
|
|
|
|
// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
|
2013-09-24 16:47:29 +00:00
|
|
|
package cobra
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2020-02-20 06:29:50 +00:00
|
|
|
"context"
|
2022-06-21 02:02:33 +00:00
|
|
|
"errors"
|
2013-09-24 16:47:29 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2013-11-01 22:36:24 +00:00
|
|
|
"os"
|
2015-11-08 06:21:50 +00:00
|
|
|
"path/filepath"
|
2016-06-14 14:04:53 +00:00
|
|
|
"sort"
|
2013-09-24 16:47:29 +00:00
|
|
|
"strings"
|
2015-05-13 01:38:01 +00:00
|
|
|
|
|
|
|
flag "github.com/spf13/pflag"
|
2013-09-24 16:47:29 +00:00
|
|
|
)
|
|
|
|
|
2023-11-02 12:15:26 +00:00
|
|
|
const (
|
|
|
|
FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"
|
|
|
|
CommandDisplayNameAnnotation = "cobra_annotation_command_display_name"
|
|
|
|
)
|
2022-10-04 22:41:30 +00:00
|
|
|
|
2018-03-31 12:36:20 +00:00
|
|
|
// FParseErrWhitelist configures Flag parse errors to be ignored
|
|
|
|
type FParseErrWhitelist flag.ParseErrorsWhitelist
|
|
|
|
|
2022-12-25 20:08:39 +00:00
|
|
|
// Group Structure to manage groups for commands
|
2022-10-10 20:59:11 +00:00
|
|
|
type Group struct {
|
|
|
|
ID string
|
|
|
|
Title string
|
|
|
|
}
|
|
|
|
|
2013-09-24 16:47:29 +00:00
|
|
|
// Command is just that, a command for your application.
|
2017-05-09 09:15:05 +00:00
|
|
|
// E.g. 'go run ...' - 'run' is the command. Cobra requires
|
2013-09-24 16:47:29 +00:00
|
|
|
// you to define the usage and description as part of your command
|
|
|
|
// definition to ensure usability.
|
|
|
|
type Command struct {
|
2017-05-09 09:15:05 +00:00
|
|
|
// Use is the one-line usage message.
|
2022-12-25 20:08:39 +00:00
|
|
|
// Recommended syntax is as follows:
|
2020-08-18 20:14:09 +00:00
|
|
|
// [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
|
|
|
|
// ... indicates that you can specify multiple values for the previous argument.
|
|
|
|
// | indicates mutually exclusive information. You can use the argument to the left of the separator or the
|
|
|
|
// argument to the right of the separator. You cannot use both arguments in a single use of the command.
|
|
|
|
// { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are
|
|
|
|
// optional, they are enclosed in brackets ([ ]).
|
|
|
|
// Example: add [-F file | -D dir]... [-f format] profile
|
2013-09-24 16:47:29 +00:00
|
|
|
Use string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// Aliases is an array of aliases that can be used instead of the first word in Use.
|
2014-09-25 23:03:34 +00:00
|
|
|
Aliases []string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// SuggestFor is an array of command names for which this command will be suggested -
|
|
|
|
// similar to aliases but only suggests.
|
2015-09-25 15:04:28 +00:00
|
|
|
SuggestFor []string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// Short is the short description shown in the 'help' output.
|
2013-09-24 16:47:29 +00:00
|
|
|
Short string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2022-10-10 20:59:11 +00:00
|
|
|
// The group id under which this subcommand is grouped in the 'help' output of its parent.
|
|
|
|
GroupID string
|
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// Long is the long message shown in the 'help <this-command>' output.
|
2013-09-24 16:47:29 +00:00
|
|
|
Long string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// Example is examples of how to use the command.
|
2015-02-12 23:12:07 +00:00
|
|
|
Example string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2021-06-30 21:24:58 +00:00
|
|
|
// ValidArgs is list of all valid non-flag arguments that are accepted in shell completions
|
2015-03-16 19:31:03 +00:00
|
|
|
ValidArgs []string
|
2021-06-30 21:24:58 +00:00
|
|
|
// ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.
|
2020-04-03 19:43:43 +00:00
|
|
|
// It is a dynamic version of using ValidArgs.
|
|
|
|
// Only one of ValidArgs and ValidArgsFunction can be used for a command.
|
2020-04-06 17:28:44 +00:00
|
|
|
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-07-26 12:51:25 +00:00
|
|
|
// Expected arguments
|
|
|
|
Args PositionalArgs
|
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// ArgAliases is List of aliases for ValidArgs.
|
2021-06-30 21:24:58 +00:00
|
|
|
// These are not suggested to the user in the shell completion,
|
2017-05-09 09:15:05 +00:00
|
|
|
// but accepted if entered manually.
|
2016-03-25 15:05:56 +00:00
|
|
|
ArgAliases []string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2021-06-30 21:24:58 +00:00
|
|
|
// BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.
|
|
|
|
// For portability with other shells, it is recommended to instead use ValidArgsFunction
|
2015-03-16 19:31:03 +00:00
|
|
|
BashCompletionFunction string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-05-09 09:25:41 +00:00
|
|
|
// Deprecated defines, if this command is deprecated and should print this string when used.
|
2015-04-07 21:38:22 +00:00
|
|
|
Deprecated string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-02-07 21:20:48 +00:00
|
|
|
// Annotations are key/value pairs that can be used by applications to identify or
|
2023-11-02 12:15:26 +00:00
|
|
|
// group commands or set special options.
|
2017-02-07 21:20:48 +00:00
|
|
|
Annotations map[string]string
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// Version defines the version for this command. If this value is non-empty and the command does not
|
|
|
|
// define a "version" flag, a "version" boolean flag will be added to the command and, if specified,
|
2020-02-28 18:13:40 +00:00
|
|
|
// will print content of the "Version" variable. A shorthand "v" flag will also be added if the
|
|
|
|
// command does not define one.
|
2017-12-01 21:37:16 +00:00
|
|
|
Version string
|
|
|
|
|
2015-04-30 17:58:29 +00:00
|
|
|
// The *Run functions are executed in the following order:
|
|
|
|
// * PersistentPreRun()
|
|
|
|
// * PreRun()
|
|
|
|
// * Run()
|
|
|
|
// * PostRun()
|
|
|
|
// * PersistentPostRun()
|
2017-05-09 09:15:05 +00:00
|
|
|
// All functions get the same args, the arguments after the command name.
|
2023-10-09 12:50:40 +00:00
|
|
|
// The *PreRun and *PostRun functions will only be executed if the Run function of the current
|
|
|
|
// command has been declared.
|
2017-05-09 09:33:56 +00:00
|
|
|
//
|
2017-05-09 09:15:05 +00:00
|
|
|
// PersistentPreRun: children of this command will inherit and execute.
|
2015-04-30 17:58:29 +00:00
|
|
|
PersistentPreRun func(cmd *Command, args []string)
|
2017-05-09 09:15:05 +00:00
|
|
|
// PersistentPreRunE: PersistentPreRun but returns an error.
|
2015-08-31 01:03:16 +00:00
|
|
|
PersistentPreRunE func(cmd *Command, args []string) error
|
2015-04-30 17:58:29 +00:00
|
|
|
// PreRun: children of this command will not inherit.
|
2015-02-09 22:44:14 +00:00
|
|
|
PreRun func(cmd *Command, args []string)
|
2017-05-09 09:15:05 +00:00
|
|
|
// PreRunE: PreRun but returns an error.
|
2015-08-31 01:03:16 +00:00
|
|
|
PreRunE func(cmd *Command, args []string) error
|
2017-05-09 09:15:05 +00:00
|
|
|
// Run: Typically the actual work function. Most commands will only implement this.
|
2015-04-30 17:58:29 +00:00
|
|
|
Run func(cmd *Command, args []string)
|
2017-05-09 09:15:05 +00:00
|
|
|
// RunE: Run but returns an error.
|
2015-08-31 01:03:16 +00:00
|
|
|
RunE func(cmd *Command, args []string) error
|
2015-04-30 17:58:29 +00:00
|
|
|
// PostRun: run after the Run command.
|
2015-02-09 22:44:14 +00:00
|
|
|
PostRun func(cmd *Command, args []string)
|
2017-05-09 09:15:05 +00:00
|
|
|
// PostRunE: PostRun but returns an error.
|
2015-08-31 01:03:16 +00:00
|
|
|
PostRunE func(cmd *Command, args []string) error
|
2017-05-09 09:15:05 +00:00
|
|
|
// PersistentPostRun: children of this command will inherit and execute after PostRun.
|
2015-02-17 21:09:49 +00:00
|
|
|
PersistentPostRun func(cmd *Command, args []string)
|
2017-05-09 09:15:05 +00:00
|
|
|
// PersistentPostRunE: PersistentPostRun but returns an error.
|
2015-08-31 01:03:16 +00:00
|
|
|
PersistentPostRunE func(cmd *Command, args []string) error
|
2017-05-09 09:33:56 +00:00
|
|
|
|
2022-10-10 20:59:11 +00:00
|
|
|
// groups for subcommands
|
|
|
|
commandgroups []*Group
|
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// args is actual args parsed from flags.
|
|
|
|
args []string
|
2017-05-09 09:25:41 +00:00
|
|
|
// flagErrorBuf contains all error messages from pflag.
|
|
|
|
flagErrorBuf *bytes.Buffer
|
|
|
|
// flags is full set of flags.
|
|
|
|
flags *flag.FlagSet
|
|
|
|
// pflags contains persistent flags.
|
|
|
|
pflags *flag.FlagSet
|
|
|
|
// lflags contains local flags.
|
2024-01-06 21:49:13 +00:00
|
|
|
// This field does not represent internal state, it's used as a cache to optimise LocalFlags function call
|
2017-05-09 09:25:41 +00:00
|
|
|
lflags *flag.FlagSet
|
|
|
|
// iflags contains inherited flags.
|
2024-01-06 21:49:13 +00:00
|
|
|
// This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call
|
2017-05-09 09:25:41 +00:00
|
|
|
iflags *flag.FlagSet
|
|
|
|
// parentsPflags is all persistent flags of cmd's parents.
|
|
|
|
parentsPflags *flag.FlagSet
|
|
|
|
// globNormFunc is the global normalization function
|
|
|
|
// that we can use on every pflag set and children commands
|
|
|
|
globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
|
|
|
|
|
2017-05-09 09:15:05 +00:00
|
|
|
// usageFunc is usage func defined by user.
|
|
|
|
usageFunc func(*Command) error
|
|
|
|
// usageTemplate is usage template defined by user.
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
usageTemplate *tmplFunc
|
2017-05-09 09:15:05 +00:00
|
|
|
// flagErrorFunc is func defined by user and it's called when the parsing of
|
|
|
|
// flags returns an error.
|
2016-05-25 21:27:02 +00:00
|
|
|
flagErrorFunc func(*Command, error) error
|
2017-05-09 09:15:05 +00:00
|
|
|
// helpTemplate is help template defined by user.
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
helpTemplate *tmplFunc
|
2017-05-09 09:15:05 +00:00
|
|
|
// helpFunc is help func defined by user.
|
|
|
|
helpFunc func(*Command, []string)
|
2017-05-09 09:25:41 +00:00
|
|
|
// helpCommand is command with usage 'help'. If it's not defined by user,
|
2017-05-09 09:15:05 +00:00
|
|
|
// cobra uses default help command.
|
|
|
|
helpCommand *Command
|
2022-10-10 20:59:11 +00:00
|
|
|
// helpCommandGroupID is the group id for the helpCommand
|
|
|
|
helpCommandGroupID string
|
|
|
|
|
|
|
|
// completionCommandGroupID is the group id for the completion command
|
|
|
|
completionCommandGroupID string
|
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// versionTemplate is the version template defined by user.
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
versionTemplate *tmplFunc
|
2019-02-11 06:10:59 +00:00
|
|
|
|
2023-09-08 17:29:06 +00:00
|
|
|
// errPrefix is the error message prefix defined by user.
|
|
|
|
errPrefix string
|
|
|
|
|
2019-02-11 06:10:59 +00:00
|
|
|
// inReader is a reader defined by the user that replaces stdin
|
|
|
|
inReader io.Reader
|
|
|
|
// outWriter is a writer defined by the user that replaces stdout
|
|
|
|
outWriter io.Writer
|
|
|
|
// errWriter is a writer defined by the user that replaces stderr
|
|
|
|
errWriter io.Writer
|
2021-02-08 00:08:50 +00:00
|
|
|
|
2022-03-21 17:35:35 +00:00
|
|
|
// FParseErrWhitelist flag parse errors to be ignored
|
2021-02-08 00:08:50 +00:00
|
|
|
FParseErrWhitelist FParseErrWhitelist
|
|
|
|
|
2021-02-15 17:47:01 +00:00
|
|
|
// CompletionOptions is a set of options to control the handling of shell completion
|
|
|
|
CompletionOptions CompletionOptions
|
|
|
|
|
2021-02-08 00:08:50 +00:00
|
|
|
// commandsAreSorted defines, if command slice are sorted or not.
|
|
|
|
commandsAreSorted bool
|
|
|
|
// commandCalledAs is the name or alias value used to call this command.
|
|
|
|
commandCalledAs struct {
|
|
|
|
name string
|
|
|
|
called bool
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
|
|
|
|
// commands is the list of commands supported by this program.
|
|
|
|
commands []*Command
|
|
|
|
// parent is a parent command for this command.
|
|
|
|
parent *Command
|
|
|
|
// Max lengths of commands' string lengths for use in padding.
|
|
|
|
commandsMaxUseLen int
|
|
|
|
commandsMaxCommandPathLen int
|
|
|
|
commandsMaxNameLen int
|
|
|
|
|
|
|
|
// TraverseChildren parses flags on all parents before executing child command.
|
|
|
|
TraverseChildren bool
|
|
|
|
|
|
|
|
// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
|
|
|
|
Hidden bool
|
|
|
|
|
|
|
|
// SilenceErrors is an option to quiet errors down stream.
|
|
|
|
SilenceErrors bool
|
|
|
|
|
|
|
|
// SilenceUsage is an option to silence usage when an error occurs.
|
|
|
|
SilenceUsage bool
|
|
|
|
|
|
|
|
// DisableFlagParsing disables the flag parsing.
|
|
|
|
// If this is true all flags will be passed to the command as arguments.
|
|
|
|
DisableFlagParsing bool
|
|
|
|
|
|
|
|
// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
|
|
|
|
// will be printed by generating docs for this command.
|
|
|
|
DisableAutoGenTag bool
|
|
|
|
|
|
|
|
// DisableFlagsInUseLine will disable the addition of [flags] to the usage
|
|
|
|
// line of a command when printing help or generating docs
|
|
|
|
DisableFlagsInUseLine bool
|
|
|
|
|
|
|
|
// DisableSuggestions disables the suggestions based on Levenshtein distance
|
|
|
|
// that go along with 'unknown command' messages.
|
|
|
|
DisableSuggestions bool
|
|
|
|
|
|
|
|
// SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions.
|
|
|
|
// Must be > 0.
|
|
|
|
SuggestionsMinimumDistance int
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2022-03-21 17:35:35 +00:00
|
|
|
// Context returns underlying command context. If command was executed
|
|
|
|
// with ExecuteContext or the context was set with SetContext, the
|
|
|
|
// previously set context will be returned. Otherwise, nil is returned.
|
|
|
|
//
|
|
|
|
// Notice that a call to Execute and ExecuteC will replace a nil context of
|
|
|
|
// a command with a context.Background, so a background context will be
|
|
|
|
// returned by Context after one of these functions has been called.
|
2020-02-20 06:29:50 +00:00
|
|
|
func (c *Command) Context() context.Context {
|
|
|
|
return c.ctx
|
|
|
|
}
|
|
|
|
|
2022-08-30 02:12:56 +00:00
|
|
|
// SetContext sets context for the command. This context will be overwritten by
|
|
|
|
// Command.ExecuteContext or Command.ExecuteContextC.
|
2022-03-18 10:01:58 +00:00
|
|
|
func (c *Command) SetContext(ctx context.Context) {
|
|
|
|
c.ctx = ctx
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
2013-11-01 22:36:24 +00:00
|
|
|
// particularly useful when testing.
|
|
|
|
func (c *Command) SetArgs(a []string) {
|
|
|
|
c.args = a
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetOutput sets the destination for usage and error messages.
|
|
|
|
// If output is nil, os.Stderr is used.
|
2024-07-16 23:36:29 +00:00
|
|
|
//
|
2019-02-13 05:32:16 +00:00
|
|
|
// Deprecated: Use SetOut and/or SetErr instead
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) SetOutput(output io.Writer) {
|
2019-02-11 06:10:59 +00:00
|
|
|
c.outWriter = output
|
2019-02-13 05:32:16 +00:00
|
|
|
c.errWriter = output
|
2019-02-11 06:10:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetOut sets the destination for usage messages.
|
|
|
|
// If newOut is nil, os.Stdout is used.
|
|
|
|
func (c *Command) SetOut(newOut io.Writer) {
|
2019-02-11 07:22:54 +00:00
|
|
|
c.outWriter = newOut
|
2019-02-11 06:10:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetErr sets the destination for error messages.
|
|
|
|
// If newErr is nil, os.Stderr is used.
|
2019-02-11 07:22:54 +00:00
|
|
|
func (c *Command) SetErr(newErr io.Writer) {
|
2019-02-11 06:10:59 +00:00
|
|
|
c.errWriter = newErr
|
|
|
|
}
|
|
|
|
|
2019-07-30 22:26:11 +00:00
|
|
|
// SetIn sets the source for input data
|
2019-02-11 06:10:59 +00:00
|
|
|
// If newIn is nil, os.Stdin is used.
|
|
|
|
func (c *Command) SetIn(newIn io.Reader) {
|
|
|
|
c.inReader = newIn
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// SetUsageFunc sets usage function. Usage can be defined by application.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) SetUsageFunc(f func(*Command) error) {
|
|
|
|
c.usageFunc = f
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// SetUsageTemplate sets usage template. Can be defined by Application.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) SetUsageTemplate(s string) {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
c.usageTemplate = tmpl(s)
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
2016-05-25 21:27:02 +00:00
|
|
|
// SetFlagErrorFunc sets a function to generate an error when flag parsing
|
2017-02-28 19:17:48 +00:00
|
|
|
// fails.
|
2016-05-25 21:27:02 +00:00
|
|
|
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
|
|
|
|
c.flagErrorFunc = f
|
|
|
|
}
|
|
|
|
|
2017-02-28 19:17:48 +00:00
|
|
|
// SetHelpFunc sets help function. Can be defined by Application.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) SetHelpFunc(f func(*Command, []string)) {
|
|
|
|
c.helpFunc = f
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// SetHelpCommand sets help command.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) SetHelpCommand(cmd *Command) {
|
|
|
|
c.helpCommand = cmd
|
|
|
|
}
|
|
|
|
|
2022-12-25 20:08:39 +00:00
|
|
|
// SetHelpCommandGroupID sets the group id of the help command.
|
2022-10-10 20:59:11 +00:00
|
|
|
func (c *Command) SetHelpCommandGroupID(groupID string) {
|
|
|
|
if c.helpCommand != nil {
|
|
|
|
c.helpCommand.GroupID = groupID
|
|
|
|
}
|
|
|
|
// helpCommandGroupID is used if no helpCommand is defined by the user
|
|
|
|
c.helpCommandGroupID = groupID
|
|
|
|
}
|
|
|
|
|
2022-12-25 20:08:39 +00:00
|
|
|
// SetCompletionCommandGroupID sets the group id of the completion command.
|
2022-10-10 20:59:11 +00:00
|
|
|
func (c *Command) SetCompletionCommandGroupID(groupID string) {
|
|
|
|
// completionCommandGroupID is used if no completion command is defined by the user
|
|
|
|
c.Root().completionCommandGroupID = groupID
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) SetHelpTemplate(s string) {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
c.helpTemplate = tmpl(s)
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// SetVersionTemplate sets version template to be used. Application can use it to set custom template.
|
|
|
|
func (c *Command) SetVersionTemplate(s string) {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
c.versionTemplate = tmpl(s)
|
2017-12-01 21:37:16 +00:00
|
|
|
}
|
|
|
|
|
2023-09-08 17:29:06 +00:00
|
|
|
// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix.
|
|
|
|
func (c *Command) SetErrPrefix(s string) {
|
|
|
|
c.errPrefix = s
|
|
|
|
}
|
|
|
|
|
2015-05-14 17:38:15 +00:00
|
|
|
// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
|
|
|
|
// The user should not have a cyclic dependency on commands.
|
|
|
|
func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
|
|
|
|
c.Flags().SetNormalizeFunc(n)
|
|
|
|
c.PersistentFlags().SetNormalizeFunc(n)
|
|
|
|
c.globNormFunc = n
|
|
|
|
|
|
|
|
for _, command := range c.commands {
|
|
|
|
command.SetGlobalNormalizationFunc(n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-28 19:17:48 +00:00
|
|
|
// OutOrStdout returns output to stdout.
|
2016-07-15 20:12:07 +00:00
|
|
|
func (c *Command) OutOrStdout() io.Writer {
|
2016-07-06 15:51:57 +00:00
|
|
|
return c.getOut(os.Stdout)
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// OutOrStderr returns output to stderr
|
2016-07-15 20:12:07 +00:00
|
|
|
func (c *Command) OutOrStderr() io.Writer {
|
2016-07-06 15:51:57 +00:00
|
|
|
return c.getOut(os.Stderr)
|
|
|
|
}
|
|
|
|
|
2019-02-11 06:10:59 +00:00
|
|
|
// ErrOrStderr returns output to stderr
|
|
|
|
func (c *Command) ErrOrStderr() io.Writer {
|
|
|
|
return c.getErr(os.Stderr)
|
|
|
|
}
|
|
|
|
|
2020-02-20 18:42:29 +00:00
|
|
|
// InOrStdin returns input to stdin
|
2019-02-11 06:10:59 +00:00
|
|
|
func (c *Command) InOrStdin() io.Reader {
|
|
|
|
return c.getIn(os.Stdin)
|
|
|
|
}
|
|
|
|
|
2016-07-06 15:51:57 +00:00
|
|
|
func (c *Command) getOut(def io.Writer) io.Writer {
|
2019-02-11 06:10:59 +00:00
|
|
|
if c.outWriter != nil {
|
|
|
|
return c.outWriter
|
2016-07-06 15:51:57 +00:00
|
|
|
}
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.getOut(def)
|
|
|
|
}
|
|
|
|
return def
|
|
|
|
}
|
|
|
|
|
2019-02-11 06:10:59 +00:00
|
|
|
func (c *Command) getErr(def io.Writer) io.Writer {
|
|
|
|
if c.errWriter != nil {
|
|
|
|
return c.errWriter
|
|
|
|
}
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.getErr(def)
|
|
|
|
}
|
|
|
|
return def
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Command) getIn(def io.Reader) io.Reader {
|
|
|
|
if c.inReader != nil {
|
|
|
|
return c.inReader
|
|
|
|
}
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.getIn(def)
|
|
|
|
}
|
|
|
|
return def
|
|
|
|
}
|
|
|
|
|
2016-07-06 15:51:57 +00:00
|
|
|
// UsageFunc returns either the function set by SetUsageFunc for this command
|
2016-08-30 17:14:27 +00:00
|
|
|
// or a parent, or it returns a default usage function.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) UsageFunc() (f func(*Command) error) {
|
|
|
|
if c.usageFunc != nil {
|
|
|
|
return c.usageFunc
|
|
|
|
}
|
|
|
|
if c.HasParent() {
|
2017-04-23 07:17:44 +00:00
|
|
|
return c.Parent().UsageFunc()
|
2016-03-31 13:53:34 +00:00
|
|
|
}
|
|
|
|
return func(c *Command) error {
|
2016-07-15 20:17:29 +00:00
|
|
|
c.mergePersistentFlags()
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
fn := defaultUsageFunc
|
|
|
|
if c.usageTemplate != nil {
|
|
|
|
fn = c.usageTemplate.fn
|
|
|
|
}
|
|
|
|
err := fn(c.OutOrStderr(), c)
|
2016-03-31 13:53:34 +00:00
|
|
|
if err != nil {
|
2020-10-01 15:28:00 +00:00
|
|
|
c.PrintErrln(err)
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
2016-03-31 13:53:34 +00:00
|
|
|
return err
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
}
|
2015-09-01 17:58:55 +00:00
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Usage puts out the usage for the command.
|
|
|
|
// Used when a user provides invalid input.
|
|
|
|
// Can be defined by user by overriding UsageFunc.
|
2016-07-20 14:39:46 +00:00
|
|
|
func (c *Command) Usage() error {
|
|
|
|
return c.UsageFunc()(c)
|
|
|
|
}
|
|
|
|
|
2015-09-01 17:58:55 +00:00
|
|
|
// HelpFunc returns either the function set by SetHelpFunc for this command
|
2016-08-30 17:14:27 +00:00
|
|
|
// or a parent, or it returns a function with default help behavior.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) HelpFunc() func(*Command, []string) {
|
2017-04-23 07:17:44 +00:00
|
|
|
if c.helpFunc != nil {
|
|
|
|
return c.helpFunc
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
2017-04-23 07:17:44 +00:00
|
|
|
if c.HasParent() {
|
|
|
|
return c.Parent().HelpFunc()
|
|
|
|
}
|
|
|
|
return func(c *Command, a []string) {
|
2016-07-15 20:17:29 +00:00
|
|
|
c.mergePersistentFlags()
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
fn := defaultHelpFunc
|
|
|
|
if c.helpTemplate != nil {
|
|
|
|
fn = c.helpTemplate.fn
|
|
|
|
}
|
2019-12-23 18:38:24 +00:00
|
|
|
// The help should be sent to stdout
|
|
|
|
// See https://github.com/spf13/cobra/issues/1002
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
err := fn(c.OutOrStdout(), c)
|
2015-09-01 17:58:55 +00:00
|
|
|
if err != nil {
|
2020-10-01 15:28:00 +00:00
|
|
|
c.PrintErrln(err)
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Help puts out the help for the command.
|
|
|
|
// Used when a user calls help [command].
|
|
|
|
// Can be defined by user by overriding HelpFunc.
|
2016-07-20 14:39:46 +00:00
|
|
|
func (c *Command) Help() error {
|
|
|
|
c.HelpFunc()(c, []string{})
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-15 16:49:16 +00:00
|
|
|
// UsageString returns usage string.
|
2016-07-06 15:51:57 +00:00
|
|
|
func (c *Command) UsageString() string {
|
2019-05-15 16:49:16 +00:00
|
|
|
// Storing normal writers
|
2019-02-11 06:10:59 +00:00
|
|
|
tmpOutput := c.outWriter
|
2019-05-15 16:49:16 +00:00
|
|
|
tmpErr := c.errWriter
|
|
|
|
|
2016-07-06 15:51:57 +00:00
|
|
|
bb := new(bytes.Buffer)
|
2019-02-11 06:10:59 +00:00
|
|
|
c.outWriter = bb
|
2019-05-15 16:49:16 +00:00
|
|
|
c.errWriter = bb
|
|
|
|
|
2021-02-08 00:08:50 +00:00
|
|
|
CheckErr(c.Usage())
|
2019-05-15 16:49:16 +00:00
|
|
|
|
|
|
|
// Setting things back to normal
|
2019-02-11 06:10:59 +00:00
|
|
|
c.outWriter = tmpOutput
|
2019-05-15 16:49:16 +00:00
|
|
|
c.errWriter = tmpErr
|
|
|
|
|
2016-07-06 15:51:57 +00:00
|
|
|
return bb.String()
|
|
|
|
}
|
|
|
|
|
2016-05-25 21:27:02 +00:00
|
|
|
// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
|
|
|
|
// command or a parent, or it returns a function which returns the original
|
|
|
|
// error.
|
|
|
|
func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
|
|
|
|
if c.flagErrorFunc != nil {
|
|
|
|
return c.flagErrorFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.FlagErrorFunc()
|
|
|
|
}
|
|
|
|
return func(c *Command, err error) error {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-31 13:53:34 +00:00
|
|
|
var minUsagePadding = 25
|
2014-01-17 12:36:57 +00:00
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// UsagePadding return padding for the usage.
|
2014-01-17 12:36:57 +00:00
|
|
|
func (c *Command) UsagePadding() int {
|
|
|
|
if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
|
|
|
|
return minUsagePadding
|
|
|
|
}
|
2016-03-31 13:53:34 +00:00
|
|
|
return c.parent.commandsMaxUseLen
|
2014-01-17 12:36:57 +00:00
|
|
|
}
|
|
|
|
|
2016-03-31 13:53:34 +00:00
|
|
|
var minCommandPathPadding = 11
|
2014-01-17 12:36:57 +00:00
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// CommandPathPadding return padding for the command path.
|
2014-01-17 12:36:57 +00:00
|
|
|
func (c *Command) CommandPathPadding() int {
|
|
|
|
if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
|
|
|
|
return minCommandPathPadding
|
|
|
|
}
|
2016-03-31 13:53:34 +00:00
|
|
|
return c.parent.commandsMaxCommandPathLen
|
2014-01-17 12:36:57 +00:00
|
|
|
}
|
|
|
|
|
2016-03-31 13:53:34 +00:00
|
|
|
var minNamePadding = 11
|
2015-02-11 09:20:29 +00:00
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// NamePadding returns padding for the name.
|
2015-02-11 09:20:29 +00:00
|
|
|
func (c *Command) NamePadding() int {
|
|
|
|
if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
|
|
|
|
return minNamePadding
|
|
|
|
}
|
2016-03-31 13:53:34 +00:00
|
|
|
return c.parent.commandsMaxNameLen
|
2015-02-11 09:20:29 +00:00
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// UsageTemplate returns usage template for the command.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) UsageTemplate() string {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
if c.usageTemplate != nil {
|
|
|
|
return c.usageTemplate.tmpl
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.UsageTemplate()
|
2016-03-31 13:53:34 +00:00
|
|
|
}
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
return defaultUsageTemplate
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HelpTemplate return help template for the command.
|
2013-11-01 22:36:24 +00:00
|
|
|
func (c *Command) HelpTemplate() string {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
if c.helpTemplate != nil {
|
|
|
|
return c.helpTemplate.tmpl
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.HelpTemplate()
|
2016-03-31 13:53:34 +00:00
|
|
|
}
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
return defaultHelpTemplate
|
2013-09-29 05:57:50 +00:00
|
|
|
}
|
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// VersionTemplate return version template for the command.
|
|
|
|
func (c *Command) VersionTemplate() string {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
if c.versionTemplate != nil {
|
|
|
|
return c.versionTemplate.tmpl
|
2017-12-01 21:37:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.VersionTemplate()
|
|
|
|
}
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
return defaultVersionTemplate
|
2017-12-01 21:37:16 +00:00
|
|
|
}
|
|
|
|
|
2023-09-08 17:29:06 +00:00
|
|
|
// ErrPrefix return error message prefix for the command
|
|
|
|
func (c *Command) ErrPrefix() string {
|
|
|
|
if c.errPrefix != "" {
|
|
|
|
return c.errPrefix
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.HasParent() {
|
|
|
|
return c.parent.ErrPrefix()
|
|
|
|
}
|
|
|
|
return "Error:"
|
|
|
|
}
|
|
|
|
|
2017-05-05 06:08:38 +00:00
|
|
|
func hasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
|
|
|
flag := fs.Lookup(name)
|
2015-03-11 18:52:35 +00:00
|
|
|
if flag == nil {
|
|
|
|
return false
|
|
|
|
}
|
2017-04-24 13:20:01 +00:00
|
|
|
return flag.NoOptDefVal != ""
|
2015-03-11 18:52:35 +00:00
|
|
|
}
|
|
|
|
|
2017-02-23 13:12:51 +00:00
|
|
|
func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
2017-05-05 06:08:38 +00:00
|
|
|
if len(name) == 0 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
flag := fs.ShorthandLookup(name[:1])
|
|
|
|
if flag == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return flag.NoOptDefVal != ""
|
2015-03-11 18:52:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func stripFlags(args []string, c *Command) []string {
|
2017-04-23 20:38:30 +00:00
|
|
|
if len(args) == 0 {
|
2014-06-17 16:32:27 +00:00
|
|
|
return args
|
|
|
|
}
|
2015-03-16 19:47:32 +00:00
|
|
|
c.mergePersistentFlags()
|
2014-06-17 16:32:27 +00:00
|
|
|
|
|
|
|
commands := []string{}
|
2017-04-24 13:20:01 +00:00
|
|
|
flags := c.Flags()
|
2017-04-23 20:38:30 +00:00
|
|
|
|
|
|
|
Loop:
|
|
|
|
for len(args) > 0 {
|
|
|
|
s := args[0]
|
2017-04-24 13:20:01 +00:00
|
|
|
args = args[1:]
|
2017-05-14 12:51:04 +00:00
|
|
|
switch {
|
2018-03-19 06:20:04 +00:00
|
|
|
case s == "--":
|
|
|
|
// "--" terminates the flags
|
|
|
|
break Loop
|
2017-05-14 12:51:04 +00:00
|
|
|
case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
|
|
|
|
// If '--flag arg' then
|
|
|
|
// delete arg from args.
|
|
|
|
fallthrough // (do the same as below)
|
|
|
|
case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
|
|
|
|
// If '-f arg' then
|
|
|
|
// delete 'arg' from args or break the loop if len(args) <= 1.
|
|
|
|
if len(args) <= 1 {
|
|
|
|
break Loop
|
|
|
|
} else {
|
|
|
|
args = args[1:]
|
|
|
|
continue
|
2014-06-17 16:32:27 +00:00
|
|
|
}
|
2017-05-14 12:51:04 +00:00
|
|
|
case s != "" && !strings.HasPrefix(s, "-"):
|
|
|
|
commands = append(commands, s)
|
2014-06-17 16:32:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return commands
|
|
|
|
}
|
|
|
|
|
2015-04-24 15:39:11 +00:00
|
|
|
// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like
|
|
|
|
// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
|
2022-11-08 04:12:02 +00:00
|
|
|
// Special care needs to be taken not to remove a flag value.
|
|
|
|
func (c *Command) argsMinusFirstX(args []string, x string) []string {
|
|
|
|
if len(args) == 0 {
|
|
|
|
return args
|
|
|
|
}
|
|
|
|
c.mergePersistentFlags()
|
|
|
|
flags := c.Flags()
|
|
|
|
|
|
|
|
Loop:
|
|
|
|
for pos := 0; pos < len(args); pos++ {
|
|
|
|
s := args[pos]
|
|
|
|
switch {
|
|
|
|
case s == "--":
|
|
|
|
// -- means we have reached the end of the parseable args. Break out of the loop now.
|
|
|
|
break Loop
|
|
|
|
case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
|
|
|
|
fallthrough
|
|
|
|
case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):
|
|
|
|
// This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip
|
|
|
|
// over the next arg, because that is the value of this flag.
|
|
|
|
pos++
|
|
|
|
continue
|
|
|
|
case !strings.HasPrefix(s, "-"):
|
|
|
|
// This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,
|
|
|
|
// return the args, excluding the one at this position.
|
|
|
|
if s == x {
|
2023-11-23 17:24:33 +00:00
|
|
|
ret := make([]string, 0, len(args)-1)
|
2022-11-08 04:12:02 +00:00
|
|
|
ret = append(ret, args[:pos]...)
|
|
|
|
ret = append(ret, args[pos+1:]...)
|
|
|
|
return ret
|
|
|
|
}
|
2014-06-17 16:32:27 +00:00
|
|
|
}
|
|
|
|
}
|
2015-04-24 15:39:11 +00:00
|
|
|
return args
|
2014-06-17 16:32:27 +00:00
|
|
|
}
|
|
|
|
|
2017-10-07 21:29:11 +00:00
|
|
|
func isFlagArg(arg string) bool {
|
2023-01-03 00:58:36 +00:00
|
|
|
return ((len(arg) >= 3 && arg[0:2] == "--") ||
|
2017-10-07 21:29:11 +00:00
|
|
|
(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
|
|
|
|
}
|
|
|
|
|
2017-02-07 21:20:48 +00:00
|
|
|
// Find the target command given the args and command tree
|
2013-09-24 20:03:22 +00:00
|
|
|
// Meant to be run on the highest node. Only searches down.
|
2015-05-13 01:38:01 +00:00
|
|
|
func (c *Command) Find(args []string) (*Command, []string, error) {
|
2013-09-29 05:59:13 +00:00
|
|
|
var innerfind func(*Command, []string) (*Command, []string)
|
|
|
|
|
2015-05-13 01:38:01 +00:00
|
|
|
innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
|
2015-06-09 17:52:43 +00:00
|
|
|
argsWOflags := stripFlags(innerArgs, c)
|
|
|
|
if len(argsWOflags) == 0 {
|
|
|
|
return c, innerArgs
|
|
|
|
}
|
|
|
|
nextSubCmd := argsWOflags[0]
|
2013-09-29 05:59:13 +00:00
|
|
|
|
2017-10-07 21:29:11 +00:00
|
|
|
cmd := c.findNext(nextSubCmd)
|
|
|
|
if cmd != nil {
|
2022-11-08 04:12:02 +00:00
|
|
|
return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd))
|
2015-06-09 17:52:43 +00:00
|
|
|
}
|
2015-05-13 01:38:01 +00:00
|
|
|
return c, innerArgs
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2013-09-29 05:59:13 +00:00
|
|
|
|
2015-05-13 01:38:01 +00:00
|
|
|
commandFound, a := innerfind(c, args)
|
2016-05-07 17:24:05 +00:00
|
|
|
if commandFound.Args == nil {
|
|
|
|
return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound))
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2013-09-29 05:59:13 +00:00
|
|
|
return commandFound, a, nil
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-05-07 17:24:05 +00:00
|
|
|
func (c *Command) findSuggestions(arg string) string {
|
2015-06-09 18:17:58 +00:00
|
|
|
if c.DisableSuggestions {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
if c.SuggestionsMinimumDistance <= 0 {
|
|
|
|
c.SuggestionsMinimumDistance = 2
|
|
|
|
}
|
2023-11-23 17:24:33 +00:00
|
|
|
var sb strings.Builder
|
2016-05-07 17:24:05 +00:00
|
|
|
if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {
|
2023-11-23 17:24:33 +00:00
|
|
|
sb.WriteString("\n\nDid you mean this?\n")
|
2015-06-09 18:17:58 +00:00
|
|
|
for _, s := range suggestions {
|
2023-11-23 17:24:33 +00:00
|
|
|
_, _ = fmt.Fprintf(&sb, "\t%v\n", s)
|
2015-06-09 18:17:58 +00:00
|
|
|
}
|
|
|
|
}
|
2023-11-23 17:24:33 +00:00
|
|
|
return sb.String()
|
2015-06-09 18:17:58 +00:00
|
|
|
}
|
|
|
|
|
2017-10-07 21:29:11 +00:00
|
|
|
func (c *Command) findNext(next string) *Command {
|
|
|
|
matches := make([]*Command, 0)
|
|
|
|
for _, cmd := range c.commands {
|
2022-09-11 12:25:22 +00:00
|
|
|
if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) {
|
2018-02-04 16:58:53 +00:00
|
|
|
cmd.commandCalledAs.name = next
|
2017-10-07 21:29:11 +00:00
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) {
|
|
|
|
matches = append(matches, cmd)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(matches) == 1 {
|
2023-08-29 14:04:59 +00:00
|
|
|
// Temporarily disable gosec G602, which produces a false positive.
|
|
|
|
// See https://github.com/securego/gosec/issues/1005.
|
|
|
|
return matches[0] // #nosec G602
|
2017-10-07 21:29:11 +00:00
|
|
|
}
|
2018-02-04 16:58:53 +00:00
|
|
|
|
2017-10-07 21:29:11 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Traverse the command tree to find the command, and parse args for
|
|
|
|
// each parent.
|
|
|
|
func (c *Command) Traverse(args []string) (*Command, []string, error) {
|
|
|
|
flags := []string{}
|
|
|
|
inFlag := false
|
|
|
|
|
|
|
|
for i, arg := range args {
|
|
|
|
switch {
|
|
|
|
// A long flag with a space separated value
|
|
|
|
case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
|
|
|
|
// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
|
|
|
|
inFlag = !hasNoOptDefVal(arg[2:], c.Flags())
|
|
|
|
flags = append(flags, arg)
|
|
|
|
continue
|
|
|
|
// A short flag with a space separated value
|
|
|
|
case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()):
|
|
|
|
inFlag = true
|
|
|
|
flags = append(flags, arg)
|
|
|
|
continue
|
|
|
|
// The value for a flag
|
|
|
|
case inFlag:
|
|
|
|
inFlag = false
|
|
|
|
flags = append(flags, arg)
|
|
|
|
continue
|
|
|
|
// A flag without a value, or with an `=` separated value
|
|
|
|
case isFlagArg(arg):
|
|
|
|
flags = append(flags, arg)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd := c.findNext(arg)
|
|
|
|
if cmd == nil {
|
|
|
|
return c, args, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := c.ParseFlags(flags); err != nil {
|
|
|
|
return nil, args, err
|
|
|
|
}
|
|
|
|
return cmd.Traverse(args[i+1:])
|
|
|
|
}
|
|
|
|
return c, args, nil
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// SuggestionsFor provides suggestions for the typedName.
|
2015-09-25 15:04:28 +00:00
|
|
|
func (c *Command) SuggestionsFor(typedName string) []string {
|
2015-09-25 14:41:47 +00:00
|
|
|
suggestions := []string{}
|
|
|
|
for _, cmd := range c.commands {
|
|
|
|
if cmd.IsAvailableCommand() {
|
2015-09-25 15:04:28 +00:00
|
|
|
levenshteinDistance := ld(typedName, cmd.Name(), true)
|
|
|
|
suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
|
|
|
|
suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
|
|
|
|
if suggestByLevenshtein || suggestByPrefix {
|
2015-09-25 14:41:47 +00:00
|
|
|
suggestions = append(suggestions, cmd.Name())
|
|
|
|
}
|
2015-09-25 15:04:28 +00:00
|
|
|
for _, explicitSuggestion := range cmd.SuggestFor {
|
|
|
|
if strings.EqualFold(typedName, explicitSuggestion) {
|
|
|
|
suggestions = append(suggestions, cmd.Name())
|
|
|
|
}
|
|
|
|
}
|
2015-09-25 14:41:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return suggestions
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// VisitParents visits all parents of the command and invokes fn on each parent.
|
2015-11-08 01:21:25 +00:00
|
|
|
func (c *Command) VisitParents(fn func(*Command)) {
|
2017-04-05 16:44:50 +00:00
|
|
|
if c.HasParent() {
|
|
|
|
fn(c.Parent())
|
|
|
|
c.Parent().VisitParents(fn)
|
2015-11-08 01:21:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// Root finds root command.
|
2013-09-24 20:03:22 +00:00
|
|
|
func (c *Command) Root() *Command {
|
2017-04-05 16:44:50 +00:00
|
|
|
if c.HasParent() {
|
|
|
|
return c.Parent().Root()
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2017-04-05 16:44:50 +00:00
|
|
|
return c
|
2013-09-24 20:03:22 +00:00
|
|
|
}
|
|
|
|
|
2017-10-31 18:58:37 +00:00
|
|
|
// ArgsLenAtDash will return the length of c.Flags().Args at the moment
|
|
|
|
// when a -- was found during args parsing.
|
2015-09-16 16:31:41 +00:00
|
|
|
func (c *Command) ArgsLenAtDash() int {
|
|
|
|
return c.Flags().ArgsLenAtDash()
|
|
|
|
}
|
|
|
|
|
2013-10-01 01:54:46 +00:00
|
|
|
func (c *Command) execute(a []string) (err error) {
|
2013-09-24 16:47:29 +00:00
|
|
|
if c == nil {
|
2024-05-19 02:12:02 +00:00
|
|
|
return fmt.Errorf("called Execute() on a nil Command")
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2015-04-07 21:38:22 +00:00
|
|
|
if len(c.Deprecated) > 0 {
|
|
|
|
c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
|
|
|
|
}
|
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// initialize help and version flag at the last point possible to allow for user
|
2015-09-01 04:16:41 +00:00
|
|
|
// overriding
|
2017-04-27 08:55:15 +00:00
|
|
|
c.InitDefaultHelpFlag()
|
2017-12-01 21:37:16 +00:00
|
|
|
c.InitDefaultVersionFlag()
|
2015-09-01 04:16:41 +00:00
|
|
|
|
2013-10-01 01:54:46 +00:00
|
|
|
err = c.ParseFlags(a)
|
|
|
|
if err != nil {
|
2016-05-25 21:27:02 +00:00
|
|
|
return c.FlagErrorFunc()(c, err)
|
2015-04-06 18:54:26 +00:00
|
|
|
}
|
2017-04-27 08:55:15 +00:00
|
|
|
|
|
|
|
// If help is called, regardless of other flags, return we want help.
|
2015-09-02 17:59:31 +00:00
|
|
|
// Also say we need help if the command isn't runnable.
|
2015-09-01 04:16:41 +00:00
|
|
|
helpVal, err := c.Flags().GetBool("help")
|
|
|
|
if err != nil {
|
|
|
|
// should be impossible to get here as we always declare a help
|
2017-04-27 08:55:15 +00:00
|
|
|
// flag in InitDefaultHelpFlag()
|
2015-09-01 04:16:41 +00:00
|
|
|
c.Println("\"help\" flag declared as non-bool. Please correct your code")
|
|
|
|
return err
|
|
|
|
}
|
2016-07-06 15:51:57 +00:00
|
|
|
|
2017-12-07 07:49:35 +00:00
|
|
|
if helpVal {
|
2015-06-09 22:26:25 +00:00
|
|
|
return flag.ErrHelp
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2015-04-06 18:54:26 +00:00
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// for back-compat, only add version flag behavior if version is defined
|
|
|
|
if c.Version != "" {
|
|
|
|
versionVal, err := c.Flags().GetBool("version")
|
|
|
|
if err != nil {
|
|
|
|
c.Println("\"version\" flag declared as non-bool. Please correct your code")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if versionVal {
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
fn := defaultVersionFunc
|
|
|
|
if c.versionTemplate != nil {
|
|
|
|
fn = c.versionTemplate.fn
|
|
|
|
}
|
|
|
|
err := fn(c.OutOrStdout(), c)
|
2017-12-01 21:37:16 +00:00
|
|
|
if err != nil {
|
|
|
|
c.Println(err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-07 07:49:35 +00:00
|
|
|
if !c.Runnable() {
|
2020-03-27 20:38:32 +00:00
|
|
|
return flag.ErrHelp
|
2017-12-07 07:49:35 +00:00
|
|
|
}
|
|
|
|
|
2015-04-06 18:54:26 +00:00
|
|
|
c.preRun()
|
2016-06-04 00:25:52 +00:00
|
|
|
|
2022-10-03 14:52:50 +00:00
|
|
|
defer c.postRun()
|
|
|
|
|
2015-04-06 18:54:26 +00:00
|
|
|
argWoFlags := c.Flags().Args()
|
2016-06-04 00:25:52 +00:00
|
|
|
if c.DisableFlagParsing {
|
|
|
|
argWoFlags = a
|
|
|
|
}
|
2015-02-09 22:44:14 +00:00
|
|
|
|
2016-05-07 17:24:05 +00:00
|
|
|
if err := c.ValidateArgs(argWoFlags); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-10-22 00:36:12 +00:00
|
|
|
parents := make([]*Command, 0, 5)
|
2015-05-04 01:36:05 +00:00
|
|
|
for p := c; p != nil; p = p.Parent() {
|
2023-10-22 00:36:12 +00:00
|
|
|
if EnableTraverseRunHooks {
|
|
|
|
// When EnableTraverseRunHooks is set:
|
|
|
|
// - Execute all persistent pre-runs from the root parent till this command.
|
|
|
|
// - Execute all persistent post-runs from this command till the root parent.
|
|
|
|
parents = append([]*Command{p}, parents...)
|
|
|
|
} else {
|
|
|
|
// Otherwise, execute only the first found persistent hook.
|
|
|
|
parents = append(parents, p)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, p := range parents {
|
2015-08-31 01:03:16 +00:00
|
|
|
if p.PersistentPreRunE != nil {
|
2015-09-30 07:09:17 +00:00
|
|
|
if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
|
2015-08-31 01:03:16 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-10-22 00:36:12 +00:00
|
|
|
if !EnableTraverseRunHooks {
|
|
|
|
break
|
|
|
|
}
|
2015-08-31 01:03:16 +00:00
|
|
|
} else if p.PersistentPreRun != nil {
|
2015-05-04 01:36:05 +00:00
|
|
|
p.PersistentPreRun(c, argWoFlags)
|
2023-10-22 00:36:12 +00:00
|
|
|
if !EnableTraverseRunHooks {
|
|
|
|
break
|
|
|
|
}
|
2015-05-04 01:36:05 +00:00
|
|
|
}
|
2015-02-17 21:09:49 +00:00
|
|
|
}
|
2015-08-31 01:03:16 +00:00
|
|
|
if c.PreRunE != nil {
|
|
|
|
if err := c.PreRunE(c, argWoFlags); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if c.PreRun != nil {
|
2015-02-09 22:44:14 +00:00
|
|
|
c.PreRun(c, argWoFlags)
|
|
|
|
}
|
|
|
|
|
2022-09-27 10:27:48 +00:00
|
|
|
if err := c.ValidateRequiredFlags(); err != nil {
|
2017-10-10 03:44:33 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-09-27 10:27:48 +00:00
|
|
|
if err := c.ValidateFlagGroups(); err != nil {
|
2022-04-17 21:04:57 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-08-31 01:03:16 +00:00
|
|
|
if c.RunE != nil {
|
|
|
|
if err := c.RunE(c, argWoFlags); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
c.Run(c, argWoFlags)
|
|
|
|
}
|
|
|
|
if c.PostRunE != nil {
|
|
|
|
if err := c.PostRunE(c, argWoFlags); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if c.PostRun != nil {
|
2015-02-09 22:44:14 +00:00
|
|
|
c.PostRun(c, argWoFlags)
|
|
|
|
}
|
2015-05-04 01:36:05 +00:00
|
|
|
for p := c; p != nil; p = p.Parent() {
|
2015-08-31 01:03:16 +00:00
|
|
|
if p.PersistentPostRunE != nil {
|
|
|
|
if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-10-22 00:36:12 +00:00
|
|
|
if !EnableTraverseRunHooks {
|
|
|
|
break
|
|
|
|
}
|
2015-08-31 01:03:16 +00:00
|
|
|
} else if p.PersistentPostRun != nil {
|
2015-05-04 01:36:05 +00:00
|
|
|
p.PersistentPostRun(c, argWoFlags)
|
2023-10-22 00:36:12 +00:00
|
|
|
if !EnableTraverseRunHooks {
|
|
|
|
break
|
|
|
|
}
|
2015-05-04 01:36:05 +00:00
|
|
|
}
|
2015-02-17 21:09:49 +00:00
|
|
|
}
|
2015-02-09 22:44:14 +00:00
|
|
|
|
2015-04-06 18:54:26 +00:00
|
|
|
return nil
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2014-06-27 16:27:46 +00:00
|
|
|
func (c *Command) preRun() {
|
2014-07-11 14:57:53 +00:00
|
|
|
for _, x := range initializers {
|
|
|
|
x()
|
|
|
|
}
|
2014-06-27 16:27:46 +00:00
|
|
|
}
|
|
|
|
|
2022-10-03 14:52:50 +00:00
|
|
|
func (c *Command) postRun() {
|
|
|
|
for _, x := range finalizers {
|
|
|
|
x()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-20 06:29:50 +00:00
|
|
|
// ExecuteContext is the same as Execute(), but sets the ctx on the command.
|
2021-05-03 16:33:57 +00:00
|
|
|
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
|
|
|
|
// functions.
|
2020-02-20 06:29:50 +00:00
|
|
|
func (c *Command) ExecuteContext(ctx context.Context) error {
|
|
|
|
c.ctx = ctx
|
|
|
|
return c.Execute()
|
|
|
|
}
|
|
|
|
|
2017-05-28 10:56:30 +00:00
|
|
|
// Execute uses the args (os.Args[1:] by default)
|
2013-11-01 22:36:24 +00:00
|
|
|
// and run through the command tree finding appropriate matches
|
|
|
|
// for commands and then corresponding flags.
|
2015-11-17 18:41:21 +00:00
|
|
|
func (c *Command) Execute() error {
|
|
|
|
_, err := c.ExecuteC()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-03 16:33:57 +00:00
|
|
|
// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command.
|
|
|
|
// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs
|
|
|
|
// functions.
|
|
|
|
func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) {
|
|
|
|
c.ctx = ctx
|
|
|
|
return c.ExecuteC()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// ExecuteC executes the command.
|
2015-11-17 18:41:21 +00:00
|
|
|
func (c *Command) ExecuteC() (cmd *Command, err error) {
|
2020-02-20 06:29:50 +00:00
|
|
|
if c.ctx == nil {
|
|
|
|
c.ctx = context.Background()
|
|
|
|
}
|
|
|
|
|
2013-11-01 22:36:24 +00:00
|
|
|
// Regardless of what command execute is called on, run on Root only
|
|
|
|
if c.HasParent() {
|
2015-11-17 18:41:21 +00:00
|
|
|
return c.Root().ExecuteC()
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
2015-11-23 23:19:32 +00:00
|
|
|
// windows hook
|
|
|
|
if preExecHookFn != nil {
|
|
|
|
preExecHookFn(c)
|
2015-04-01 19:14:40 +00:00
|
|
|
}
|
|
|
|
|
2021-02-15 17:47:01 +00:00
|
|
|
// initialize help at the last point to allow for user overriding
|
2017-05-20 17:23:33 +00:00
|
|
|
c.InitDefaultHelpCmd()
|
2021-02-15 17:47:01 +00:00
|
|
|
// initialize completion at the last point to allow for user overriding
|
2022-10-10 23:06:30 +00:00
|
|
|
c.InitDefaultCompletionCmd()
|
2013-11-01 22:36:24 +00:00
|
|
|
|
2022-10-24 15:11:57 +00:00
|
|
|
// Now that all commands have been created, let's make sure all groups
|
|
|
|
// are properly created also
|
|
|
|
c.checkCommandGroups()
|
|
|
|
|
2019-03-20 21:21:26 +00:00
|
|
|
args := c.args
|
2013-11-01 22:36:24 +00:00
|
|
|
|
2015-11-08 06:21:50 +00:00
|
|
|
// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
|
2016-01-14 04:55:11 +00:00
|
|
|
if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
|
2013-11-01 22:36:24 +00:00
|
|
|
args = os.Args[1:]
|
|
|
|
}
|
|
|
|
|
2021-06-30 21:24:58 +00:00
|
|
|
// initialize the hidden command to be used for shell completion
|
2020-04-03 19:43:43 +00:00
|
|
|
c.initCompleteCmd(args)
|
|
|
|
|
2017-10-07 21:29:11 +00:00
|
|
|
var flags []string
|
|
|
|
if c.TraverseChildren {
|
|
|
|
cmd, flags, err = c.Traverse(args)
|
|
|
|
} else {
|
|
|
|
cmd, flags, err = c.Find(args)
|
|
|
|
}
|
2015-06-09 22:26:25 +00:00
|
|
|
if err != nil {
|
2015-06-29 21:05:49 +00:00
|
|
|
// If found parse to a subcommand and then failed, talk about the subcommand
|
|
|
|
if cmd != nil {
|
|
|
|
c = cmd
|
|
|
|
}
|
2015-10-26 01:58:53 +00:00
|
|
|
if !c.SilenceErrors {
|
2023-09-08 17:29:06 +00:00
|
|
|
c.PrintErrln(c.ErrPrefix(), err.Error())
|
2020-10-01 15:28:00 +00:00
|
|
|
c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath())
|
2015-10-26 01:58:53 +00:00
|
|
|
}
|
2015-11-17 18:41:21 +00:00
|
|
|
return c, err
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
2017-10-07 21:29:11 +00:00
|
|
|
|
2018-02-04 16:58:53 +00:00
|
|
|
cmd.commandCalledAs.called = true
|
|
|
|
if cmd.commandCalledAs.name == "" {
|
|
|
|
cmd.commandCalledAs.name = cmd.Name()
|
|
|
|
}
|
|
|
|
|
2020-02-20 06:29:50 +00:00
|
|
|
// We have to pass global context to children command
|
|
|
|
// if context is present on the parent command.
|
|
|
|
if cmd.ctx == nil {
|
|
|
|
cmd.ctx = c.ctx
|
|
|
|
}
|
|
|
|
|
2015-06-09 22:26:25 +00:00
|
|
|
err = cmd.execute(flags)
|
2013-11-01 22:36:24 +00:00
|
|
|
if err != nil {
|
2015-12-03 13:58:31 +00:00
|
|
|
// Always show help if requested, even if SilenceErrors is in
|
|
|
|
// effect
|
2022-06-21 02:02:33 +00:00
|
|
|
if errors.Is(err, flag.ErrHelp) {
|
2015-12-03 13:58:31 +00:00
|
|
|
cmd.HelpFunc()(cmd, args)
|
|
|
|
return cmd, nil
|
|
|
|
}
|
|
|
|
|
2020-12-04 19:34:11 +00:00
|
|
|
// If root command has SilenceErrors flagged,
|
2015-10-26 23:42:06 +00:00
|
|
|
// all subcommands should respect it
|
2015-10-26 03:17:39 +00:00
|
|
|
if !cmd.SilenceErrors && !c.SilenceErrors {
|
2023-09-08 17:29:06 +00:00
|
|
|
c.PrintErrln(cmd.ErrPrefix(), err.Error())
|
2015-06-09 22:26:25 +00:00
|
|
|
}
|
2015-10-31 13:22:19 +00:00
|
|
|
|
2020-12-04 19:34:11 +00:00
|
|
|
// If root command has SilenceUsage flagged,
|
2015-10-31 13:22:19 +00:00
|
|
|
// all subcommands should respect it
|
|
|
|
if !cmd.SilenceUsage && !c.SilenceUsage {
|
|
|
|
c.Println(cmd.UsageString())
|
|
|
|
}
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
2017-05-28 10:56:30 +00:00
|
|
|
return cmd, err
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
|
|
|
|
2016-05-07 17:24:05 +00:00
|
|
|
func (c *Command) ValidateArgs(args []string) error {
|
|
|
|
if c.Args == nil {
|
2022-06-21 02:00:50 +00:00
|
|
|
return ArbitraryArgs(c, args)
|
2016-05-07 17:24:05 +00:00
|
|
|
}
|
|
|
|
return c.Args(c, args)
|
|
|
|
}
|
|
|
|
|
2022-09-27 10:27:48 +00:00
|
|
|
// ValidateRequiredFlags validates all required flags are present and returns an error otherwise
|
|
|
|
func (c *Command) ValidateRequiredFlags() error {
|
2020-05-08 01:18:16 +00:00
|
|
|
if c.DisableFlagParsing {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-10-10 03:44:33 +00:00
|
|
|
flags := c.Flags()
|
|
|
|
missingFlagNames := []string{}
|
|
|
|
flags.VisitAll(func(pflag *flag.Flag) {
|
|
|
|
requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag]
|
|
|
|
if !found {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (requiredAnnotation[0] == "true") && !pflag.Changed {
|
|
|
|
missingFlagNames = append(missingFlagNames, pflag.Name)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
if len(missingFlagNames) > 0 {
|
2017-11-19 09:22:51 +00:00
|
|
|
return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`))
|
2017-10-10 03:44:33 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-10-24 15:11:57 +00:00
|
|
|
// checkCommandGroups checks if a command has been added to a group that does not exists.
|
|
|
|
// If so, we panic because it indicates a coding error that should be corrected.
|
|
|
|
func (c *Command) checkCommandGroups() {
|
|
|
|
for _, sub := range c.commands {
|
|
|
|
// if Group is not defined let the developer know right away
|
|
|
|
if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) {
|
|
|
|
panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath()))
|
|
|
|
}
|
|
|
|
|
|
|
|
sub.checkCommandGroups()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-27 08:55:15 +00:00
|
|
|
// InitDefaultHelpFlag adds default help flag to c.
|
|
|
|
// It is called automatically by executing the c or by calling help and usage.
|
2017-05-07 08:52:40 +00:00
|
|
|
// If c already has help flag, it will do nothing.
|
2017-04-27 08:55:15 +00:00
|
|
|
func (c *Command) InitDefaultHelpFlag() {
|
2016-05-31 22:38:12 +00:00
|
|
|
c.mergePersistentFlags()
|
2015-08-30 16:10:14 +00:00
|
|
|
if c.Flags().Lookup("help") == nil {
|
2017-04-20 20:16:25 +00:00
|
|
|
usage := "help for "
|
2024-10-12 16:08:27 +00:00
|
|
|
name := c.DisplayName()
|
2023-11-12 15:20:47 +00:00
|
|
|
if name == "" {
|
2017-04-20 20:16:25 +00:00
|
|
|
usage += "this command"
|
|
|
|
} else {
|
2023-11-12 15:20:47 +00:00
|
|
|
usage += name
|
2017-04-20 20:16:25 +00:00
|
|
|
}
|
|
|
|
c.Flags().BoolP("help", "h", false, usage)
|
2022-10-04 22:41:30 +00:00
|
|
|
_ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})
|
2015-08-30 16:10:14 +00:00
|
|
|
}
|
2015-09-01 04:16:41 +00:00
|
|
|
}
|
|
|
|
|
2017-12-01 21:37:16 +00:00
|
|
|
// InitDefaultVersionFlag adds default version flag to c.
|
|
|
|
// It is called automatically by executing the c.
|
|
|
|
// If c already has a version flag, it will do nothing.
|
|
|
|
// If c.Version is empty, it will do nothing.
|
|
|
|
func (c *Command) InitDefaultVersionFlag() {
|
|
|
|
if c.Version == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c.mergePersistentFlags()
|
|
|
|
if c.Flags().Lookup("version") == nil {
|
|
|
|
usage := "version for "
|
|
|
|
if c.Name() == "" {
|
|
|
|
usage += "this command"
|
|
|
|
} else {
|
2024-10-12 16:08:27 +00:00
|
|
|
usage += c.DisplayName()
|
2017-12-01 21:37:16 +00:00
|
|
|
}
|
2020-02-28 18:13:40 +00:00
|
|
|
if c.Flags().ShorthandLookup("v") == nil {
|
|
|
|
c.Flags().BoolP("version", "v", false, usage)
|
|
|
|
} else {
|
|
|
|
c.Flags().Bool("version", false, usage)
|
|
|
|
}
|
2022-10-04 22:41:30 +00:00
|
|
|
_ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})
|
2017-12-01 21:37:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-20 17:23:33 +00:00
|
|
|
// InitDefaultHelpCmd adds default help command to c.
|
|
|
|
// It is called automatically by executing the c or by calling help and usage.
|
|
|
|
// If c already has help command or c has no subcommands, it will do nothing.
|
|
|
|
func (c *Command) InitDefaultHelpCmd() {
|
2017-06-29 10:52:34 +00:00
|
|
|
if !c.HasSubCommands() {
|
2017-05-20 17:23:33 +00:00
|
|
|
return
|
|
|
|
}
|
2014-11-12 04:32:54 +00:00
|
|
|
|
2017-06-29 10:52:34 +00:00
|
|
|
if c.helpCommand == nil {
|
|
|
|
c.helpCommand = &Command{
|
|
|
|
Use: "help [command]",
|
|
|
|
Short: "Help about any command",
|
|
|
|
Long: `Help provides help for any command in the application.
|
2024-10-12 16:08:27 +00:00
|
|
|
Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
|
2020-06-16 20:49:26 +00:00
|
|
|
ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
|
|
|
|
var completions []string
|
|
|
|
cmd, _, e := c.Root().Find(args)
|
|
|
|
if e != nil {
|
|
|
|
return nil, ShellCompDirectiveNoFileComp
|
|
|
|
}
|
|
|
|
if cmd == nil {
|
|
|
|
// Root help command.
|
|
|
|
cmd = c.Root()
|
|
|
|
}
|
|
|
|
for _, subCmd := range cmd.Commands() {
|
|
|
|
if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand {
|
|
|
|
if strings.HasPrefix(subCmd.Name(), toComplete) {
|
|
|
|
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return completions, ShellCompDirectiveNoFileComp
|
|
|
|
},
|
2017-06-29 10:52:34 +00:00
|
|
|
Run: func(c *Command, args []string) {
|
|
|
|
cmd, _, e := c.Root().Find(args)
|
|
|
|
if cmd == nil || e != nil {
|
|
|
|
c.Printf("Unknown help topic %#q\n", args)
|
2021-02-08 00:08:50 +00:00
|
|
|
CheckErr(c.Root().Usage())
|
2017-06-29 10:52:34 +00:00
|
|
|
} else {
|
2022-09-30 18:26:05 +00:00
|
|
|
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
|
|
|
|
cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
|
2021-02-08 00:08:50 +00:00
|
|
|
CheckErr(cmd.Help())
|
2017-06-29 10:52:34 +00:00
|
|
|
}
|
|
|
|
},
|
2022-10-10 20:59:11 +00:00
|
|
|
GroupID: c.helpCommandGroupID,
|
2017-06-29 10:52:34 +00:00
|
|
|
}
|
2013-11-01 22:36:24 +00:00
|
|
|
}
|
2017-03-14 17:12:53 +00:00
|
|
|
c.RemoveCommand(c.helpCommand)
|
2013-11-01 22:36:24 +00:00
|
|
|
c.AddCommand(c.helpCommand)
|
|
|
|
}
|
|
|
|
|
2017-11-02 13:27:24 +00:00
|
|
|
// ResetCommands delete parent, subcommand and help command from c.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) ResetCommands() {
|
2017-10-02 10:00:25 +00:00
|
|
|
c.parent = nil
|
2013-09-24 16:47:29 +00:00
|
|
|
c.commands = nil
|
2014-11-12 04:32:54 +00:00
|
|
|
c.helpCommand = nil
|
2017-04-06 13:28:17 +00:00
|
|
|
c.parentsPflags = nil
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Sorts commands by their names.
|
2016-06-14 14:04:53 +00:00
|
|
|
type commandSorterByName []*Command
|
|
|
|
|
|
|
|
func (c commandSorterByName) Len() int { return len(c) }
|
|
|
|
func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
|
|
|
|
func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
|
|
|
|
|
|
|
|
// Commands returns a sorted slice of child commands.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Commands() []*Command {
|
2016-06-14 14:04:53 +00:00
|
|
|
// do not sort commands if it already sorted or sorting was disabled
|
2016-07-06 15:51:57 +00:00
|
|
|
if EnableCommandSorting && !c.commandsAreSorted {
|
2016-06-14 14:04:53 +00:00
|
|
|
sort.Sort(commandSorterByName(c.commands))
|
|
|
|
c.commandsAreSorted = true
|
|
|
|
}
|
2013-09-24 16:47:29 +00:00
|
|
|
return c.commands
|
|
|
|
}
|
|
|
|
|
2014-12-13 05:05:43 +00:00
|
|
|
// AddCommand adds one or more commands to this parent command.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) AddCommand(cmds ...*Command) {
|
|
|
|
for i, x := range cmds {
|
|
|
|
if cmds[i] == c {
|
|
|
|
panic("Command can't be a child of itself")
|
|
|
|
}
|
|
|
|
cmds[i].parent = c
|
2014-01-17 12:36:57 +00:00
|
|
|
// update max lengths
|
|
|
|
usageLen := len(x.Use)
|
|
|
|
if usageLen > c.commandsMaxUseLen {
|
|
|
|
c.commandsMaxUseLen = usageLen
|
|
|
|
}
|
|
|
|
commandPathLen := len(x.CommandPath())
|
|
|
|
if commandPathLen > c.commandsMaxCommandPathLen {
|
|
|
|
c.commandsMaxCommandPathLen = commandPathLen
|
|
|
|
}
|
2015-02-11 09:20:29 +00:00
|
|
|
nameLen := len(x.Name())
|
|
|
|
if nameLen > c.commandsMaxNameLen {
|
|
|
|
c.commandsMaxNameLen = nameLen
|
|
|
|
}
|
2015-12-16 08:14:10 +00:00
|
|
|
// If global normalization function exists, update all children
|
2015-05-14 17:38:15 +00:00
|
|
|
if c.globNormFunc != nil {
|
|
|
|
x.SetGlobalNormalizationFunc(c.globNormFunc)
|
|
|
|
}
|
2013-09-24 16:47:29 +00:00
|
|
|
c.commands = append(c.commands, x)
|
2016-06-14 14:04:53 +00:00
|
|
|
c.commandsAreSorted = false
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-10 20:59:11 +00:00
|
|
|
// Groups returns a slice of child command groups.
|
|
|
|
func (c *Command) Groups() []*Group {
|
|
|
|
return c.commandgroups
|
|
|
|
}
|
|
|
|
|
|
|
|
// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group
|
|
|
|
func (c *Command) AllChildCommandsHaveGroup() bool {
|
|
|
|
for _, sub := range c.commands {
|
|
|
|
if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-12-25 20:08:39 +00:00
|
|
|
// ContainsGroup return if groupID exists in the list of command groups.
|
2022-10-10 20:59:11 +00:00
|
|
|
func (c *Command) ContainsGroup(groupID string) bool {
|
|
|
|
for _, x := range c.commandgroups {
|
|
|
|
if x.ID == groupID {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddGroup adds one or more command groups to this parent command.
|
|
|
|
func (c *Command) AddGroup(groups ...*Group) {
|
|
|
|
c.commandgroups = append(c.commandgroups, groups...)
|
|
|
|
}
|
|
|
|
|
2016-05-17 17:17:01 +00:00
|
|
|
// RemoveCommand removes one or more commands from a parent command.
|
2015-03-03 06:50:53 +00:00
|
|
|
func (c *Command) RemoveCommand(cmds ...*Command) {
|
|
|
|
commands := []*Command{}
|
|
|
|
main:
|
|
|
|
for _, command := range c.commands {
|
|
|
|
for _, cmd := range cmds {
|
|
|
|
if command == cmd {
|
|
|
|
command.parent = nil
|
|
|
|
continue main
|
|
|
|
}
|
|
|
|
}
|
|
|
|
commands = append(commands, command)
|
|
|
|
}
|
|
|
|
c.commands = commands
|
|
|
|
// recompute all lengths
|
|
|
|
c.commandsMaxUseLen = 0
|
|
|
|
c.commandsMaxCommandPathLen = 0
|
|
|
|
c.commandsMaxNameLen = 0
|
|
|
|
for _, command := range c.commands {
|
|
|
|
usageLen := len(command.Use)
|
|
|
|
if usageLen > c.commandsMaxUseLen {
|
|
|
|
c.commandsMaxUseLen = usageLen
|
|
|
|
}
|
|
|
|
commandPathLen := len(command.CommandPath())
|
|
|
|
if commandPathLen > c.commandsMaxCommandPathLen {
|
|
|
|
c.commandsMaxCommandPathLen = commandPathLen
|
|
|
|
}
|
|
|
|
nameLen := len(command.Name())
|
|
|
|
if nameLen > c.commandsMaxNameLen {
|
|
|
|
c.commandsMaxNameLen = nameLen
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Print(i ...interface{}) {
|
2016-07-15 20:12:07 +00:00
|
|
|
fmt.Fprint(c.OutOrStderr(), i...)
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Println(i ...interface{}) {
|
2017-04-23 12:55:23 +00:00
|
|
|
c.Print(fmt.Sprintln(i...))
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Printf(format string, i ...interface{}) {
|
2017-04-23 12:55:23 +00:00
|
|
|
c.Print(fmt.Sprintf(format, i...))
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2019-02-11 15:06:55 +00:00
|
|
|
// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.
|
|
|
|
func (c *Command) PrintErr(i ...interface{}) {
|
|
|
|
fmt.Fprint(c.ErrOrStderr(), i...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.
|
|
|
|
func (c *Command) PrintErrln(i ...interface{}) {
|
2020-10-01 15:28:00 +00:00
|
|
|
c.PrintErr(fmt.Sprintln(i...))
|
2019-02-11 15:06:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.
|
|
|
|
func (c *Command) PrintErrf(format string, i ...interface{}) {
|
2020-10-01 15:28:00 +00:00
|
|
|
c.PrintErr(fmt.Sprintf(format, i...))
|
2019-02-11 15:06:55 +00:00
|
|
|
}
|
|
|
|
|
2014-12-13 05:05:43 +00:00
|
|
|
// CommandPath returns the full path to this command.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) CommandPath() string {
|
2017-04-23 12:55:23 +00:00
|
|
|
if c.HasParent() {
|
|
|
|
return c.Parent().CommandPath() + " " + c.Name()
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2024-10-12 16:08:27 +00:00
|
|
|
return c.DisplayName()
|
2023-11-12 15:20:47 +00:00
|
|
|
}
|
|
|
|
|
2024-10-12 16:08:27 +00:00
|
|
|
// DisplayName returns the name to display in help text. Returns command Name()
|
|
|
|
// If CommandDisplayNameAnnoation is not set
|
|
|
|
func (c *Command) DisplayName() string {
|
2023-11-02 12:15:26 +00:00
|
|
|
if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok {
|
|
|
|
return displayName
|
|
|
|
}
|
2017-04-23 12:55:23 +00:00
|
|
|
return c.Name()
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// UseLine puts out the full usage for a given command (including parents).
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) UseLine() string {
|
2017-04-23 12:55:23 +00:00
|
|
|
var useline string
|
2024-10-12 16:08:27 +00:00
|
|
|
use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1)
|
2013-09-24 16:47:29 +00:00
|
|
|
if c.HasParent() {
|
2023-11-12 18:07:59 +00:00
|
|
|
useline = c.parent.CommandPath() + " " + use
|
2017-04-23 12:55:23 +00:00
|
|
|
} else {
|
2023-11-12 18:07:59 +00:00
|
|
|
useline = use
|
2017-04-23 12:55:23 +00:00
|
|
|
}
|
2017-11-19 07:58:54 +00:00
|
|
|
if c.DisableFlagsInUseLine {
|
|
|
|
return useline
|
|
|
|
}
|
2017-04-23 12:55:23 +00:00
|
|
|
if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {
|
|
|
|
useline += " [flags]"
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2017-04-23 12:55:23 +00:00
|
|
|
return useline
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// DebugFlags used to determine which flags have been assigned to which commands
|
2016-08-30 17:14:27 +00:00
|
|
|
// and which persist.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) DebugFlags() {
|
|
|
|
c.Println("DebugFlags called on", c.Name())
|
|
|
|
var debugflags func(*Command)
|
|
|
|
|
|
|
|
debugflags = func(x *Command) {
|
|
|
|
if x.HasFlags() || x.HasPersistentFlags() {
|
|
|
|
c.Println(x.Name())
|
|
|
|
}
|
|
|
|
if x.HasFlags() {
|
|
|
|
x.flags.VisitAll(func(f *flag.Flag) {
|
2017-04-05 16:44:50 +00:00
|
|
|
if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil {
|
|
|
|
c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]")
|
2013-09-24 16:47:29 +00:00
|
|
|
} else {
|
|
|
|
c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if x.HasPersistentFlags() {
|
|
|
|
x.pflags.VisitAll(func(f *flag.Flag) {
|
|
|
|
if x.HasFlags() {
|
|
|
|
if x.flags.Lookup(f.Name) == nil {
|
|
|
|
c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2017-04-27 12:55:09 +00:00
|
|
|
c.Println(x.flagErrorBuf)
|
2013-09-24 16:47:29 +00:00
|
|
|
if x.HasSubCommands() {
|
|
|
|
for _, y := range x.commands {
|
|
|
|
debugflags(y)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
debugflags(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the command's name: the first word in the use line.
|
|
|
|
func (c *Command) Name() string {
|
2017-10-11 14:15:37 +00:00
|
|
|
name := c.Use
|
|
|
|
i := strings.Index(name, " ")
|
|
|
|
if i >= 0 {
|
|
|
|
name = name[:i]
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2017-10-11 14:15:37 +00:00
|
|
|
return name
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-03-31 13:53:34 +00:00
|
|
|
// HasAlias determines if a given string is an alias of the command.
|
2014-09-25 23:03:34 +00:00
|
|
|
func (c *Command) HasAlias(s string) bool {
|
|
|
|
for _, a := range c.Aliases {
|
2022-09-11 12:25:22 +00:00
|
|
|
if commandNameMatches(a, s) {
|
2014-09-25 23:03:34 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2018-02-04 16:58:53 +00:00
|
|
|
// CalledAs returns the command name or alias that was used to invoke
|
|
|
|
// this command or an empty string if the command has not been called.
|
|
|
|
func (c *Command) CalledAs() string {
|
|
|
|
if c.commandCalledAs.called {
|
|
|
|
return c.commandCalledAs.name
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2017-10-07 21:29:11 +00:00
|
|
|
// hasNameOrAliasPrefix returns true if the Name or any of aliases start
|
|
|
|
// with prefix
|
|
|
|
func (c *Command) hasNameOrAliasPrefix(prefix string) bool {
|
|
|
|
if strings.HasPrefix(c.Name(), prefix) {
|
2018-02-04 16:58:53 +00:00
|
|
|
c.commandCalledAs.name = c.Name()
|
2017-10-07 21:29:11 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
for _, alias := range c.Aliases {
|
|
|
|
if strings.HasPrefix(alias, prefix) {
|
2018-02-04 16:58:53 +00:00
|
|
|
c.commandCalledAs.name = alias
|
2017-10-07 21:29:11 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// NameAndAliases returns a list of the command name and all aliases
|
2014-09-25 23:03:34 +00:00
|
|
|
func (c *Command) NameAndAliases() string {
|
|
|
|
return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasExample determines if the command has example.
|
2015-02-12 23:12:07 +00:00
|
|
|
func (c *Command) HasExample() bool {
|
|
|
|
return len(c.Example) > 0
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Runnable determines if the command is itself runnable.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Runnable() bool {
|
2015-09-02 17:59:31 +00:00
|
|
|
return c.Run != nil || c.RunE != nil
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// HasSubCommands determines if the command has children commands.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) HasSubCommands() bool {
|
|
|
|
return len(c.commands) > 0
|
|
|
|
}
|
|
|
|
|
2015-09-04 20:34:51 +00:00
|
|
|
// IsAvailableCommand determines if a command is available as a non-help command
|
2016-08-30 17:14:27 +00:00
|
|
|
// (this includes all non deprecated/hidden commands).
|
2015-09-04 20:34:51 +00:00
|
|
|
func (c *Command) IsAvailableCommand() bool {
|
2015-09-09 02:43:49 +00:00
|
|
|
if len(c.Deprecated) != 0 || c.Hidden {
|
|
|
|
return false
|
|
|
|
}
|
2015-09-04 20:34:51 +00:00
|
|
|
|
2015-09-11 22:18:36 +00:00
|
|
|
if c.HasParent() && c.Parent().helpCommand == c {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-09-09 02:43:49 +00:00
|
|
|
if c.Runnable() || c.HasAvailableSubCommands() {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
2015-09-04 20:34:51 +00:00
|
|
|
}
|
|
|
|
|
2017-03-09 15:37:15 +00:00
|
|
|
// IsAdditionalHelpTopicCommand determines if a command is an additional
|
|
|
|
// help topic command; additional help topic command is determined by the
|
|
|
|
// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
|
|
|
|
// are runnable/hidden/deprecated.
|
|
|
|
// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
|
|
|
|
func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
2015-09-04 20:34:51 +00:00
|
|
|
// if a command is runnable, deprecated, or hidden it is not a 'help' command
|
|
|
|
if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
|
2015-03-20 18:47:56 +00:00
|
|
|
return false
|
|
|
|
}
|
2015-09-04 20:34:51 +00:00
|
|
|
|
|
|
|
// if any non-help sub commands are found, the command is not a 'help' command
|
2015-06-30 00:06:04 +00:00
|
|
|
for _, sub := range c.commands {
|
2017-03-09 15:37:15 +00:00
|
|
|
if !sub.IsAdditionalHelpTopicCommand() {
|
2015-06-30 00:06:04 +00:00
|
|
|
return false
|
2015-03-20 18:47:56 +00:00
|
|
|
}
|
|
|
|
}
|
2015-09-04 20:34:51 +00:00
|
|
|
|
|
|
|
// the command either has no sub commands, or no non-help sub commands
|
2015-06-30 00:06:04 +00:00
|
|
|
return true
|
2015-03-20 18:47:56 +00:00
|
|
|
}
|
|
|
|
|
2016-08-20 07:04:53 +00:00
|
|
|
// HasHelpSubCommands determines if a command has any available 'help' sub commands
|
2015-09-04 20:34:51 +00:00
|
|
|
// that need to be shown in the usage/help default template under 'additional help
|
2016-08-30 17:14:27 +00:00
|
|
|
// topics'.
|
2015-03-20 18:47:56 +00:00
|
|
|
func (c *Command) HasHelpSubCommands() bool {
|
2015-09-04 20:34:51 +00:00
|
|
|
// return true on the first found available 'help' sub command
|
2015-03-20 18:47:56 +00:00
|
|
|
for _, sub := range c.commands {
|
2017-03-09 15:37:15 +00:00
|
|
|
if sub.IsAdditionalHelpTopicCommand() {
|
2015-03-20 18:47:56 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2015-09-04 20:34:51 +00:00
|
|
|
|
|
|
|
// the command either has no sub commands, or no available 'help' sub commands
|
2015-03-20 18:47:56 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-09-04 20:34:51 +00:00
|
|
|
// HasAvailableSubCommands determines if a command has available sub commands that
|
2016-08-30 17:14:27 +00:00
|
|
|
// need to be shown in the usage/help default template under 'available commands'.
|
2015-09-04 20:34:51 +00:00
|
|
|
func (c *Command) HasAvailableSubCommands() bool {
|
|
|
|
// return true on the first found available (non deprecated/help/hidden)
|
|
|
|
// sub command
|
2015-03-20 18:47:56 +00:00
|
|
|
for _, sub := range c.commands {
|
2015-09-04 20:34:51 +00:00
|
|
|
if sub.IsAvailableCommand() {
|
2015-03-20 18:47:56 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2015-09-04 20:34:51 +00:00
|
|
|
|
2017-11-08 10:47:54 +00:00
|
|
|
// the command either has no sub commands, or no available (non deprecated/help/hidden)
|
2015-09-04 20:34:51 +00:00
|
|
|
// sub commands
|
2015-03-20 18:47:56 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// HasParent determines if the command is a child command.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) HasParent() bool {
|
|
|
|
return c.parent != nil
|
|
|
|
}
|
|
|
|
|
2018-02-02 06:04:56 +00:00
|
|
|
// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist.
|
2015-05-14 17:38:15 +00:00
|
|
|
func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
|
|
|
|
return c.globNormFunc
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// Flags returns the complete FlagSet that applies
|
2016-08-30 17:14:27 +00:00
|
|
|
// to this command (local and persistent declared here and by all parents).
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Flags() *flag.FlagSet {
|
|
|
|
if c.flags == nil {
|
2024-10-12 16:08:27 +00:00
|
|
|
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
if c.flagErrorBuf == nil {
|
|
|
|
c.flagErrorBuf = new(bytes.Buffer)
|
|
|
|
}
|
|
|
|
c.flags.SetOutput(c.flagErrorBuf)
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2017-04-05 16:44:50 +00:00
|
|
|
|
2013-09-24 16:47:29 +00:00
|
|
|
return c.flags
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
|
2024-01-06 21:49:13 +00:00
|
|
|
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
2016-06-03 16:37:40 +00:00
|
|
|
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
|
|
|
persistentFlags := c.PersistentFlags()
|
|
|
|
|
2024-10-12 16:08:27 +00:00
|
|
|
out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2016-06-03 16:37:40 +00:00
|
|
|
c.LocalFlags().VisitAll(func(f *flag.Flag) {
|
|
|
|
if persistentFlags.Lookup(f.Name) == nil {
|
|
|
|
out.AddFlag(f)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
return out
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// LocalFlags returns the local FlagSet specifically set in the current command.
|
2024-01-06 21:49:13 +00:00
|
|
|
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
2015-01-29 20:55:29 +00:00
|
|
|
func (c *Command) LocalFlags() *flag.FlagSet {
|
|
|
|
c.mergePersistentFlags()
|
|
|
|
|
2017-04-05 16:44:50 +00:00
|
|
|
if c.lflags == nil {
|
2024-10-12 16:08:27 +00:00
|
|
|
c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
if c.flagErrorBuf == nil {
|
|
|
|
c.flagErrorBuf = new(bytes.Buffer)
|
|
|
|
}
|
|
|
|
c.lflags.SetOutput(c.flagErrorBuf)
|
2017-04-05 16:44:50 +00:00
|
|
|
}
|
2017-04-19 09:17:48 +00:00
|
|
|
c.lflags.SortFlags = c.Flags().SortFlags
|
2017-10-02 10:00:25 +00:00
|
|
|
if c.globNormFunc != nil {
|
|
|
|
c.lflags.SetNormalizeFunc(c.globNormFunc)
|
|
|
|
}
|
2017-04-05 16:44:50 +00:00
|
|
|
|
|
|
|
addToLocal := func(f *flag.Flag) {
|
2022-08-28 16:46:39 +00:00
|
|
|
// Add the flag if it is not a parent PFlag, or it shadows a parent PFlag
|
|
|
|
if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) {
|
2017-04-05 16:44:50 +00:00
|
|
|
c.lflags.AddFlag(f)
|
|
|
|
}
|
2015-08-17 05:14:43 +00:00
|
|
|
}
|
2017-04-19 09:17:48 +00:00
|
|
|
c.Flags().VisitAll(addToLocal)
|
2017-04-05 16:44:50 +00:00
|
|
|
c.PersistentFlags().VisitAll(addToLocal)
|
|
|
|
return c.lflags
|
2015-01-29 20:55:29 +00:00
|
|
|
}
|
|
|
|
|
2019-03-20 21:21:26 +00:00
|
|
|
// InheritedFlags returns all flags which were inherited from parent commands.
|
2024-01-06 21:49:13 +00:00
|
|
|
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
2015-02-14 00:44:12 +00:00
|
|
|
func (c *Command) InheritedFlags() *flag.FlagSet {
|
|
|
|
c.mergePersistentFlags()
|
|
|
|
|
2017-04-05 16:44:50 +00:00
|
|
|
if c.iflags == nil {
|
2024-10-12 16:08:27 +00:00
|
|
|
c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
if c.flagErrorBuf == nil {
|
|
|
|
c.flagErrorBuf = new(bytes.Buffer)
|
|
|
|
}
|
|
|
|
c.iflags.SetOutput(c.flagErrorBuf)
|
2017-04-05 16:44:50 +00:00
|
|
|
}
|
2015-02-28 00:26:56 +00:00
|
|
|
|
2017-04-05 16:44:50 +00:00
|
|
|
local := c.LocalFlags()
|
2017-10-02 10:00:25 +00:00
|
|
|
if c.globNormFunc != nil {
|
|
|
|
c.iflags.SetNormalizeFunc(c.globNormFunc)
|
|
|
|
}
|
|
|
|
|
2017-04-05 16:44:50 +00:00
|
|
|
c.parentsPflags.VisitAll(func(f *flag.Flag) {
|
|
|
|
if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
|
|
|
|
c.iflags.AddFlag(f)
|
2015-02-28 00:26:56 +00:00
|
|
|
}
|
2017-04-05 16:44:50 +00:00
|
|
|
})
|
|
|
|
return c.iflags
|
2015-02-14 00:44:12 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// NonInheritedFlags returns all flags which were not inherited from parent commands.
|
2024-01-06 21:49:13 +00:00
|
|
|
// This function does not modify the flags of the current command, it's purpose is to return the current state.
|
2015-02-14 00:45:00 +00:00
|
|
|
func (c *Command) NonInheritedFlags() *flag.FlagSet {
|
2015-02-28 00:26:56 +00:00
|
|
|
return c.LocalFlags()
|
2015-02-14 00:45:00 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) PersistentFlags() *flag.FlagSet {
|
|
|
|
if c.pflags == nil {
|
2024-10-12 16:08:27 +00:00
|
|
|
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
if c.flagErrorBuf == nil {
|
|
|
|
c.flagErrorBuf = new(bytes.Buffer)
|
|
|
|
}
|
|
|
|
c.pflags.SetOutput(c.flagErrorBuf)
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
return c.pflags
|
|
|
|
}
|
|
|
|
|
2017-11-02 13:27:24 +00:00
|
|
|
// ResetFlags deletes all flags from command.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) ResetFlags() {
|
2017-04-27 12:55:09 +00:00
|
|
|
c.flagErrorBuf = new(bytes.Buffer)
|
|
|
|
c.flagErrorBuf.Reset()
|
2024-10-12 16:08:27 +00:00
|
|
|
c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
c.flags.SetOutput(c.flagErrorBuf)
|
2024-10-12 16:08:27 +00:00
|
|
|
c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
c.pflags.SetOutput(c.flagErrorBuf)
|
2017-10-02 10:00:25 +00:00
|
|
|
|
|
|
|
c.lflags = nil
|
|
|
|
c.iflags = nil
|
|
|
|
c.parentsPflags = nil
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) HasFlags() bool {
|
|
|
|
return c.Flags().HasFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasPersistentFlags checks if the command contains persistent flags.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) HasPersistentFlags() bool {
|
|
|
|
return c.PersistentFlags().HasFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasLocalFlags checks if the command has flags specifically declared locally.
|
2015-01-29 20:55:29 +00:00
|
|
|
func (c *Command) HasLocalFlags() bool {
|
|
|
|
return c.LocalFlags().HasFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasInheritedFlags checks if the command has flags inherited from its parent command.
|
2015-02-28 00:26:56 +00:00
|
|
|
func (c *Command) HasInheritedFlags() bool {
|
|
|
|
return c.InheritedFlags().HasFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
|
2016-08-30 17:14:27 +00:00
|
|
|
// structure) which are not hidden or deprecated.
|
2016-04-13 18:27:05 +00:00
|
|
|
func (c *Command) HasAvailableFlags() bool {
|
|
|
|
return c.Flags().HasAvailableFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
|
2016-04-13 18:27:05 +00:00
|
|
|
func (c *Command) HasAvailablePersistentFlags() bool {
|
|
|
|
return c.PersistentFlags().HasAvailableFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
|
2016-08-30 17:14:27 +00:00
|
|
|
// or deprecated.
|
2016-04-13 18:27:05 +00:00
|
|
|
func (c *Command) HasAvailableLocalFlags() bool {
|
|
|
|
return c.LocalFlags().HasAvailableFlags()
|
|
|
|
}
|
|
|
|
|
2017-01-24 16:30:45 +00:00
|
|
|
// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
|
2016-08-30 17:14:27 +00:00
|
|
|
// not hidden or deprecated.
|
2016-04-13 18:27:05 +00:00
|
|
|
func (c *Command) HasAvailableInheritedFlags() bool {
|
|
|
|
return c.InheritedFlags().HasAvailableFlags()
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Flag climbs up the command tree looking for matching flag.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) Flag(name string) (flag *flag.Flag) {
|
|
|
|
flag = c.Flags().Lookup(name)
|
|
|
|
|
|
|
|
if flag == nil {
|
|
|
|
flag = c.persistentFlag(name)
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Recursively find matching persistent flag.
|
2013-09-24 16:47:29 +00:00
|
|
|
func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
|
|
|
if c.HasPersistentFlags() {
|
|
|
|
flag = c.PersistentFlags().Lookup(name)
|
|
|
|
}
|
|
|
|
|
2017-04-19 09:17:48 +00:00
|
|
|
if flag == nil {
|
|
|
|
c.updateParentsPflags()
|
|
|
|
flag = c.parentsPflags.Lookup(name)
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// ParseFlags parses persistent flag tree and local flags.
|
2017-06-13 08:33:50 +00:00
|
|
|
func (c *Command) ParseFlags(args []string) error {
|
2016-06-04 00:25:52 +00:00
|
|
|
if c.DisableFlagParsing {
|
|
|
|
return nil
|
|
|
|
}
|
2017-06-13 08:33:50 +00:00
|
|
|
|
2017-10-12 18:25:33 +00:00
|
|
|
if c.flagErrorBuf == nil {
|
|
|
|
c.flagErrorBuf = new(bytes.Buffer)
|
|
|
|
}
|
2017-06-13 08:33:50 +00:00
|
|
|
beforeErrorBufLen := c.flagErrorBuf.Len()
|
2013-09-24 16:47:29 +00:00
|
|
|
c.mergePersistentFlags()
|
2018-03-31 12:36:20 +00:00
|
|
|
|
2020-02-20 06:29:50 +00:00
|
|
|
// do it here after merging all flags and just before parse
|
2018-03-31 12:36:20 +00:00
|
|
|
c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist)
|
|
|
|
|
2017-06-13 08:33:50 +00:00
|
|
|
err := c.Flags().Parse(args)
|
|
|
|
// Print warnings if they occurred (e.g. deprecated flag messages).
|
|
|
|
if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil {
|
|
|
|
c.Print(c.flagErrorBuf.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
|
|
|
|
2016-08-30 17:14:27 +00:00
|
|
|
// Parent returns a commands parent command.
|
2015-01-29 20:55:29 +00:00
|
|
|
func (c *Command) Parent() *Command {
|
|
|
|
return c.parent
|
|
|
|
}
|
|
|
|
|
2017-04-06 13:28:17 +00:00
|
|
|
// mergePersistentFlags merges c.PersistentFlags() to c.Flags()
|
|
|
|
// and adds missing persistent flags of all parents.
|
|
|
|
func (c *Command) mergePersistentFlags() {
|
2017-04-19 09:17:48 +00:00
|
|
|
c.updateParentsPflags()
|
2017-05-12 18:22:26 +00:00
|
|
|
c.Flags().AddFlagSet(c.PersistentFlags())
|
2017-04-19 09:17:48 +00:00
|
|
|
c.Flags().AddFlagSet(c.parentsPflags)
|
2017-04-06 13:28:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// updateParentsPflags updates c.parentsPflags by adding
|
2017-04-19 09:17:48 +00:00
|
|
|
// new persistent flags of all parents.
|
2017-04-06 13:28:17 +00:00
|
|
|
// If c.parentsPflags == nil, it makes new.
|
2017-04-19 09:17:48 +00:00
|
|
|
func (c *Command) updateParentsPflags() {
|
2017-04-05 16:44:50 +00:00
|
|
|
if c.parentsPflags == nil {
|
2024-10-12 16:08:27 +00:00
|
|
|
c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError)
|
2017-04-27 12:55:09 +00:00
|
|
|
c.parentsPflags.SetOutput(c.flagErrorBuf)
|
2017-04-06 13:28:17 +00:00
|
|
|
c.parentsPflags.SortFlags = false
|
2017-04-05 16:44:50 +00:00
|
|
|
}
|
2013-09-24 16:47:29 +00:00
|
|
|
|
2017-10-02 10:00:25 +00:00
|
|
|
if c.globNormFunc != nil {
|
|
|
|
c.parentsPflags.SetNormalizeFunc(c.globNormFunc)
|
|
|
|
}
|
|
|
|
|
2017-04-19 08:49:22 +00:00
|
|
|
c.Root().PersistentFlags().AddFlagSet(flag.CommandLine)
|
|
|
|
|
2017-04-19 09:17:48 +00:00
|
|
|
c.VisitParents(func(parent *Command) {
|
|
|
|
c.parentsPflags.AddFlagSet(parent.PersistentFlags())
|
2017-04-05 16:44:50 +00:00
|
|
|
})
|
2013-09-24 16:47:29 +00:00
|
|
|
}
|
2022-09-11 12:25:22 +00:00
|
|
|
|
|
|
|
// commandNameMatches checks if two command names are equal
|
|
|
|
// taking into account case sensitivity according to
|
|
|
|
// EnableCaseInsensitive global configuration.
|
|
|
|
func commandNameMatches(s string, t string) bool {
|
|
|
|
if EnableCaseInsensitive {
|
|
|
|
return strings.EqualFold(s, t)
|
|
|
|
}
|
|
|
|
|
|
|
|
return s == t
|
|
|
|
}
|
Restructure code to let linker perform deadcode elimination step
Cobra, in its default configuration, will execute a template to generate
help, usage and version outputs. Text/template execution calls MethodByName
and MethodByName disables dead code elimination in the Go linker, therefore
all programs that make use of cobra will be linked with dead code
elimination disabled, even if they end up replacing the default usage, help
and version formatters with a custom function and no actual text/template
evaluations are ever made at runtime.
Dead code elimination in the linker helps reduce disk space and memory
utilization of programs. For example, for the simple example program used by
TestDeadcodeElimination 40% of the final executable size is dead code. For a
more realistic example, 12% of the size of Delve's executable is deadcode.
This PR changes Cobra so that, in its default configuration, it does not
automatically inhibit deadcode elimination by:
1. changing Cobra's default behavior to emit output for usage and help using
simple Go functions instead of template execution
2. quarantining all calls to template execution into SetUsageTemplate,
SetHelpTemplate and SetVersionTemplate so that the linker can statically
determine if they are reachable
2023-05-05 20:14:12 +00:00
|
|
|
|
|
|
|
// tmplFunc holds a template and a function that will execute said template.
|
|
|
|
type tmplFunc struct {
|
|
|
|
tmpl string
|
|
|
|
fn func(io.Writer, interface{}) error
|
|
|
|
}
|
|
|
|
|
|
|
|
var defaultUsageTemplate = `Usage:{{if .Runnable}}
|
|
|
|
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
|
|
|
|
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
|
|
|
|
|
|
|
|
Aliases:
|
|
|
|
{{.NameAndAliases}}{{end}}{{if .HasExample}}
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}
|
|
|
|
|
|
|
|
Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
|
|
|
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}
|
|
|
|
|
|
|
|
{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}}
|
|
|
|
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}
|
|
|
|
|
|
|
|
Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}}
|
|
|
|
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
|
|
|
|
|
|
|
Flags:
|
|
|
|
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
|
|
|
|
|
|
|
|
Global Flags:
|
|
|
|
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
|
|
|
|
|
|
|
|
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
|
|
|
|
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
|
|
|
|
|
|
|
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
|
|
|
|
`
|
|
|
|
|
|
|
|
// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync.
|
|
|
|
func defaultUsageFunc(w io.Writer, in interface{}) error {
|
|
|
|
c := in.(*Command)
|
|
|
|
fmt.Fprint(w, "Usage:")
|
|
|
|
if c.Runnable() {
|
|
|
|
fmt.Fprintf(w, "\n %s", c.UseLine())
|
|
|
|
}
|
|
|
|
if c.HasAvailableSubCommands() {
|
|
|
|
fmt.Fprintf(w, "\n %s [command]", c.CommandPath())
|
|
|
|
}
|
|
|
|
if len(c.Aliases) > 0 {
|
|
|
|
fmt.Fprintf(w, "\n\nAliases:\n")
|
|
|
|
fmt.Fprintf(w, " %s", c.NameAndAliases())
|
|
|
|
}
|
|
|
|
if c.HasExample() {
|
|
|
|
fmt.Fprintf(w, "\n\nExamples:\n")
|
|
|
|
fmt.Fprintf(w, "%s", c.Example)
|
|
|
|
}
|
|
|
|
if c.HasAvailableSubCommands() {
|
|
|
|
cmds := c.Commands()
|
|
|
|
if len(c.Groups()) == 0 {
|
|
|
|
fmt.Fprintf(w, "\n\nAvailable Commands:")
|
|
|
|
for _, subcmd := range cmds {
|
|
|
|
if subcmd.IsAvailableCommand() || subcmd.Name() == "help" {
|
|
|
|
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
for _, group := range c.Groups() {
|
|
|
|
fmt.Fprintf(w, "\n\n%s", group.Title)
|
|
|
|
for _, subcmd := range cmds {
|
|
|
|
if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == "help") {
|
|
|
|
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !c.AllChildCommandsHaveGroup() {
|
|
|
|
fmt.Fprintf(w, "\n\nAdditional Commands:")
|
|
|
|
for _, subcmd := range cmds {
|
|
|
|
if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == "help") {
|
|
|
|
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if c.HasAvailableLocalFlags() {
|
|
|
|
fmt.Fprintf(w, "\n\nFlags:\n")
|
|
|
|
fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages()))
|
|
|
|
}
|
|
|
|
if c.HasAvailableInheritedFlags() {
|
|
|
|
fmt.Fprintf(w, "\n\nGlobal Flags:\n")
|
|
|
|
fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages()))
|
|
|
|
}
|
|
|
|
if c.HasHelpSubCommands() {
|
|
|
|
fmt.Fprintf(w, "\n\nAdditional help topcis:")
|
|
|
|
for _, subcmd := range c.Commands() {
|
|
|
|
if subcmd.IsAdditionalHelpTopicCommand() {
|
|
|
|
fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if c.HasAvailableSubCommands() {
|
|
|
|
fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath())
|
|
|
|
}
|
|
|
|
fmt.Fprintln(w)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
|
|
|
|
|
|
|
|
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
|
|
|
|
|
|
|
|
// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync.
|
|
|
|
func defaultHelpFunc(w io.Writer, in interface{}) error {
|
|
|
|
c := in.(*Command)
|
|
|
|
usage := c.Long
|
|
|
|
if usage == "" {
|
|
|
|
usage = c.Short
|
|
|
|
}
|
|
|
|
usage = trimRightSpace(usage)
|
|
|
|
if usage != "" {
|
|
|
|
fmt.Fprintln(w, usage)
|
|
|
|
fmt.Fprintln(w)
|
|
|
|
}
|
|
|
|
if c.Runnable() || c.HasSubCommands() {
|
|
|
|
fmt.Fprint(w, c.UsageString())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
|
|
|
|
`
|
|
|
|
|
|
|
|
// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync.
|
|
|
|
func defaultVersionFunc(w io.Writer, in interface{}) error {
|
|
|
|
c := in.(*Command)
|
|
|
|
_, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version)
|
|
|
|
return err
|
|
|
|
}
|