无法在文件位于文件夹内时添加新的 cobra CLI 命令。

huangapple go评论97阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年4月3日 20:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/61011873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定