MCPcopy Index your code
hub / github.com/gookit/goutil

github.com/gookit/goutil @v0.8.0 sqlite

repository ↗ · DeepWiki ↗ · release v0.8.0 ↗
4,264 symbols 20,123 edges 468 files 3,166 documented · 74% 2 cross-repo links
README

GoUtil

GitHub go.mod Go version GitHub tag (latest SemVer) Go Report Card Unit-Tests Coverage Status Go Reference

goutil Go 常用功能的扩展工具库(900+)。包含:数字,byte, 字符串,slice/数组,Map,结构体,反射,文本,文件,错误,时间日期,测试,特殊处理,格式化,常用信息获取等等。

EN README

工具包说明

基础工具包

  • arrutil array/slice 相关操作的函数工具包 如:类型转换,元素检查等等
  • byteutil: 提供一些常用的 byte 操作函数工具包. eg: convert, check and more
  • maputil map 相关操作的函数工具包. eg: convert, sub-value get, simple merge
  • mathutil int/number 相关操作的函数工具包. eg: convert, math calc, random
  • reflects 提供一些扩展性的反射使用工具函数.
  • structs 为 struct 提供一些扩展 util 函数。 eg: tag parse, struct data
  • strutil string 相关操作的函数工具包. eg: bytes, check, convert, encode, format and more
  • cliutil CLI 的一些工具函数包. eg: read input, exec command
  • envutil ENV 信息获取判断工具包. eg: get one, get info, parse var
  • fsutil 文件系统操作相关的工具函数包. eg: file and dir check, operate
  • jsonutil 一些用于快速读取、写入、编码、解码 JSON 数据的实用函数。
  • sysutil system 相关操作的函数工具包. eg: sysenv, exec, user, process

Debug & Test & Errors

  • dump GO变量打印工具,打印 slice, map 会自动换行显示每个元素,同时会显示打印调用位置
  • errorx 为 go 提供增强的错误实现,允许带有堆栈跟踪信息和包装另一个错误。
  • testutil test help 相关操作的函数工具包. eg: http test, mock ENV value
  • assert 用于帮助测试的断言函数工具包,方便编写单元测试。
  • fakeobj 提供一些接口的MOCK的实现,用于模拟测试. 例如 fs.File, fs.FileInfo, fs.DirEntry 等等.

扩展工具包

  • cflag: 包装和扩展 go flag.FlagSet 以方便快速的构建简单的命令行应用程序
  • ccolor: 简单的命令行颜色输出库,它使用 ANSI 颜色代码来输出带有颜色的文本。
  • syncs 提供一些同步、协程、信号相关的工具函数.
  • httpreq 包装 http.Client 实现的更加易于使用的HTTP客户端, 和一些 http 工具函数
  • clipboard 提供简单的OS剪贴板读写操作工具库
  • timex 提供增强的 time.Time 实现。添加更多常用的功能方法
  • 提供类似 Y-m-d H:i:s 的日期时间格式解析处理
  • 常用时间方法。例如: DayStart(), DayAfter(), DayAgo(), DateFormat() 等等

更多 ...

  • netutil Network util functions. eg: Ip, IpV4, IpV6, Mac, Port, Hostname, etc.
  • cmdline 提供 cmdline 解析,args 构建到 cmdline
  • encodes: Provide some encoding/decoding, hash, crypto util functions. eg: base64, hex, etc.
  • finder 提供简单方便的file/dir查找功能,支持过滤、排除、匹配、忽略等。
  • textscan 实现了一个快速扫描和分析文本内容的解析器. 可用于解析 INI, Properties 等格式内容
  • textutil 提供一些常用的扩展文本处理功能函数。
  • cmdr 提供快速构建和运行一个cmd,批量运行多个cmd任务
  • process 提供一些进程操作相关的实用功能。
  • fmtutil 格式化数据工具函数 eg:数据size
  • goinfo 提供一些与Go info, runtime 相关的工具函数。

GoDoc

获取

go get github.com/gookit/goutil

Usage

// github.com/gookit/goutil
is.True(goutil.IsEmpty(nil))
is.False(goutil.IsEmpty("abc"))

is.True(goutil.IsEqual("a", "a"))
is.True(goutil.IsEqual([]string{"a"}, []string{"a"}))
is.True(goutil.IsEqual(23, 23))

is.True(goutil.Contains("abc", "a"))
is.True(goutil.Contains([]string{"abc", "def"}, "abc"))
is.True(goutil.Contains(map[int]string{2: "abc", 4: "def"}, 4))

// convert type
str = goutil.String(23) // "23"
iVal = goutil.Int("-2") // 2
i64Val = goutil.Int64("-2") // -2
u64Val = goutil.Uint("2") // 2

Dump go variable

dump.Print(somevar, somevar2, ...)

dump nested struct

preview-nested-struct

Packages Details

Array and Slice

Package github.com/gookit/goutil/arrutil

Click to see functions 👈

// source at arrutil/arrutil.go
func GetRandomOne[T any](arr []T) T
func RandomOne[T any](arr []T) T
// source at arrutil/check.go
func SliceHas[T comdef.ScalarType](slice []T, val T) bool
func IntsHas[T comdef.Integer](ints []T, val T) bool
func Int64sHas(ints []int64, val int64) bool
func StringsHas[T ~string](ss []T, val T) bool
func InStrings[T ~string](elem T, ss []T) bool
func NotIn[T comdef.ScalarType](value T, list []T) bool
func In[T comdef.ScalarType](value T, list []T) bool
func ContainsAll[T comdef.ScalarType](list, values []T) bool
func IsSubList[T comdef.ScalarType](values, list []T) bool
func IsParent[T comdef.ScalarType](values, list []T) bool
func HasValue(arr, val any) bool
func Contains(arr, val any) bool
func NotContains(arr, val any) bool
// source at arrutil/collection.go
func StringEqualsComparer(a, b string) int
func ValueEqualsComparer[T comdef.Compared](a, b T) int
func ReflectEqualsComparer[T any](a, b T) int
func ElemTypeEqualsComparer[T any](a, b T) int
func TwowaySearch[T any](data []T, item T, fn Comparer[T]) (int, error)
func CloneSlice[T any](data []T) []T
func Diff[T any](first, second []T, fn Comparer[T]) []T
func Differences[T any](first, second []T, fn Comparer[T]) []T
func Excepts[T any](first, second []T, fn Comparer[T]) []T
func Intersects[T any](first, second []T, fn Comparer[T]) []T
func Union[T any](first, second []T, fn Comparer[T]) []T
func Find[T any](source []T, fn Predicate[T]) (v T, err error)
func FindOrDefault[T any](source []T, fn Predicate[T], defaultValue T) T
func TakeWhile[T any](data []T, fn Predicate[T]) []T
func ExceptWhile[T any](data []T, fn Predicate[T]) []T
// source at arrutil/convert.go
func JoinStrings(sep string, ss ...string) string
func StringsJoin(sep string, ss ...string) string
func JoinTyped[T any](sep string, arr ...T) string
func JoinSlice(sep string, arr ...any) string
func IntsToString[T comdef.Integer](ints []T) string
func ToInt64s(arr any) (ret []int64, err error)
func MustToInt64s(arr any) []int64
func SliceToInt64s(arr []any) []int64
func ToMap[T any, K comdef.ScalarType, V any](list []T, mapFn func(T) (K, V)) map[K]V
func AnyToSlice(sl any) (ls []any, err error)
func AnyToStrings(arr any) []string
func MustToStrings(arr any) []string
func ToStrings(arr any) (ret []string, err error)
func SliceToStrings(arr []any) []string
func QuietStrings(arr []any) []string
func ConvType[T any, R any](arr []T, newElemTyp R) ([]R, error)
func AnyToString(arr any) string
func SliceToString(arr ...any) string
func ToString[T any](arr []T) string
func CombineToMap[K comdef.SortedType, V any](keys []K, values []V) map[K]V
func CombineToSMap(keys, values []string) map[string]string
// source at arrutil/format.go
func NewFormatter(arr any) *ArrFormatter
func FormatIndent(arr any, indent string) string
// source at arrutil/process.go
func Reverse[T any](ls []T)
func Remove[T comdef.Compared](ls []T, val T) []T
func Filter[T any](ls []T, filter ...comdef.MatchFunc[T]) []T
func Map[T, V any](list []T, mapFn MapFn[T, V]) []V
func Map1[T, R any](list []T, fn func(t T) R) []R
func Column[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V
func Unique[T comdef.NumberOrString](list []T) []T
func IndexOf[T comdef.NumberOrString](val T, list []T) int
func FirstOr[T any](list []T, defVal ...T) T
// source at arrutil/strings.go
func StringsToAnys(ss []string) []any
func StringsToSlice(ss []string) []any
func StringsAsInts(ss []string) []int
func StringsToInts(ss []string) (ints []int, err error)
func StringsTryInts(ss []string) (ints []int, err error)
func StringsUnique(ss []string) []string
func StringsContains(ss []string, s string) bool
func StringsRemove(ss []string, s string) []string
func StringsFilter(ss []string, filter ...comdef.StringMatchFunc) []string
func StringsMap(ss []string, mapFn func(s string) string) []string
func TrimStrings(ss []string, cutSet ...string) []string

ArrUtil Usage

check value:

arrutil.IntsHas([]int{2, 4, 5}, 2) // True
arrutil.Int64sHas([]int64{2, 4, 5}, 2) // True
arrutil.StringsHas([]string{"a", "b"}, "a") // True

// list and val interface{}
arrutil.Contains(list, val)
arrutil.Contains([]uint32{9, 2, 3}, 9) // True

convert:

ints, err := arrutil.ToInt64s([]string{"1", "2"}) // ints: []int64{1, 2} 
ss, err := arrutil.ToStrings([]int{1, 2}) // ss: []string{"1", "2"}

Bytes Utils

Package github.com/gookit/goutil/byteutil

Click to see functions 👈

// source at byteutil/buffer.go
func NewBuffer() *Buffer
// source at byteutil/byteutil.go
func Md5(src any) []byte
func Md5Sum(src any) []byte
func ShortMd5(src any) []byte
func Random(length int) ([]byte, error)
func FirstLine(bs []byte) []byte
func AppendAny(dst []byte, v any) []byte
func Cut(bs []byte, sep byte) (before, after []byte, found bool)
func SafeCut(bs []byte, sep byte) (before, after []byte)
func SafeCuts(bs []byte, sep []byte) (before, after []byte)
// source at byteutil/check.go
func IsNumChar(c byte) bool
func IsAlphaChar(c byte) bool
// source at byteutil/conv.go
func StrOrErr(bs []byte, err error) (string, error)
func SafeString(bs []byte, err error) string
func String(b []byte) string
func ToString(b []byte) string
func ToBytes(v any) ([]byte, error)
func SafeBytes(v any) []byte
func ToBytesWithFunc(v any, usrFn ToBytesFunc) ([]byte, error)
// source at byteutil/encoder.go
func NewStdEncoder(encFn BytesEncodeFunc, decFn BytesDecodeFunc) *StdEncoder
// source at byteutil/pool.go
func NewChanPool(chSize int, width int, capWidth int) *ChanPool

Cflag

Package github.com/gookit/goutil/cflag

cflag - Wraps and extends go flag.FlagSet to build simple command line applications

Click to see functions 👈

// source at cflag/cflag.go
func New(fns ...func(c *CFlags)) *CFlags
func NewWith(name, version, desc string, fns ...func(c *CFlags)) *CFlags
func NewEmpty(fns ...func(c *CFlags)) *CFlags
func WithDesc(desc string) func(c *CFlags)
func WithVersion(version string) func(c *CFlags)
// source at cflag/ext.go
func LimitInt(min, max int) comdef.IntCheckFunc
func NewIntVar(checkFn comdef.IntCheckFunc) IntVar
func NewStrVar(checkFn comdef.StrCheckFunc) StrVar
func NewEnumString(enum ...string) EnumString
func NewKVString() KVString
func Value
// source at cflag/optarg.go
func NewArg(name, desc string, required bool) *FlagArg
// source at cflag/util.go
func SetDebug(open bool)
func DebugMsg(format string, args ...any)
func IsGoodName(name string) bool
func IsZeroValue(opt *flag.Flag, value string) (bool, bool)
func AddPrefix(name string) string
func AddPrefixes(name string, shorts []string) string
func AddPrefixes2(name string, shorts []string, nameAtEnd bool) string
func SplitShortcut(shortcut string) []string
func FilterNames(names []string) []string
func IsFlagHelpErr(err error) bool
func WrapColorForCode(s string) string
func ReplaceShorts(args []string, shortsMap map[string]string) []string

cflag Usage

cflag usage please see cflag/README.md

CLI Utils

Package github.com/gookit/goutil/cliutil

Click to see functions 👈

// source at cliutil/cliutil.go
func SplitMulti(ss []string, sep string) []string
func LineBuild(binFile string, args []string) string
func BuildLine(binFile string, args []string) string
func String2OSArgs(line string) []string
func StringToOSArgs(line string) []string
func ParseLine(line string) []string
func QuickExec(cmdLine string, workDir ...string) (string, error)
func ExecLine(cmdLine string, workDir ...string) (string, error)
func ExecCmd(binName string, args []string, workDir ...string) (string, error)
func ExecCommand(binName string, args []string, workDir ...string) (string, error)
func ShellExec(cmdLine string, shells ...string) (string, error)
func CurrentShell(onlyName bool) (path string)
func HasShellEnv(shell string) bool
func BuildOptionHelpName(names []string) string
func ShellQuote(s string) string
func OutputLines(output string) []string
// source at cliutil/info.go
func Workdir() string
func BinDir() string
func BinFile() string
func BinName() string
func GetTermSize(refresh ...bool) (w int, h int)
// source at cliutil/read.go
func ReadInput(question string) (string, error)
func ReadLine(question string) (string, error)
func ReadFirst(question string) (string, error)
func ReadFirstByte(question string) (byte, error)
func ReadFirstRune(question string) (rune, error)
func ReadAsBool(tip string, defVal bool) bool
func Confirm(tip string, defVal ...bool) bool
func InputIsYes(ans string) bool
func ByteIsYes(ans byte) bool
func ReadPassword(question ...string) string

CLI Util Usage

helper functions:

cliutil.Workdir() // current workdir
cliutil.BinDir() // the program exe file dir

cliutil.ReadInput("Your name?")
cliutil.ReadPassword("Input password:")
ans, _ := cliutil.ReadFirstByte("continue?[y/n] ")

cmdline parse:

package main

import (
    "fmt"

    "github.com/gookit/goutil/cliutil"
    "github.com/gookit/goutil/dump"
)

func main() {
    args := cliutil.ParseLine(`./app top sub --msg "has multi words"`)
    dump.P(args)

    s := cliutil.BuildLine("./myapp", []string{
        "-a", "val0",
        "-m", "this is message",
        "arg0",
    })
    fmt.Println("Build line:", s)
}

output:

```shell PRINT AT github.com/gookit/goutil/cliutil_test.TestParseLine(line_parser_test.go:30) []string [ #len=5 string("./app"), #len=5 string("top"), #len=3 string("sub"), #len=3 string("--msg"), #len=5 string("has multi words"), #len=15 ]

Build line: ./myapp -a val0 -m

Extension points exported contracts — how you extend this code

Flusher (Interface)
Flusher interface [3 implementers]
x/stdio/iface.go
DataFormatter (Interface)
DataFormatter interface [3 implementers]
comdef/formatter.go
FileInfo (Interface)
FileInfo extends fs.FileInfo, add some useful methods [3 implementers]
fsutil/define.go
Token (Interface)
Token parser [2 implementers]
strutil/textscan/tokens.go
BodyMatcher (Interface)
------------------ Body Matcher ------------------ BodyMatcher for match file contents. [2 implementers]
x/finder/matcher.go
StringMatcher (Interface)
StringMatcher interface [2 implementers]
comdef/interface.go
RepeatableFlag (Interface)
RepeatableFlag interface. [1 implementers]
cflag/ext.go
ReqLogger (Interface)
ReqLogger request logger interface [1 implementers]
netutil/httpreq/httpreq.go

Core symbols most depended-on inside this repo

Eq
called by 1491
x/assert/asserts.go
True
called by 459
x/assert/asserts.go
NoErr
called by 421
x/assert/asserts.go
False
called by 335
x/assert/asserts.go
Eq
called by 308
x/assert/assertions_methods.go
String
called by 269
strutil/textscan/tokens.go
NotEmpty
called by 219
x/assert/asserts.go
Run
called by 198
group.go

Shape

Function 2,776
Method 1,174
Struct 171
FuncType 57
Interface 52
TypeAlias 34

Languages

Go100%

Modules by API surface

x/finder/config.go88 symbols
cflag/ext.go70 symbols
testutil/assert/compat.go63 symbols
strutil/convert.go59 symbols
x/assert/asserts.go58 symbols
sysutil/cmdr/cmd.go57 symbols
x/assert/assertions_methods.go56 symbols
testutil/assert/assertions_methods.go56 symbols
strutil/check.go55 symbols
timex/timex.go47 symbols
mathutil/conv2int.go42 symbols
cflag/cflag.go38 symbols

Used by 2 indexed graphs manifest dependencies, hub-wide

Dependencies from manifests, versioned

github.com/gookit/goutilv0.6.6-0001010100000 · 1×
github.com/kortschak/utterv1.0.1 · 1×
github.com/kr/prettyv0.2.1 · 1×
github.com/kr/textv0.1.0 · 1×
golang.org/x/syncv0.11.0 · 1×
golang.org/x/sysv0.30.0 · 1×
golang.org/x/termv0.29.0 · 1×
golang.org/x/textv0.22.0 · 1×

For agents

$ claude mcp add goutil \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact