From 6783c04015a0648c326245d5210dda15f0cca06e Mon Sep 17 00:00:00 2001 From: Ola Rozenfeld Date: Thu, 12 Sep 2019 20:33:28 -0400 Subject: [PATCH] Making moreflag.Parse safe to call repeatedly. (#75) --- go/pkg/moreflag/moreflag.go | 7 +++++-- go/pkg/moreflag/moreflag_test.go | 6 +++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/go/pkg/moreflag/moreflag.go b/go/pkg/moreflag/moreflag.go index 6b772153..8bf9997d 100644 --- a/go/pkg/moreflag/moreflag.go +++ b/go/pkg/moreflag/moreflag.go @@ -13,10 +13,13 @@ import ( // Parse parses flags which are set in environment variables using the FLAG_ prefix. That is // for a flag named x, x=$FLAG_x if $FLAG_x is set. If the flag is set in the command line, the // command line value of the flag takes precedence over the environment variable value. -// It also calls flag.Parse() to parse flags sent directly as arguments. +// It also calls flag.Parse() to parse flags sent directly as arguments, unless flag.Parse +// has been previously called. func Parse() { ParseFromEnv() - flag.Parse() + if !flag.Parsed() { + flag.Parse() + } } // ParseFromEnv parses flags which are set in environment variables using the FLAG_ prefix. That is diff --git a/go/pkg/moreflag/moreflag_test.go b/go/pkg/moreflag/moreflag_test.go index 5ed7b609..2b96e72c 100644 --- a/go/pkg/moreflag/moreflag_test.go +++ b/go/pkg/moreflag/moreflag_test.go @@ -8,17 +8,17 @@ import ( "github.com/google/go-cmp/cmp" ) -func TestParseFromEnv(t *testing.T) { +func TestParse(t *testing.T) { f := flag.String("value", "", "Some value") - ParseFromEnv() + Parse() if *f != "" { t.Errorf("Flag has wrong value, want '', got %q", *f) } os.Setenv("FLAG_value", "test") defer os.Setenv("FLAG_value", "") - ParseFromEnv() + Parse() if *f != "test" { t.Errorf("Flag has wrong value, want 'test', got %q", *f) }