2

The built-in flags package seems to break parsing upon encountering the first non-flag argument for a process. Consider this application:

package main

import (
    "flag"
    "fmt"
)

func main() {
    alpha := flag.String("alpha", "", "the first")
    beta := flag.String("beta", "", "the second")
    flag.Parse()
    fmt.Println("ALPHA: " + *alpha)
    fmt.Println("BETA: " + *beta)
}

The output of three different invocations where a "subcommand" is provided then look like this:

$ ./app --alpha 1 --beta 2 hi
ALPHA: 1
BETA: 2
$ ./app --alpha 1 hi --beta 2 
ALPHA: 1
BETA: 
$ ./app hi --alpha 1 --beta 2 
ALPHA: 
BETA: 

How can a subcommand followed by a flag such as git status --short be recreated using the flags package?

Thomas Hunter II
  • 5,081
  • 7
  • 35
  • 54
  • You need to write some code. Package `flag` is not comprehensive. Many people for this reason use some 3rd party package for their cli programs, rather than the stdlib `flag` package. – mkopriva Dec 30 '22 at 05:56
  • For example you can take `os.Args`, take the command and subcommands from the left side, and then pass the rest to `fs.Parse` where `fs` is the instance of `flag.FlagSet` which you used to specify the flags. – mkopriva Dec 30 '22 at 06:01
  • You can also take a look at [`cmd/go`](https://github.com/golang/go/blob/master/src/cmd/go/main.go) to see how the Go team implements the `go` tool (the subcommands are in the `cmd/go/internal/` directory). – mkopriva Dec 30 '22 at 06:07
  • 1
    Example: https://gobyexample.com/command-line-subcommands – solideo Dec 30 '22 at 12:05
  • I ultimately went with the following Go package as it allowed for flexibility with `app cmd --flag` and `app --flag cmd`. https://pkg.go.dev/github.com/DavidGamba/go-getoptions – Thomas Hunter II Dec 30 '22 at 21:11

1 Answers1

3

I faced this same issue once, this helped me.

Basically, go flag package uses the UNIX option parser getopt() that stops parsing after the first non-option.

You can find the solution in the above link as well.

Deeksha Sharma
  • 159
  • 1
  • 1
  • 6