Skip to content

Commit

Permalink
feat: customized slice flag separator
Browse files Browse the repository at this point in the history
  • Loading branch information
FGYFFFF committed Oct 24, 2022
1 parent 7732a51 commit dffd74a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
6 changes: 6 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ type App struct {
// single-character bool arguments into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool
// SliceFlagSeparator is used to customize the separator for SliceFlag, the default is ","
SliceFlagSeparator string
// Enable suggestions for commands and flags
Suggest bool

Expand Down Expand Up @@ -241,6 +243,10 @@ func (a *App) Setup() {
if a.Metadata == nil {
a.Metadata = make(map[string]interface{})
}

if len(a.SliceFlagSeparator) != 0 {
defaultSliceFlagSeparator = a.SliceFlagSeparator
}
}

func (a *App) newRootCommand() *Command {
Expand Down
4 changes: 3 additions & 1 deletion flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import (

const defaultPlaceholder = "value"

var defaultSliceFlagSeparator = ","

var (
slPfx = fmt.Sprintf("sl:::%d:::", time.Now().UTC().UnixNano())

Expand Down Expand Up @@ -378,5 +380,5 @@ func flagFromEnvOrFile(envVars []string, filePath string) (value string, fromWhe
}

func flagSplitMultiValues(val string) []string {
return strings.Split(val, ",")
return strings.Split(val, defaultSliceFlagSeparator)
}
16 changes: 16 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3384,3 +3384,19 @@ func TestSliceShortOptionHandle(t *testing.T) {
t.Fatal("Action callback was never called")
}
}

func TestCustomizedSliceFlagSeparator(t *testing.T) {
defaultSliceFlagSeparator = ";"
opts := []string{"opt1", "opt2", "opt3,op", "opt4"}
ret := flagSplitMultiValues(strings.Join(opts, ";"))
defaultSliceFlagSeparator = ","
if len(ret) != 4 {
t.Fatalf("split slice flag failed, want: 4, but get: %d", len(ret))
}
for idx, r := range ret {
if r != opts[idx] {
t.Fatalf("get %dth failed, wanted: %s, but get: %s", idx, opts[idx], r)
}
}
}

0 comments on commit dffd74a

Please sign in to comment.