Search code examples
gocommandgo-cobra

Can't add new cobra CLI command when the file is inside a folder


I am using cobra to build CLI.
I want to create a new command called config that will be inside the file config.go and the file inside the folder proxy.

This is the structure:

MyProject
├── cmd
|  ├── proxy
|  |    └── config.go
|  └── root.go
└── main.go  

I created the command with cobra:

cobra add config  

It created the file under cmd and I moved the file to be under the proxy folder (as appeared in the structure above).

The problem is that the command is not being added.
This is config.go code:

// config.go
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
    "MyProject/cmd"
)

var configCmd = &cobra.Command{
    Use:   "config",
    Short: "A brief description.",
    Long: `A longer description.`,
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("config called")
    },
}

func init() {
    cmd.RootCmd.AddCommand(configCmd)
}

It build successfully but I don't see the command when I run MyProj.exe -h.
Am I doning something wrong ?


Solution

  • The package is not included in the build, so the command never initializes.

    Go builds packages. When you build the cmd package, all go files in that package will be compiled, and all the init() functions will be called. But if there's nothing referencing to the proxy package, it will not be compiled.

    Your proxy package has package cmd in it, so that package is a cmd package under proxy directory. You should rename that to proxy package.

    Then, include it in the build. In main.go:

    import {
      _ "github.com/MyProject/cmd/proxy"
    }
    

    This will cause the init() for that package to run, and it will add itself to the command.