Skip to content

Commit

Permalink
Merge pull request #76 from Teamwork/enhancement/default
Browse files Browse the repository at this point in the history
Enhancement: `Default`
  • Loading branch information
ripexz authored Sep 5, 2023
2 parents 01a08db + bf03225 commit 519412a
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions goutil/goutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
"",
},
Expand Down
2 changes: 1 addition & 1 deletion ioutilx/copy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
Expand Down
15 changes: 15 additions & 0 deletions typeutil/typeutil.go
Original file line number Diff line number Diff line change
@@ -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
}
34 changes: 34 additions & 0 deletions typeutil/typeutil_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit 519412a

Please sign in to comment.