Skip to content

Commit

Permalink
Add template Value() for JSONs
Browse files Browse the repository at this point in the history
  • Loading branch information
sgreben committed Sep 27, 2018
1 parent 84f0ae2 commit 6958e18
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
12 changes: 9 additions & 3 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ func (fv *JSON) String() string {
return fv.Text
}

// JSONs is a `flag.Value` for JSON arguments.
// JSONs is a `flag.Value` for JSON arguments. If non-nil, the `Value` field is used to generate template values.
type JSONs struct {
Value func() interface{}
Values []interface{}
Texts []string
}
Expand All @@ -38,9 +39,14 @@ func (fv *JSONs) Help() string {
}

// Set is flag.Value.Set
func (fv *JSONs) Set(v string) error {
func (fv *JSONs) Set(v string) (err error) {
var value interface{}
err := json.Unmarshal([]byte(v), &value)
if fv.Value != nil {
value = fv.Value()
err = json.Unmarshal([]byte(v), value)
} else {
err = json.Unmarshal([]byte(v), &value)
}
if err == nil {
fv.Texts = append(fv.Texts, v)
fv.Values = append(fv.Values, value)
Expand Down
22 changes: 22 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,28 @@ func TestJSONs(t *testing.T) {
}
}

func TestJSONsValue(t *testing.T) {
type example struct {
A string
B int
}
fv := flagvar.JSONs{
Value: func() interface{} {
return &example{}
},
}
var fs flag.FlagSet
fs.Var(&fv, "json", "")

err := fs.Parse([]string{"-json", `{"A":"abc","B":123}`})
if err != nil {
t.Fail()
}
if !reflect.DeepEqual(fv.Values, []interface{}{&example{A: "abc", B: 123}}) {
t.Fail()
}
}

func TestJSONsFail(t *testing.T) {
fv := flagvar.JSONs{}
var fs flag.FlagSet
Expand Down

0 comments on commit 6958e18

Please sign in to comment.