go - Cobra MarkPersistentFlagRequired 不适用于 Root

标签 go go-cobra

使用 spf13/Cobra 进行 cli 标志解析。

root 命令有一个标记为必填的字段:

rootCmd.PersistentFlags().StringVarP(&configFilePath, "config", "c","", "REQUIRED: config file")
    rootCmd.MarkPersistentFlagRequired("config")    
    rootCmd.MarkFlagRequired("config")

但是,如果是 root 命令,cobra 不会引发错误。

如果我添加子命令并添加必填字段,如果命令行上未提供参数,.MarkFlagRequired 会按预期引发错误。

最佳答案

这对我有用。

package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    var strTmp string
    rootCmd := &cobra.Command{
        Use: "root",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println(strTmp)
        },
    }
    subCmd := &cobra.Command{
        Use: "sub",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println(strTmp)
        },
    }
    rootCmd.PersistentFlags().StringVarP((&strTmp), "test", "t", "", "test required")
    rootCmd.MarkPersistentFlagRequired("test")
    rootCmd.AddCommand(subCmd)
    rootCmd.Execute()
}

输出

子命令

 ⇒  go run test.go sub     
Error: required flag(s) "test" not set
Usage:
  root sub [flags]

Flags:
  -h, --help   help for sub

Global Flags:
  -t, --test string   test required

根命令

⇒  go run test.go     
Error: required flag(s) "test" not set
Usage:
  root [flags]
  root [command]

Available Commands:
  completion  generate the autocompletion script for the specified shell
  help        Help about any command
  sub         

Flags:
  -h, --help          help for root
  -t, --test string   test required

Use "root [command] --help" for more information about a command.

关于go - Cobra MarkPersistentFlagRequired 不适用于 Root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322279/

相关文章:

go - 它是一个空值结构 nil

go - 只允许一组中的一个的数据结构?戈朗

reflection - 获取Go结构体中字段的reflect.Ptr类型

go - 如何使用具有两个不同名称(短名称和长名称)的标志

go - 从单独的命令/进程共享属性

shell - 如何为 go bin 提供命令

json - 被 gin c.BindJSON 捕获时如何断言错误类型 json.UnmarshalTypeError

go - 如何将时区偏移量转换为另一种格式

bash - 使用远程数据制作 Cobra 标志 bash 完成

testing - Cobra:如何在测试中以编程方式设置标志