helper/flag-kv: can parse JSON files

This commit is contained in:
Mitchell Hashimoto 2015-05-26 09:58:04 -07:00
parent dd0a775500
commit 7f78a2c5d9
3 changed files with 96 additions and 0 deletions

View File

@ -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
}

View File

@ -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)
}
}
}

View File

@ -0,0 +1,3 @@
{
"key": "value"
}