2

I am using cobra to create a CLI application (app). I need to implement a behavior in which I can pass flags as arguments. These flags will be passed|used further to another application via exec.Command(). All flag arguments passed to app must be ignored by the app itself, i.e. not recognized as flags.

I do not rule out that this is strange behavior. But if there is an opportunity to implement I will be grateful.

Examples of interaction with the application:

> app --help
or
> app --first --second

I want the arguments (--help --first --second, and all others) to not be taken as flags for app.

fabelx
  • 197
  • 1
  • 12

1 Answers1

3

You can pass them after a double dash -- which by convention indicates that following flags and args are not meant to be interpreted as args and flags for the main program. They are ignored unless you explicitly use them in some way. i.e.:

if len(pflag.Args()) != 0 {
    afterDash := pflag.Args()[pflag.CommandLine.ArgsLenAtDash():]
    fmt.Printf("args after dash: %v\n", afterDash)
}
$ go run ./cmd/tpl/ -d yaml -- --foo --bar
args after dash: [--foo --bar]

cobra is using the pflag package https://pkg.go.dev/github.com/spf13/pflag

The Fool
  • 16,715
  • 5
  • 52
  • 86
  • In general, this is a good answer, although it does not meet my expectations. Apparently, I do not correctly understand the conceptual purpose of cobra. That's why I marked this answer as the solution. Thanks. – fabelx May 03 '22 at 16:52
  • 1
    @fabel, perhaps cobra is not the right choice for your application. If you want to read some arbitrary args and handle them yourself, you can use `os.Args`, whatever was passed as argument will be in this slice https://cs.opensource.google/go/go/+/refs/tags/go1.18.1:src/os/proc.go;l=16. cobra is meant to provide handling around those for you. You may want to do it yourself, as it sounds. – The Fool May 03 '22 at 16:56
  • You're right. I did some research and did exactly what you describe. – fabelx May 03 '22 at 17:02