Bump github.com/gookit/config/v2 from 2.2.2 to 2.2.3

Bumps [github.com/gookit/config/v2](https://github.com/gookit/config) from 2.2.2 to 2.2.3.
- [Release notes](https://github.com/gookit/config/releases)
- [Commits](https://github.com/gookit/config/compare/v2.2.2...v2.2.3)

---
updated-dependencies:
- dependency-name: github.com/gookit/config/v2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot]
2023-08-30 10:01:43 +00:00
committed by Ralf Haferkamp
parent 69bd2c24a7
commit 0aafeccb93
20 changed files with 335 additions and 182 deletions

4
go.mod
View File

@@ -44,7 +44,7 @@ require (
github.com/google/go-cmp v0.5.9
github.com/google/go-tika v0.3.0
github.com/google/uuid v1.3.1
github.com/gookit/config/v2 v2.2.2
github.com/gookit/config/v2 v2.2.3
github.com/gorilla/mux v1.8.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.2
github.com/jellydator/ttlcache/v2 v2.11.1
@@ -213,7 +213,7 @@ require (
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect
github.com/google/renameio/v2 v2.0.0 // indirect
github.com/gookit/color v1.5.3 // indirect
github.com/gookit/goutil v0.6.9 // indirect
github.com/gookit/goutil v0.6.10 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/gorilla/schema v1.2.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect

8
go.sum
View File

@@ -1242,10 +1242,10 @@ github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+
github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g=
github.com/gookit/color v1.5.3 h1:twfIhZs4QLCtimkP7MOxlF3A0U/5cDPseRT9M/+2SCE=
github.com/gookit/color v1.5.3/go.mod h1:NUzwzeehUfl7GIb36pqId+UGmRfQcU/WiiyTTeNjHtE=
github.com/gookit/config/v2 v2.2.2 h1:/iVW3H/5oPdNulrjSI370kf14Hs6D4Gc5E15u0AYxX8=
github.com/gookit/config/v2 v2.2.2/go.mod h1:9wXrsGnOc9nLTr4mU+tuaR0ORzFyZdf3q5DuqsTyodU=
github.com/gookit/goutil v0.6.9 h1:NrbGKt3cnWoqxjZonC5bTr0FrltTCRdzGReGQwnwhUk=
github.com/gookit/goutil v0.6.9/go.mod h1:ZYNl/t+EIMo0rCRe1mwfC7jKyF/q1FdOEOgrXzJpr5o=
github.com/gookit/config/v2 v2.2.3 h1:GlnYPduYeY7lRgWQmGld9juy0xpFUo06BUC9Pzyjuew=
github.com/gookit/config/v2 v2.2.3/go.mod h1:FhmMu+2wg0UhyOjVGo+DZ1+ov34q4G4aWXzh86boEsY=
github.com/gookit/goutil v0.6.10 h1:iq7CXOf+fYLvrVAh3+ZoLgufGfK65TwbzE8NpnPGtyk=
github.com/gookit/goutil v0.6.10/go.mod h1:qqrPoX+Pm6YmxqqccgkNLPirTFX7UYMES1SK+fokqQU=
github.com/gookit/ini/v2 v2.2.2 h1:3B8abZJrVH1vi/7TU4STuTBxdhiAq1ORSt6NJZCahaI=
github.com/gophercloud/gophercloud v0.15.1-0.20210202035223-633d73521055/go.mod h1:wRtmUelyIIv3CSSDI47aUwbs075O6i+LY+pXsKCBsb4=
github.com/gophercloud/gophercloud v0.16.0/go.mod h1:wRtmUelyIIv3CSSDI47aUwbs075O6i+LY+pXsKCBsb4=

View File

@@ -90,23 +90,21 @@ func (c *Config) Structure(key string, dst any) error {
}
}
// init default value by tag: default
if c.opts.ParseDefault {
err := structs.InitDefaults(dst, func(opt *structs.InitOptions) {
opt.ParseEnv = c.opts.ParseEnv
})
if err != nil {
return err
}
}
bindConf := c.opts.makeDecoderConfig()
// set result struct ptr
bindConf.Result = dst
decoder, err := mapstructure.NewDecoder(bindConf)
if err == nil {
err = decoder.Decode(data)
if err = decoder.Decode(data); err != nil {
return err
}
}
// init default value by tag: default
if c.opts.ParseDefault {
err = structs.InitDefaults(dst, func(opt *structs.InitOptions) {
opt.ParseEnv = c.opts.ParseEnv
})
}
return err
}

View File

@@ -18,7 +18,7 @@
- [`envutil`](./envutil) ENV util for current runtime env information. eg: get one, get info, parse var
- [`fmtutil`](./fmtutil) Format data util functions. eg: data, size, time
- [`fsutil`](./fsutil) Filesystem util functions, quick create, read and write file. eg: file and dir check, operate
- [`jsonutil`](./jsonutil) some util functions for quick read, write, encode, decode JSON data.
- [`jsonutil`](./jsonutil) Provide some util functions for quick read, write, encode, decode JSON data.
- [`maputil`](./maputil) Map data util functions. eg: convert, sub-value get, simple merge
- [`mathutil`](./mathutil) Math(int, number) util functions. eg: convert, math calc, random
- `netutil` Network util functions
@@ -35,16 +35,19 @@
- [cmdline](./cliutil/cmdline) Provide cmdline parse, args build to cmdline
- [`dump`](./dump): GO value printing tool. print slice, map will auto wrap each element and display the call location
- [`errorx`](./errorx) Provide an enhanced error implements for go, allow with stacktrace and wrap another error.
- [`finder`](./fsutil/finder) Provides a simple and convenient filedir lookup function, supports filtering, excluding, matching, ignoring, etc.
- net util:
- [httpreq](netutil/httpreq) An easier-to-use HTTP client that wraps http.Client
- string util:
- [textscan](strutil/textscan) Implemented a parser that quickly scans and analyzes text content. It can be used to parse INI, Properties and other formats
- sys util:
- [textutil](strutil/textutil) Provide some extensions text handle util functions. eg: text replace, etc.
- system util:
- [clipboard](./sysutil/clipboard) Provide a simple clipboard read and write operations.
- [cmdr](./sysutil/cmdr) Provide for quick build and run a cmd, batch run multi cmd tasks
- [process](./sysutil/process) Provide some process handle util functions.
- [`testutil`](./testutil) Test help util functions. eg: http test, mock ENV value
- [assert](./testutil/assert) Asserts functions for help testing
- [`testutil`](testutil) Test help util functions. eg: http test, mock ENV value
- [assert](testutil/assert) Provides commonly asserts functions for help testing
- [fakeobj](testutil/fakeobj) provides a fake object for testing. such as fake fs.File, fs.FileInfo, fs.DirEntry etc.
- [`timex`](./timex) Provides an enhanced time.Time implementation. Add more commonly used functional methods
- such as: DayStart(), DayAfter(), DayAgo(), DateFormat() and more.
@@ -174,27 +177,6 @@ ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"}
```
### Basefn
> Package `github.com/gookit/goutil/basefn`
```go
// source at basefn/basefunc.go
func Panicf(format string, v ...any)
func MustOK(err error)
func Must[T any](v T, err error) T
func ErrOnFail(cond bool, err error) error
func OrError(cond bool, err error) error
func FirstOr[T any](sl []T, elseVal T) T
func OrValue[T any](cond bool, okVal, elVal T) T
func OrReturn[T any](cond bool, okFn, elseFn func() T) T
func CallOn(cond bool, fn ErrFunc) error
func CallOrElse(cond bool, okFn, elseFn ErrFunc) error
// source at basefn/extfunc.go
func DataSize(size uint64) string
func HowLongAgo(sec int64) string
```
### Bytes Utils
> Package `github.com/gookit/goutil/byteutil`
@@ -686,9 +668,11 @@ func PathMatch(pattern, s string) bool
func SearchNameUp(dirPath, name string) string
func SearchNameUpx(dirPath, name string) (string, bool)
func WalkDir(dir string, fn fs.WalkDirFunc) error
func Glob(pattern string, fls ...comdef.StringMatchFunc) []string
func GlobWithFunc(pattern string, fn func(filePath string) error) (err error)
func OnlyFindDir(_ string, ent fs.DirEntry) bool
func OnlyFindFile(_ string, ent fs.DirEntry) bool
func ExcludeNames(names ...string) FilterFunc
func IncludeSuffix(ss ...string) FilterFunc
func ExcludeDotFile(_ string, ent fs.DirEntry) bool
func ExcludeSuffix(ss ...string) FilterFunc
@@ -739,6 +723,7 @@ func RmIfExist(fPath string) error
func DeleteIfExist(fPath string) error
func RmFileIfExist(fPath string) error
func DeleteIfFileExist(fPath string) error
func RemoveSub(dirPath string, fns ...FilterFunc) error
func Unzip(archive, targetDir string) (err error)
// source at fsutil/opread.go
func NewIOReader(in any) (r io.Reader, err error)
@@ -833,6 +818,7 @@ func CombineToMap[K comdef.SortedType, V any](keys []K, values []V) map[K]V
func ToAnyMap(mp any) map[string]any
func TryAnyMap(mp any) (map[string]any, error)
func HTTPQueryString(data map[string]any) string
func StringsMapToAnyMap(ssMp map[string][]string) map[string]any
func ToString(mp map[string]any) string
func ToString2(mp any) string
func FormatIndent(mp any, indent string) string
@@ -844,6 +830,7 @@ func NewFormatter(mp any) *MapFormatter
func DeepGet(mp map[string]any, path string) (val any)
func QuietGet(mp map[string]any, path string) (val any)
func GetByPath(path string, mp map[string]any) (val any, ok bool)
func GetByPathKeys(mp map[string]any, keys []string) (val any, ok bool)
func Keys(mp any) (keys []string)
func Values(mp any) (values []any)
func EachAnyMap(mp any, fn func(key string, val any))
@@ -1065,10 +1052,10 @@ func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error)
// source at structs/copy.go
func MapStruct(srcSt, dstSt any)
// source at structs/data.go
func NewLiteData(data map[string]any) *Data
func NewData() *Data
func NewOrderedMap(len int) *OrderedMap
// source at structs/init.go
func InitStructSlice(opt *InitOptions)
func Init(ptr any, optFns ...InitOptFunc) error
func InitDefaults(ptr any, optFns ...InitOptFunc) error
// source at structs/structs.go
@@ -1217,6 +1204,7 @@ func Rtrim(s string, cutSet ...string) string
func RTrim(s string, cutSet ...string) string
func TrimRight(s string, cutSet ...string) string
func FilterEmail(s string) string
func Filter(ss []string, fls ...comdef.StringMatchFunc) []string
// source at strutil/format.go
func Title(s string) string
func Lower(s string) string
@@ -1354,8 +1342,8 @@ func Workdir() string
func BinDir() string
func BinName() string
func BinFile() string
func Open(fileOrUrl string) error
func OpenBrowser(fileOrUrl string) error
func Open(fileOrURL string) error
func OpenBrowser(fileOrURL string) error
func OpenFile(path string) error
// source at sysutil/sysutil_nonwin.go
func Kill(pid int, signal syscall.Signal) error
@@ -1381,7 +1369,7 @@ func ExpandPath(path string) string
func ExpandHome(path string) string
// source at sysutil/user_nonwin.go
func ChangeUserByName(newUname string) (err error)
func ChangeUserUidGid(newUid int, newGid int) (err error)
func ChangeUserUidGid(newUID int, newGid int) (err error)
```
### Testing Utils
@@ -1390,7 +1378,7 @@ func ChangeUserUidGid(newUid int, newGid int) (err error)
```go
// source at testutil/buffer.go
func NewBuffer() *Buffer
func NewBuffer() *byteutil.Buffer
// source at testutil/envmock.go
func MockEnvValue(key, val string, fn func(nv string))
func MockEnvValues(kvMap map[string]string, fn func())
@@ -1400,10 +1388,15 @@ func ClearOSEnv()
func RevertOSEnv()
func MockCleanOsEnv(mp map[string]string, fn func())
// source at testutil/fsmock.go
func NewDirEnt(fpath string, isDir ...bool) *DirEnt
func NewDirEnt(fpath string, isDir ...bool) *fakeobj.DirEntry
// source at testutil/httpmock.go
func NewHttpRequest(method, path string, data *MD) *http.Request
func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder
func TestMain(m *testing.M)
func NewEchoServer() *httptest.Server
func BuildEchoReply(r *http.Request) *EchoReply
func ParseRespToReply(w *http.Response) *EchoReply
func ParseBodyToReply(bd io.ReadCloser) *EchoReply
// source at testutil/testutil.go
func DiscardStdout() error
func ReadOutput() (s string)

View File

@@ -33,16 +33,19 @@
- [`cflag`](./cflag): 包装和扩展 go `flag.FlagSet` 以方便快速的构建简单的命令行应用程序
- [`dump`](./dump) GO变量打印工具打印 slice, map 会自动换行显示每个元素,同时会显示打印调用位置
- [`errorx`](./errorx) 为 go 提供增强的错误实现,允许带有堆栈跟踪信息和包装另一个错误。
- strutil:
- [`finder`](./fsutil/finder) 提供简单方便的file/dir查找功能支持过滤、排除、匹配、忽略等。
- netutil:
- `netutil/httpreq` 包装 http.Client 实现的更加易于使用的HTTP客户端
- strutil:
- [textscan](strutil/textscan) 实现了一个快速扫描和分析文本内容的解析器. 可用于解析 INI, Properties 等格式内容
- [textutil](strutil/textutil) 提供一些常用的扩展文本处理功能函数。
- sysutil:
- [clipboard](sysutil/clipboard) 提供简单的剪贴板读写操作工具库
- [cmdr](sysutil/cmdr) 提供快速构建和运行一个cmd批量运行多个cmd任务
- [process](./sysutil/process) 提供一些进程操作相关的实用功能。
- [process](sysutil/process) 提供一些进程操作相关的实用功能。
- [`testutil`](testutil) test help 相关操作的函数工具包. eg: http test, mock ENV value
- [assert](testutil/assert) 用于帮助测试的断言函数工具包
- [assert](testutil/assert) 用于帮助测试的断言函数工具包,方便编写单元测试。
- [fakeobj](testutil/fakeobj) 提供一些接口的假的实现,用于模拟测试. 例如 fs.File, fs.FileInfo, fs.DirEntry 等等.
- [`timex`](timex) 提供增强的 time.Time 实现。添加更多常用的功能方法
- 提供类似 `Y-m-d H:i:s` 的日期时间格式解析处理
- 例如: DayStart(), DayAfter(), DayAgo(), DateFormat() 等等
@@ -173,27 +176,6 @@ ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"}
```
### Basefn
> Package `github.com/gookit/goutil/basefn`
```go
// source at basefn/basefunc.go
func Panicf(format string, v ...any)
func MustOK(err error)
func Must[T any](v T, err error) T
func ErrOnFail(cond bool, err error) error
func OrError(cond bool, err error) error
func FirstOr[T any](sl []T, elseVal T) T
func OrValue[T any](cond bool, okVal, elVal T) T
func OrReturn[T any](cond bool, okFn, elseFn func() T) T
func CallOn(cond bool, fn ErrFunc) error
func CallOrElse(cond bool, okFn, elseFn ErrFunc) error
// source at basefn/extfunc.go
func DataSize(size uint64) string
func HowLongAgo(sec int64) string
```
### Bytes Utils
> Package `github.com/gookit/goutil/byteutil`
@@ -687,9 +669,11 @@ func PathMatch(pattern, s string) bool
func SearchNameUp(dirPath, name string) string
func SearchNameUpx(dirPath, name string) (string, bool)
func WalkDir(dir string, fn fs.WalkDirFunc) error
func Glob(pattern string, fls ...comdef.StringMatchFunc) []string
func GlobWithFunc(pattern string, fn func(filePath string) error) (err error)
func OnlyFindDir(_ string, ent fs.DirEntry) bool
func OnlyFindFile(_ string, ent fs.DirEntry) bool
func ExcludeNames(names ...string) FilterFunc
func IncludeSuffix(ss ...string) FilterFunc
func ExcludeDotFile(_ string, ent fs.DirEntry) bool
func ExcludeSuffix(ss ...string) FilterFunc
@@ -740,6 +724,7 @@ func RmIfExist(fPath string) error
func DeleteIfExist(fPath string) error
func RmFileIfExist(fPath string) error
func DeleteIfFileExist(fPath string) error
func RemoveSub(dirPath string, fns ...FilterFunc) error
func Unzip(archive, targetDir string) (err error)
// source at fsutil/opread.go
func NewIOReader(in any) (r io.Reader, err error)
@@ -834,6 +819,7 @@ func CombineToMap[K comdef.SortedType, V any](keys []K, values []V) map[K]V
func ToAnyMap(mp any) map[string]any
func TryAnyMap(mp any) (map[string]any, error)
func HTTPQueryString(data map[string]any) string
func StringsMapToAnyMap(ssMp map[string][]string) map[string]any
func ToString(mp map[string]any) string
func ToString2(mp any) string
func FormatIndent(mp any, indent string) string
@@ -845,6 +831,7 @@ func NewFormatter(mp any) *MapFormatter
func DeepGet(mp map[string]any, path string) (val any)
func QuietGet(mp map[string]any, path string) (val any)
func GetByPath(path string, mp map[string]any) (val any, ok bool)
func GetByPathKeys(mp map[string]any, keys []string) (val any, ok bool)
func Keys(mp any) (keys []string)
func Values(mp any) (values []any)
func EachAnyMap(mp any, fn func(key string, val any))
@@ -1066,10 +1053,10 @@ func StructToMap(st any, optFns ...MapOptFunc) (map[string]any, error)
// source at structs/copy.go
func MapStruct(srcSt, dstSt any)
// source at structs/data.go
func NewLiteData(data map[string]any) *Data
func NewData() *Data
func NewOrderedMap(len int) *OrderedMap
// source at structs/init.go
func InitStructSlice(opt *InitOptions)
func Init(ptr any, optFns ...InitOptFunc) error
func InitDefaults(ptr any, optFns ...InitOptFunc) error
// source at structs/structs.go
@@ -1218,6 +1205,7 @@ func Rtrim(s string, cutSet ...string) string
func RTrim(s string, cutSet ...string) string
func TrimRight(s string, cutSet ...string) string
func FilterEmail(s string) string
func Filter(ss []string, fls ...comdef.StringMatchFunc) []string
// source at strutil/format.go
func Title(s string) string
func Lower(s string) string
@@ -1355,8 +1343,8 @@ func Workdir() string
func BinDir() string
func BinName() string
func BinFile() string
func Open(fileOrUrl string) error
func OpenBrowser(fileOrUrl string) error
func Open(fileOrURL string) error
func OpenBrowser(fileOrURL string) error
func OpenFile(path string) error
// source at sysutil/sysutil_nonwin.go
func Kill(pid int, signal syscall.Signal) error
@@ -1382,7 +1370,7 @@ func ExpandPath(path string) string
func ExpandHome(path string) string
// source at sysutil/user_nonwin.go
func ChangeUserByName(newUname string) (err error)
func ChangeUserUidGid(newUid int, newGid int) (err error)
func ChangeUserUidGid(newUID int, newGid int) (err error)
```
### Testing Utils
@@ -1391,7 +1379,7 @@ func ChangeUserUidGid(newUid int, newGid int) (err error)
```go
// source at testutil/buffer.go
func NewBuffer() *Buffer
func NewBuffer() *byteutil.Buffer
// source at testutil/envmock.go
func MockEnvValue(key, val string, fn func(nv string))
func MockEnvValues(kvMap map[string]string, fn func())
@@ -1401,10 +1389,15 @@ func ClearOSEnv()
func RevertOSEnv()
func MockCleanOsEnv(mp map[string]string, fn func())
// source at testutil/fsmock.go
func NewDirEnt(fpath string, isDir ...bool) *DirEnt
func NewDirEnt(fpath string, isDir ...bool) *fakeobj.DirEntry
// source at testutil/httpmock.go
func NewHttpRequest(method, path string, data *MD) *http.Request
func MockRequest(h http.Handler, method, path string, data *MD) *httptest.ResponseRecorder
func TestMain(m *testing.M)
func NewEchoServer() *httptest.Server
func BuildEchoReply(r *http.Request) *EchoReply
func ParseRespToReply(w *http.Response) *EchoReply
func ParseBodyToReply(bd io.ReadCloser) *EchoReply
// source at testutil/testutil.go
func DiscardStdout() error
func ReadOutput() (s string)

View File

@@ -3,12 +3,14 @@ package byteutil
import (
"bytes"
"fmt"
"strings"
)
// Buffer wrap and extends the bytes.Buffer
// Buffer wrap and extends the bytes.Buffer, add some useful methods
type Buffer struct {
bytes.Buffer
// custom error for testing
CloseErr error
FlushErr error
}
// NewBuffer instance
@@ -16,45 +18,87 @@ func NewBuffer() *Buffer {
return &Buffer{}
}
// WriteAny type value to buffer
func (b *Buffer) WriteAny(vs ...any) {
for _, v := range vs {
_, _ = b.Buffer.WriteString(fmt.Sprint(v))
}
}
// QuietWriteByte to buffer
func (b *Buffer) QuietWriteByte(c byte) {
// PrintByte to buffer, ignore error. alias of WriteByte()
func (b *Buffer) PrintByte(c byte) {
_ = b.WriteByte(c)
}
// QuietWritef write message to buffer
func (b *Buffer) QuietWritef(tpl string, vs ...any) {
// WriteStr1 quiet write one string to buffer
func (b *Buffer) WriteStr1(s string) {
b.writeStringNl(s, false)
}
// WriteStr1Nl quiet write one string and end with newline
func (b *Buffer) WriteStr1Nl(s string) {
b.writeStringNl(s, true)
}
// writeStringNl quiet write one string and end with newline
func (b *Buffer) writeStringNl(s string, nl bool) {
_, _ = b.Buffer.WriteString(s)
if nl {
_ = b.WriteByte('\n')
}
}
// WriteStr quiet write strings to buffer
func (b *Buffer) WriteStr(ss ...string) {
b.writeStringsNl(ss, false)
}
// WriteStrings to buffer, ignore error.
func (b *Buffer) WriteStrings(ss []string) {
b.writeStringsNl(ss, false)
}
// WriteStringNl write message to buffer and end with newline
func (b *Buffer) WriteStringNl(ss ...string) {
b.writeStringsNl(ss, true)
}
// writeStringsNl to buffer, ignore error.
func (b *Buffer) writeStringsNl(ss []string, nl bool) {
for _, s := range ss {
_, _ = b.Buffer.WriteString(s)
}
if nl {
_ = b.WriteByte('\n')
}
}
// WriteAny type value to buffer
func (b *Buffer) WriteAny(vs ...any) {
b.writeAnysWithNl(vs, false)
}
// Writeln write values to buffer and end with newline
func (b *Buffer) Writeln(vs ...any) {
b.writeAnysWithNl(vs, true)
}
// WriteAnyNl type value to buffer and end with newline
func (b *Buffer) WriteAnyNl(vs ...any) {
b.writeAnysWithNl(vs, true)
}
// WriteAnyLn type value to buffer and end with newline
func (b *Buffer) writeAnysWithNl(vs []any, nl bool) {
for _, v := range vs {
_, _ = b.Buffer.WriteString(fmt.Sprint(v))
}
if nl {
_ = b.WriteByte('\n')
}
}
// Printf quiet write message to buffer, ignore error.
func (b *Buffer) Printf(tpl string, vs ...any) {
_, _ = b.WriteString(fmt.Sprintf(tpl, vs...))
}
// Writeln write message to buffer with newline
func (b *Buffer) Writeln(ss ...string) {
b.QuietWriteln(ss...)
}
// QuietWriteln write message to buffer with newline
func (b *Buffer) QuietWriteln(ss ...string) {
_, _ = b.WriteString(strings.Join(ss, ""))
_ = b.WriteByte('\n')
}
// QuietWriteString to buffer
func (b *Buffer) QuietWriteString(ss ...string) {
_, _ = b.WriteString(strings.Join(ss, ""))
}
// MustWriteString to buffer
func (b *Buffer) MustWriteString(ss ...string) {
_, err := b.WriteString(strings.Join(ss, ""))
if err != nil {
panic(err)
}
// ResetGet buffer string. alias of ResetAndGet()
func (b *Buffer) ResetGet() string {
return b.ResetAndGet()
}
// ResetAndGet buffer string.
@@ -63,3 +107,13 @@ func (b *Buffer) ResetAndGet() string {
b.Reset()
return s
}
// Close buffer
func (b *Buffer) Close() error {
return b.CloseErr
}
// Flush buffer
func (b *Buffer) Flush() error {
return b.FlushErr
}

View File

@@ -20,6 +20,19 @@ type StringWriteStringer interface {
fmt.Stringer
}
// StringMatcher interface
type StringMatcher interface {
Match(s string) bool
}
// StringMatchFunc definition
type StringMatchFunc func(s string) bool
// Match satisfies the StringMatcher interface
func (fn StringMatchFunc) Match(s string) bool {
return fn(s)
}
type (
// MarshalFunc define
MarshalFunc func(v any) ([]byte, error)

View File

@@ -3,9 +3,11 @@ package fsutil
import (
"io/fs"
"os"
"path"
"path/filepath"
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/strutil"
)
@@ -43,11 +45,37 @@ func SearchNameUpx(dirPath, name string) (string, bool) {
// WalkDir walks the file tree rooted at root, calling fn for each file or
// directory in the tree, including root.
//
// TIP: will recursively find in sub dirs.
func WalkDir(dir string, fn fs.WalkDirFunc) error {
return filepath.WalkDir(dir, fn)
}
// GlobWithFunc handle matched file
// Glob find files by glob path pattern. alias of filepath.Glob()
// and support filter matched files by name.
//
// Usage:
//
// files := fsutil.Glob("/path/to/dir/*.go")
func Glob(pattern string, fls ...comdef.StringMatchFunc) []string {
files, _ := filepath.Glob(pattern)
if len(fls) == 0 || len(files) == 0 {
return files
}
var matched []string
for _, file := range files {
for _, fn := range fls {
if fn(path.Base(file)) {
matched = append(matched, file)
break
}
}
}
return matched
}
// GlobWithFunc find files by glob path pattern, then handle matched file
//
// - TIP: will be not find in subdir.
func GlobWithFunc(pattern string, fn func(filePath string) error) (err error) {

View File

@@ -74,6 +74,30 @@ func HTTPQueryString(data map[string]any) string {
return strings.Join(ss, "&")
}
// StringsMapToAnyMap convert map[string][]string to map[string]any
//
// Example:
// {"k1": []string{"v1", "v2"}, "k2": []string{"v3"}}
// =>
// {"k": []string{"v1", "v2"}, "k2": "v3"}
//
// mp := StringsMapToAnyMap(httpReq.Header)
func StringsMapToAnyMap(ssMp map[string][]string) map[string]any {
if len(ssMp) == 0 {
return nil
}
anyMp := make(map[string]any, len(ssMp))
for k, v := range ssMp {
if len(v) == 1 {
anyMp[k] = v[0]
continue
}
anyMp[k] = v
}
return anyMp
}
// ToString simple and quickly convert map[string]any to string.
func ToString(mp map[string]any) string {
if mp == nil {

View File

@@ -22,12 +22,19 @@ func SimpleMerge(src, dst map[string]any) map[string]any {
if len(src) == 0 {
return dst
}
if len(dst) == 0 {
return src
}
for key, val := range src {
if mp, ok := val.(map[string]any); ok {
if dmp, ok := dst[key].(map[string]any); ok {
dst[key] = SimpleMerge(mp, dmp)
continue
}
}
// simple merge
dst[key] = val
}
return dst
@@ -54,7 +61,6 @@ func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]stri
if ignoreCase {
k = strings.ToLower(k)
}
dst[k] = v
}
return dst

View File

@@ -16,6 +16,58 @@ go get github.com/gookit/goutil/reflects
## Usage
```go
import "github.com/gookit/goutil/reflects"
// get struct field value
reflects.GetFieldValue(obj, "Name")
```
## Functions API
> **Note**: doc by run `go doc ./reflects`
```go
func BaseTypeVal(v reflect.Value) (value any, err error)
func ConvSlice(oldSlRv reflect.Value, newElemTyp reflect.Type) (rv reflect.Value, err error)
func EachMap(mp reflect.Value, fn func(key, val reflect.Value))
func EachStrAnyMap(mp reflect.Value, fn func(key string, val any))
func Elem(v reflect.Value) reflect.Value
func FlatMap(rv reflect.Value, fn FlatFunc)
func HasChild(v reflect.Value) bool
func Indirect(v reflect.Value) reflect.Value
func IsAnyInt(k reflect.Kind) bool
func IsArrayOrSlice(k reflect.Kind) bool
func IsEmpty(v reflect.Value) bool
func IsEmptyValue(v reflect.Value) bool
func IsEqual(src, dst any) bool
func IsFunc(val any) bool
func IsIntx(k reflect.Kind) bool
func IsNil(v reflect.Value) bool
func IsSimpleKind(k reflect.Kind) bool
func IsUintX(k reflect.Kind) bool
func Len(v reflect.Value) int
func SetRValue(rv, val reflect.Value)
func SetUnexportedValue(rv reflect.Value, value any)
func SetValue(rv reflect.Value, val any) error
func SliceElemKind(typ reflect.Type) reflect.Kind
func SliceSubKind(typ reflect.Type) reflect.Kind
func String(rv reflect.Value) string
func ToString(rv reflect.Value) (str string, err error)
func UnexportedValue(rv reflect.Value) any
func ValToString(rv reflect.Value, defaultAsErr bool) (str string, err error)
func ValueByKind(val any, kind reflect.Kind) (rv reflect.Value, err error)
func ValueByType(val any, typ reflect.Type) (rv reflect.Value, err error)
type BKind uint
func ToBKind(kind reflect.Kind) BKind
func ToBaseKind(kind reflect.Kind) BKind
type FlatFunc func(path string, val reflect.Value)
type Type interface{ ... }
func TypeOf(v any) Type
type Value struct{ ... }
func ValueOf(v any) Value
func Wrap(rv reflect.Value) Value
```
## Testings

View File

@@ -32,12 +32,12 @@ func IsAnyInt(k reflect.Kind) bool {
return k >= reflect.Int && k <= reflect.Uintptr
}
// IsIntx check is intX or uintX type
// IsIntx check is intX type
func IsIntx(k reflect.Kind) bool {
return k >= reflect.Int && k <= reflect.Int64
}
// IsUintX check is intX or uintX type
// IsUintX check is uintX type
func IsUintX(k reflect.Kind) bool {
return k >= reflect.Uint && k <= reflect.Uintptr
}

View File

@@ -27,7 +27,6 @@ func (as *Aliases) AddAlias(real, alias string) {
if rn, ok := as.mapping[alias]; ok {
panic(fmt.Sprintf("The alias '%s' is already used by '%s'", alias, rn))
}
as.mapping[alias] = real
}

View File

@@ -10,76 +10,47 @@ import (
)
// LiteData simple map[string]any struct. no lock
type LiteData struct {
data map[string]any
}
type LiteData = Data
// Data get all
func (d *LiteData) Data() map[string]any {
return d.data
}
// SetData set all data
func (d *LiteData) SetData(data map[string]any) {
d.data = data
}
// Value get from data
func (d *LiteData) Value(key string) any {
return d.data[key]
}
// GetVal get from data
func (d *LiteData) GetVal(key string) any {
return d.data[key]
}
// StrValue get from data
func (d *LiteData) StrValue(key string) string {
return strutil.QuietString(d.data[key])
}
// IntVal get from data
func (d *LiteData) IntVal(key string) int {
return mathutil.QuietInt(d.data[key])
}
// SetValue to data
func (d *LiteData) SetValue(key string, val any) {
if d.data == nil {
d.data = make(map[string]any)
// NewLiteData create, not lock
func NewLiteData(data map[string]any) *Data {
if data == nil {
data = make(map[string]any)
}
d.data[key] = val
}
// ResetData all data
func (d *LiteData) ResetData() {
d.data = nil
return &LiteData{
data: data,
}
}
/*************************************************************
* data struct and allow enable lock
*************************************************************/
// Data struct, allow enable lock TODO
// Data struct, allow enable lock
type Data struct {
sync.RWMutex
enableLock bool
// data store
lock bool
data map[string]any
}
// NewData create
// NewData create new data instance
func NewData() *Data {
return &Data{
lock: true,
data: make(map[string]any),
}
}
// WithLock for operate data
func (d *Data) WithLock() *Data {
d.lock = true
return d
}
// EnableLock for operate data
func (d *Data) EnableLock() *Data {
d.enableLock = true
return d
return d.WithLock()
}
// Data get all
@@ -89,7 +60,7 @@ func (d *Data) Data() map[string]any {
// SetData set all data
func (d *Data) SetData(data map[string]any) {
if !d.enableLock {
if !d.lock {
d.data = data
return
}
@@ -109,6 +80,11 @@ func (d *Data) ResetData() {
d.data = make(map[string]any)
}
// Merge load new data
func (d *Data) Merge(mp map[string]any) {
d.data = maputil.SimpleMerge(d.data, mp)
}
// Set value to data
func (d *Data) Set(key string, val any) {
d.SetValue(key, val)
@@ -116,7 +92,7 @@ func (d *Data) Set(key string, val any) {
// SetValue to data
func (d *Data) SetValue(key string, val any) {
if d.enableLock {
if d.lock {
d.Lock()
defer d.Unlock()
}
@@ -126,12 +102,12 @@ func (d *Data) SetValue(key string, val any) {
// Value get from data
func (d *Data) Value(key string) (val any, ok bool) {
if d.enableLock {
if d.lock {
d.RLock()
defer d.RUnlock()
}
val, ok = d.data[key]
val, ok = maputil.GetByPath(key, d.data)
return
}
@@ -142,12 +118,13 @@ func (d *Data) Get(key string) any {
// GetVal get from data
func (d *Data) GetVal(key string) any {
if d.enableLock {
if d.lock {
d.RLock()
defer d.RUnlock()
}
return d.data[key]
val, _ := maputil.GetByPath(key, d.data)
return val
}
// StrVal get from data

View File

@@ -99,6 +99,21 @@ func initDefaults(rv reflect.Value, opt *InitOptions) error {
return err
}
}
} else if fv.Kind() == reflect.Slice {
el := sf.Type.Elem()
if el.Kind() == reflect.Pointer {
el = el.Elem()
}
// init sub struct in slice. like `[]SubStruct` or `[]*SubStruct`
if el.Kind() == reflect.Struct && fv.Len() > 0 {
for i := 0; i < fv.Len(); i++ {
subFv := reflect.Indirect(fv.Index(i))
if err := initDefaults(subFv, opt); err != nil {
return err
}
}
}
}
continue
}

View File

@@ -64,6 +64,9 @@ func FilterEmail(s string) string {
return s
}
// According to rfc5321, "The local-part of a mailbox MUST BE treated as case sensitive"
// According to rfc5321, "The local-part of a mailbox MUST BE treated as case-sensitive"
return s[0:i] + "@" + strings.ToLower(s[i+1:])
}
// func Filter(ss []string, fls ...comdef.StringMatchFunc) []string {
// }

View File

@@ -39,7 +39,8 @@ func MicroTimeHexID() string {
// DatetimeNo generate. can use for order-no.
//
// No prefix, return like: 2023041410484904074285478388(len: 28)
// - No prefix, return like: 2023041410484904074285478388(len: 28)
// - With prefix, return like: prefix2023041410484904074285478388(len: 28 + len(prefix))
func DatetimeNo(prefix string) string {
nt := time.Now()
pl := len(prefix)

View File

@@ -1,4 +1,4 @@
// Package textutil provide some extra text handle util
// Package textutil provide some extensions text handle util functions.
package textutil
import (

View File

@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package sysutil
@@ -12,7 +11,6 @@ import (
// ChangeUserByName change work user by new username.
func ChangeUserByName(newUname string) (err error) {
u := MustFindUser(newUname)
// syscall.Setlogin(newUname)
return ChangeUserUidGid(strutil.IntOrPanic(u.Uid), strutil.IntOrPanic(u.Gid))
}
@@ -27,6 +25,5 @@ func ChangeUserUidGid(newUID int, newGid int) (err error) {
err = syscall.Setgid(newGid)
}
}
return
}

4
vendor/modules.txt vendored
View File

@@ -1065,11 +1065,11 @@ github.com/google/uuid
# github.com/gookit/color v1.5.3
## explicit; go 1.18
github.com/gookit/color
# github.com/gookit/config/v2 v2.2.2
# github.com/gookit/config/v2 v2.2.3
## explicit; go 1.18
github.com/gookit/config/v2
github.com/gookit/config/v2/yaml
# github.com/gookit/goutil v0.6.9
# github.com/gookit/goutil v0.6.10
## explicit; go 1.18
github.com/gookit/goutil
github.com/gookit/goutil/arrutil