亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號