gogo-cobra

How to extract registered information?


I'm using Cobra in 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.


Solution

  • 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.