pflag icon indicating copy to clipboard operation
pflag copied to clipboard

Unexpected flag value when asterisk (*) is passed as string flag value

Open jakedoublev opened this issue 1 year ago • 2 comments

When a single or series of asterisks (i.e. * or ***) are passed as the values of string flags, pflag will return a file name within the current directory instead of the asterisk strings.

Code to reproduce:

package main

import (
	"fmt"

	flags "github.com/spf13/pflag"
)

var coolflag string

func init() {
	flags.StringVar(&coolflag, "coolflag", "", "This is a cool flag")
}

func main() {
	flags.Parse()
	if coolflag == "" {
		flags.PrintDefaults()
		return
	}
	fmt.Println("cool flag value: ", coolflag)
}

Execution is in a directory with the above code in main.go, a go.mod like the below, and the generated go.sum:

module flagstest

go 1.22.3

require github.com/spf13/pflag v1.0.5

Results:

jake.vanvorhis$ go run . --coolflag *
cool flag value:  go.mod
jake.vanvorhis$ go run . --coolflag ***
cool flag value:  go.mod
jake.vanvorhis$ go run . --coolflag hello
cool flag value:  hello

I have also seen this reproduced where CODEOWNERS was the file read into the string flag value.

jakedoublev avatar Jun 11 '24 20:06 jakedoublev

I believe this is actually the shell expanding the glob * before passing the arguments, and it doesn't have anything to do with pflag. Try wrapping the asterisk in ':

go run . --coolflag '*'

eamonburns avatar Jun 24 '24 17:06 eamonburns

The same thing happens with echo:

$ echo *
go.mod go.sum main.go
$ echo '*'
*

eamonburns avatar Jun 24 '24 18:06 eamonburns