Skip to content

Commit

Permalink
commons
Browse files Browse the repository at this point in the history
  • Loading branch information
youthlin committed Oct 6, 2024
0 parents commit ae1ba64
Show file tree
Hide file tree
Showing 48 changed files with 3,526 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/gitee.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# https://github.com/Yikun/hub-mirror-action
name: 同步到 Gitee
on: push
jobs:
run:
runs-on: ubuntu-latest
steps:
- name: Checkout source codes
uses: actions/checkout@v1
- name: sync to gitee
uses: Yikun/hub-mirror-action@master
with:
src: github/pub-go
dst: gitee/pub-go
account_type: org
dst_key: ${{ secrets.dst_key }}
dst_token: ${{ secrets.dst_token }}
static_list: 'commons'
debug: true
27 changes: 27 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Test
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
with:
fetch-depth: 2
- uses: actions/setup-go@v4
with:
go-version: "1.23"
- uses: szenius/set-timezone@v1.2
with:
timezoneLinux: "Asia/Shanghai"
timezoneMacos: "Asia/Shanghai"
timezoneWindows: "China Standard Time"
- name: Run Test
run: |
mkdir -p output
go test -race -gcflags all=-l -coverprofile=output/coverage.out ./... -coverpkg=./...
go tool cover -html=output/coverage.out -o output/coverage.html
go run example/main.go || echo $?
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with: # https://github.com/codecov/codecov-action
directory: ./output
26 changes: 26 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

# Go workspace file
go.work
go.work.sum

# env file
.env
.DS_Store
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 pub-go

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
130 changes: 130 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# code.gopub.tech/commons

```bash
go get code.gopub.tech/commons@latest
```

```go
// code.gopub.tech/commons/arg
var xxx = ...
t.Logf("xxx = %v", arg.JSON(xxx))

// code.gopub.tech/commons/assert
assert.Equal(t, 1, 1)
assert.DeepEqual(t, []int{1}, []int{1})
assert.True(t, values.IsNotNil(xxx))
assert.False(t, values.IsNil(xxx))
assert.Nil(t, xxx)
assert.NotNil(t, xxx)
assert.ShouldNotPanic(t, func(){})
assert.ShouldPanic(t, func(){panic("xxx")})

// code.gopub.tech/commons/conv
conv.Bytes2String([]byte(`abc`)) == "abc"
conv.String2ReadOnlyBytes("abc") // []byte(`abc`)

// code.gopub.tech/commons/choose
s := choose.If(true, "T", "F")
assert.Equal(t, s, "T")
choose.IfLazy(bool, onTrue, onFalse funcs.Supplier[T])
choose.IfLazyT(bool, onTrue funcs.Supplier[T], onFalse T)
choose.IfLazyF(bool, onTrue T, onFalse funcs.Supplier[T])

// code.gopub.tech/commons/funcs
type (
// Supplier 产生一个元素
Supplier[T any] func() T
// Consumer 消费一个元素
Consumer[T any] func(T)
// Function 将一个类型转为另一个类型
Function[T, R any] func(T) R
// Predicate 断言是否满足指定条件
Predicate[T any] Function[T, bool]
// UnaryOperator 对输入进行一元运算返回相同类型的结果
UnaryOperator[T any] Function[T, T]
// BiFunction 将两个类型转为第三个类型
BiFunction[X, Y, R any] func(X, Y) R
// BinaryOperator 输入两个相同类型的参数,对其做二元运算,返回相同类型的结果
BinaryOperator[T any] BiFunction[T, T, T]
)

func TestIdentidy(t *testing.T) {
assert.Equal(t, funcs.Identidy(1), 1)
}

func TestNot(t *testing.T) {
assert.True(t, values.IsZero(0))
assert.True(t, funcs.Not(values.IsZero[int])(1))
}

func TestPartial(t *testing.T) {
format10to := funcs.Partial2(strconv.FormatInt, 10)
assert.Equal(t, format10to(10), "10")
assert.Equal(t, format10to(2), "1010")
}

// code.gopub.tech/commons/iters
func TestSeq(t *testing.T) {
iters.Range(0, 10).
Peek(func(i int) {
t.Logf("from source: %d", i)
}).
Filter(func(i int) bool { return i%2 == 0 }).
Peek(func(i int) {
t.Logf("after filter: %d", i)
}).
Map(func(i int) int { return 2 * i }).
Peek(func(i int) {
t.Logf("map to *2: %d", i)
}).
FlatMap(func(i int) iter.Seq[int] {
return iters.Repeat(i).Limit(2).Seq()
}).
Peek(func(i int) {
t.Logf("after flatten: %d", i)
}).
Distinct(funcs.Identidy).
Sorted(order.Reversed[int]).
Skip(1).
ForEach(func(i int) {
t.Logf("got: %v", i)
})
}

// code.gopub.tech/commons/jsons
t.Logf("xxx=%s", jsons.ToJSON(xxx))
// 区别于 arg.JSON(xxx): 格式化时(调用到String函数时)才会 to json
logs.Debug(ctx, "xxx=%v", arg.JSON(xxx))
// 即使 logs level 更高, 不打印 Debug 日志, 也会执行 to json
logs.Debug(ctx, "xxx=%v", jsons.JSON(xxx))

// code.gopub.tech/commons/nums
type(
Signed,
Unsigned,
Int,
Float,
Complex,
Number
)
nums.To[float64](MyInt(10)) == float64(10)

// code.gopub.tech/commons/order
type: order.Comparator
order.Natural
order.Reversed
order.Reverse

// code.gopub.tech/commons/values
tuple := values.Make2("a", 2)
tuple.Val1 == "a"
tuple.Val2 == 2
values.IsNotZero(tuple.Val1)

// code.gopub.tech/commons/values
values.IsNil(xx)
values.IsNotNil(xx)
values.Zero[string]() == ""
values.IsZero("") == true

```
33 changes: 33 additions & 0 deletions arg/arg.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package arg

import (
"fmt"

"code.gopub.tech/commons/conv"
"code.gopub.tech/commons/jsons"
)

// JSON 使用 %v 打印(实现了 fmt.Stringer 的)返回值 将会得到 JSON
func JSON(argument any, opts ...jsons.Opt) fmt.Stringer {
return &Arg{data: argument, opts: opts}
}

// Indent 使用 %v 打印(实现了 fmt.Stringer 的)返回值 将会得到缩进格式的 JSON
func Indent(argument any, opts ...jsons.Opt) fmt.Stringer {
opts = append([]jsons.Opt{jsons.UseIndent("", " ")}, opts...)
return &Arg{data: argument, opts: opts}
}

type Arg struct {
data any
opts []jsons.Opt
}

// String 实现 Stringer 接口,打印自身将会返回 JSON 字符串
func (a *Arg) String() string {
b, err := jsons.ToBytesE(a.data, a.opts...)
if err != nil {
return fmt.Sprintf("!(BADJSON|err=%+v|data=%#v)", err, a.data)
}
return conv.Bytes2String(b)
}
15 changes: 15 additions & 0 deletions arg/arg_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package arg_test

import (
"testing"

"code.gopub.tech/commons/arg"
)

func TestArgs(t *testing.T) {
data := map[string]any{"key": true}
t.Logf("%v", data)
t.Logf("%v", arg.JSON(data))
t.Logf("%v", arg.Indent(data))
t.Logf("%v", arg.JSON(arg.JSON))
}
88 changes: 88 additions & 0 deletions assert/assert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package assert

import (
"reflect"
"testing"

"code.gopub.tech/commons/fmts"
"code.gopub.tech/commons/values"
)

func Equal[T comparable](t *testing.T, got, want T, msgs ...any) {
if got != want { // 使用泛型确保入参类型一致, 避免 int(0) != int64(0) 的情况
t.Helper()
t.Errorf("[%v] assert equal failed: got %v(%T), want %v(%T).%s",
t.Name(), got, got, want, want, msg(msgs...))
}
}

func DeepEqual(t *testing.T, got, want any, msgs ...any) {
if !reflect.DeepEqual(got, want) {
t.Helper()
t.Errorf("[%v] assert deep equal failed: got %v(%T), want %v(%T).%s",
t.Name(), got, got, want, want, msg(msgs...))
}
}

func True(t *testing.T, cond bool, msgs ...any) {
if !cond {
t.Helper()
t.Errorf("[%v] assert true failed: got %v(%T).%s",
t.Name(), cond, cond, msg(msgs...))
}
}

func False(t *testing.T, cond bool, msgs ...any) {
if cond {
t.Helper()
t.Errorf("[%v] assert false failed: got %v(%T).%s",
t.Name(), cond, cond, msg(msgs...))
}
}

func Nil(t *testing.T, a any, msgs ...any) {
if !values.IsNil(a) {
t.Helper()
t.Errorf("[%v] assert nil failed: got %v(%T).%s",
t.Name(), a, a, msg(msgs...))
}
}

func NotNil(t *testing.T, a any, msgs ...any) {
if values.IsNil(a) {
t.Helper()
t.Errorf("[%v] assert not nil failed: got %v(%T).%s",
t.Name(), a, a, msg(msgs...))
}
}

func ShouldNotPanic(t *testing.T, fn func(), msgs ...any) {
t.Helper()
defer func() {
if x := recover(); x != nil {
t.Errorf("[%v] assert should not panic failed: got panic %v(%T).%s",
t.Name(), x, x, msg(append(msgs, x)...))
}
}()
fn()
}

func ShouldPanic(t *testing.T, fn func(), msgs ...any) {
t.Helper()
defer func() {
if recover() == nil {
t.Errorf("[%v] assert should panic failed: not panic.%s",
t.Name(), msg(msgs...))
}
}()
fn()
}

func msg(msgs ...any) string {
if len(msgs) > 0 {
if format, ok := msgs[0].(string); ok {
return fmts.Sprintf(" "+format, msgs[1:]...)
}
}
return ""
}
Loading

0 comments on commit ae1ba64

Please sign in to comment.