Is it possible to prevent flag.Parse() from "swallowing" (removing) the -- from the flag.Args()?
Example
package main
import (
"flag"
"fmt"
)
func main() {
flag.Parse()
fmt.Println(flag.Args())
}
I can't differentiate these 2 invocations:
$ go run . hello
[hello]
$ go run . -- hello
[hello]
Why would I like to differentiate these 2 invocations?
I'm writing a Go program that wraps another subprogram.
My program has some optional positional args:
myprog [options] [ARG1 ARG2 ...] [-- SUBARG1 SUBARG2...]
Invocation examples:
$ myprog -flag1 val1
$ myprog -flag1 val1 foo
# foo is for myprog
$ myprog -flag1 val1 foo -- bar
# foo is for myprog
# bar is for the subprogram
$ myprog -flag1 val1 -- bar
# bar is normally for the subprogram, BUT flag.Args() = ["bar"] so I have no way to know that it was after "--"
I understand that I can use --- as separator or any other combination, but I was just curious to know for the -- argument.
Edit after accepted answer
Source:
package main
import (
"flag"
"fmt"
"os"
)
func main() {
var initFlag = flag.Bool("init", false, "init")
var subArgs []string
for i := len(os.Args) - 1; i > 0; i-- {
if os.Args[i] == "--" {
subArgs = os.Args[i+1:]
os.Args = os.Args[:i]
break
}
}
flag.Parse()
fmt.Println(*initFlag)
fmt.Println(flag.Args())
fmt.Println(subArgs)
}
All tests succeeded!
$ go run .
false
[]
[]
$ go run . foo
false
[foo]
[]
$ go run . -- bar
false
[]
[bar]
$ go run . foo -- bar
false
[foo]
[bar]
$ go run . -init foo -- bar
true
[foo]
[bar]
$ go run . -init -- bar
true
[]
[bar]