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.
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
},
}
why does the following CLI program using the cobra package throw a stack overflow error when ran with go run /tmp/test.go branch leaf, but does not error when when leaf subcommand is directly connected to root(as commented in the main function)?
This suggests that I'm not using the cobra PersistenRun* functions properly. My understanding of the PersistenRun* functions is that they only apply to command's children. The issue seems that a command's parent has been somehow set to the command itself.
package main
import (
"fmt"
"os"
"path"
"github.com/spf13/cobra"
)
var programName = path.Base(os.Args[0])
var rootCmd = &cobra.Command{
Use: programName,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
fmt.Println("in root pre run")
},
}
var branchCmd = &cobra.Command{
Use: "branch",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Parent().PersistentPreRun(cmd, args)
fmt.Println("in branch pre run")
},
}
var leafCmd = &cobra.Command{
Use: "leaf",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Parent().PersistentPreRun(cmd, args)
fmt.Println("in leaf pre run")
},
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("in leaf run")
},
}
func main() {
branchCmd.AddCommand(leafCmd)
rootCmd.AddCommand(branchCmd)
rootCmd.Execute()
// If I connect the root to the leaf directly, like the following, then
// the program no longer stack overflow
// rootCmd.AddCommand(leafCmd)
// rootCmd.Execute()
}
NVM, I figured it out.
Intead of
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Parent().PersistentPreRun(cmd, args)
fmt.Println("in * pre run")
},
It should be:
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Parent().PersistentPreRun(cmd.Parent(), args)
fmt.Println("in * pre run")
},
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 urfave/cli to build a CLI application in Go.
What I would like is options given after the first command to be treated as arguments and not flags (so that I can handle them myself or pass them to an other executable).
When using app.Action (see below), this is the behavior that I get, but if I am using cli.Commands then I get an error.
package main
import (
"fmt"
"github.com/urfave/cli"
"log"
"os"
)
func main() {
app := cli.NewApp()
app.Commands = []cli.Command{
{
Name: "test",
Action: func(c *cli.Context) error {
fmt.Println("test", c.Args())
return nil
},
},
}
app.Action = func(c *cli.Context) error {
fmt.Println(c.Args())
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
Output of: go run main.go cmd -f flag:
[cmd -f flag]
but go run main.go test cmd -f flag exits with an error where I would like it to oupput
test [cmd -f flag]
After looking at the documentation of cli.Command, there is actually a very simple way to have what I want: setting SkipFlagParsing to true will treat all flags as normal arguments.
app.Commands = []cli.Command{
{
Name: "test",
SkipFlagParsing: true
Action: func(c *cli.Context) error {
fmt.Println("test", c.Args())
return nil
},
},
}
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.