英文:
Can't add new cobra CLI command when the file is inside a folder
问题
我正在使用cobra构建CLI。
我想创建一个名为config
的新命令,它将位于文件config.go
中,文件位于文件夹proxy
中。
这是目录结构:
MyProject
├── cmd
| ├── proxy
| | └── config.go
| └── root.go
└── main.go
我使用cobra创建了该命令:
cobra add config
它在cmd
下创建了文件,然后我将该文件移动到proxy
文件夹下(如上面的目录结构所示)。
问题是命令没有被添加。
这是config.go
的代码:
// 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)
}
它构建成功,但是当我运行MyProj.exe -h
时,我看不到该命令。
我做错了什么吗?
英文:
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 ?
答案1
得分: 5
该软件包未包含在构建中,因此该命令从未初始化。
Go构建软件包。当您构建cmd
软件包时,该软件包中的所有Go文件将被编译,并且将调用所有init()
函数。但是,如果没有引用到proxy
软件包,它将不会被编译。
您的代理软件包中有package cmd
,因此该软件包是代理目录下的cmd
软件包。您应该将其重命名为proxy
软件包。
然后,将其包含在构建中。在main.go中:
import {
_ "github.com/MyProject/cmd/proxy"
}
这将导致该软件包的init()
函数运行,并将其添加到命令中。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论