【golang】第三方命令行 cli 的使用

引入包

     

"github.com/urfave/cli"


    结构体

         App 结构体定义了命令行的应用结构,如下很庞大的样子

    // App is the main structure of a cli application. It is recommended that
    // an app be created with the cli.NewApp() function
    type App struct {
           // The name of the program. Defaults to path.Base(os.Args[0])
           Name string
           // Full name of command for help, defaults to Name
           HelpName string
           // Description of the program.
           Usage string
           // Text to override the USAGE section of help
           UsageText string
           // Description of the program argument format.
           ArgsUsage string
           // Version of the program
           Version string
           // List of commands to execute
           Commands []Command
           // List of flags to parse
           Flags []Flag
           // Boolean to enable bash completion commands
           EnableBashCompletion bool
           // Boolean to hide built-in help command
           HideHelp bool
           // Boolean to hide built-in version flag and the VERSION section of help
           HideVersion bool
           // Populate on app startup, only gettable through method Categories()
           categories CommandCategories
           // An action to execute when the bash-completion flag is set
           BashComplete BashCompleteFunc
           // An action to execute before any subcommands are run, but after the context is ready
           // If a non-nil error is returned, no subcommands are run
           Before BeforeFunc
           // An action to execute after any subcommands are run, but after the subcommand has finished
           // It is run even if Action() panics
           After AfterFunc
    
           // The action to execute when no subcommands are specified
           // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
           // *Note*: support for the deprecated `Action` signature will be removed in a future version
           Action interface{}
    
           // Execute this function if the proper command cannot be found
           CommandNotFound CommandNotFoundFunc
           // Execute this function if an usage error occurs
           OnUsageError OnUsageErrorFunc
           // Compilation date
           Compiled time.Time
           // List of all authors who contributed
           Authors []Author
           // Copyright of the binary if any
           Copyright string
           // Name of Author (Note: Use App.Authors, this is deprecated)
           Author string
           // Email of Author (Note: Use App.Authors, this is deprecated)
           Email string
           // Writer writer to write output to
           Writer io.Writer
           // ErrWriter writes error output
           ErrWriter io.Writer
           // Other custom info
           Metadata map[string]interface{}
    
           didSetup bool
    }

    // Context is a type that is passed through to
    // each Handler action in a cli application. Context
    // can be used to retrieve context-specific Args and
    // parsed command-line options.
    type Context struct {
           App           *App
           Command       Command
           flagSet       *flag.FlagSet
           setFlags      map[string]bool
           parentContext *Context
    }



    初始化 APP

         

    // NewApp creates a new cli Application with some reasonable defaults for Name,
    // Usage, Version and Action.
    func NewApp() *App {
           return &App{
                  Name:         filepath.Base(os.Args[0]),
                  HelpName:     filepath.Base(os.Args[0]),
                  Usage:        "A new cli application",
                  UsageText:    "",
                  Version:      "0.0.0",
                  BashComplete: DefaultAppComplete,
                  Action:       helpCommand.Action,
                  Compiled:     compileTime(),
                  Writer:       os.Stdout,
           }
    }



    例子主函数

         

    const (
           usage      = "xxxxxxxxxxxxxx"
    )

    func main() {
           app := cli.NewApp()
           app.Name = "name"
           app.Usage = usage
    
           app.Version = "xxxxx"
           app.Flags = []cli.Flag{
                  cli.BoolFlag{
                         Name:  "debug",
                         Usage: "enable debug output for logging",
                  },
                  cli.StringFlag{
                         Name:  "log",
                         Value: "/dev/null",
                         Usage: "set the log file path where internal debug information is written",
                  },
           }
           app.Commands = []cli.Command{  
                 createCommand,
                 deleteCommand,
           }
           app.Before = func(context *cli.Context) error {
                  if context.GlobalBool("debug") {
                         logrus.SetLevel(logrus.DebugLevel)
                  }
                  if path := context.GlobalString("log"); path != "" {
                         f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0666)
                         if err != nil {
                                return err
                         }
                         logrus.SetOutput(f)
                  }
                  return nil
           }
     
           if err := app.Run(os.Args); err != nil {
                  fatal(err)
           }
    }



    例子子命令

         自命令可以使用模版,在 Action 中调用实现的函数

    var createCommand = cli.Command{
           Name:  "create",
           Usage: "create a xxxxx",
           ArgsUsage: `xxxxxxx`,
           Flags: []cli.Flag{
                  cli.StringFlag{
                         Name:  "bundle, b",
                         Value: "",
                         Usage: `path to the root of directory, defaults to the current directory`,
                  },
           },
           Action: func(context *cli.Context) error {
                  do-something
                  return nil
           },
    }




    例子子命令

         自命令可以使用模版,在 Action 中调用实现的函数

    // loadSpec loads the specification from the provided path.
    func loadSpec(cPath string) (spec *specs.Spec, err error) {
           cf, err := os.Open(cPath)
           if err != nil {
                  if os.IsNotExist(err) {
                         return nil, fmt.Errorf("JSON specification file %s not found", cPath)
                  }
                  return nil, err
           }
           defer cf.Close()
    
           if err = json.NewDecoder(cf).Decode(&spec); err != nil {
                  return nil, err
           }
           return spec, validateProcessSpec(spec.Process)
    }


          具体可以参考 runc 源码 main.go 文件
    • 2
      点赞
    • 1
      收藏
      觉得还不错? 一键收藏
    • 0
      评论
    Go语言的第三方包管理机制经历了三个重要的阶段:GOPATH、Vendor和Go Module。 1. 第一阶段:GOPATH 在Go语言早期版本中,使用全局的GOPATH来管理所有的第三方包。GOPATH是一个环境变量,它指定了Go语言的工作目录。当我们使用go get命令下载第三方包时,它会被下载到GOPATH目录下的src、pkg和bin目录中。这种方式的缺点是所有的项目都共享同一个GOPATH,当不同项目使用同一个第三方包的不同版本时,会出现冲突。 2. 第二阶段:Vendor 为了解决GOPATH的缺点,Go语言引入了Vendor机制。Vendor机制将项目的依赖包局部化,每个项目都有自己的Vendor目录,用于存放项目所依赖的第三方包。当我们使用go get命令下载第三方包时,它会被下载到项目的Vendor目录中。这种方式的缺点是当我们需要更新第三方包时,需要手动更新Vendor目录中的包。 3. 第三阶段:Go Module Go语言的最新功能Go Module是一种更加先进的第三方包管理机制。它将每个项目都看作一个独立的模块,每个模块都有自己的go.mod文件,用于记录项目所依赖的第三方包及其版本信息。当我们使用go get命令下载第三方包时,它会被下载到项目的go.mod文件中指定的目录中。这种方式的优点是可以自动管理第三方包的版本,当我们需要更新第三方包时,只需要修改go.mod文件中的版本信息即可。 以下是一个使用Go Module管理第三方包的例子: 1. 创建一个新的项目目录,并初始化Go Module: ``` mkdir myproject cd myproject go mod init example.com/myproject ``` 2. 在项目中使用第三方包: ``` import "github.com/go-redis/redis" ``` 3. 下载第三方包: ``` go get github.com/go-redis/redis ``` 4. 查看项目依赖的第三方包: ``` go list -m all ```

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值