diff --git a/helper/flag-kv/flag_json.go b/helper/flag-kv/flag_json.go new file mode 100644 index 000000000..9af9fe1da --- /dev/null +++ b/helper/flag-kv/flag_json.go @@ -0,0 +1,34 @@ +package kvflag + +import ( + "encoding/json" + "fmt" + "os" +) + +// FlagJSON is a flag.Value implementation for parsing user variables +// from the command-line using JSON files. +type FlagJSON map[string]string + +func (v *FlagJSON) String() string { + return "" +} + +func (v *FlagJSON) Set(raw string) error { + f, err := os.Open(raw) + if err != nil { + return err + } + defer f.Close() + + if *v == nil { + *v = make(map[string]string) + } + + if err := json.NewDecoder(f).Decode(v); err != nil { + return fmt.Errorf( + "Error reading variables in '%s': %s", raw, err) + } + + return nil +} diff --git a/helper/flag-kv/flag_json_test.go b/helper/flag-kv/flag_json_test.go new file mode 100644 index 000000000..df5a99e64 --- /dev/null +++ b/helper/flag-kv/flag_json_test.go @@ -0,0 +1,59 @@ +package kvflag + +import ( + "flag" + "path/filepath" + "reflect" + "testing" +) + +func TestFlagJSON_impl(t *testing.T) { + var _ flag.Value = new(FlagJSON) +} + +func TestFlagJSON(t *testing.T) { + cases := []struct { + Input string + Initial map[string]string + Output map[string]string + Error bool + }{ + { + "basic.json", + nil, + map[string]string{"key": "value"}, + false, + }, + + { + "basic.json", + map[string]string{"foo": "bar"}, + map[string]string{"foo": "bar", "key": "value"}, + false, + }, + + { + "basic.json", + map[string]string{"key": "bar"}, + map[string]string{"key": "value"}, + false, + }, + } + + for _, tc := range cases { + f := new(FlagJSON) + if tc.Initial != nil { + f = (*FlagJSON)(&tc.Initial) + } + + err := f.Set(filepath.Join("./test-fixtures", tc.Input)) + if (err != nil) != tc.Error { + t.Fatalf("bad error. Input: %#v\n\n%s", tc.Input, err) + } + + actual := map[string]string(*f) + if !reflect.DeepEqual(actual, tc.Output) { + t.Fatalf("bad: %#v", actual) + } + } +} diff --git a/helper/flag-kv/test-fixtures/basic.json b/helper/flag-kv/test-fixtures/basic.json new file mode 100644 index 000000000..21da3b262 --- /dev/null +++ b/helper/flag-kv/test-fixtures/basic.json @@ -0,0 +1,3 @@ +{ + "key": "value" +}