Skip to content

Commit

Permalink
Fix moreflag to make command line args win over env vars. (bazelbuild…
Browse files Browse the repository at this point in the history
…#123)

* Fix moreflag to make command line args win over env vars.

* Fix moreflag to make command line args win over env vars.
  • Loading branch information
ramymedhat authored Feb 19, 2020
1 parent d02017f commit a4d2940
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion go/pkg/moreflag/moreflag.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import (
// It also calls flag.Parse() to parse flags sent directly as arguments, unless flag.Parse
// has been previously called.
func Parse() {
ParseFromEnv()
if !flag.Parsed() {
ParseFromEnv()
flag.Parse()
}
}
Expand Down
29 changes: 28 additions & 1 deletion go/pkg/moreflag/moreflag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,21 @@ import (
"github.com/google/go-cmp/cmp"
)

func TestParse(t *testing.T) {
func TestParseUnset(t *testing.T) {
cleanup := setCommandLine(t, []string{"cmd"})
defer cleanup()
f := flag.String("value", "", "Some value")

Parse()
if *f != "" {
t.Errorf("Flag has wrong value, want '', got %q", *f)
}
}

func TestParseSet(t *testing.T) {
cleanup := setCommandLine(t, []string{"cmd"})
defer cleanup()
f := flag.String("value", "", "Some value")
os.Setenv("FLAG_value", "test")
defer os.Setenv("FLAG_value", "")
Parse()
Expand All @@ -24,6 +31,26 @@ func TestParse(t *testing.T) {
}
}

func TestParseCommandLineWins(t *testing.T) {
cleanup := setCommandLine(t, []string{"cmd", "--value=cmd"})
defer cleanup()
f := flag.String("value", "", "Some value")
os.Setenv("FLAG_value", "test")
defer os.Setenv("FLAG_value", "")
Parse()
if *f != "cmd" {
t.Errorf("Flag has wrong value, want 'cmd', got %q", *f)
}
}

func setCommandLine(t *testing.T, args []string) func() {
t.Helper()
oldArgs := os.Args
os.Args = args
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
return func() { os.Args = oldArgs }
}

func TestMapValueSet(t *testing.T) {
tests := []struct {
name string
Expand Down

0 comments on commit a4d2940

Please sign in to comment.