Thomas Hunter II
Thomas Hunter II

Reputation: 5201

Golang flag package stops parsing when encountering a non-flag

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?

Upvotes: 2

Views: 1417

Answers (1)

Deeksha Sharma
Deeksha Sharma

Reputation: 569

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.

Upvotes: 4

Related Questions