diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 411ae30..965d093 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -7,7 +7,7 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Lint uses: golangci/golangci-lint-action@v3 @@ -19,7 +19,7 @@ jobs: env: GORACE: history_size=4 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Go uses: actions/setup-go@v4 diff --git a/goutil/goutil_test.go b/goutil/goutil_test.go index 171002b..65a33c0 100644 --- a/goutil/goutil_test.go +++ b/goutil/goutil_test.go @@ -90,6 +90,7 @@ func TestExpand(t *testing.T) { "github.com/teamwork/utils/v2/stringutil", "github.com/teamwork/utils/v2/syncutil", "github.com/teamwork/utils/v2/timeutil", + "github.com/teamwork/utils/v2/typeutil", }, "", }, diff --git a/ioutilx/copy_test.go b/ioutilx/copy_test.go index f85493e..55b412c 100644 --- a/ioutilx/copy_test.go +++ b/ioutilx/copy_test.go @@ -298,7 +298,7 @@ func TestCopyTree(t *testing.T) { }) t.Run("permission", func(t *testing.T) { err := CopyTree("test", "/cant/write/here", nil) - if !test.ErrorContains(err, "permission denied") { + if !test.ErrorContains(err, "permission denied") && !test.ErrorContains(err, "read-only file system") { t.Error(err) } }) diff --git a/typeutil/typeutil.go b/typeutil/typeutil.go new file mode 100644 index 0000000..28aa7b1 --- /dev/null +++ b/typeutil/typeutil.go @@ -0,0 +1,15 @@ +// Package typeutil adds functions for types. +package typeutil // import "github.com/teamwork/utils/v2/typeutil" + +// Default returns `val` if it is not zero, otherwise returns +// `def`. +// +// v := Default("", "hello") // return "hello" +// v := Default("world", "hello") // return "world" +func Default[T comparable](val, def T) T { + if val == *new(T) { + return def + } + + return val +} diff --git a/typeutil/typeutil_test.go b/typeutil/typeutil_test.go new file mode 100644 index 0000000..6ad20bc --- /dev/null +++ b/typeutil/typeutil_test.go @@ -0,0 +1,34 @@ +package typeutil_test + +import ( + "testing" + + "github.com/teamwork/utils/v2/typeutil" +) + +func Test_Default(t *testing.T) { + tests := map[string]struct { + in string + exp string + }{ + "empty string returns default": { + in: "", + exp: "default value", + }, + "non-empty string returns value": { + in: "hello there", + exp: "hello there", + }, + } + + for name, test := range tests { + test := test + t.Run(name, func(t *testing.T) { + t.Parallel() + + if val := typeutil.Default(test.in, "default value"); val != test.exp { + t.Fatalf("expected '%s', got '%s'", test.exp, val) + } + }) + } +}