I'm using cobra with my Golang application. How can I get the list of commands and values that I have registered with Cobra.
If I add a root command and then a DisplayName command.
var Name = "sample_"
var rootCmd = &cobra.Command{Use: "Use help to find out more options"}
rootCmd.AddCommand(cmd.DisplayNameCommand(Name))
Will I be able to know what is the value in Name from within my program by using some Cobra function? Ideally I want to access this value in Name and use it for checking some logic.
You can use the value stored in the Name variable for performing operations within your program. An example usage of cobra is:
var Name = "sample_"
var rootCmd = &cobra.Command{
Use: "hello",
Short: "Example short description",
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
var echoCmd = &cobra.Command{
Use: "echo",
Short: "Echo description",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("hello %s", Name)
},
}
func init() {
rootCmd.AddCommand(echoCmd)
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
`
In the above code, you can see that hello is the root command and echo is a sub command. If you do hello echo, it'll echo the value sample_ which is stored in the Name variable.
You can also do something like this:
var echoCmd = &cobra.Command{
Use: "echo",
Short: "Echo description",
Run: func(cmd *cobra.Command, args []string) {
// Perform some logical operations
if Name == "sample_" {
fmt.Printf("hello %s", Name)
} else {
fmt.Println("Name did not match")
}
},
}
For knowing more about how to use cobra, you can also view my project from the below link.
https://github.com/bharath-srinivas/nephele
Hope this helps.
Related
The sketch below is a command line application written using Cobra and Go. I'd like to throw an error if the value of flag1 doesn't match the regex ^\s+\/\s+. How do I do that?
package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
var flag1 string
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "cobra-sketch",
Short: "Sketch for Cobra flags",
Long: "Sketch for Cobra flags",
Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Flag1 is %s\n", flag1)},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
cobra.CheckErr(rootCmd.Execute())
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-sketch.yaml)")
rootCmd.PersistentFlags().StringVar(&flag1, "flag1", "", "Value of Flag 1")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
cobra.CheckErr(err)
// Search config in home directory with name ".cobra-sketch" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".cobra-sketch")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
}
}
Let's say a user runs the command like this: cobra-sketch --flag1 "hello". "hello" will be stored in the var flag1 string variable you have assigned to the flag, to check if the input matches any regexp, you can do:
var rootCmd = &cobra.Command{
Use: "cobra-sketch",
...
RunE: func(cmd *cobra.Command, args []string) error {
// You can also use MustCompile if you are sure the regular expression
// is valid, it panics instead of returning an error
re, err := regexp.Compile(`^\s+\/\s+`)
if err != nil {
return err // Handle error
}
if !regexp.MatchString(flag1) {
return fmt.Errorf("invalid value: %q", flag1)
}
fmt.Printf("Flag1 is %s\n", flag1)
return nil
},
}
I'm moving my cobra command flags inside a function so I can use it in other commands. I can able to see the commands but when I type the flage it always returns false.
Following is my code:
func NewCommand(ctx context.Context) *cobra.Command {
var opts ListOptions
cmd := &cobra.Command{
Use: "list",
Short: "List",
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println(args) // []
opts.refs = args
return List(ctx, gh, opts, os.Stdout)
},
}
cmd = GetCommandFlags(cmd, opts)
return cmd
}
// GetListCommandFlags for list
func GetCommandFlags(cmd *cobra.Command, opts ListOptions) *cobra.Command {
flags := cmd.Flags()
flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")
flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")
return cmd
}
So when I type the following command
data-check list --ignore-latest
The the flag value of --ignore-latest should be true but I get false as a value in RunE args. Am I missing something here?
GetCommandFlags is something I want to use it in other commands I don't want to repeat the same flags.
You should use func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) and call the func like cmd = GetCommandFlags(cmd, &opts).
You can print opts.IgnoreLatest and opts.IgnoreOld to see the changed value.
Works fine for me. Hope it will work for you too.
func NewCommand(ctx context.Context) *cobra.Command {
var opts ListOptions
cmd := &cobra.Command{
Use: "list",
Short: "List",
RunE: func(cmd *cobra.Command, args []string) error {
// fmt.Println(args) // []
fmt.Println(opts.IgnoreLatest, ", ", opts.IgnoreOld)
opts.refs = args
return List(ctx, gh, opts, os.Stdout)
},
}
cmd = GetCommandFlags(cmd, &opts)
return cmd
}
// GetListCommandFlags for list
func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
flags := cmd.Flags()
flags.BoolVar(&opts.IgnoreLatest, "ignore-latest", false, "Do not display latest")
flags.BoolVar(&opts.IgnoreOld, "ignore-old", false, "Do not display old data")
return cmd
}
You are passing opts to GetCommandFlags by value. You should pass a pointer to it, so the addresses registered for the flags use the opts declared in the calling function.
func GetCommandFlags(cmd *cobra.Command, opts *ListOptions) *cobra.Command {
...
}
You are passing value parameter not a pointer parameter.
Try someting like:
cmd = GetCommandFlags(cmd, &opts, "")
I am using Cobra to make some cli updated to my app. I want to make this command required, meaning the application should fail if it doesn't find the argument it is looking for.
package commands
import (
"github.com/spf13/cobra"
"errors"
"fmt"
)
var (
Env string
)
var RootCmd = &cobra.Command{
Use: "myapp",
Short: "tool",
Long: `tool`,
Run: func(cmd *cobra.Command, args []string) {
// Root command does nothing
},
}
func init() {
RootCmd.AddCommand(Environment)
}
var Environment = &cobra.Command{
Use: "env",
Short: "Specify Environment to run against",
Long: `Can be dev or prod`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return errors.New("requires at least one arg")
}
if args[0] == "dev" || args[0] == "prod" {
return nil
}else {
return errors.New("input can only be dev or prod")
}
return fmt.Errorf("invalid env specified: %s", args[0])
},
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("env is required")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
Env = args[0]
},
}
and main package is
package main
import (
"fmt"
"log"
"os"
"util"
"commands"
)
func main() {
log.Println("Executing")
if err := commands.RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
log.Println("Executing")
}
Now if I run this as ./myApp without any env, it doesn't complain about it. However if I use env after myapp then it activates the function and runs all the validations.
You can just make the body of the function handle it, perhaps by printing help and exiting as non-successful:
Run: func(cmd *cobra.Command, args []string) {
// Root command does nothing
cmd.Help()
os.Exit(1)
},
Omitting the Run (and RunE) field from the cobra.Command will make it a requirement for a valid subcommand to be given:
var RootCmd = &cobra.Command{
Use: "myapp",
Short: "tool",
Long: `tool long help...`,
}
If no subcommand is given on the command line, Cobra will print out the command's Help() text , which will include the root command's Long help text and the autogenerated usage help for all subcommands.
The documentation in Cobra and Viper are confusing me. I did cobra init fooproject and then inside the project dir I did cobra add bar. I have a PersistentFlag that is named foo and here is the init function from the root command.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
fmt.Println(cfgFile)
fmt.Println("fooString is: ", fooString)
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags, which, if defined here,
// will be global for your application.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.fooproject.yaml)")
RootCmd.PersistentFlags().StringVar(&fooString, "foo", "", "loaded from config")
viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))
// Cobra also supports local flags, which will only run
// when this action is called directly.
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
My configuration file looks like this...
---
foo: aFooString
And when I call go run main.go I see this...
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
fooproject [command]
Available Commands:
bar A brief description of your command
help Help about any command
Flags:
--config string config file (default is $HOME/.fooproject.yaml)
--foo string loaded from config
-h, --help help for fooproject
-t, --toggle Help message for toggle
Use "fooproject [command] --help" for more information about a command.
fooString is:
When I call go run main.go bar I see this...
Using config file: my/gopath/github.com/user/fooproject/.fooproject.yaml
bar called
fooString is:
So it is using the configuration file, but neither one of them seems to be reading it. Maybe I am misunderstanding the way that Cobra and Viper work. Any ideas?
To combine spf13/cobra and spf13/viper, first define the flag with Cobra:
RootCmd.PersistentFlags().StringP("foo", "", "loaded from config")
Bind it with Viper:
viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))
And get the variable via the Viper's method:
fmt.Println("fooString is: ", viper.GetString("foo"))
Since Viper values are somewhat inferior to pflags (e.g. no support for custom data types), I was not satisfied with answer "use Viper to retrieve values", and ended up writing small helper type to put values back in pflags.
type viperPFlagBinding struct {
configName string
flagValue pflag.Value
}
type viperPFlagHelper struct {
bindings []viperPFlagBinding
}
func (vch *viperPFlagHelper) BindPFlag(configName string, flag *pflag.Flag) (err error) {
err = viper.BindPFlag(configName, flag)
if err == nil {
vch.bindings = append(vch.bindings, viperPFlagBinding{configName, flag.Value})
}
return
}
func (vch *viperPFlagHelper) setPFlagsFromViper() {
for _, v := range vch.bindings {
v.flagValue.Set(viper.GetString(v.configName))
}
}
func main() {
var rootCmd = &cobra.Command{}
var viperPFlagHelper viperPFlagHelper
rootCmd.PersistentFlags().StringVar(&config.Password, "password", "", "API server password (remote HTTPS mode only)")
viperPFlagHelper.BindPFlag("password", rootCmd.Flag("password"))
rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
err := viper.ReadInConfig()
if err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return err
}
}
viperPFlagHelper.setPFlagsFromViper()
return nil
}
}
For those facing the same issue, the problem is on this call:
cobra.OnInitialize(initConfig)
The function initConfig is not executed directly but append to an array of initializers https://github.com/spf13/cobra/blob/master/cobra.go#L80
So, the values stored in your config file will be loaded when the Run field is executed:
rootCmd = &cobra.Command{
Use: "example",
Short: "example cmd",
Run: func(cmd *cobra.Command, args []string) { // OnInitialize is called first
fmt.Println(viper.AllKeys())
},
}
#WGH 's answer is correct, you can do something with the persistent flag in rootCmd.PersistenPreRun, which will be available in all other sub commands.
var rootCmd = &cobra.Command{
PersistentPreRun: func(_ *cobra.Command, _ []string) {
if persistentflag {
// do something with persistentflag
}
},
In cobra I've create a command of commands:
myapp zip -directory "xzy" -output="zipname"
myapp upload -filename="abc"
I want to make a zipAndUpload command and reuse the existing commands, i.e.,
myapp zipup -directory "xzy" -outout="zipname"
Here the zipup would first call the "zip" command and then use the output name from the "zip" command as the "filename" flag for the "upload" command.
How can I execute this without a lot of code duplication?
The "shared" switches make as global.
The "run" sections of the sub-commands, convert to functions.
To do this you must define the commands manually:
var (
cfgDirectory string
cfgFilename string
cfgOutput string
)
var rootCmd = &cobra.Command{
Use: "root",
Short: "root",
Long: "root",
Run: func(cmd *cobra.Command, args []string) {
// something
},
}
var uploadCmd = &cobra.Command{
Use: 'upload',
Short: 'upload',
Long: `upload`,
Run: func(cmd *cobra.Command, args []string) {
Upload()
},
}
var zipCmd = &cobra.Command{
Use: "zip",
Short: "zip",
Long: "zip",
Run: func(cmd *cobra.Command, args []string) {
Zip()
},
}
var zipupCmd = &cobra.Command{
Use: "zipup",
Short: "zipup",
Long: "zipup",
Run: func(cmd *cobra.Command, args []string) {
Zip()
Upload()
},
}
func setFlags() {
rootCmd.PersistentFlags().StringVar(&cfgDirectory, "directory", "", "explanation")
rootCmd.PersistentFlags().StringVar(&cfgFilename, "filename", "", "explanation")
rootCmd.PersistentFlags().StringVar(&cfgOutput, "output", "", "explanation")
}
func Upload() {
// you know what to do
}
func Zip() {
// you know what to do
}
...
// Add subcommands
rootCmd.AddCommand(zipCmd)
rootCmd.AddCommand(uploadCmd)
rootCmd.AddCommand(zipupCmd)
Hope this helps, this is the best I could do without any example code.
When you create new commands from the cobra CLI, it usually puts them into separate files. If you want to run a command from a different command file, it would look something like this:
package cmd
import "github.com/spf13/cobra"
// DirectoryFlag specifies the directory
var DirectoryFlag string
// OutputFlag specifies the output
var OutputFlag string
// zipupCmd represents the "zipup" command
var zipupCmd = &cobra.Command{
Use: "zipup",
Short: "Zip & Upload",
Long: `Zip & Upload`,
Run: func(cmd *cobra.Command, args []string) {
anyArgs := "whatever"
zipCmd.Run(cmd, []string{anyArgs})
uploadCmd.Run(cmd, []string{anyArgs})
},
}
func init() {
rootCmd.AddCommand(zipupCmd)
zipupCmd.Flags().StringVarP(&DirectoryFlag, "directory", "d", "", "set the directory")
zipupCmd.Flags().StringVarP(&OutputFlag, "output", "o", "", "set the output")
}