Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions assert/assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,42 @@ package assert

import (
"fmt"

"github.com/pubgo/funk/errors"
)

var EnablePrintStack bool

func Assert(b bool, format string, a ...interface{}) {
if b {
panic(errors.WrapStack(fmt.Errorf(format, a...)))
must(fmt.Errorf(format, a...))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider adding a comment here to explain what must does, as it's not immediately obvious from the name.

}
}

func If(b bool, format string, a ...interface{}) {
if b {
panic(errors.WrapStack(fmt.Errorf(format, a...)))
must(fmt.Errorf(format, a...))
}
}

func T(b bool, format string, a ...interface{}) {
if b {
panic(errors.WrapStack(fmt.Errorf(format, a...)))
must(fmt.Errorf(format, a...))
}
}

func Err(b bool, err error) {
if b {
panic(errors.WrapStack(err))
must(err)
}
}

func Fn(b bool, fn func() error) {
if b {
panic(errors.WrapStack(fn()))
must(fn())
}
}

func Lazy(lazy func() bool, err error) {
if lazy() {
panic(errors.WrapStack(err))
must(err)
}
}
15 changes: 9 additions & 6 deletions assert/assert_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
package assert
package assert_test

import (
"testing"

"github.com/pubgo/funk/errors"
"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/recovery"
)

func init() {
assert.EnablePrintStack = true
}

func TestCheckNil(t *testing.T) {
var a *int

defer func() {
errors.Debug(errors.Parse(recover()))
}()
defer recovery.DebugPrint()

Assert(a == nil, "ok")
assert.Assert(a == nil, "ok")
}
26 changes: 12 additions & 14 deletions assert/must.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,39 @@ package assert

import (
"fmt"
"log/slog"
"os"
"runtime/debug"

"github.com/pubgo/funk/errors"
"github.com/pubgo/funk/try"
)

func Must(err error, args ...interface{}) {
if err == nil {
return
}

panic(errors.WrapStack(errors.Wrap(err, fmt.Sprint(args...))))
must(err, args...)
}

func MustFn(errFn func() error, args ...interface{}) {
err := try.Try(errFn)
err := try(errFn)
if err == nil {
return
}

panic(errors.WrapStack(errors.Wrap(err, fmt.Sprint(args...))))
must(err, args...)
}

func MustF(err error, msg string, args ...interface{}) {
if err == nil {
return
}

panic(errors.WrapStack(errors.Wrap(err, fmt.Sprintf(msg, args...))))
must(err, fmt.Sprintf(msg, args...))
}

func Must1[T any](ret T, err error) T {
func Must1[T any](ret T, err error, args ...any) T {
if err != nil {
panic(errors.WrapStack(err))
must(err, args...)
}

return ret
Expand All @@ -47,18 +45,18 @@ func Exit(err error, args ...interface{}) {
return
}

errors.Debug(errors.WrapStack(errors.Wrap(err, fmt.Sprint(args...))))
slog.Error("os exit with error", "err", err, "msg", fmt.Sprint(args...))
debug.PrintStack()
os.Exit(1)
}

func ExitFn(errFn func() error, args ...interface{}) {
err := try.Try(errFn)
err := try(errFn)
if err == nil {
return
}

errors.Debug(errors.WrapStack(errors.Wrap(err, fmt.Sprint(args...))))
slog.Error("os exit with error func", "err", err, "msg", fmt.Sprint(args...))
debug.PrintStack()
os.Exit(1)
}
Expand All @@ -68,14 +66,14 @@ func ExitF(err error, msg string, args ...interface{}) {
return
}

errors.Debug(errors.WrapStack(errors.Wrapf(err, msg, args...)))
slog.Error("os exit with error format", "err", err, "msg", fmt.Sprintf(msg, args...))
debug.PrintStack()
os.Exit(1)
}

func Exit1[T any](ret T, err error) T {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

This function unconditionally calls os.Exit(1) which will terminate the program. This is a very severe action, and should only be done in exceptional circumstances. Consider if there are alternative error handling strategies that can be used instead, such as returning the error to the caller.

if err != nil {
errors.Debug(errors.WrapStack(err))
slog.Error("os exit with error unwrap", "err", err)
debug.PrintStack()
os.Exit(1)
}
Expand Down
15 changes: 8 additions & 7 deletions assert/must_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package assert
package assert_test

import (
"fmt"
"testing"

assert1 "github.com/pubgo/funk/assert"
"github.com/pubgo/funk/errors"
"github.com/stretchr/testify/assert"
)
Expand All @@ -23,12 +24,12 @@ func panicNoErr() (*errBase, error) {
func TestPanicErr(t *testing.T) {
is := assert.New(t)
is.Panics(func() {
ret := Must1(panicErr())
ret := assert1.Must1(panicErr())
fmt.Println(ret == nil)
})

is.NotPanics(func() {
ret := Must1(panicNoErr())
ret := assert1.Must1(panicNoErr())
fmt.Println(ret.msg)
})
}
Expand All @@ -37,22 +38,22 @@ func TestRespTest(t *testing.T) {
defer func() {
errors.Debug(errors.Parse(recover()))
}()
Must(init1Next())
assert1.Must(init1Next())
}

func TestRespNext(t *testing.T) {
Must(init1Next())
assert1.Must(init1Next())
}

func init1Next() (err error) {
Must(fmt.Errorf("test next"))
assert1.Must(fmt.Errorf("test next"))
return nil
}

func BenchmarkNoPanic(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = func() (err error) {
Must(nil)
assert1.Must(nil)
return
}()
}
Expand Down
66 changes: 66 additions & 0 deletions assert/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package assert

import (
"fmt"
"log/slog"
"runtime/debug"

"github.com/pubgo/funk/stack"
)

func messageFromMsgAndArgs(msgAndArgs ...any) string {
if len(msgAndArgs) == 0 {
return ""
}

if len(msgAndArgs) == 1 {
if msgAsStr, ok := msgAndArgs[0].(string); ok {
return msgAsStr
}
return fmt.Sprintf("%+v", msgAndArgs[0])
}

return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
}

func must(err error, messageArgs ...any) {
if err == nil {
return
}

message := messageFromMsgAndArgs(messageArgs...)
if message == "" {
message = err.Error()
} else {
message = fmt.Sprintf("msg:%s err:%s", message, err.Error())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider whether including the original error message in the formatted message is always desirable. It could lead to redundant information in some cases. Perhaps provide an option to control this behavior.

}

if EnablePrintStack {
slog.Error(message)
debug.PrintStack()
}

panic(message)
}

func try(fn func() error) (gErr error) {
if fn == nil {
gErr = fmt.Errorf("[fn] is nil")
return
}

defer func() {
if gErr != nil {
gErr = fmt.Errorf("stack:%s, err:%w", stack.CallerWithFunc(fn).String(), gErr)
}
}()

defer func() {
if err := recover(); err != nil {
gErr = fmt.Errorf("%v", err)
}
}()

gErr = fn()
return
}
14 changes: 14 additions & 0 deletions cliutils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package cliutils

import (
"os"
"strings"
)

func IsHelp() bool {
help := strings.TrimSpace(os.Args[len(os.Args)-1])
if strings.HasSuffix(help, "--help") || strings.HasSuffix(help, "-h") {
return true
}
return false
}
14 changes: 8 additions & 6 deletions cmds/configcmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"context"
"fmt"

"github.com/pubgo/dix"
"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/config"
"github.com/urfave/cli/v3"
"gopkg.in/yaml.v3"

"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/config"
"github.com/pubgo/funk/recovery"
)

func New[Cfg any](di *dix.Dix) *cli.Command {
func New[Cfg any]() *cli.Command {
return &cli.Command{
Name: "config",
Usage: "config management",
Expand All @@ -20,8 +21,9 @@ func New[Cfg any](di *dix.Dix) *cli.Command {
Name: "show",
Description: "show config data",
Action: func(ctx context.Context, command *cli.Command) error {
fmt.Println("config path:", config.GetConfigPath())
fmt.Println("config raw data:", string(assert.Must1(yaml.Marshal(config.Load[Cfg]().T))))
defer recovery.Exit()
fmt.Println("config path:\n", config.GetConfigPath())
fmt.Println("config raw data:\n", string(assert.Must1(yaml.Marshal(config.Load[Cfg]().T))))
return nil
},
},
Expand Down
37 changes: 37 additions & 0 deletions cmds/envcmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package envcmd

import (
"context"
"fmt"

"github.com/urfave/cli/v3"

"github.com/pubgo/funk/config"
"github.com/pubgo/funk/env"
"github.com/pubgo/funk/pretty"
"github.com/pubgo/funk/recovery"
)

func New() *cli.Command {
return &cli.Command{
Name: "envs",
Usage: "show all envs",
Action: func(ctx context.Context, command *cli.Command) error {
defer recovery.Exit()

env.Reload()

fmt.Println("config path:", config.GetConfigPath())
envs := config.LoadEnvConfigMap(config.GetConfigPath())
for name, cfg := range envs {
envData := env.Get(name)
if envData != "" {
cfg.Default = envData
}
}

pretty.Println(envs)
return nil
},
}
}
2 changes: 1 addition & 1 deletion cmds/protoc-gen-go-cloudevent/internal/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.Generated
info := subjects[subName]
var keyName = fmt.Sprintf("%sCloudEventKey", info.mth.GoName)
genFile.Commentf("%s /%s/%s", keyName, info.srv.Desc.FullName(), info.mth.GoName)
genFile.Commentf(strings.TrimSpace(info.mth.Comments.Leading.String()))
genFile.Comment(strings.TrimSpace(info.mth.Comments.Leading.String()))
genFile.Const().
Id(keyName).
Op("=").
Expand Down
2 changes: 1 addition & 1 deletion cmds/protoc-gen-go-enum/internal/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
filename := file.GeneratedFilenamePrefix + ".pb.enum.go"
genFile := jen.NewFile(string(file.GoPackageName))
genFile.HeaderComment("Code generated by protoc-gen-go-sql. DO NOT EDIT.")
genFile.HeaderComment("Code generated by protoc-gen-go-enum. DO NOT EDIT.")
genFile.HeaderComment("versions:")
genFile.HeaderComment(fmt.Sprintf("- protoc-gen-go-enum %s", version))
genFile.HeaderComment(fmt.Sprintf("- protoc %s", protocVersion(gen)))
Expand Down
Loading
Loading