Skip to content

Commit

Permalink
feat(main): implement []string flag valuer
Browse files Browse the repository at this point in the history
Implement flag.Value to automnatically split strings into an array at
their spaces.

Change-Id: Ia9139e23d74a30acfc74cb65935bb7fc2b322aec
  • Loading branch information
terinjokes committed Jan 14, 2018
1 parent 61302e4 commit 4dabf65
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 34 additions & 0 deletions internal/flag/flag.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package flag

import (
"fmt"
"strings"
)

// A StringsValue is a command-line flag that interprets its argument
// as a space-separated list of strings.
type StringsValue []string

// Set implements the flag.Value interface by spliting the provided string at
// spaces.
func (v *StringsValue) Set(s string) error {
if s == "" {
*v = []string{}
return nil
}

*v = strings.Fields(s)

return nil
}

// Get implements the flag.Getter interface by returning the contents of this
// value.
func (v *StringsValue) Get() interface{} {
return []string(*v)
}

// String returns a string
func (v *StringsValue) String() string {
return fmt.Sprintf("%s", *v)
}
29 changes: 29 additions & 0 deletions internal/flag/flag_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package flag_test

import (
"testing"

"github.com/google/go-cmp/cmp"
"github.com/terinjokes/bakelite/internal/flag"
)

func TestStringsValue(t *testing.T) {
tests := []struct {
v string
want []string
}{
{"", []string{}},
{"a b c", []string{"a", "b", "c"}},
{"foo bar baz", []string{"foo", "bar", "baz"}},
{"foo bar baz", []string{"foo", "bar", "baz"}},
}

for i, tt := range tests {
got := flag.StringsValue([]string{})
got.Set(tt.v)

if diff := cmp.Diff(tt.want, got.Get()); diff != "" {
t.Errorf("#%d: manifest differs. (-got +want):\n%s", i, diff)
}
}
}

0 comments on commit 4dabf65

Please sign in to comment.