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

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

概述引入包       "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() functiontyp 引入包
"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() functiontype 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 (  @H_539_404@usage = "xxxxxxxxxxxxxx")
@H_465_419@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""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 != "" {                     ferr := os.Openfile(pathos.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC0666)                     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 文件 总结

以上是内存溢出为你收集整理的【golang】第三方命令行 cli 的使用全部内容,希望文章能够帮你解决【golang】第三方命令行 cli 的使用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1275609.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-09
下一篇2022-06-09

发表评论

登录后才能评论

评论列表(0条)

    保存