Skip to content

Commit

Permalink
✨ feat: cflag - add new built in ext type SafeFuncVar
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 1, 2023
1 parent b2889bb commit db5b927
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
9 changes: 9 additions & 0 deletions cflag/ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,3 +474,12 @@ func (s *ConfString) Set(value string) error {
}
return nil
}

// SafeFuncVar safe func Value
type SafeFuncVar func(string)

// Set value
func (f SafeFuncVar) Set(s string) error { f(s); return nil }

// String get
func (f SafeFuncVar) String() string { return "" }
24 changes: 24 additions & 0 deletions cflag/ext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cflag_test

import (
"errors"
"flag"
"testing"

"github.com/gookit/goutil/cflag"
Expand Down Expand Up @@ -150,6 +151,18 @@ func TestStrings_methods(t *testing.T) {
assert.NoErr(t, ss.Set("val2"))
assert.Eq(t, "val,val2", ss.String())
assert.True(t, ss.IsRepeatable())

var v1 any

v1 = &cflag.Strings{}
val, ok := v1.(flag.Value)
assert.True(t, ok)
assert.NotNil(t, val)

v1 = cflag.Strings{}
val, ok = v1.(flag.Value)
assert.False(t, ok)
assert.Nil(t, val)
}

func TestBooleans_methods(t *testing.T) {
Expand All @@ -162,3 +175,14 @@ func TestBooleans_methods(t *testing.T) {
assert.Eq(t, "[true,false]", bs.String())
assert.True(t, bs.IsRepeatable())
}

func TestSafeFuncVar(t *testing.T) {
var s string
fv := cflag.SafeFuncVar(func(val string) {
s = val
})

assert.NoErr(t, fv.Set("val"))
assert.Eq(t, "val", s)
assert.Eq(t, "", fv.String())
}

0 comments on commit db5b927

Please sign in to comment.