命令行应用之cobra
1、文件目录
2、代码
主要分为两步:
1)定义子命令
wordCmd = &cobra.Command{。。。。。。}
2)将子命令添加进根命令
rootCmd.AddCommand(wordCmd)
cmd/word.go
package cmd import ( "log" "strings" cobra "github.com/spf13/cobra" "flag/internal/word" ) const ( ModeUpper = iota + 1 // 全部转大写 ModeLower // 全部转小写 ModeUnderscoreToUpperCamelCase // 下划线转大写驼峰 ModeUnderscoreToLowerCamelCase // 下线线转小写驼峰 ModeCamelCaseToUnderscore // 驼峰转下划线 ) var str string var mode int8 var desc = strings.Join([]string{ "该子命令支持各种单词格式转换,模式如下:", "1:全部转大写", "2:全部转小写", "3:下划线转大写驼峰", "4:下划线转小写驼峰", "5:驼峰转下划线", }, "\n") var wordCmd = &cobra.Command{ Use: "word", Short: "单词格式转换", Long: desc, Run: func(cmd *cobra.Command, args []string) { var content string switch mode { case ModeUpper: content = word.ToUpper(str) case ModeLower: content = word.ToLower(str) case ModeUnderscoreToUpperCamelCase: content = word.UnderscoreToUpperCamelCase(str) case ModeUnderscoreToLowerCamelCase: content = word.UnderscoreToLowerCamelCase(str) case ModeCamelCaseToUnderscore: content = word.CamelCaseToUnderscore(str) default: log.Fatalf("暂不支持该转换模式,请执行 help word 查看帮助文档") } log.Printf("输出结果: %s", content) }, } func init() { wordCmd.Flags().StringVarP(&str, "str", "s", "", "请输入单词内容") wordCmd.Flags().Int8VarP(&mode, "mode", "m", 0, "请输入单词转换的模式") }
cmd/root.go
package cmd import ( cobra "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{} func Execute() error { return rootCmd.Execute() } func init() { rootCmd.AddCommand(wordCmd) }
word/word.go
package word import ( "strings" "unicode" ) func ToUpper(s string) string { return strings.ToUpper(s) } func ToLower(s string) string { return strings.ToLower(s) } func UnderscoreToUpperCamelCase(s string) string { s = strings.Replace(s, "_", " ", -1) s = strings.Title(s) return strings.Replace(s, " ", "", -1) } func UnderscoreToLowerCamelCase(s string) string { s = UnderscoreToUpperCamelCase(s) return string(unicode.ToLower(rune(s[0]))) + s[1:] } func CamelCaseToUnderscore(s string) string { var output []rune for i, r := range s { if i == 0 { output = append(output, unicode.ToLower(r)) continue } if unicode.IsUpper(r) { output = append(output, '_') } output = append(output, unicode.ToLower(r)) } return string(output) }
main.go
package main import ( "log" "flag/cmd" ) var name string func main() { err := cmd.Execute() if err != nil { log.Fatalf("cmd.Execute err: %v", err) } }