dongzh1988 2017-11-13 19:46
浏览 54

如何使用眼镜蛇在Go CLI中制作所需的子命令

I am using Cobra to make some cli updated to my app. I want to make this command required, meaning the application should fail if it doesn't find the argument it is looking for.

package commands

import (
    "github.com/spf13/cobra"
    "errors"
    "fmt"
)

var (
    Env string
)

var RootCmd = &cobra.Command{
    Use:   "myapp",
    Short: "tool",
    Long:  `tool`,
    Run: func(cmd *cobra.Command, args []string)  {
        // Root command does nothing
    },
}

func init() {
    RootCmd.AddCommand(Environment)
}

var Environment = &cobra.Command{
    Use:   "env",
    Short: "Specify Environment to run against",
    Long: `Can be dev or prod`,
    Args: func(cmd *cobra.Command, args []string) error {
        if len(args) != 1 {
            return errors.New("requires at least one arg")
        }

        if args[0] == "dev" || args[0] == "prod" {
            return nil
        }else {
            return errors.New("input can only be dev or prod")
        }
        return fmt.Errorf("invalid env specified: %s", args[0])
    },
    PreRunE: func(cmd *cobra.Command, args []string) error {
        if len(args) != 1 {
          return fmt.Errorf("env is required")
        }
      return nil
    },
    Run: func(cmd *cobra.Command, args []string) {
        Env = args[0]
    },
}

and main package is

package main

import (
    "fmt"
    "log"
    "os"
    "util"
    "commands"
)

func main() {
    log.Println("Executing")

    if err := commands.RootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    log.Println("Executing")
}

Now if I run this as ./myApp without any env, it doesn't complain about it. However if I use env after myapp then it activates the function and runs all the validations.

  • 写回答

1条回答 默认 最新

  • douchen2595 2017-11-13 19:50
    关注

    You can just make the body of the function handle it, perhaps by printing help and exiting as non-successful:

    Run: func(cmd *cobra.Command, args []string)  {
        // Root command does nothing
        cmd.Help()
        os.Exit(1)
    },
    
    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch