0

我在 a 中添加了以下标志cobra.Cmd

    myCmd.PersistentFlags().StringP(applicationLongFlag, applicationShortFlag, applicationDefaultValue, applicationFlagHelpMsg)

在哪里

    applicationLongFlag     = "application"
    applicationShortFlag    = "a"
    applicationDefaultValue = ""
    applicationFlagHelpMsg  = "The application name"

这可以按预期工作,但是当尝试根据需要制作上述标志时,该过程会失败


    if err := myCmd.MarkFlagRequired(applicationShortFlag); err != nil {
        return errors.Wrapf(err, "error marking %s as required flag", applicationShortFlag)
    }
error marking a as required flag: no such flag -a

-a/--application按预期工作,它也打印在我的帮助中

▶ go run myprog.go mycommand --help

Usage:
  myprog.go mycommand [flags]

Flags:
  -a, --application string   The application name

为什么没有按要求设置?

4

1 回答 1

0

我认为您应该使用MarkPersistentFlagRequired而不是MarkFlagRequired尝试标记持久标志。您只能使用nameflag 而不能使用shorthand.

代码

package main

import (
    "fmt"

    "github.com/spf13/cobra"
)

func main() {
    rootCmd := &cobra.Command{
        Use: "root",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Mark using `MarkPersistentFlagRequired` ")
        },
    }

    rootCmd.PersistentFlags().StringP("test", "t", "", "test required")
    // Change this
    if err := rootCmd.MarkPersistentFlagRequired("test"); err != nil {
        fmt.Println(err.Error())
        return
    }
    rootCmd.Execute()
}

输出

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

Flags:
  -h, --help          help for root
  -t, --test string   test required
于 2022-01-19T16:19:58.903 回答