Skip to content
Closed
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
dbcd970
feat(errors): 添加错误接口和日志上下文功能
kooksee Jun 27, 2025
d78f7f6
feat(errors): 为错误添加唯一标识符
kooksee Jun 27, 2025
dc854bb
feat(errors): 为错误添加错误ID并优化日志记录
kooksee Jun 27, 2025
925c150
refactor(log): 调整导入路径
kooksee Jun 27, 2025
e412504
refactor(errors): 优化错误处理逻辑
kooksee Jun 27, 2025
cf4960b
feat(errors): 添加错误生成函数 NewErr
kooksee Jun 27, 2025
3a0b94c
feat(result): 添加错误包装函数- 在 Error 类型中添加 WrapErr 方法,用于包装错误并添加标签
kooksee Jun 27, 2025
77bee82
feat(result): 为 Error 类型添加 WithErr 方法
kooksee Jun 27, 2025
fa9638d
fix: barry quick fix, 2025-06-27 22:14:36
kooksee Jun 27, 2025
55ff163
refactor(v2): replace aherrcheck with resultchecker
kooksee Jun 27, 2025
6e0ee72
Merge remote-tracking branch 'origin/feat/error_id' into feat/error_id
kooksee Jun 28, 2025
1d4d293
fix(result): remove error wrapping in error handling
kooksee Jun 28, 2025
debe88d
refactor(errors): remove unused error ID field
kooksee Jun 28, 2025
8ba16e0
perf(errors): cache error ID in ErrWrap struct
kooksee Jun 28, 2025
5b2abd6
refactor(errors): replace repr with pretty for error formatting
kooksee Jun 28, 2025
2608440
refactor(log): improve error handling and logging
kooksee Jun 28, 2025
8741605
fix: barry quick fix, 2025-06-28 22:14:14
kooksee Jun 28, 2025
f70bbef
fix: barry quick fix, 2025-06-28 22:16:21
kooksee Jun 28, 2025
f758f62
feat(config): add environment variable configuration support
kooksee Jul 1, 2025
22f33d6
fix: barry quick fix, 2025-07-01 17:35:49
kooksee Jul 1, 2025
957cf56
Merge branch 'feat/error_id' of github.com:pubgo/funk into feat/error_id
kooksee Jul 1, 2025
a17c964
fix: barry quick fix, 2025-07-01 17:51:18
kooksee Jul 1, 2025
c1e41d3
fix: barry quick fix, 2025-07-02 10:59:56
kooksee Jul 2, 2025
2c40b3e
fix: barry quick fix, 2025-07-04 16:21:34
kooksee Jul 4, 2025
df93cb7
fix: barry quick fix, 2025-07-05 16:08:21
kooksee Jul 5, 2025
66fa286
fix: barry quick fix, 2025-07-05 19:51:48
kooksee Jul 5, 2025
94d8c7d
fix: barry quick fix, 2025-07-05 19:55:00
kooksee Jul 5, 2025
9a4ce8b
fix: barry quick fix, 2025-07-05 21:58:05
kooksee Jul 5, 2025
e7f9f75
fix: barry quick fix, 2025-07-19 00:08:03
kooksee Jul 18, 2025
2fd0eda
fix: barry quick fix, 2025-07-19 16:59:13
kooksee Jul 19, 2025
d7519f9
fix: barry quick fix, 2025-07-19 18:17:36
kooksee Jul 19, 2025
1f400ea
fix: barry quick fix, 2025-07-19 21:26:05
kooksee Jul 19, 2025
22f0d00
fix: barry quick fix, 2025-07-21 21:10:29
kooksee Jul 21, 2025
4389ef3
fix: barry quick fix, 2025-07-22 22:53:43
kooksee Jul 22, 2025
b0933a8
fix: barry quick fix, 2025-07-22 22:55:03
kooksee Jul 22, 2025
4eb2a65
fix: barry quick fix, 2025-07-23 23:22:57
kooksee Jul 23, 2025
0f4fae2
fix: barry quick fix, 2025-07-25 21:17:02
kooksee Jul 25, 2025
c2b6de1
fix: barry quick fix, 2025-07-25 22:02:30
kooksee Jul 25, 2025
059ce8c
fix: barry quick fix, 2025-07-25 22:07:26
kooksee Jul 25, 2025
d5c19c7
fix: barry quick fix, 2025-07-29 23:19:42
kooksee Jul 29, 2025
f0bf598
fix: barry quick fix, 2025-07-30 14:18:31
kooksee Jul 30, 2025
59c0949
fix: barry quick fix, 2025-07-30 21:31:06
kooksee Jul 30, 2025
51def87
fix: barry quick fix, 2025-08-11 16:42:02
kooksee Aug 11, 2025
a56d0ea
Merge branch 'feat/error_id' of github.com:pubgo/funk into feat/error_id
kooksee Aug 11, 2025
19f9b48
fix: barry quick fix, 2025-08-11 22:48:49
kooksee Aug 11, 2025
6d8d484
fix: barry quick fix, 2025-08-14 14:05:14
kooksee Aug 14, 2025
c21d839
fix: barry quick fix, 2025-08-15 15:17:50
kooksee Aug 15, 2025
c8dec7d
fix: barry@feat/error_id, 2025-08-16 17:11:28
kooksee Aug 16, 2025
c3fbd7e
fix: barry quick fix, 2025-08-19 20:27:49
kooksee Aug 19, 2025
78cea65
Merge branch 'feat/error_id' of github.com:pubgo/funk into feat/error_id
kooksee Aug 19, 2025
7366811
fix: barry@feat/error_id, 2025-08-20 14:16:44
kooksee Aug 20, 2025
149a5cb
Merge branch 'feat/error_id' of github.com:pubgo/funk into feat/error_id
kooksee Aug 20, 2025
b0220ea
fix: barry@feat/error_id, 2025-08-20 14:17:55
kooksee Aug 20, 2025
030ef4d
fix: barry@feat/error_id, 2025-08-20 14:18:09
kooksee Aug 20, 2025
065eb0c
fix: barry@feat/error_id, 2025-08-20 18:14:33
kooksee Aug 20, 2025
195d36a
fix: barry quick fix, 2025-08-20 21:05:52
kooksee Aug 20, 2025
2a812f4
fix: barry quick fix, 2025-08-21 22:30:03
kooksee Aug 21, 2025
3f9d1e2
fix: barry quick fix, 2025-08-21 22:32:47
kooksee Aug 21, 2025
4a3d1fb
fix: barry quick fix, 2025-08-21 22:46:21
kooksee Aug 21, 2025
2933d32
fix: barry quick fix, 2025-08-21 23:04:22
kooksee Aug 21, 2025
ad46d48
fix: barry@feat/error_id, 2025-08-22 18:05:48
kooksee Aug 22, 2025
34a2b17
fix: barry quick fix, 2025-08-22 20:44:36
kooksee Aug 22, 2025
1cd57fb
fix: barry quick fix, 2025-08-23 23:48:05
kooksee Aug 23, 2025
d731cdf
fix: barry quick fix, 2025-08-26 20:44:57
kooksee Aug 26, 2025
ffaae77
fix: barry quick fix, 2025-08-26 20:58:19
kooksee Aug 26, 2025
e03ae0e
refactor: rename errMust to errNilOrPanic
kooksee Sep 1, 2025
49c9c44
Merge branch 'feat/error_id' of github.com:pubgo/funk into feat/error_id
kooksee Sep 1, 2025
27551a6
fix: barry@feat/error_id, 2025-09-01 17:08:13
kooksee Sep 1, 2025
b9e9697
fix: barry@feat/error_id, 2025-09-02 18:27:30
kooksee Sep 2, 2025
bc36b0c
fix: barry@feat/error_id, 2025-09-02 18:35:59
kooksee Sep 2, 2025
7acbee2
fix: barry quick fix, 2025-09-02 21:17:33
kooksee Sep 2, 2025
e7ecadb
fix: barry quick fix, 2025-09-02 23:29:41
kooksee Sep 2, 2025
0db2995
fix: barry quick fix, 2025-09-04 21:40:32
kooksee Sep 4, 2025
10c55c0
fix: barry quick fix, 2025-09-04 22:10:19
kooksee Sep 4, 2025
79e6979
fix: barry quick fix, 2025-09-04 22:14:50
kooksee Sep 4, 2025
d1176b3
fix: barry quick fix, 2025-09-04 22:21:56
kooksee Sep 4, 2025
ed864db
fix: barry@feat/error_id, 2025-09-05 09:56:28
kooksee Sep 5, 2025
a7579d2
Merge branch 'feat/error_id' of github.com:pubgo/funk into feat/error_id
kooksee Sep 5, 2025
7e0f979
fix: barry quick fix, 2025-09-06 01:52:47
kooksee Sep 5, 2025
0b8e185
fix: barry quick fix, 2025-09-06 01:54:15
kooksee Sep 5, 2025
fad225d
fix: barry quick fix, 2025-09-06 02:03:54
kooksee Sep 5, 2025
2aeede8
fix: barry quick fix, 2025-09-06 12:51:59
kooksee Sep 6, 2025
171de64
fix: barry quick fix, 2025-09-06 13:36:08
kooksee Sep 6, 2025
155d563
fix: barry quick fix, 2025-09-06 14:00:45
kooksee Sep 6, 2025
cbaa02f
fix: barry quick fix, 2025-09-06 19:03:03
kooksee Sep 6, 2025
0aba861
fix: barry quick fix, 2025-09-06 19:17:48
kooksee Sep 6, 2025
ed6d56d
fix: barry quick fix, 2025-09-06 19:21:18
kooksee Sep 6, 2025
acdceea
fix: barry quick fix, 2025-09-06 19:29:21
kooksee Sep 6, 2025
79ea27d
fix: barry quick fix, 2025-09-06 22:16:48
kooksee Sep 6, 2025
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
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
}
Comment on lines +10 to +12

Choose a reason for hiding this comment

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

medium

The use of strings.HasSuffix can lead to false positives. For example, an argument like --some-option-h would be incorrectly identified as the -h help flag. A direct string comparison is safer.

Additionally, this implementation is fragile because it only checks the last command-line argument. If a help flag is provided anywhere else in the command, it will not be detected.

Suggested change
if strings.HasSuffix(help, "--help") || strings.HasSuffix(help, "-h") {
return true
}
if help == "--help" || help == "-h" {
return true
}

return false
}
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
42 changes: 42 additions & 0 deletions cmds/testmain/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"context"
"fmt"
"os"
"sort"

"github.com/moby/term"
"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/cliutils"
"github.com/pubgo/funk/cmds/versioncmd"
"github.com/pubgo/funk/ctxutil"
"github.com/pubgo/funk/version"
"github.com/urfave/cli/v3"
)

func main() {
app := &cli.Command{
Name: "testmain",
Suggest: true,
UseShortOptionHandling: true,
ShellComplete: cli.DefaultAppComplete,
Version: version.Version(),
Commands: []*cli.Command{
versioncmd.New(),
},
Before: func(ctx context.Context, command *cli.Command) (context.Context, error) {
if !term.IsTerminal(os.Stdin.Fd()) {
return ctx, fmt.Errorf("stdin is not a terminal")
}

if cliutils.IsHelp() {
return ctx, cli.ShowAppHelp(command)
}
return ctx, nil
},
}

sort.Sort(cli.FlagsByName(app.Flags))
assert.Exit(app.Run(ctxutil.Signal(), os.Args))
}
25 changes: 25 additions & 0 deletions cmds/versioncmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package versioncmd

import (
"context"
"fmt"

"github.com/urfave/cli/v3"

"github.com/pubgo/funk/pretty"
"github.com/pubgo/funk/recovery"
"github.com/pubgo/funk/running"
"github.com/pubgo/funk/version"
)

func New() *cli.Command {
return &cli.Command{
Name: "version",
Usage: fmt.Sprintf("%s version info", version.Project()),
Action: func(ctx context.Context, command *cli.Command) error {
defer recovery.Exit()
pretty.Println(running.GetSysInfo())
return nil
},
}
}
4 changes: 2 additions & 2 deletions component/cloudevent/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/nats-io/nats.go/jetstream"
ants "github.com/panjf2000/ants/v2"
"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/component/lifecycle"
"github.com/pubgo/funk/component/natsclient"
"github.com/pubgo/funk/errors"
"github.com/pubgo/funk/errors/errcheck"
Expand All @@ -22,7 +23,6 @@ import (
"github.com/pubgo/funk/try"
"github.com/pubgo/funk/typex"
"github.com/pubgo/funk/version"
"github.com/pubgo/lava/core/lifecycle"
"github.com/rs/zerolog"
"github.com/samber/lo"
"google.golang.org/protobuf/proto"
Expand Down Expand Up @@ -454,7 +454,7 @@ func (c *Client) doConsume() (r error) {
c.doConsumeHandler(streamName, consumerName, jobSubjects, concurrent),
c.doErrHandler(streamName, consumerName),
))
c.p.Lc.BeforeStop(func() { con.Stop() })
c.p.Lc.BeforeStop(lifecycle.WrapNoCtxErr(con.Stop))
}
}
return
Expand Down
4 changes: 2 additions & 2 deletions component/gormclient/migratecmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ func New(di *dix.Dix) *cli.Command {
Destination: &id,
},
},
Before: func(ctx context.Context, command *cli.Command) error {
Before: func(ctx context.Context, command *cli.Command) (context.Context, error) {
p := dix.Inject(di, new(params))
options.TableName = p.Db.TablePrefix + migrates.DefaultConfig.TableName
return nil
return ctx, nil
},
Commands: []*cli.Command{
{
Expand Down
37 changes: 37 additions & 0 deletions component/lifecycle/lifecycle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package lifecycle

import "context"

func WrapNoError(fn func(context.Context)) ExecFunc {
return func(ctx context.Context) error { fn(ctx); return nil }
}

func WrapNoCtx(fn func() error) ExecFunc {
return func(ctx context.Context) error { return fn() }
}

func WrapNoCtxErr(fn func()) ExecFunc {
return func(ctx context.Context) error { fn(); return nil }
}

type ExecFunc = func(context.Context) error

type Executor struct {
Exec ExecFunc
}

type Handler func(lc Lifecycle)

type Lifecycle interface {
AfterStop(f ExecFunc)
BeforeStop(f ExecFunc)
AfterStart(f ExecFunc)
BeforeStart(f ExecFunc)
}

type Getter interface {
GetAfterStops() []Executor
GetBeforeStops() []Executor
GetAfterStarts() []Executor
GetBeforeStarts() []Executor
}
4 changes: 2 additions & 2 deletions component/natsclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (

"github.com/nats-io/nats.go"
"github.com/pubgo/funk/assert"
"github.com/pubgo/funk/component/lifecycle"
"github.com/pubgo/funk/log"
"github.com/pubgo/funk/running"
"github.com/pubgo/lava/core/lifecycle"
)

type Param struct {
Expand Down Expand Up @@ -50,7 +50,7 @@ func New(p Param) *Client {

log.Info().Bool("is_connected", nc.IsConnected()).Msg("nats connection ...")

p.Lc.BeforeStop(func() { nc.Close() })
p.Lc.BeforeStop(lifecycle.WrapNoCtxErr(nc.Close))

return &Client{Param: p, logger: logger, Conn: nc}
}
3 changes: 3 additions & 0 deletions config/aaa.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ type Resources struct {

// PatchResources resource config not required to exist
PatchResources []string `yaml:"patch_resources"`

// PatchEnvs config file or path, not required to exist
PatchEnvs []string `yaml:"patch_envs"`
}
42 changes: 35 additions & 7 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,35 @@ func GetConfigData(cfgPath string) (_ []byte, gErr error) {

configBytes = result.Of(os.ReadFile(cfgPath)).Expect("failed to read config data: %s", cfgPath)
configBytes = result.Of(envsubst.Bytes(configBytes)).Expect("failed to handler config env data: %s", cfgPath)
configBytes = []byte(cfgFormat(string(configBytes), &config{workDir: filepath.Dir(cfgPath)}))
configBytes = cfgFormat(configBytes, &config{workDir: filepath.Dir(cfgPath)})
return configBytes, nil
}

func LoadFromPath[T any](val *T, cfgPath string) {
func loadEnvConfigMap(cfgPath string) EnvConfigMap {
var res Resources
configBytes := result.Of(os.ReadFile(cfgPath)).Expect("failed to read config data: %s", cfgPath)
assert.Must(yaml.Unmarshal(configBytes, &res), "failed to unmarshal resource config")

parentDir := filepath.Dir(cfgPath)
var envCfgMap EnvConfigMap
for _, envPath := range res.PatchEnvs {
envPath = filepath.Join(parentDir, envPath)
if pathutil.IsNotExist(envPath) {
log.Warn().Str("env_path", envPath).Msg("env config cfgPath not found")
continue
}

pathList := listAllPath(envPath).Expect("failed to list envPath: %s", envPath)
for _, p := range pathList {
envConfigBytes := result.Of(os.ReadFile(p)).Expect("failed to handler env config data, path=%s", p)
assert.MustF(yaml.Unmarshal(envConfigBytes, &envCfgMap), "failed to unmarshal env config, path=%s", p)
}
}
initEnv(envCfgMap)
return envCfgMap
}

func LoadFromPath[T any](val *T, cfgPath string) EnvConfigMap {
defer recovery.Exit(func(err error) error {
log.Err(err).Str("config_path", cfgPath).Msg("failed to load config")
return err
Expand All @@ -75,6 +99,8 @@ func LoadFromPath[T any](val *T, cfgPath string) {
Msg("config type not correct")
}

var envCfgMap = loadEnvConfigMap(cfgPath)

configBytes := result.Of(GetConfigData(cfgPath)).Expect("failed to handler config data")
defer recovery.Exit(func(err error) error {
log.Err(err).
Expand All @@ -90,7 +116,7 @@ func LoadFromPath[T any](val *T, cfgPath string) {
Str("config_data", string(configBytes)).
Str("config_path", cfgPath).
Msg("failed to unmarshal config")
return
return nil
}

parentDir := filepath.Dir(cfgPath)
Expand Down Expand Up @@ -160,11 +186,13 @@ func LoadFromPath[T any](val *T, cfgPath string) {
})...)

assert.Exit(Merge(val, cfgList...), "failed to merge config")
return envCfgMap
}

type Cfg[T any] struct {
T T
P *T
T T
P *T
EnvCfg *EnvConfigMap
}

func Load[T any]() Cfg[T] {
Expand All @@ -175,6 +203,6 @@ func Load[T any]() Cfg[T] {
}

var cfg T
LoadFromPath(&cfg, configPath)
return Cfg[T]{T: cfg, P: &cfg}
cfgMap := LoadFromPath(&cfg, configPath)
return Cfg[T]{T: cfg, P: &cfg, EnvCfg: lo.ToPtr(cfgMap)}
}
4 changes: 2 additions & 2 deletions config/configs/assets/assets.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
assets:
test_md:
test_abc:
secret: ${{embed("test.md")}}
path_dir: ${{get_path_dir()}}
secret: {{embed("test.md")}}
path_dir: {{get_path_dir()}}
32 changes: 32 additions & 0 deletions config/envs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package config

import (
"strings"

"github.com/pubgo/funk/env"
"github.com/samber/lo"
)

type EnvConfigMap map[string]*EnvConf

type EnvConf struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Default string `yaml:"default"`
Required bool `yaml:"required"`
Example string `yaml:"example"`
Versions string `yaml:"versions"`
Tags string `yaml:"tags"`
}

func initEnv(envMap EnvConfigMap) {
for name, cfg := range envMap {
envData := env.Get(name)
envData = strings.TrimSpace(lo.Ternary(envData != "", envData, cfg.Default))
if cfg.Required && envData == "" {
panic("env " + cfg.Name + " is required")
Copy link

Copilot AI Jul 28, 2025

Choose a reason for hiding this comment

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

The panic message should use proper formatting instead of string concatenation. Consider using fmt.Sprintf for better readability: fmt.Sprintf("required environment variable %s is missing", cfg.Name).

Suggested change
panic("env " + cfg.Name + " is required")
panic(fmt.Sprintf("env %s is required", cfg.Name))

Copilot uses AI. Check for mistakes.

Choose a reason for hiding this comment

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

medium

The panic message uses cfg.Name. However, the key of the envMap is name, which is the actual environment variable name being processed. If cfg.Name is not set in the YAML configuration, the panic message will be unhelpful (e.g., "env is required"). It would be more robust to use the map key name in the panic message.

Suggested change
panic("env " + cfg.Name + " is required")
panic("env " + name + " is required")

}

env.Set(name, envData).Must()
}
}
13 changes: 8 additions & 5 deletions config/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func unmarshalOneOrList[T any](list *[]T, value *yaml.Node) error {
if value.Kind == yaml.SequenceNode {
return value.Decode(list)
}
return errors.Format("unmarshalled node: %v", value.Value)
return errors.Errorf("unmarshalled node: %v", value.Value)
Copy link

Copilot AI Jul 28, 2025

Choose a reason for hiding this comment

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

The error message 'unmarshalled node' should be 'unmarshal node' - 'unmarshalled' is the past tense while 'unmarshal' is the action being attempted.

Suggested change
return errors.Errorf("unmarshalled node: %v", value.Value)
return errors.Errorf("unmarshal node: %v", value.Value)

Copilot uses AI. Check for mistakes.
}

func listAllPath(dirOrPath string) (ret result.Result[[]string]) {
Expand Down Expand Up @@ -220,6 +220,9 @@ func getEnvData(cfg *config) map[string]any {
"get_path_dir": func() string {
return cfg.workDir
},
"path_dir": func() string {
return cfg.workDir
},
"embed": func(name string) string {
if name == "" {
return ""
Expand All @@ -239,9 +242,9 @@ func getEnvData(cfg *config) map[string]any {
}
}

func cfgFormat(template string, cfg *config) string {
tpl := fasttemplate.New(template, "${{", "}}")
return tpl.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
func cfgFormat(template []byte, cfg *config) []byte {
tpl := fasttemplate.New(string(template), "{{", "}}")
return []byte(tpl.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
tag = strings.TrimSpace(tag)
evalData, err := eval(tag, cfg)
if err != nil {
Expand All @@ -257,7 +260,7 @@ func cfgFormat(template string, cfg *config) string {
}

return w.Write(bytes.TrimSpace(data))
})
}))
}

func eval(code string, cfg *config) (any, error) {
Expand Down
11 changes: 6 additions & 5 deletions config/util_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"bytes"
_ "embed"
"os"
"sort"
Expand Down Expand Up @@ -30,16 +31,16 @@ func TestExpr(t *testing.T) {
os.Setenv("testAbc", "hello")
env.Init()

assert.Equal(t, cfgFormat("${{env.TEST_ABC}}", &config{}), "hello")
assert.Equal(t, cfgFormat(`${{embed("configs/assets/secret")}}`, &config{}), strings.TrimSpace(`MTIzNDU2CjEyMzQ1NgoxMjM0NTYKMTIzNDU2CjEyMzQ1NgoxMjM0NTYKMTIzNDU2CjEyMzQ1Ng==`))
assert.Equal(t, string(cfgFormat([]byte("{{env.TEST_ABC}}"), &config{})), "hello")
assert.Equal(t, string(cfgFormat([]byte(`{{embed("configs/assets/secret")}}`), &config{})), strings.TrimSpace(`MTIzNDU2CjEyMzQ1NgoxMjM0NTYKMTIzNDU2CjEyMzQ1NgoxMjM0NTYKMTIzNDU2CjEyMzQ1Ng==`))

var dd, err = os.ReadFile("configs/assets/assets.yaml")
assert.NoError(t, err)
var dd1 = strings.TrimSpace(cfgFormat(string(dd), &config{workDir: "configs/assets"}))
var dd1 = bytes.TrimSpace(cfgFormat(dd, &config{workDir: "configs/assets"}))
var cfg testCfg
assert.NoError(t, yaml.Unmarshal([]byte(dd1), &cfg))
assert.NoError(t, yaml.Unmarshal(dd1, &cfg))

assert.Equal(t, dd1, strings.TrimSpace(genYaml))
assert.Equal(t, string(dd1), strings.TrimSpace(genYaml))
}

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