为了账号安全,请及时绑定邮箱和手机立即绑定

Cobra MarkPersistentFlagRequired 不适用于 Root

Cobra MarkPersistentFlagRequired 不适用于 Root

Go
慕无忌1623718 2023-04-04 15:07:16
使用 spf13/Cobra 进行 cli 标志解析。root 命令有一个标记为必填的字段:rootCmd.PersistentFlags().StringVarP(&configFilePath, "config", "c","", "REQUIRED: config file")     rootCmd.MarkPersistentFlagRequired("config")         rootCmd.MarkFlagRequired("config")但是,如果它是根命令,cobra 不会引发错误。如果我添加一个子命令并添加一个必填字段,如果命令行上未提供参数,.MarkFlagRequired 会按预期引发错误。
查看完整描述

1 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

这对我有用。


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.


查看完整回答
反对 回复 2023-04-04
  • 1 回答
  • 0 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信