我目前正在使用 Go 和 cobra 开发一个 CLI 项目。我已经完成了代码,现在构建了项目并尝试运行。但是,我遇到了一个似乎无法解决的错误。我收到的错误消息是:
Error: unknown shorthand flag: 'o' in -o
我不确定导致此错误的原因,也不知道如何继续。
主要功能如下:
func main() {
var rootCmd = &cobra.Command{
Use: "Convertica",
Short: "Convertica is a file format converter",
}
var convCmd = &cobra.Command{
Use: "convert",
Short: "Convert file format",
Run: func(cmd *cobra.Command, args []string) {
converter(cmd, args)
},
}
var outCmd = &cobra.Command{
Use: "outDir",
Short: "The directory of the converted file",
Run: func(cmd *cobra.Command, args []string) {
content, _ := readContent(cmd, args)
newName := converter(cmd, args)
saveContentToDirectory(cmd, content, newName)
},
}
var formatCmd = &cobra.Command{
Use: "format",
Short: "Format of the new file",
Run: func(cmd *cobra.Command, args []string) {
converter(cmd, args)
},
}
convCmd.Flags().StringP("file", "c", "", "The directory of the file to be compressed")
outCmd.Flags().StringP("dir", "o", "", "The directory of the converted file")
formatCmd.Flags().StringP("format", "f", "", "Format of the new file")
rootCmd.AddCommand(convCmd)
rootCmd.AddCommand(outCmd)
rootCmd.AddCommand(formatCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
./convertica conv -c 桌面/abc/hey.txt -o 桌面/abc/ -f .md
这意味着子命令
conv
有3个标志:-c
、-o
和-f
。以下示例展示了如何修改代码来实现此目的:
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
func main() {
var file, dir, format *string
rootCmd := &cobra.Command{
Use: "Convertica",
Short: "Convertica is a file format converter",
}
convCmd := &cobra.Command{
Use: "conv",
Short: "Convert file format",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("flags:\n\t%v\n\t%v\n\t%v\n", *file, *dir, *format)
},
}
file = convCmd.Flags().StringP("file", "c", "", "The directory of the file to be compressed")
dir = convCmd.Flags().StringP("dir", "o", "", "The directory of the converted file")
format = convCmd.Flags().StringP("format", "f", "", "Format of the new file")
rootCmd.AddCommand(convCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
请参阅用户指南了解更多信息。