Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Mar 24, 2024
2 parents 470a81e + 7c5136a commit 3e6bcb9
Show file tree
Hide file tree
Showing 36 changed files with 357 additions and 88 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
go-version: ${{ matrix.go_version }}

- name: Revive check
uses: morphy2k/revive-action@v2.5.6
uses: morphy2k/revive-action@v2.5.7
if: ${{ matrix.os == 'ubuntu-latest' && matrix.go_version == '1.20' }}
with:
# Exclude patterns, separated by semicolons (optional)
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
# https://github.com/softprops/action-gh-release
- name: Create release and upload assets
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
Expand Down
6 changes: 3 additions & 3 deletions arrutil/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,13 @@ func Differences[T any](first, second []T, fn Comparer[T]) []T {
return CloneSlice(first)
}

max := firstLen
maxLn := firstLen
if secondLen > firstLen {
max = secondLen
maxLn = secondLen
}

result := make([]T, 0)
for i := 0; i < max; i++ {
for i := 0; i < maxLn; i++ {
if i < firstLen {
s := first[i]
if i, _ := TwowaySearch(second, s, fn); i < 0 {
Expand Down
29 changes: 28 additions & 1 deletion basefn/basefn.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,41 @@ func MustOK(err error) {
}
}

// Must if error is not empty, will panic
// Must return like (v, error). will panic on error, otherwise return v.
//
// Usage:
//
// // old
// v, err := fn()
// if err != nil {
// panic(err)
// }
//
// // new
// v := goutil.Must(fn())
func Must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}

// MustIgnore for return like (v, error). Ignore return v and will panic on error.
//
// Useful for io, file operation func: (n int, err error)
//
// Usage:
//
// // old
// _, err := fn()
// if err != nil {
// panic(err)
// }
//
// // new
// basefn.MustIgnore(fn())
func MustIgnore(_ any, err error) { PanicErr(err) }

// ErrOnFail return input error on cond is false, otherwise return nil
func ErrOnFail(cond bool, err error) error {
return OrError(cond, err)
Expand Down
9 changes: 9 additions & 0 deletions basefn/basefn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,19 @@ func TestPanicIf(t *testing.T) {
}

func TestPanicErr(t *testing.T) {
basefn.MustOK(nil)
basefn.PanicErr(nil)
assert.Panics(t, func() {
basefn.PanicErr(errors.New("a error"))
})

// must ignore
assert.NotPanics(t, func() {
basefn.MustIgnore(nil, nil)
})
assert.Panics(t, func() {
basefn.MustIgnore(nil, errors.New("a error"))
})
}

func TestPanicf(t *testing.T) {
Expand Down
9 changes: 5 additions & 4 deletions byteutil/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,11 @@ func (b *Buffer) writeAnysWithNl(vs []any, nl bool) {
}
}

// Printf quiet write message to buffer, ignore error.
func (b *Buffer) Printf(tpl string, vs ...any) {
_, _ = b.WriteString(fmt.Sprintf(tpl, vs...))
}
// Printf quick write message to buffer, ignore error.
func (b *Buffer) Printf(tpl string, vs ...any) { _, _ = fmt.Fprintf(b, tpl, vs...) }

// Println quick write message with newline to buffer, will ignore error.
func (b *Buffer) Println(vs ...any) { _, _ = fmt.Fprintln(b, vs...) }

// ResetGet buffer string. alias of ResetAndGet()
func (b *Buffer) ResetGet() string {
Expand Down
7 changes: 5 additions & 2 deletions byteutil/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@ func TestBuffer_WriteAny(t *testing.T) {
buf.WriteAny(23, "abc")
assert.Eq(t, "23abc", buf.ResetGet())

buf.Writeln("abc")
assert.Eq(t, "abc\n", buf.ResetAndGet())
buf.Writeln("abc", 123)
assert.Eq(t, "abc123\n", buf.ResetAndGet())

buf.Println("abc", 123)
assert.Eq(t, "abc 123\n", buf.ResetAndGet())

assert.NoErr(t, buf.Close())
assert.NoErr(t, buf.Flush())
Expand Down
2 changes: 1 addition & 1 deletion comdef/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ type SimpleType interface {
Int | Uint | Float | ~string | ~bool
}

// ScalarType interface type.
// ScalarType basic interface type.
//
// TIP: has bool type, it cannot be ordered
//
Expand Down
8 changes: 4 additions & 4 deletions dump/dumper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ func TestDumper_AccessCantExportedField1(t *testing.T) {

// ------------------------- map -------------------------

func TestDump_Map(t *testing.T) {
func TestDump_Map(_ *testing.T) {
m4 := map[string]any{
"key1": 12,
"key2": "val1",
Expand Down Expand Up @@ -360,11 +360,11 @@ var (
s1 = st1{st0{2}, 23, "inhere"}
)

func TestDump_Struct(t *testing.T) {
func TestDump_Struct(_ *testing.T) {
P(user)
}

func TestStruct_WithNested(t *testing.T) {
func TestStruct_WithNested(_ *testing.T) {
// buffer := new(bytes.Buffer)
dumper := newStd()
dumper.IndentChar = '.'
Expand Down Expand Up @@ -423,7 +423,7 @@ func TestStruct_WithNested(t *testing.T) {
// }
}

func TestDumper_Dump_userType(t *testing.T) {
func TestDumper_Dump_userType(_ *testing.T) {
type testSt struct {
name string
mod fs.FileMode
Expand Down
20 changes: 17 additions & 3 deletions fsutil/fsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path/filepath"
"strings"

"github.com/gookit/goutil/basefn"
"github.com/gookit/goutil/internal/comfunc"
)

Expand Down Expand Up @@ -35,11 +36,21 @@ func UnixPath(path string) string {
return strings.ReplaceAll(path, "\\", "/")
}

// ToAbsPath convert process. will expand home dir
// ToAbsPath convert path to absolute path.
// Will expand home dir, if empty will return current work dir
//
// TIP: will don't check path
// TIP: will don't check path is really exists
func ToAbsPath(p string) string {
if len(p) == 0 || IsAbsPath(p) {
// return current work dir
if len(p) == 0 {
wd, err := os.Getwd()
if err != nil {
return p
}
return wd
}

if IsAbsPath(p) {
return p
}

Expand All @@ -54,3 +65,6 @@ func ToAbsPath(p string) string {
}
return filepath.Join(wd, p)
}

// Must2 ok for (any, error) result. if has error, will panic
func Must2(_ any, err error) { basefn.MustOK(err) }
2 changes: 1 addition & 1 deletion fsutil/fsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ func TestSplitPath(t *testing.T) {
}

func TestToAbsPath(t *testing.T) {
assert.Eq(t, "", fsutil.ToAbsPath(""))
assert.Eq(t, "/path/to/dir/", fsutil.ToAbsPath("/path/to/dir/"))
assert.Neq(t, "~/path/to/dir", fsutil.ToAbsPath("~/path/to/dir"))
assert.NotEmpty(t, fsutil.ToAbsPath(""))
assert.Neq(t, ".", fsutil.ToAbsPath("."))
assert.Neq(t, "..", fsutil.ToAbsPath(".."))
assert.Neq(t, "./", fsutil.ToAbsPath("./"))
Expand Down
12 changes: 3 additions & 9 deletions fsutil/opread.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ func DiscardReader(src io.Reader) {
}

// ReadFile read file contents, will panic on error
func ReadFile(filePath string) []byte {
return MustReadFile(filePath)
}
func ReadFile(filePath string) []byte { return MustReadFile(filePath) }

// MustReadFile read file contents, will panic on error
func MustReadFile(filePath string) []byte {
Expand All @@ -53,9 +51,7 @@ func MustReadReader(r io.Reader) []byte {
}

// ReadString read contents from path or io.Reader, will panic on in type error
func ReadString(in any) string {
return string(GetContents(in))
}
func ReadString(in any) string { return string(GetContents(in)) }

// ReadStringOrErr read contents from path or io.Reader, will panic on in type error
func ReadStringOrErr(in any) (string, error) {
Expand All @@ -78,9 +74,7 @@ func ReadAll(in any) []byte { return MustRead(in) }
func GetContents(in any) []byte { return MustRead(in) }

// MustRead read contents from path or io.Reader, will panic on in type error
func MustRead(in any) []byte {
return basefn.Must(ReadOrErr(in))
}
func MustRead(in any) []byte { return basefn.Must(ReadOrErr(in)) }

// ReadOrErr read contents from path or io.Reader, will panic on in type error
func ReadOrErr(in any) ([]byte, error) {
Expand Down
1 change: 1 addition & 0 deletions fsutil/opwrite.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func SaveFile(filePath string, data any, optFns ...OpenOptionFunc) error {
// Usage:
//
// fsutil.PutContents(filePath, contents, fsutil.FsCWAFlags) // append write
// fsutil.Must2(fsutil.PutContents(filePath, contents)) // panic on error
func PutContents(filePath string, data any, fileFlag ...int) (int, error) {
f, err := QuickOpenFile(filePath, basefn.FirstOr(fileFlag, FsCWTFlags))
if err != nil {
Expand Down
4 changes: 1 addition & 3 deletions fsutil/opwrite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ func TestMustCopyFile(t *testing.T) {
assert.NoErr(t, fsutil.RmIfExist(srcPath))
assert.NoErr(t, fsutil.RmFileIfExist(dstPath))

_, err := fsutil.PutContents(srcPath, "hello")
assert.NoErr(t, err)

fsutil.Must2(fsutil.PutContents(srcPath, "hello"))
fsutil.MustCopyFile(srcPath, dstPath)
assert.Eq(t, []byte("hello"), fsutil.GetContents(dstPath))
assert.Eq(t, "hello", fsutil.ReadString(dstPath))
Expand Down
6 changes: 3 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ go 1.19

require (
github.com/gookit/color v1.5.4
golang.org/x/sync v0.5.0
golang.org/x/sys v0.15.0
golang.org/x/term v0.15.0
golang.org/x/sync v0.6.0
golang.org/x/sys v0.18.0
golang.org/x/term v0.18.0
golang.org/x/text v0.14.0
)

Expand Down
12 changes: 6 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
52 changes: 37 additions & 15 deletions goutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,50 @@ func PanicIf(cond bool, fmtAndArgs ...any) {
basefn.PanicIf(cond, fmtAndArgs...)
}

// PanicIfErr if error is not empty, will panic
func PanicIfErr(err error) {
if err != nil {
panic(err)
}
}

// PanicErr if error is not empty, will panic
// PanicErr if error is not empty, will panic.
// Alias of basefn.PanicErr()
func PanicErr(err error) {
if err != nil {
panic(err)
}
}

// MustOK if error is not empty, will panic
func MustOK(err error) {
if err != nil {
panic(err)
}
}
// PanicIfErr if error is not empty, will panic.
// Alias of basefn.PanicErr()
func PanicIfErr(err error) { PanicErr(err) }

// MustOK if error is not empty, will panic.
// Alias of basefn.MustOK()
func MustOK(err error) { PanicErr(err) }

// Must if error is not empty, will panic
// MustIgnore for return like (v, error). Ignore return v and will panic on error.
//
// Useful for io, file operation func: (n int, err error)
//
// Usage:
//
// // old
// _, err := fn()
// if err != nil {
// panic(err)
// }
//
// // new
// goutil.MustIgnore(fn())
func MustIgnore(_ any, err error) { PanicErr(err) }

// Must return like (v, error). will panic on error, otherwise return v.
//
// Usage:
//
// // old
// v, err := fn()
// if err != nil {
// panic(err)
// }
//
// // new
// v := goutil.Must(fn())
func Must[T any](v T, err error) T {
if err != nil {
panic(err)
Expand Down
9 changes: 8 additions & 1 deletion goutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var testSrvAddr string
func TestMain(m *testing.M) {
s := testutil.NewEchoServer()
defer s.Close()
testSrvAddr = "http://" + s.Listener.Addr().String()
testSrvAddr = s.HTTPHost()
fmt.Println("Test server listen on:", testSrvAddr)

m.Run()
Expand Down Expand Up @@ -51,6 +51,13 @@ func TestPanicIfErr(t *testing.T) {
assert.Panics(t, func() {
goutil.Must("hi", errors.New("a error"))
})

assert.NotPanics(t, func() {
goutil.MustIgnore(nil, nil)
})
assert.Panics(t, func() {
goutil.MustIgnore(nil, errors.New("a error"))
})
}

func TestPanicf(t *testing.T) {
Expand Down
Loading

0 comments on commit 3e6bcb9

Please sign in to comment.