golang命令行库cobra

Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.

github:https://github.com/spf13/cobra.git

cobra基于command、arguments和flags组织命令行,如:

hugo server --port=1313

hugo是command,server是arguments,port是flags。

目录

一般程序目录结构如下:

app
├── cmd
│   ├── root.go
│   └── version.go
├── go.mod
└── main.go

main.go是主程序,cmd/root.go为基本命令文件,一般rootCmd表示在没有任何子命令的情况下的基本命令。

command

// Command is just that, a command for your application.
// E.g.  'go run ...' - 'run' is the command. Cobra requires
// you to define the usage and description as part of your command
// definition to ensure usability.
type Command struct {
    // Use is the one-line usage message.
    Use string

    // Aliases is an array of aliases that can be used instead of the first word in Use.
    Aliases []string

    // SuggestFor is an array of command names for which this command will be suggested -
    // similar to aliases but only suggests.
    SuggestFor []string

    // Short is the short description shown in the 'help' output.
    Short string

    // Long is the long message shown in the 'help <this-command>' output.
    Long string

    // Example is examples of how to use the command.
    Example string

    // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
    ValidArgs []string

    // Expected arguments
    Args PositionalArgs

    // ArgAliases is List of aliases for ValidArgs.
    // These are not suggested to the user in the bash completion,
    // but accepted if entered manually.
    ArgAliases []string

    // BashCompletionFunction is custom functions used by the bash autocompletion generator.
    BashCompletionFunction string

    // Deprecated defines, if this command is deprecated and should print this string when used.
    Deprecated string

    // Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
    Hidden bool

    // Annotations are key/value pairs that can be used by applications to identify or
    // group commands.
    Annotations map[string]string

    // 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,
    // will print content of the "Version" variable. A shorthand "v" flag will also be added if the
    // command does not define one.
    Version string

    // The *Run functions are executed in the following order:
    //   * PersistentPreRun()
    //   * PreRun()
    //   * Run()
    //   * PostRun()
    //   * PersistentPostRun()
    // All functions get the same args, the arguments after the command name.
    //
    // PersistentPreRun: children of this command will inherit and execute.
    PersistentPreRun func(cmd *Command, args []string)
    // PersistentPreRunE: PersistentPreRun but returns an error.
    PersistentPreRunE func(cmd *Command, args []string) error
    // PreRun: children of this command will not inherit.
    PreRun func(cmd *Command, args []string)
    // PreRunE: PreRun but returns an error.
    PreRunE func(cmd *Command, args []string) error
    // Run: Typically the actual work function. Most commands will only implement this.
    Run func(cmd *Command, args []string)
    // RunE: Run but returns an error.
    RunE func(cmd *Command, args []string) error
    // PostRun: run after the Run command.
    PostRun func(cmd *Command, args []string)
    // PostRunE: PostRun but returns an error.
    PostRunE func(cmd *Command, args []string) error
    // PersistentPostRun: children of this command will inherit and execute after PostRun.
    PersistentPostRun func(cmd *Command, args []string)
    // PersistentPostRunE: PersistentPostRun but returns an error.
    PersistentPostRunE func(cmd *Command, args []string) error

    // 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

    // TraverseChildren parses flags on all parents before executing child command.
    TraverseChildren bool

    // FParseErrWhitelist flag parse errors to be ignored
    FParseErrWhitelist FParseErrWhitelist

    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
    // 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
    }

    // args is actual args parsed from flags.
    args []string
    // 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.
    lflags *flag.FlagSet
    // iflags contains inherited flags.
    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

    // usageFunc is usage func defined by user.
    usageFunc func(*Command) error
    // usageTemplate is usage template defined by user.
    usageTemplate string
    // flagErrorFunc is func defined by user and it's called when the parsing of
    // flags returns an error.
    flagErrorFunc func(*Command, error) error
    // helpTemplate is help template defined by user.
    helpTemplate string
    // helpFunc is help func defined by user.
    helpFunc func(*Command, []string)
    // helpCommand is command with usage 'help'. If it's not defined by user,
    // cobra uses default help command.
    helpCommand *Command
    // versionTemplate is the version template defined by user.
    versionTemplate string

    // 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
}
cobra.Command

常用command示例如下:

  var cmdPrint = &cobra.Command{
    Use:   "print [string to print]",
    Short: "Print anything to the screen",
    Long: `print is for printing anything back to the screen.
For many years people have printed back to the screen.`,
    Args: cobra.MinimumNArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
      fmt.Println("Print: " + strings.Join(args, " "))
    },
  }

flags

一般来说,在init()函数中定义flags和处理配置。

flags分为持久flags(Persistent Flags)和本地flags(local Flags)。

Local flags:flags仅适用于指定command。以serverCmd.Flags().StringVarP(&server.ServerPort, "port", "p", "50052", "server port")为例,定义了一个flag,值存储在&server.ServerPort中,长命令为--port,短命令为-p,,默认值为50052,命令的描述为server port

Persisten flags:flags适用于指定命令及其子命令。如rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output"),flag是可以持久的,这意味着该flag将被分配给它所分配的命令以及该命令下的每个命令。对于全局标记,将标记作为根上的持久标志。

// https://github.com/spf13/pflag.git
// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
    f.VarP(newStringValue(value, p), name, shorthand, usage)
}

// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
    p := new(string)
    f.StringVarP(p, name, shorthand, value, usage)
    return p 
}

// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func (f *FlagSet) String(name string, value string, usage string) *string {
    p := new(string)
    f.StringVarP(p, name, "", value, usage)
    return p
}

Args

Command中的Args用于指定位置参数(positional arguments)。 

  • NoArgs - the command will report an error if there are any positional args.
  • ArbitraryArgs - the command will accept any args.
  • OnlyValidArgs - the command will report an error if there are any positional args that are not in the ValidArgs field of Command.
  • MinimumNArgs(int) - the command will report an error if there are not at least N positional args.
  • MaximumNArgs(int) - the command will report an error if there are more than N positional args.
  • ExactArgs(int) - the command will report an error if there are not exactly N positional args.
  • ExactValidArgs(int) - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the ValidArgs field of Command
  • RangeArgs(min, max) - the command will report an error if the number of args is not between the minimum and maximum number of expected args.

 Help

cmd.SetHelpCommand(cmd *Command)
cmd.SetHelpFunc(f func(*Command, []string))
cmd.SetHelpTemplate(s string)

后面两个用于任何子命令。

Usage

cmd.SetUsageFunc(f func(*Command) error)
cmd.SetUsageTemplate(s string)

参考:

1. grpc+grpc-gateway 「连载二」Hello World

2. https://gitee.com/yuxio/edgecontroller/blob/master/cnca/cmd/cnca.go

猜你喜欢

转载自www.cnblogs.com/embedded-linux/p/12741113.html