1

I want to invoke other urfave/cli based CLIs, e.g., kubectl with myapp kubectl command. For that, I've a minimal project

.
├── go.mod
├── go.sum
├── main.go
└── pkg
    └── cmds
        └── kubectl.go

2 directories, 4 files

pkg/cmds/kubectl.go

package cmds

import (
    "k8s.io/component-base/cli"
    "k8s.io/kubectl/pkg/cmd"
    "k8s.io/kubectl/pkg/cmd/util"

    _ "k8s.io/client-go/plugin/pkg/client/auth"
)

func Kubectl() {
    command := cmd.NewDefaultKubectlCommand()
    if err := cli.RunNoErrOutput(command); err != nil {
        util.CheckErr(err)
    }
}

main.go

package main

import (
    "fmt"
    "log"
    "os"
    "strings"

    "github.com/user/repo/pkg/cmds"
    "github.com/urfave/cli/v2"
)

func main() {
    app := &cli.App{
        Commands: []*cli.Command{
            {
                Name:    "kubectl",
                Aliases: []string{"k"},
                Usage:   `Should run kubectl with all args and flags`,
                Description: `go run . kubectl version

                error: unknown command "kubectl" for "kubectl"
                exit status 1`,
                Action: func(cCtx *cli.Context) error {
                    strings.Join(cCtx.Args().Slice(), " ")
                    fmt.Println(strings.Join(cCtx.Args().Slice(), " "))
                    cmds.Kubectl()
                    return nil
                },
            },
            {
                Name:        "get",
                Aliases:     []string{"v"},
                Usage:       "Executes `kubectl get` with all args and flags",
                Description: `Apparently kubectl runs with root coomand context`,
                Action: func(cCtx *cli.Context) error {
                    fmt.Println(strings.Join(cCtx.Args().Slice(), " "))
                    cmds.Kubectl()
                    return nil
                },
            },
        },
    }

    if err := app.Run(os.Args); err != nil {
        log.Fatal(err)
    }
}

With this, I can now run go run . get ... and get expected kubectl get ... response. What I want is to run go run . kubectl get ... but this errors

error: unknown command "kubectl" for "kubectl"
exit status 1

How to run NewDefaultKubectlCommand() with kubectl command context (ie remove remove `kubectl from args slice)?

0 Answers0