Skip to main content

Cobra命令行

huhxLess than 1 minutegoGo

cobra

cobra-cli

# install
go install github.com/spf13/cobra-cli@latest

# 如果执行安装了,cobra-cli command not found,对么参考:https://github.com/spf13/cobra/issues/1964

# create repo
mkdir demo && cd demo

# download dependencies
go mod init demo
go mod tidy

# more
cobra-cli init --author "huhx" --viper --license apache
touch $HOME/.demo.yaml

# add command
cobra-cli add team
cobra-cli add create -p 'teamCmd'

flags

// 1. Working with Flags
Persistent Flags: 
	rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
Local Flags: 
	localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")

// 2. Required flags
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "description")
rootCmd.MarkFlagRequired("region")

// 3. groups
// must be provided together or none of them
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
rootCmd.MarkFlagsRequiredTogether("username", "password")

// either --json or --yaml but never both
rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")
rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")
rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")

auto completion

zsh

echo "autoload -U compinit; compinit" >> ~/.zshrc
./rbctl completion zsh > "${fpath[1]}/_rbctl"

inside cobra

viper

inside viper

FAQ

总结

参考