[英]cobra-cli pass all arguments and flags to an executable
I have a cobra CLI for my own stuff.我有一个 cobra CLI 用于我自己的东西。 Now I want to add commonly used executables eg kubectl
, calicoctl
as subcommands which will consume all arguments and flags like现在我想添加常用的可执行文件,例如kubectl
, calicoctl
作为子命令,它们将使用所有参数和标志,如
mywrapper kubectl get all --all-namespaces
mywrapper kubectl create deployment nginx --image=nginx --port=80
Reproduce cobra project复制眼镜蛇项目
mkdir mywrapper; cd mywrapper; go mod init mywrapper; cobra-cli init .
And add a subcommand eg kubectl
并添加一个子命令,例如kubectl
cobra-cli add kubectl
Then populate ./cmd/kubectl.go
with然后用./cmd/kubectl.go
填充
package cmd
import (
"fmt"
"os/exec"
"strings"
"github.com/spf13/cobra"
)
var kubectlCmd = &cobra.Command{
Use: "kubectl",
Short: "run kubectl",
Run: func(cmd *cobra.Command, args []string) {
out, err := exec.Command("/bin/bash", "-c", fmt.Sprintf("kubectl %v", strings.Join(args, " "))).Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
},
}
func init() {
rootCmd.AddCommand(kubectlCmd)
}
I can now run kubectl
command eg go run . kubectl get pods
我现在可以运行kubectl
命令,例如go run . kubectl get pods
go run . kubectl get pods
. go run . kubectl get pods
。 But it fails when flags are added eg go run . kubectl get pods --selector app=nginx
但是当添加标志时它会失败,例如go run . kubectl get pods --selector app=nginx
go run . kubectl get pods --selector app=nginx
Pass your flags after the --
.在--
之后传递你的标志。 A double dash (--) is used to signify the end of command options.双破折号 (--) 用于表示命令选项的结束。 In our case it is required to distinguish between the flags passed to go
and those that aren't.在我们的例子中,需要区分传递给go
的标志和没有传递的标志。 Everything after the double dash wont be considered to be go
's flags.双破折号之后的所有内容都不会被视为go
的标志。
I tried with gcloud:我尝试使用 gcloud:
package cmd
import (
"fmt"
"os/exec"
"github.com/spf13/cobra"
)
var gcloudCmd = &cobra.Command{
Use: "gcloud",
Short: "run gcloud",
Run: func(cmd *cobra.Command, args []string) {
out, err := exec.Command("gcloud", args...).Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
},
}
func init() {
rootCmd.AddCommand(gcloudCmd)
}
Then tried:然后尝试:
$ go run . gcloud compute regions list -- --filter="id<1250"
NAME CPUS DISKS_GB ADDRESSES RESERVED_ADDRESSES STATUS TURNDOWN_DATE
asia-east1 0/24 0/4096 0/8 0/8 UP
europe-west1 0/24 0/4096 0/8 0/8 UP
us-central1 0/24 0/4096 0/8 0/8 UP
us-east1 0/24 0/4096 0/8 0/8 UP
us-west1 0/24 0/4096 0/8 0/8 UP
Adding more flags:添加更多标志:
$ go run . gcloud compute regions list -- --filter="id<1250" --format="table(name,id)"
NAME ID
asia-east1 1220
europe-west1 1100
us-central1 1000
us-east1 1230
us-west1 1210
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.