comm

package module
v2.7.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 61 Imported by: 1

README

go_comm

Documentation

Overview

copy of github.com/go-task/task/v3/internal/execext/devnull.go

Package godotenv is a go port of the ruby dotenv library (https://github.com/bkeepers/dotenv)

Examples/readme can be found on the github page at https://github.com/joho/godotenv

The TL;DR is that you make a .env file that looks something like

SOME_ENV_VAR=somevalue

and then in your go code you can call

godotenv.Load()

and all the env vars declared in .env will be available through os.Getenv("SOME_ENV_VAR")

Index

Constants

View Source
const (
	HTTP  = services.HTTP + "://"
	HTTPS = services.HTTPS + "://"
	FTP   = services.FTP + "://"
	FTPS  = services.FTPS + "://"
	SFTP  = services.SFTP + "://"
	S3    = services.S3 + "://"
	FILE  = "file://"
)
View Source
const (
	PLUGIN_LANG_GO         = "go"
	PLUGIN_LANG_JAVASCRIPT = "javascript"
	PLUGIN_LANG_SHELL      = "shell"
)
View Source
const DefaultPasswordCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

DefaultPasswordCharset 默认密码字符集 (字母数字混合)

Variables

View Source
var AppFs = afero.NewOsFs()
View Source
var BlockedCommands = map[string]bool{
	"rm":         true,
	"mkfs":       true,
	"dd":         true,
	"fdisk":      true,
	"shred":      true,
	"partprobe":  true,
	"sfdisk":     true,
	"cfdisk":     true,
	"cryptsetup": true,
	"losetup":    true,
	"init":       true,
	"shutdown":   true,
	"reboot":     true,
	"halt":       true,
	"poweroff":   true,
}

BlockedCommands 定义被阻止的命令列表

View Source
var ConfigureGinWithSonic = qgin.ConfigureGinWithSonic

ConfigureGinWithSonic 配置 gin 使用 sonic 作为 JSON 编解码器 gin v1.12.0+ 支持通过替换 json.API 来切换 JSON 后端

Deprecated: 请使用 qgin.ConfigureGinWithSonic()

View Source
var ConfigureGinWithSonicConfig = qgin.ConfigureGinWithSonicConfig

ConfigureGinWithSonicConfig 使用自定义 sonic 配置来配置 gin 允许更精细地控制 sonic 的行为

Deprecated: 请使用 qgin.ConfigureGinWithSonicConfig()

View Source
var JSONConfig = struct {
	// Backend 控制使用哪个 JSON 后端
	// 默认为 JSONBackendSonic
	Backend JSONBackend
}{
	Backend: JSONBackendSonic,
}

JSONConfig 全局 JSON 配置

View Source
var TraceId atomic.Int64

Functions

func AbsPath

func AbsPath(cwd string, _path string) string

func AnyArrayToStringArray added in v2.4.3

func AnyArrayToStringArray(anyArray []any) []string

func Bool added in v2.4.0

func Bool(hint string, v any) (bool, error)

Cast the value to bool. If parsing error occurred, returns the error.

func BoolArray added in v2.4.4

func BoolArray(hint string, v any) ([]bool, error)

func BoolArrayP added in v2.4.4

func BoolArrayP(hint string, v any) []bool

func BoolMap added in v2.4.6

func BoolMap(hint string, v any) (map[string]bool, error)

func BoolMapP added in v2.4.6

func BoolMapP(hint string, v any) map[string]bool

func BoolP added in v2.4.0

func BoolP(hint string, v any) bool

Cast the value to bool. If parsing error occurred, raise a panic.

func BroadcastInterfaces

func BroadcastInterfaces(dump bool) ([]net.Interface, error)

func BroadcastInterfacesP

func BroadcastInterfacesP(dump bool) []net.Interface

func BroadcastIpWithInterface

func BroadcastIpWithInterface(intf net.Interface) (net.IP, error)

func BroadcastIpWithInterfaceP

func BroadcastIpWithInterfaceP(intf net.Interface) net.IP

func BuildSSHURL added in v2.5.7

func BuildSSHURL(protocol, user, hostname string, port int, path string) string

BuildSSHURL builds a full SSH URL from credentials and hostname

func CheckCommands added in v2.6.13

func CheckCommands(cmds []ExtractedCommand, checker SecurityChecker) error

CheckCommands 检查命令是否通过安全检查的便捷函数

func CheckTerminalCommand added in v2.6.17

func CheckTerminalCommand(command string, args []string)

CheckTerminalCommand 检查终端命令是否允许执行 使用 panic 替代 error 返回,符合项目 Error 处理规范

func CloseQuietly added in v2.7.0

func CloseQuietly(c io.Closer)

CloseQuietly 关闭 io.Closer,忽略错误 用于资源可能已经关闭的场景,nil closer 不会 panic

func CommLocalize added in v2.5.5

func CommLocalize(id string, args ...map[string]any) string

CommLocalize is an alias for localize, for backward compatibility

func CopyFile

func CopyFile(fs afero.Fs, path string, newPath string) (int64, error)

func CopyFileP

func CopyFileP(fs afero.Fs, path string, newPath string) int64

func CreateLockFile

func CreateLockFile(fs afero.Fs, filename string, data any) (afero.File, error)

CreateLockFile tries to create a file with given name and acquire an exclusive lock on it. If the file already exists AND is still locked, it will fail.

func DeepCopyMap

func DeepCopyMap[T any](that map[string]T) map[string]T

func DefaultEtcHosts

func DefaultEtcHosts() (string, error)

func DefaultEtcHostsP

func DefaultEtcHostsP() string

func DefaultOutput

func DefaultOutput() io.Writer

func DetectLanguage added in v2.6.11

func DetectLanguage() string

DetectLanguage detects the user's language from environment variables or default. 检测顺序: LANGUAGE 环境变量 > LANG 环境变量 > 默认英语

func DirExists

func DirExists(fs afero.Fs, path string) (bool, error)

DirExists ...

func DirExistsP

func DirExistsP(fs afero.Fs, path string) bool

func DowncastMap

func DowncastMap[V any](m map[string]V) map[string]any

func DownloadBytes

func DownloadBytes(logger Logger, fallbackDir string, fs afero.Fs, url string, credentials Credentials, timeout time.Duration) (result []byte, err error)

func DownloadBytesP

func DownloadBytesP(logger Logger, fallbackDir string, fs afero.Fs, url string, credentials Credentials, timeout time.Duration) []byte

func DownloadText

func DownloadText(logger Logger, fallbackDir string, fs afero.Fs, url string, credentials Credentials, timeout time.Duration) (string, error)

func DownloadTextP

func DownloadTextP(logger Logger, fallbackDir string, fs afero.Fs, url string, credentials Credentials, timeout time.Duration) string

func EnsureDirExists

func EnsureDirExists(fs afero.Fs, path string) error

func EnsureDirExistsP

func EnsureDirExistsP(fs afero.Fs, path string)

func EnsureDirNotExists added in v2.5.1

func EnsureDirNotExists(fs afero.Fs, path string) error

func EnsureDirNotExistsP added in v2.5.1

func EnsureDirNotExistsP(fs afero.Fs, path string)

func EnsureDirWithSubdirs added in v2.6.22

func EnsureDirWithSubdirs(fs afero.Fs, mainDir string, subdirs ...string) error

EnsureDirWithSubdirs 确保目录及其子目录存在

func EnsureDirWithSubdirsP added in v2.6.22

func EnsureDirWithSubdirsP(fs afero.Fs, mainDir string, subdirs ...string)

EnsureDirWithSubdirsP 确保目录及其子目录存在(panic 版本)

func EnsureFileExists

func EnsureFileExists(fs afero.Fs, path string) error

func EnsureFileExistsP

func EnsureFileExistsP(fs afero.Fs, path string)

func EnsureFileNotExists added in v2.5.1

func EnsureFileNotExists(fs afero.Fs, path string) error

func EnsureFileNotExistsP added in v2.5.1

func EnsureFileNotExistsP(fs afero.Fs, path string)

func EnsureFileWithContent added in v2.6.22

func EnsureFileWithContent(fs afero.Fs, path string, defaultContent []byte, subdirs ...string) (bool, error)

EnsureFileWithContent 确保文件存在,如果不存在则使用指定内容创建 返回 true 表示文件是新创建的,false 表示文件已存在 subdirs: 需要在文件父目录下创建的子目录列表

func EnsureFileWithContentP added in v2.6.22

func EnsureFileWithContentP(fs afero.Fs, path string, defaultContent []byte, subdirs ...string) bool

EnsureFileWithContentP 确保文件存在,如果不存在则使用指定内容创建(panic 版本) 返回 true 表示文件是新创建的,false 表示文件已存在

func EnvSubst

func EnvSubst(input string, env map[string]string) (string, error)

func EnvSubstP

func EnvSubstP(input string, env map[string]string) string

func EnvSubstSlice

func EnvSubstSlice(inputs []string, env map[string]string) ([]string, error)

func EnvSubstSliceP

func EnvSubstSliceP(inputs []string, env map[string]string) []string

func EnvironList

func EnvironList(overrides map[string]string) ([]string, error)

func EnvironListP

func EnvironListP(overrides map[string]string) []string

func EnvironMap

func EnvironMap(overrides map[string]string) (map[string]string, error)

func EnvironMapP

func EnvironMapP(overrides map[string]string) map[string]string

func ExecEnv

func ExecEnv(fs afero.Fs, filenames []string, cmd string, cmdArgs []string) error

Exec loads env vars from the specified filenames (empty map falls back to default) then executes the cmd specified.

Simply hooks up os.Stdin/err/out to the command and calls Run()

If you want more fine grained control over your command it's recommended that you use `Load()` or `Read()` and the `os/exec` package yourself.

func ExecZenityHandler added in v2.6.12

func ExecZenityHandler(ctx context.Context, hc interp.HandlerContext, args []string) error

ExecZenityHandler zenity 命令处理器

func Executable

func Executable() (string, error)

func ExecutableP

func ExecutableP() string

func ExpandHomePath

func ExpandHomePath(path string) (string, error)

ExpandHomePath ...

func ExpandHomePathP

func ExpandHomePathP(path string) string

func ExtractTitle

func ExtractTitle(filePath string) string

func FallbackFilePath

func FallbackFilePath(fallbackDir string, url string) string

func FileExists

func FileExists(fs afero.Fs, path string) (bool, error)

FileExists ...

func FileExistsP

func FileExistsP(fs afero.Fs, path string) bool

func Float added in v2.4.4

func Float(hint string, v any) (float64, error)

Cast the value to float64. If parsing error occurred, returns the error.

func FloatArray added in v2.4.4

func FloatArray(hint string, v any) ([]float64, error)

func FloatArrayP added in v2.4.4

func FloatArrayP(hint string, v any) []float64

func FloatMap added in v2.4.6

func FloatMap(hint string, v any) (map[string]float64, error)

func FloatMapP added in v2.4.6

func FloatMapP(hint string, v any) map[string]float64

func FloatP added in v2.4.4

func FloatP(hint string, v any) float64

Cast the value to float64. If parsing error occurred, raise a panic.

func FormatBits added in v2.5.5

func FormatBits(bits float64) string

FormatBits 格式化比特数为人类可读格式

func FormatBytes added in v2.5.5

func FormatBytes(bytes int64) string

FormatBytes 格式化字节数为人类可读格式

func FormatDuration added in v2.5.5

func FormatDuration(seconds float64) string

FormatDuration 格式化时间为人类可读格式

func FormatSpeed added in v2.5.5

func FormatSpeed(bytesPerSec float64, format string) string

FormatSpeed 格式化传输速度

func FromJson

func FromJson(jsonText string, envsubt bool, result any) (err error)

func FromJsonFile

func FromJsonFile(fs afero.Fs, path string, envsubt bool, result any) error

func FromJsonFileP

func FromJsonFileP(fs afero.Fs, path string, envsubt bool, result any)

func FromJsonP

func FromJsonP(jsonText string, envsubt bool, result any)

func FromYaml

func FromYaml(yamlText string, envsubt bool, result any) (err error)

func FromYamlFile

func FromYamlFile(fs afero.Fs, path string, envsubt bool, result any) error

func FromYamlFileP

func FromYamlFileP(fs afero.Fs, path string, envsubt bool, result any)

func FromYamlP

func FromYamlP(yamlText string, envsubt bool, result any)

func GeneratePassword added in v2.7.0

func GeneratePassword(length int, charset string) (string, error)

GeneratePassword 生成指定长度的随机密码 使用指定的字符集,如果 charset 为空则使用默认字符集 使用拒绝采样确保均匀分布

func GeneratePasswordP added in v2.7.0

func GeneratePasswordP(length int, charset string) string

GeneratePasswordP 生成指定长度的随机密码 使用指定的字符集,如果 charset 为空则使用默认字符集 失败时 panic

func GetLanguage added in v2.5.4

func GetLanguage() string

GetLanguage returns the current language code

func GetLanguageTag added in v2.6.11

func GetLanguageTag(lang string) language.Tag

GetLanguageTag returns the language.Tag for the given language code. If the language is not supported, returns English tag.

func GetMapValue

func GetMapValue[T any](m map[string]any, key string, devault func() T) T

func HasFallbackFile

func HasFallbackFile(fallbackDir string, fs afero.Fs, url string) (bool, error)

func Hostname

func Hostname() (string, error)

func HostnameP

func HostnameP() string

func InitI18n added in v2.5.4

func InitI18n(lang string)

InitI18n initializes the i18n system with the specified language. Supported languages: zh, en, ru, fr, es, it, de, hu, ko, ja, vi, th, id If an unsupported language is provided, it defaults to "en".

func InputSudoPassword

func InputSudoPassword(passwordInput FnInput) string

func InstrumentSudoCommand

func InstrumentSudoCommand(cmd string) string

func Int added in v2.4.2

func Int(hint string, v any) (int, error)

Cast the value to int. If parsing error occurred, returns the error.

func IntArray added in v2.4.4

func IntArray(hint string, v any) ([]int, error)

func IntArrayP added in v2.4.4

func IntArrayP(hint string, v any) []int

func IntMap added in v2.4.6

func IntMap(hint string, v any) (map[string]int, error)

func IntMapP added in v2.4.6

func IntMapP(hint string, v any) map[string]int

func IntP added in v2.4.2

func IntP(hint string, v any) int

Cast the value to int. If parsing error occurred, raise a panic.

func IsAsciiSpace added in v2.4.3

func IsAsciiSpace(s uint8) bool

func IsDarwin

func IsDarwin() bool

func IsDiscardLogger

func IsDiscardLogger(logger Logger) bool

IsDiscardLogger 检查是否为 discard logger

func IsEmptyReflectValue

func IsEmptyReflectValue(v reflect.Value) bool

Copied From http://golang.org/src/encoding/json/encode.go Lines 280 - 296

func IsEmptyValue

func IsEmptyValue(v any) bool

func IsFileProtocol

func IsFileProtocol(url string) bool

func IsLinux

func IsLinux() bool

func IsPrimitiveReflectValue

func IsPrimitiveReflectValue(v reflect.Value) bool

func IsPrimitiveValue

func IsPrimitiveValue(v any) bool

func IsRemote

func IsRemote(url string) bool

func IsSecurityCheckError added in v2.6.13

func IsSecurityCheckError(err error) bool

IsSecurityCheckError 检查错误是否为安全检查错误

func IsSudoCommand

func IsSudoCommand(cmd string) bool

func IsTerminal

func IsTerminal() bool

func IsWindows

func IsWindows() bool

func JoinLines added in v2.6.16

func JoinLines(lines []string) string

JoinLines 将行数组合并为文本,使用换行符连接

func JoinedLines

func JoinedLines(lines ...string) string

func JoinedLinesAsBytes

func JoinedLinesAsBytes(lines ...string) []byte

func ListSuffixedFiles

func ListSuffixedFiles(fs afero.Fs, targetDir string, suffix string, skipEmptyFile bool) (map[string]string, error)

func ListSuffixedFilesP

func ListSuffixedFilesP(fs afero.Fs, targetDir string, suffix string, skipEmptyFile bool) map[string]string

func LoadEnv

func LoadEnv(fs afero.Fs, filenames ...string) (err error)

Load will read your env file(s) and load them into ENV for this process.

Call this function as close as possible to the start of your program (ideally in main)

If you call Load without any args it will default to loading .env in the current path

You can otherwise tell it which files to load (there can be more than one) like

godotenv.Load("fileone", "filetwo")

It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults

func LoadEnvScript

func LoadEnvScript(fs afero.Fs, vars map[string]string, filename string) (map[string]string, error)

func LoadEnvScripts

func LoadEnvScripts(fs afero.Fs, vars map[string]string, filenames ...string) (map[string]string, error)

func LocalizeError added in v2.5.4

func LocalizeError(messageID string, templateData map[string]any) error

LocalizeError creates a localized error message.

func LocalizeErrorf added in v2.5.4

func LocalizeErrorf(messageID string, args ...any) error

LocalizeErrorf creates a localized error message with printf-style formatting.

func LogMap added in v2.3.1

func LogMap(logger *plog.Entry, key string, m map[string]any) *plog.Entry

func LogMapper added in v2.3.1

func LogMapper(logger *plog.Entry, key string, mapper ToMap) *plog.Entry

func Map added in v2.4.0

func Map(hint string, v any) (map[string]any, error)

func Map2Struct

func Map2Struct(src map[string]any, dest any) error

func Map2StructP

func Map2StructP(src map[string]any, dest any)

func MapArray added in v2.4.0

func MapArray(hint string, v any) ([]map[string]any, error)

MapArray casts the input any value to []map[string]any if the input value type matches, otherwise, return error.

func MapArrayP added in v2.4.0

func MapArrayP(hint string, v any) []map[string]any

func MapFromJson

func MapFromJson(yamlText string, envsubt bool) (map[string]any, error)

func MapFromJsonFile

func MapFromJsonFile(fs afero.Fs, path string, envsubt bool) (map[string]any, error)

func MapFromJsonFileP

func MapFromJsonFileP(fs afero.Fs, path string, envsubt bool) map[string]any

func MapFromJsonP

func MapFromJsonP(yamlText string, envsubt bool) map[string]any

func MapFromYaml

func MapFromYaml(yamlText string, envsubt bool) (map[string]any, error)

func MapFromYamlFile

func MapFromYamlFile(fs afero.Fs, path string, envsubt bool) (map[string]any, error)

func MapFromYamlFileP

func MapFromYamlFileP(fs afero.Fs, path string, envsubt bool) map[string]any

func MapFromYamlP

func MapFromYamlP(yamlText string, envsubt bool) map[string]any

func MapP added in v2.4.0

func MapP(hint string, v any) map[string]any

func Marshal deprecated added in v2.7.2

func Marshal(v any) ([]byte, error)

Marshal 使用 sonic 序列化对象

Deprecated: 此方法仅为向后兼容保留,请使用 qgin.ConfigureGinWithSonic() 后直接调用 json.API.Marshal()

func MarshalEnv

func MarshalEnv(envMap map[string]string) (string, error)

Marshal outputs the given environment as a dotenv-formatted environment file. Each line is in the format: KEY="VALUE" where VALUE is backslash-escaped.

func MarshalIndent deprecated added in v2.7.2

func MarshalIndent(v any, prefix, indent string) ([]byte, error)

MarshalIndent 使用 sonic 序列化对象并添加缩进

Deprecated: 此方法仅为向后兼容保留

func MarshalJSON added in v2.7.2

func MarshalJSON(v any) ([]byte, error)

MarshalJSON 公开的 JSON 序列化函数,根据 JSONConfig.Backend 选择后端 使用方法与 json.Marshal 相同,但支持动态切换 sonic/stdlib

func MarshalJSONIndent added in v2.7.2

func MarshalJSONIndent(v any, prefix, indent string) ([]byte, error)

MarshalJSONIndent 公开的 JSON 带缩进序列化函数

func MarshalJSONIndentP added in v2.7.2

func MarshalJSONIndentP(v any, prefix, indent string) []byte

MarshalJSONIndentP panic 版本的 JSON 带缩进序列化函数 失败时 panic,符合项目 Error 处理规范

func MarshalJSONP added in v2.7.2

func MarshalJSONP(v any) []byte

MarshalJSONP panic 版本的 JSON 序列化函数 失败时 panic,符合项目 Error 处理规范

func MergeMap

func MergeMap[T any](bases ...map[string]T) map[string]T

func Mkdir

func Mkdir(fs afero.Fs, path string) error

Mkdir ...

func Mkdir4File added in v2.5.2

func Mkdir4File(fs afero.Fs, filePath string) error

func Mkdir4FileP added in v2.5.2

func Mkdir4FileP(fs afero.Fs, filePath string)

func MkdirP

func MkdirP(fs afero.Fs, path string)

func NameOfKey added in v2.4.0

func NameOfKey(key string) string

func NanoID added in v2.6.21

func NanoID() (string, error)

NanoID 生成 21 字符的 NanoID(默认长度)

func NanoIDP added in v2.6.21

func NanoIDP() string

NanoIDP 生成 21 字符的 NanoID(默认长度),失败时 panic

func NanoIDWithSize added in v2.6.21

func NanoIDWithSize(size int) (string, error)

NanoIDWithSize 生成指定长度的 NanoID

func NanoIDWithSizeP added in v2.6.21

func NanoIDWithSizeP(size int) string

NanoIDWithSizeP 生成指定长度的 NanoID,失败时 panic

func NewCredentialsFromSSH added in v2.5.7

func NewCredentialsFromSSH(sshURL string) (*models.Credentials, string, int, string, error)

NewCredentialsFromSSH creates Credentials from SSH URL using ~/.ssh/config

func NewDecoder deprecated added in v2.7.2

func NewDecoder(reader io.Reader) json.Decoder

NewDecoder 创建 sonic 解码器

Deprecated: 此方法仅为向后兼容保留

func NewEncoder deprecated added in v2.7.2

func NewEncoder(writer io.Writer) json.Encoder

NewEncoder 创建 sonic 编码器

Deprecated: 此方法仅为向后兼容保留

func OptionalBool added in v2.4.0

func OptionalBool(hint string, key string, m map[string]any, devault bool) (result bool, has bool, err error)

OptionalBool returns the bool value of the key in the map. If parsing error occrred, returns the error. If the key is not found, return the default value.

func OptionalBoolP added in v2.4.0

func OptionalBoolP(hint string, key string, m map[string]any, devault bool) (result bool, has bool)

OptionalBoolP returns the bool value of the key in the map. If parsing error occurred, raise a panic. If the key is not found, return the default value.

func OptionalFloat added in v2.4.4

func OptionalFloat(hint string, key string, m map[string]any, devault float64) (result float64, has bool, err error)

OptionalFloat returns the float64 value of the key in the map. If parsing error occrred, returns the error. If the key is not found, return the default value.

func OptionalFloatP added in v2.4.4

func OptionalFloatP(hint string, key string, m map[string]any, devault float64) (result float64, has bool)

OptionalFloatP returns the float64 value of the key in the map. If parsing error occurred, raise a panic. If the key is not found, return the default value.

func OptionalInt added in v2.4.2

func OptionalInt(hint string, key string, m map[string]any, devault int) (result int, has bool, err error)

OptionalInt returns the int value of the key in the map. If parsing error occrred, returns the error. If the key is not found, return the default value.

func OptionalIntP added in v2.4.2

func OptionalIntP(hint string, key string, m map[string]any, devault int) (result int, has bool)

OptionalIntP returns the int value of the key in the map. If parsing error occurred, raise a panic. If the key is not found, return the default value.

func OptionalMap added in v2.4.0

func OptionalMap(hint string, key string, m map[string]any, defaultresult map[string]any) (result map[string]any, has bool, err error)

func OptionalMapArray added in v2.4.0

func OptionalMapArray(hint string, key string, m map[string]any, defaultresult []map[string]any) (result []map[string]any, has bool, err error)

func OptionalMapArrayP added in v2.4.0

func OptionalMapArrayP(hint string, key string, m map[string]any, defaultresult []map[string]any) (result []map[string]any, has bool)

func OptionalMapP added in v2.4.0

func OptionalMapP(hint string, key string, m map[string]any, defaultresult map[string]any) (result map[string]any, has bool)

func OptionalString added in v2.4.0

func OptionalString(hint string, key string, m map[string]any, devault string) (result string, has bool, err error)

func OptionalStringArrayValue added in v2.4.0

func OptionalStringArrayValue(hint string, key string, m map[string]any, devault []string) (result []string, has bool, err error)

func OptionalStringArrayValueP added in v2.4.0

func OptionalStringArrayValueP(hint string, key string, m map[string]any, devault []string) (result []string, has bool)

func OptionalStringP added in v2.4.0

func OptionalStringP(hint string, key string, m map[string]any, devault string) (result string, has bool)

func OverloadEnv

func OverloadEnv(fs afero.Fs, filenames ...string) (err error)

Overload will read your env file(s) and load them into ENV for this process.

Call this function as close as possible to the start of your program (ideally in main)

If you call Overload without any args it will default to loading .env in the current path

You can otherwise tell it which files to load (there can be more than one) like

godotenv.Overload("fileone", "filetwo")

It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefilly set all vars.

func Pair2Vars

func Pair2Vars(pairs []string) map[string]string

func ParseEnv

func ParseEnv(r io.Reader) (envMap map[string]string, err error)

Parse reads an env file from io.Reader, returning a map of keys and values.

func ParseSSHURL added in v2.5.7

func ParseSSHURL(urlStr string) (protocol, user, hostname, path string, port int, err error)

ParseSSHURL parses various SSH URL formats: - ssh:hostname (uses host from SSH config) - ssh://hostname - ssh://user@hostname - ssh://user@hostname:port - ssh://user@hostname:port/path - ssh://user@hostname/path - sftp://hostname - user@hostname (SSH shorthand) - user@hostname:path (SSH shorthand with path) - user@hostname:/path (SSH shorthand with absolute path)

func PluginId added in v2.5.0

func PluginId(namespace string, name string) string

func ReadBytes

func ReadBytes(reader io.Reader) ([]byte, error)

ReadBytes ...

func ReadBytesP

func ReadBytesP(reader io.Reader) []byte

ReadBytesP ...

func ReadEnv

func ReadEnv(fs afero.Fs, filenames ...string) (envMap map[string]string, err error)

Read all env (with same file loading semantics as Load) but return values as a map rather than automatically writing values into env

func ReadFallbackFile

func ReadFallbackFile(fallbackDir string, fs afero.Fs, url string) (string, []byte, error)

func ReadFileBytes

func ReadFileBytes(fs afero.Fs, path string) ([]byte, error)

ReadBytes ...

func ReadFileBytesP

func ReadFileBytesP(fs afero.Fs, path string) []byte

func ReadFileLines

func ReadFileLines(fs afero.Fs, path string) ([]string, error)

func ReadFileLinesP

func ReadFileLinesP(fs afero.Fs, path string) []string

func ReadFileText

func ReadFileText(fs afero.Fs, path string) (string, error)

func ReadFileTextP

func ReadFileTextP(fs afero.Fs, path string) string

func ReadLines

func ReadLines(reader io.Reader) []string

func ReadLockFile added in v2.4.8

func ReadLockFile(fs afero.Fs, filename string) (int, any, error)

If filename is a lock file, returns the PID of the process locking it

func ReadText

func ReadText(reader io.Reader) (string, error)

ReadText ...

func ReadTextP

func ReadTextP(reader io.Reader) string

ReadText ...

func RecoverAndLog added in v2.7.0

func RecoverAndLog(r any, logger Logger, operation string)

RecoverAndLog 在 goroutine 的 defer 中使用,记录 panic 日志 用法: defer func() { comm.RecoverAndLog(recover(), logger, "operation name") }()

func RecoverAsError added in v2.7.0

func RecoverAsError(r any) error

RecoverAsError 在 defer 中使用,将 panic 转换为 error 返回的 error 需要作为命名返回值使用 用法: defer func() { err = comm.RecoverAsError(recover()) }()

func RemoveDir

func RemoveDir(fs afero.Fs, path string) error

RemoveDir ...

func RemoveDirP

func RemoveDirP(fs afero.Fs, path string)

func RemoveFile

func RemoveFile(fs afero.Fs, path string) error

RemoveFile ...

func RemoveFileP

func RemoveFileP(fs afero.Fs, path string)

func Rename

func Rename(fs afero.Fs, path string, newPath string) error

func RenameP

func RenameP(fs afero.Fs, path string, newPath string)

func RenderAsTemplate

func RenderAsTemplate(tmpl string, data map[string]any) (string, error)

func RenderAsTemplateArray

func RenderAsTemplateArray(tmplArray []string, data map[string]any) ([]string, error)

func RenderAsTemplateArrayP

func RenderAsTemplateArrayP(tmplArray []string, data map[string]any) []string

func RenderAsTemplateP

func RenderAsTemplateP(tmpl string, data map[string]any) string

func RenderWithTemplate

func RenderWithTemplate(w io.Writer, name string, tmpl string, data map[string]any) error

func RenderWithTemplateP

func RenderWithTemplateP(w io.Writer, name string, tmpl string, data map[string]any)

func RequiredBool added in v2.4.0

func RequiredBool(hint string, key string, m map[string]any) (bool, error)

RequiredBool returns the bool value of the key in the map. If either parsing error or the key is not found, an error is returned.

func RequiredBoolP added in v2.4.0

func RequiredBoolP(hint string, key string, m map[string]any) bool

RequiredBoolP returns the bool value of the key in the map. If either parsing error or the key is not found, raise a panic.

func RequiredFloat added in v2.4.4

func RequiredFloat(hint string, key string, m map[string]any) (float64, error)

RequiredFloat returns the float64 value of the key in the map. If either parsing error or the key is not found, an error is returned.

func RequiredFloatP added in v2.4.4

func RequiredFloatP(hint string, key string, m map[string]any) float64

RequiredFloatP returns the float64 value of the key in the map. If either parsing error or the key is not found, raise a panic.

func RequiredInt added in v2.4.2

func RequiredInt(hint string, key string, m map[string]any) (int, error)

RequiredInt returns the int value of the key in the map. If either parsing error or the key is not found, an error is returned.

func RequiredIntP added in v2.4.2

func RequiredIntP(hint string, key string, m map[string]any) int

RequiredIntP returns the int value of the key in the map. If either parsing error or the key is not found, raise a panic.

func RequiredMap added in v2.4.0

func RequiredMap(hint string, key string, m map[string]any) (map[string]any, error)

func RequiredMapArray added in v2.4.0

func RequiredMapArray(hint string, key string, m map[string]any) ([]map[string]any, error)

func RequiredMapArrayP added in v2.4.0

func RequiredMapArrayP(hint string, key string, m map[string]any) []map[string]any

func RequiredMapP added in v2.4.0

func RequiredMapP(hint string, key string, m map[string]any) map[string]any

func RequiredString added in v2.4.0

func RequiredString(hint string, key string, m map[string]any) (string, error)

func RequiredStringP added in v2.4.0

func RequiredStringP(hint string, key string, m map[string]any) string

func ResolveBroadcastIp

func ResolveBroadcastIp(interfaces []net.Interface, interfaceName string) (net.IP, net.IP, error)

func ResolveBroadcastIpP

func ResolveBroadcastIpP(interfaces []net.Interface, interfaceName string) (net.IP, net.IP)

func RunCommandWithInput

func RunCommandWithInput(vars map[string]string, dir string, cmd string, args ...string) func(...string) (CommandOutput, error)

func SSHConfigToCredentials added in v2.5.7

func SSHConfigToCredentials(config *SSHHostConfig) *models.Credentials

SSHConfigToCredentials converts SSH host config to Credentials

func Set2Strings

func Set2Strings(set *hashset.Set) []string

func SetCommLang added in v2.5.5

func SetCommLang(lang string)

SetCommLang is an alias for SetLanguage, for backward compatibility

func SetLanguage added in v2.5.4

func SetLanguage(lang string)

SetLanguage changes the current language for i18n.

func ShortDescription

func ShortDescription(url string) string

func ShortUUID added in v2.6.21

func ShortUUID() (string, error)

ShortUUID 生成 Base62 编码的 UUID(22 字符) UUID 是 128 位(16 字节),Base62 编码后为 22 字符

func ShortUUIDP added in v2.6.21

func ShortUUIDP() string

ShortUUIDP 生成 Base62 编码的 UUID(22 字符),失败时 panic

func Slice2Map

func Slice2Map[V any](arr []V, keyFunc func(v V) string) map[string]V

func Slice2Set

func Slice2Set[T comparable](arr ...T) *hashset.Set

func SliceEquals

func SliceEquals[T comparable](a []T, b []T) bool

func StartPlugin added in v2.5.0

func StartPlugin(namespace string, plugin Plugin, logger Logger) (err error)

func Stat

func Stat(fs afero.Fs, path string, ensureExists bool) (os.FileInfo, error)

Stat ...

func StatP

func StatP(fs afero.Fs, path string, ensureExists bool) os.FileInfo

func StopPlugin added in v2.5.0

func StopPlugin(namespace string, plugin Plugin, logger Logger) (err error)

func String added in v2.4.0

func String(hint string, v any) (string, error)

func StringArray added in v2.4.0

func StringArray(hint string, v any) ([]string, error)

func StringArrayP added in v2.4.0

func StringArrayP(hint string, v any) []string

func StringArrayToAnyArray added in v2.4.3

func StringArrayToAnyArray(stringArray []string) []any

func StringArrayValue added in v2.4.0

func StringArrayValue(hint string, key string, m map[string]any) ([]string, error)

func StringArrayValueP added in v2.4.0

func StringArrayValueP(hint string, key string, m map[string]any) []string

func StringMap added in v2.4.6

func StringMap(hint string, v any) (map[string]string, error)

func StringMapP added in v2.4.6

func StringMapP(hint string, v any) map[string]string

func StringP added in v2.4.0

func StringP(hint string, v any) string

func StructToMap

func StructToMap(src any) map[string]any

func SubstVars

func SubstVars(useGoTemplate bool, m map[string]any, parentVars map[string]any, keysToSkip ...string) (map[string]any, error)

func SubstVarsP

func SubstVarsP(useGoTemplate bool, m map[string]any, parentVars map[string]any, keysToSkip ...string) map[string]any

func SysEnvFileNames

func SysEnvFileNames(fs afero.Fs, shell string) []string

func T added in v2.5.4

func T(messageID string, templateData map[string]any) string

T translates a message ID with optional template data. Usage:

T("error.required", map[string]any{"Hint": "config", "Key": "name"})

func TempFile

func TempFile(fs afero.Fs, pattern string) (string, error)

func TempFileP

func TempFileP(fs afero.Fs, pattern string) string

func TempTextFile

func TempTextFile(fs afero.Fs, pattern string, content string) (string, error)

func TempTextFileP

func TempTextFileP(fs afero.Fs, pattern string, content string) string

func Text2Lines

func Text2Lines(text string) []string

func Text2Vars

func Text2Vars(text string) map[string]string

func TextLine2Array

func TextLine2Array(line string) []string

func Tf added in v2.5.4

func Tf(messageID string, args ...any) string

Tf translates a message ID with formatted arguments (printf-style). This is a convenience function for simple string formatting.

func ToSlogLogger added in v2.6.20

func ToSlogLogger(logger Logger) *slog.Logger

ToSlogLogger 将 comm.Logger 转换为 *slog.Logger 使用 phuslu/log 的 Slog() 方法创建

func ToYaml

func ToYaml(hint string, me any) (string, error)

func ToYamlP

func ToYamlP(hint string, me any) string

func Unmarshal deprecated added in v2.7.2

func Unmarshal(data []byte, v any) error

Unmarshal 使用 sonic 反序列化数据

Deprecated: 此方法仅为向后兼容保留,请使用 qgin.ConfigureGinWithSonic() 后直接调用 json.API.Unmarshal()

func UnmarshalEnv

func UnmarshalEnv(str string) (envMap map[string]string, err error)

Unmarshal reads an env file from a string, returning a map of keys and values.

func UnmarshalJSON added in v2.7.2

func UnmarshalJSON(data []byte, v any) error

UnmarshalJSON 公开的 JSON 反序列化函数,根据 JSONConfig.Backend 选择后端 使用方法与 json.Unmarshal 相同,但支持动态切换 sonic/stdlib

func UnmarshalJSONP added in v2.7.2

func UnmarshalJSONP(data []byte, v any)

UnmarshalJSONP panic 版本的 JSON 反序列化函数 失败时 panic,符合项目 Error 处理规范

func UserHomeDir

func UserHomeDir() (string, error)

func UserHomeDirP

func UserHomeDirP() string

func Vars2Pair

func Vars2Pair(vars map[string]string) []string

func WorkDir

func WorkDir(url string, defaultDir string) string

func WorkingDirectory

func WorkingDirectory() (string, error)

func WorkingDirectoryP

func WorkingDirectoryP() string

func WriteEnv

func WriteEnv(fs afero.Fs, envMap map[string]string, filename string) error

Write serializes the given environment and writes it to a file

func WriteFallbackFile

func WriteFallbackFile(fallbackDir string, fs afero.Fs, url string, bytes []byte) (string, error)

func WriteFile

func WriteFile(fs afero.Fs, path string, content []byte) error

Write ...

func WriteFileIfNotFound

func WriteFileIfNotFound(fs afero.Fs, path string, content []byte) (bool, error)

WriteIfNotFound ...

func WriteFileIfNotFoundP

func WriteFileIfNotFoundP(fs afero.Fs, path string, content []byte) bool

func WriteFileLines

func WriteFileLines(fs afero.Fs, path string, lines ...string) error

func WriteFileLinesP

func WriteFileLinesP(fs afero.Fs, path string, lines ...string)

WriteLines ...

func WriteFileP

func WriteFileP(fs afero.Fs, path string, content []byte)

func WriteFileText

func WriteFileText(fs afero.Fs, path string, content string) error

WriteText ...

func WriteFileTextIfNotFound

func WriteFileTextIfNotFound(fs afero.Fs, path string, content string) (bool, error)

func WriteFileTextIfNotFoundP

func WriteFileTextIfNotFoundP(fs afero.Fs, path string, content string) bool

WriteTextIfNotFound ...

func WriteFileTextP

func WriteFileTextP(fs afero.Fs, path string, content string)

Types

type AferoBlob

type AferoBlob = *AferoBlobT

func NewAferoBlob

func NewAferoBlob(afs afero.Fs, path string) AferoBlob

func (AferoBlob) Close

func (me AferoBlob) Close() error

func (AferoBlob) Fs

func (me AferoBlob) Fs() afero.Fs

func (AferoBlob) Path

func (me AferoBlob) Path() string

func (AferoBlob) Read

func (me AferoBlob) Read(p []byte) (n int, err error)

type AferoBlobT

type AferoBlobT struct {
	// contains filtered or unexported fields
}

type AferoFile

type AferoFile = *AferoFileT

func NewAferoFile

func NewAferoFile(afs afero.Fs, apath string, credentials Credentials, timeout time.Duration) (AferoFile, error)

func NewAferoFileP

func NewAferoFileP(afs afero.Fs, apath string, credentials Credentials, timeout time.Duration) AferoFile

func (AferoFile) Credentials

func (me AferoFile) Credentials() Credentials

func (AferoFile) Dir

func (me AferoFile) Dir() string

filepath

func (AferoFile) Download

func (me AferoFile) Download() (Content, error)

func (AferoFile) DownloadP

func (me AferoFile) DownloadP() Content

func (AferoFile) Fs

func (me AferoFile) Fs() afero.Fs

func (AferoFile) Name

func (me AferoFile) Name() string

func (AferoFile) Protocol

func (me AferoFile) Protocol() string

remote protocol. May be used to explicitly tell what protocol to use (i.e. "http", "ftp", "etc").

func (AferoFile) Timeout

func (me AferoFile) Timeout() time.Duration

func (AferoFile) URL

func (me AferoFile) URL() *url.URL

func (AferoFile) Url

func (me AferoFile) Url() string

remote file/dir url

type AferoFileT

type AferoFileT struct {
	// contains filtered or unexported fields
}

type AppError added in v2.6.14

type AppError struct {
	Code    ErrCode
	Message string
	Err     error
}

func NewBusinessError added in v2.6.14

func NewBusinessError(message string, err error) *AppError

func NewBusinessErrorf added in v2.6.14

func NewBusinessErrorf(format string, args ...any) *AppError

func NewConfigError added in v2.6.14

func NewConfigError(message string, err error) *AppError

func NewConfigErrorf added in v2.6.14

func NewConfigErrorf(format string, args ...any) *AppError

func NewSecurityError added in v2.6.14

func NewSecurityError(message string, err error) *AppError

func NewSecurityErrorf added in v2.6.14

func NewSecurityErrorf(format string, args ...any) *AppError

func NewSystemError added in v2.6.14

func NewSystemError(message string, err error) *AppError

func NewSystemErrorf added in v2.6.14

func NewSystemErrorf(format string, args ...any) *AppError

func (*AppError) As added in v2.6.14

func (me *AppError) As(target any) bool

func (*AppError) Error added in v2.6.14

func (me *AppError) Error() string

func (*AppError) Is added in v2.6.14

func (me *AppError) Is(target error) bool

func (*AppError) Unwrap added in v2.6.14

func (me *AppError) Unwrap() error

func (*AppError) WithCode added in v2.6.14

func (me *AppError) WithCode(code ErrCode) *AppError

func (*AppError) WithMessage added in v2.6.14

func (me *AppError) WithMessage(format string, args ...any) *AppError

type ArgMatcher added in v2.6.13

type ArgMatcher struct {
	// Position 参数位置 (-1 表示任意位置)
	Position int
	// Pattern 匹配模式
	Pattern string
	// Mode 匹配类型
	Mode MatchMode
	// Required 是否必需 (用于组合匹配)
	Required bool
}

ArgMatcher 参数匹配器

type BasePlugin added in v2.5.0

type BasePlugin = *BasePluginT

func (BasePlugin) IsStarted added in v2.5.0

func (me BasePlugin) IsStarted() bool

func (BasePlugin) Kind added in v2.5.0

func (me BasePlugin) Kind() PluginKind

func (BasePlugin) Name added in v2.5.0

func (me BasePlugin) Name() string

func (BasePlugin) Start added in v2.5.0

func (me BasePlugin) Start(logger Logger)

func (BasePlugin) Stop added in v2.5.0

func (me BasePlugin) Stop(logger Logger)

func (BasePlugin) Version added in v2.5.0

func (me BasePlugin) Version() (major int, minor int)

type BasePluginLoader added in v2.5.0

type BasePluginLoader = *BasePluginLoaderT

func NewPluginLoader added in v2.5.0

func NewPluginLoader(namespace string) BasePluginLoader

func (BasePluginLoader) Namespace added in v2.5.0

func (me BasePluginLoader) Namespace() string

func (BasePluginLoader) Plugins added in v2.5.0

func (me BasePluginLoader) Plugins() map[string]Plugin

func (BasePluginLoader) Register added in v2.5.0

func (me BasePluginLoader) Register(plugin Plugin)

func (BasePluginLoader) RegisterThenStart added in v2.5.0

func (me BasePluginLoader) RegisterThenStart(logger Logger, plugin Plugin)

func (BasePluginLoader) Start added in v2.5.0

func (me BasePluginLoader) Start(logger Logger) error

func (BasePluginLoader) Stop added in v2.5.0

func (me BasePluginLoader) Stop(logger Logger) error

type BasePluginLoaderT added in v2.5.0

type BasePluginLoaderT struct {
	// contains filtered or unexported fields
}

type BasePluginT added in v2.5.0

type BasePluginT struct {
	// contains filtered or unexported fields
}

func NewBasePlugin added in v2.5.0

func NewBasePlugin(name string, kind PluginKind) BasePluginT

type CommandExtractor added in v2.6.13

type CommandExtractor = *CommandExtractorT

CommandExtractor 是 CommandExtractorT 的指针别名

func NewCommandExtractor added in v2.6.13

func NewCommandExtractor() CommandExtractor

NewCommandExtractor 创建命令提取器

func (CommandExtractor) Extract added in v2.6.13

func (me CommandExtractor) Extract(cmd string) ([]ExtractedCommand, error)

Extract 从命令字符串中提取所有命令

type CommandExtractorT added in v2.6.13

type CommandExtractorT struct {
	// contains filtered or unexported fields
}

CommandExtractorT 命令提取器,从 shell 命令字符串中提取所有命令

type CommandOutput

type CommandOutput = *CommandOutputT

func ParseCommandOutput

func ParseCommandOutput(outputText string) (CommandOutput, error)

func ParseCommandOutputP

func ParseCommandOutputP(outputText string) CommandOutput

func RunCommandNoInput

func RunCommandNoInput(vars map[string]string, dir string, cmd string, args ...string) (CommandOutput, error)

func RunCommandNoInputP

func RunCommandNoInputP(vars map[string]string, dir string, cmd string, args ...string) CommandOutput

func RunGoshCommand

func RunGoshCommand(vars map[string]string, dir string, cmd string, passwordInput FnInput) (CommandOutput, error)

RunGoshCommand 执行 shell 命令

func RunGoshCommandP

func RunGoshCommandP(vars map[string]string, dir string, cmd string, passwordInput FnInput) CommandOutput

RunGoshCommandP 执行 shell 命令(失败时 panic)

func RunShellCommand

func RunShellCommand(vars map[string]string, dir string, sh string, cmd string, passwordInput FnInput) (CommandOutput, error)

func RunShellCommandP

func RunShellCommandP(vars map[string]string, dir string, sh string, cmd string, passwordInput FnInput) CommandOutput

func RunSudoCommand

func RunSudoCommand(vars map[string]string, dir string, cmd string, passwordInput FnInput) (CommandOutput, error)

func RunUserCommand

func RunUserCommand(vars map[string]string, dir string, cmd string) (CommandOutput, error)

func RunUserCommandP

func RunUserCommandP(vars map[string]string, dir string, cmd string) CommandOutput

type CommandOutputKind

type CommandOutputKind byte
const (
	COMMAND_OUTPUT_KIND_TEXT CommandOutputKind
	COMMAND_OUTPUT_KIND_VARS
	COMMAND_OUTPUT_KIND_JSON
)

type CommandOutputT

type CommandOutputT struct {
	Kind CommandOutputKind
	Vars map[string]string
	Text string
	Json any
}

type CommandRule added in v2.6.12

type CommandRule = *CommandRuleT

CommandRule 是 CommandRuleT 的指针别名

func NewCommandRule added in v2.6.12

func NewCommandRule(pattern string, matchMode MatchMode) CommandRule

NewCommandRule 创建命令规则

func (CommandRule) WithArgsFilter added in v2.6.13

func (me CommandRule) WithArgsFilter(matchers ...ArgMatcher) CommandRule

WithArgsFilter 添加参数过滤器

func (CommandRule) WithSourceFilter added in v2.6.13

func (me CommandRule) WithSourceFilter(sources ...CommandSource) CommandRule

WithSourceFilter 设置命令来源过滤

type CommandRuleT added in v2.6.12

type CommandRuleT struct {
	// Pattern 命令模式
	Pattern string
	// ArgsMatchers 参数匹配器列表
	ArgsMatchers []ArgMatcher
	// MatchMode 匹配模式
	MatchMode MatchMode
	// SourceFilter 命令来源过滤 (空表示所有来源)
	SourceFilter []CommandSource
}

CommandRuleT 命令规则

type CommandSource added in v2.6.13

type CommandSource int

CommandSource 表示命令的来源类型

const (
	// SourceDirect 直接调用: echo hello
	SourceDirect CommandSource = iota
	// SourceCmdSubst 命令替换: $(cmd) 或 `cmd`
	SourceCmdSubst
	// SourceProcSubst 进程替换: <(cmd) 或 >(cmd)
	SourceProcSubst
	// SourceSubshell 子 shell: (cmd)
	SourceSubshell
)

func (CommandSource) String added in v2.6.13

func (s CommandSource) String() string

String 返回命令来源的字符串表示

type ConfigConfig

type ConfigConfig struct {
	// If ErrorUnused is true, then it is an error for there to exist
	// keys in the original map that were unused in the decoding process
	// (extra keys).
	ErrorUnused bool

	// If ErrorUnset is true, then it is an error for there to exist
	// fields in the result that were not set in the decoding process
	// (extra fields). This only applies to decoding to a struct. This
	// will affect all nested structs as well.
	ErrorUnset bool

	// ZeroFields, if set to true, will zero fields before writing them.
	// For example, a map will be emptied before decoded values are put in
	// it. If this is false, a map will be merged.
	ZeroFields bool

	// If WeaklyTypedInput is true, the decoder will make the following
	// "weak" conversions:
	//
	//   - bools to string (true = "1", false = "0")
	//   - numbers to string (base 10)
	//   - bools to int/uint (true = 1, false = 0)
	//   - strings to int/uint (base implied by prefix)
	//   - int to bool (true if value != 0)
	//   - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
	//     FALSE, false, False. Anything else is an error)
	//   - empty array = empty map and vice versa
	//   - negative numbers to overflowed uint values (base 10)
	//   - slice of maps to a merged map
	//   - single values are converted to slices if required. Each
	//     element is weakly decoded. For example: "4" can become []int{4}
	//     if the target type is an int slice.
	//
	WeaklyTypedInput bool

	// Squash will squash embedded structs.  A squash tag may also be
	// added to an individual struct field using a tag.  For example:
	//
	//  type Parent struct {
	//      Child `mapstructure:",squash"`
	//  }
	Squash bool

	// IgnoreUntaggedFields ignores all struct fields without explicit
	// TagName, comparable to `mapstructure:"-"` as default behaviour.
	IgnoreUntaggedFields bool

	Metadata ConfigMetadata

	DoValidate bool
}

Derived from mapstructure.DecodeConfig

func DynamicConfigConfig

func DynamicConfigConfig() *ConfigConfig

func StrictConfigConfig

func StrictConfigConfig() *ConfigConfig

func (*ConfigConfig) ToMapstruct

func (me *ConfigConfig) ToMapstruct() *mapstructure.DecoderConfig

type ConfigMetadata

type ConfigMetadata = mapstructure.Metadata

func DecodeWithMap

func DecodeWithMap[T any](input map[string]any, cfgcfg *ConfigConfig, result *T, devault map[string]any) (*T, *ConfigMetadata, error)

func DecodeWithMapP

func DecodeWithMapP[T any](input map[string]any, cfgcfg *ConfigConfig, result *T, devault map[string]any) (*T, *ConfigMetadata)

func DecodeWithYaml

func DecodeWithYaml[T any](yamlText string, cfgcfg *ConfigConfig, result *T, devault map[string]any) (*T, *ConfigMetadata, error)

func DecodeWithYamlP

func DecodeWithYamlP[T any](yamlText string, cfgcfg *ConfigConfig, result *T, devault map[string]any) (*T, *ConfigMetadata)

type Content

type Content = *ContentT

type ContentT

type ContentT = models.RemoteFileContent

type Credentials

type Credentials = *CredentialsT

type CredentialsT

type CredentialsT = models.Credentials

type ErrCode added in v2.6.14

type ErrCode string
const (
	ErrCodeConfig   ErrCode = "CFG"
	ErrCodeBusiness ErrCode = "BIZ"
	ErrCodeSystem   ErrCode = "SYS"
	ErrCodeSecurity ErrCode = "SEC"
)

func (ErrCode) Error added in v2.6.14

func (me ErrCode) Error() string

type ErrorGroup

type ErrorGroup = *ErrorGroupT

func NewErrorGroup

func NewErrorGroup(dumpStack bool) ErrorGroup

func (ErrorGroup) Add

func (me ErrorGroup) Add(err error)

func (ErrorGroup) AddAll

func (me ErrorGroup) AddAll(that ErrorGroup)

func (ErrorGroup) AmountOfErrors

func (me ErrorGroup) AmountOfErrors() int

func (ErrorGroup) Error

func (me ErrorGroup) Error() string

func (ErrorGroup) HasError

func (me ErrorGroup) HasError() bool

func (ErrorGroup) MayError

func (me ErrorGroup) MayError() error

type ErrorGroupT

type ErrorGroupT struct {
	// contains filtered or unexported fields
}

type EventLogger

type EventLogger = *EventLoggerT

func NewEventLogger

func NewEventLogger(target Logger) EventLogger

func (EventLogger) LogDebug

func (me EventLogger) LogDebug(enm event.LogEnum, hub string, topic string, lsner string)

func (EventLogger) LogError

func (me EventLogger) LogError(enm event.LogEnum, hub string, topic string, lsner string, err any)

func (EventLogger) LogEventDebug

func (me EventLogger) LogEventDebug(enm event.LogEnum, lsner string, evnt event.Event)

func (EventLogger) LogEventError

func (me EventLogger) LogEventError(enm event.LogEnum, lsner string, evnt event.Event, err any)

func (EventLogger) LogEventInfo

func (me EventLogger) LogEventInfo(enm event.LogEnum, lsner string, evnt event.Event)

func (EventLogger) LogInfo

func (me EventLogger) LogInfo(enm event.LogEnum, hub string, topic string, lsner string)

func (EventLogger) Target

func (me EventLogger) Target() Logger

type EventLoggerT

type EventLoggerT struct {
	// contains filtered or unexported fields
}

type ExternalGoPluginContext added in v2.5.0

type ExternalGoPluginContext = *ExternalGoPluginContextT

func NewExternalGoPluginContext added in v2.5.0

func NewExternalGoPluginContext() ExternalGoPluginContext

func (ExternalGoPluginContext) GetStartFunc added in v2.5.0

func (me ExternalGoPluginContext) GetStartFunc() *reflect.Value

func (ExternalGoPluginContext) GetStopFunc added in v2.5.0

func (me ExternalGoPluginContext) GetStopFunc() *reflect.Value

func (ExternalGoPluginContext) Init added in v2.5.0

func (me ExternalGoPluginContext) Init(logger Logger, fs afero.Fs, codeFile string)

func (ExternalGoPluginContext) Start added in v2.5.0

func (me ExternalGoPluginContext) Start() any

func (ExternalGoPluginContext) Stop added in v2.5.0

func (me ExternalGoPluginContext) Stop() any

type ExternalGoPluginContextT added in v2.5.0

type ExternalGoPluginContextT struct {
	// contains filtered or unexported fields
}

type ExternalPlugin added in v2.5.0

type ExternalPlugin = *ExternalPluginT

func ListExternalPlugins added in v2.5.0

func ListExternalPlugins(logger Logger, afs afero.Fs, baseDir string) []ExternalPlugin

func ResolveExternalPlugin added in v2.5.0

func ResolveExternalPlugin(logger Logger, fs afero.Fs, pluginDir string) (result ExternalPlugin)

func (ExternalPlugin) CodeFile added in v2.5.0

func (me ExternalPlugin) CodeFile() string

func (ExternalPlugin) Dir added in v2.5.0

func (me ExternalPlugin) Dir() string

func (ExternalPlugin) IsStarted added in v2.5.0

func (me ExternalPlugin) IsStarted() bool

func (ExternalPlugin) Kind added in v2.5.0

func (me ExternalPlugin) Kind() PluginKind

func (ExternalPlugin) Language added in v2.5.0

func (me ExternalPlugin) Language() string

func (ExternalPlugin) Name added in v2.5.0

func (me ExternalPlugin) Name() string

func (ExternalPlugin) Start added in v2.5.0

func (me ExternalPlugin) Start(logger Logger)

func (ExternalPlugin) Stop added in v2.5.0

func (me ExternalPlugin) Stop(logger Logger)

func (ExternalPlugin) Version added in v2.5.0

func (me ExternalPlugin) Version() (major int, minor int)

type ExternalPluginContext added in v2.5.0

type ExternalPluginContext interface {
	Init(logger Logger, fs afero.Fs, codeFile string)
	Start() any
	Stop() any
}

type ExternalPluginT added in v2.5.0

type ExternalPluginT struct {
	// contains filtered or unexported fields
}

type ExtractedCommand added in v2.6.13

type ExtractedCommand = *ExtractedCommandT

ExtractedCommand 是 ExtractedCommandT 的指针别名

type ExtractedCommandT added in v2.6.13

type ExtractedCommandT struct {
	// Name 命令名
	Name string
	// Args 参数列表
	Args []string
	// Source 命令来源类型
	Source CommandSource
	// Position 在源码中的位置
	Position syntax.Pos
	// Envs 环境变量设置 (如 "VAR=value")
	Envs []string
}

ExtractedCommandT 从 AST 提取的命令信息

type File

type File interface {
	Name() string
	Dir() string
	Url() string
	Protocol() string
	URL() *url.URL
	Credentials() Credentials
	Timeout() time.Duration
	DownloadP() Content
	Download() (Content, error)
}

func NewFile

func NewFile(afs afero.Fs, url string, credentials Credentials, timeout time.Duration) (File, error)

func NewFileP

func NewFileP(afs afero.Fs, url string, credentials Credentials, timeout time.Duration) File

type FileCache added in v2.5.5

type FileCache = *FileCacheT

func NewFileCache added in v2.5.5

func NewFileCache(cacheDir string) FileCache

NewFileCache 创建文件缓存管理器 cacheDir: 缓存目录路径,如果为空则使用 ~/.cache/<appName>

func (FileCache) Clear added in v2.5.5

func (me FileCache) Clear()

Clear 清空所有缓存

func (FileCache) CopyTo added in v2.5.5

func (me FileCache) CopyTo(key string, destPath string)

CopyTo 从缓存复制文件到目标位置

func (FileCache) Delete added in v2.5.5

func (me FileCache) Delete(key string)

Delete 删除缓存文件

func (FileCache) Get added in v2.5.5

func (me FileCache) Get(key string) string

Get 获取缓存文件路径 如果文件存在返回路径,否则返回空字符串

func (FileCache) GetCacheDir added in v2.5.5

func (me FileCache) GetCacheDir() string

GetCacheDir 获取缓存目录路径

func (FileCache) Has added in v2.5.5

func (me FileCache) Has(key string) bool

Has 检查缓存是否存在

func (FileCache) Put added in v2.5.5

func (me FileCache) Put(srcPath string, key string)

Put 将文件添加到缓存

func (FileCache) Size added in v2.5.5

func (me FileCache) Size() int64

Size 获取缓存总大小(字节)

type FileCacheT added in v2.5.5

type FileCacheT struct {
	// contains filtered or unexported fields
}

FileCache 文件缓存管理器

type FileOps added in v2.5.5

type FileOps = *FileOpsT

func NewFileOps added in v2.5.5

func NewFileOps(fs afero.Fs) FileOps

NewFileOps 创建文件操作器

func NewLocalizedFileOps added in v2.5.5

func NewLocalizedFileOps(fs afero.Fs) FileOps

NewLocalizedFileOps creates a FileOps with built-in i18n support

func (FileOps) CopyFile added in v2.5.5

func (f FileOps) CopyFile(srcPath, destPath string)

CopyFile 复制文件

func (FileOps) CreateDirectory added in v2.5.5

func (f FileOps) CreateDirectory(dirPath string, chmod, chown string, useSudo bool, sudoPassword string)

CreateDirectory 创建目录

func (f FileOps) CreateSymlink(targetPath, linkPath string, useSudo bool, sudoPassword string)

CreateSymlink 创建符号链接

func (FileOps) DirExists added in v2.5.5

func (f FileOps) DirExists(dirPath string) bool

DirExists 检查目录是否存在

func (FileOps) EnsureDir added in v2.5.5

func (f FileOps) EnsureDir(dirPath string)

EnsureDir 确保目录存在

func (FileOps) FileExists added in v2.5.5

func (f FileOps) FileExists(filePath string) bool

FileExists 检查文件是否存在

func (FileOps) GetFileSize added in v2.5.5

func (f FileOps) GetFileSize(filePath string) int64

GetFileSize 获取文件大小

func (FileOps) GetFs added in v2.5.5

func (f FileOps) GetFs() afero.Fs

GetFs 获取文件系统

func (FileOps) MoveFile added in v2.5.5

func (f FileOps) MoveFile(srcPath, destPath string)

MoveFile 移动文件

func (FileOps) RemoveFile added in v2.5.5

func (f FileOps) RemoveFile(filePath string, useSudo bool, sudoPassword string)

RemoveFile 删除文件

func (FileOps) RenameFile added in v2.5.5

func (f FileOps) RenameFile(oldPath, newName string) string

RenameFile 重命名文件

func (FileOps) SetLocalizeFunc added in v2.5.5

func (f FileOps) SetLocalizeFunc(localize LocalizeFunc)

SetLocalizeFunc 设置本地化函数

func (FileOps) SetOwner added in v2.5.5

func (f FileOps) SetOwner(filePath, chown string, useSudo bool, sudoPassword string)

SetOwner 设置文件所有者 chown: 所有者字符串,如 "user:group"

func (FileOps) SetPermissions added in v2.5.5

func (f FileOps) SetPermissions(filePath, chmod string)

SetPermissions 设置文件权限 chmod: 权限字符串,如 "755", "0644"

type FileOpsT added in v2.5.5

type FileOpsT struct {
	// contains filtered or unexported fields
}

FileOps 通用文件操作

type FnInput

type FnInput func() string

type FsPluginLoader added in v2.5.0

type FsPluginLoader = *FsPluginLoaderT

func (FsPluginLoader) Start added in v2.5.0

func (me FsPluginLoader) Start(logger Logger) error

type FsPluginLoaderT added in v2.5.0

type FsPluginLoaderT struct {
	BasePluginLoaderT
	// contains filtered or unexported fields
}

type GoCommandHandler added in v2.6.12

type GoCommandHandler func(ctx context.Context, hc interp.HandlerContext, args []string) error

GoCommandHandler Go 实现的命令处理器

func MatchHandler added in v2.6.13

func MatchHandler(registry HandlerRegistry, cmd string) (GoCommandHandler, bool)

MatchHandler 从注册器匹配命令处理器的便捷函数

type GoshConfig added in v2.6.12

type GoshConfig = *GoshConfigT

func DefaultGoshConfig added in v2.6.12

func DefaultGoshConfig() GoshConfig

DefaultGoshConfig 返回默认配置

func (GoshConfig) WithBlacklist added in v2.6.12

func (me GoshConfig) WithBlacklist(rules ...CommandRule) GoshConfig

WithBlacklist 设置黑名单规则

func (GoshConfig) WithBlacklistSimple added in v2.6.12

func (me GoshConfig) WithBlacklistSimple(cmds ...string) GoshConfig

WithBlacklistSimple 设置简单黑名单(仅命令名,精确匹配)

func (GoshConfig) WithGoHandler added in v2.6.12

func (me GoshConfig) WithGoHandler(pattern string, handler GoCommandHandler) GoshConfig

WithGoHandler 注册 Go 命令处理器 pattern 支持通配符,如 "curl*" 匹配 curl 和 curlconfig

func (GoshConfig) WithKillTimeout added in v2.6.12

func (me GoshConfig) WithKillTimeout(d time.Duration) GoshConfig

WithKillTimeout 设置超时

func (GoshConfig) WithWhitelist added in v2.6.12

func (me GoshConfig) WithWhitelist(rules ...CommandRule) GoshConfig

WithWhitelist 设置白名单规则

func (GoshConfig) WithWhitelistMode added in v2.6.12

func (me GoshConfig) WithWhitelistMode(enabled bool) GoshConfig

WithWhitelistMode 启用/禁用白名单模式

func (GoshConfig) WithWhitelistSimple added in v2.6.12

func (me GoshConfig) WithWhitelistSimple(cmds ...string) GoshConfig

WithWhitelistSimple 设置简单白名单(仅命令名,精确匹配)

type GoshConfigT added in v2.6.12

type GoshConfigT struct {
	// KillTimeout 命令超时时间
	KillTimeout time.Duration

	// Blacklist 黑名单规则(这些命令会被拒绝)
	// 支持通配符和参数匹配
	Blacklist []CommandRule

	// WhitelistMode 是否启用白名单模式
	// 启用后,只有 Whitelist 中的命令才能执行
	WhitelistMode bool

	// Whitelist 白名单规则(仅白名单模式生效)
	Whitelist []CommandRule

	// GoHandlers Go 实现的命令处理器
	// key 支持通配符,如 "curl*" 匹配 curl 和 curlconfig
	GoHandlers map[string]GoCommandHandler
}

GoshConfigT 命令执行器配置

type GoshExecutor added in v2.6.12

type GoshExecutor = *GoshExecutorT

func NewGoshExecutor added in v2.6.12

func NewGoshExecutor(config GoshConfig) GoshExecutor

NewGoshExecutor 创建执行器

func (GoshExecutor) Run added in v2.6.12

func (me GoshExecutor) Run(ctx context.Context, dir string, cmd string,
	stdin io.Reader, stdout, stderr io.Writer,
) error

Run 执行命令

func (GoshExecutor) RunWithVars added in v2.6.12

func (me GoshExecutor) RunWithVars(ctx context.Context, vars map[string]string,
	dir string, cmd string, stdin io.Reader, stdout, stderr io.Writer,
) error

RunWithVars 执行命令(带变量)

type GoshExecutorT added in v2.6.12

type GoshExecutorT struct {
	// contains filtered or unexported fields
}

GoshExecutorT 可配置的 Shell 命令执行器

type HandlerOption added in v2.6.13

type HandlerOption func(*handlerEntry)

HandlerOption 处理器注册选项函数

func WithDescription added in v2.6.13

func WithDescription(desc string) HandlerOption

WithDescription 设置处理器描述

func WithMatchMode added in v2.6.13

func WithMatchMode(m MatchMode) HandlerOption

WithMatchMode 设置匹配模式

func WithPriority added in v2.6.13

func WithPriority(p int) HandlerOption

WithPriority 设置处理器优先级(数值越大优先级越高)

type HandlerRegistry added in v2.6.13

type HandlerRegistry = *HandlerRegistryT

HandlerRegistry 是 HandlerRegistryT 的指针别名

func NewHandlerRegistry added in v2.6.13

func NewHandlerRegistry() HandlerRegistry

NewHandlerRegistry 创建处理器注册器

func (HandlerRegistry) Clear added in v2.6.13

func (me HandlerRegistry) Clear()

Clear 清除所有已注册的处理器

func (HandlerRegistry) Count added in v2.6.13

func (me HandlerRegistry) Count() int

Count 返回已注册处理器的数量

func (HandlerRegistry) List added in v2.6.13

func (me HandlerRegistry) List() []string

List 列出所有已注册的处理器

func (HandlerRegistry) Match added in v2.6.13

func (me HandlerRegistry) Match(cmd string) (GoCommandHandler, bool)

Match 匹配命令并返回处理器

func (HandlerRegistry) Register added in v2.6.13

func (me HandlerRegistry) Register(pattern string, handler GoCommandHandler, opts ...HandlerOption) HandlerRegistry

Register 注册处理器

type HandlerRegistryT added in v2.6.13

type HandlerRegistryT struct {
	// contains filtered or unexported fields
}

HandlerRegistryT 处理器注册器

type HashCalculator added in v2.5.5

type HashCalculator = *HashCalculatorT

func NewHashCalculator added in v2.5.5

func NewHashCalculator() HashCalculator

NewHashCalculator 创建哈希计算器

func (HashCalculator) CalculateMD5 added in v2.5.5

func (h HashCalculator) CalculateMD5(filePath string) string

CalculateMD5 计算文件的MD5哈希值

func (HashCalculator) CalculateMD5FromReader added in v2.5.5

func (h HashCalculator) CalculateMD5FromReader(r io.Reader) string

CalculateMD5FromReader 从io.Reader计算MD5

func (HashCalculator) CalculateSHA256 added in v2.5.5

func (h HashCalculator) CalculateSHA256(filePath string) string

CalculateSHA256 计算文件的SHA256哈希值

func (HashCalculator) CalculateSHA256FromReader added in v2.5.5

func (h HashCalculator) CalculateSHA256FromReader(r io.Reader) string

CalculateSHA256FromReader 从io.Reader计算SHA256

type HashCalculatorT added in v2.5.5

type HashCalculatorT struct{}

HashCalculator 哈希计算器

type JSONBackend added in v2.7.1

type JSONBackend int

JSONBackend 定义 JSON 后端类型

const (
	// JSONBackendSonic 使用 ByteDance sonic 库(默认,性能更优)
	JSONBackendSonic JSONBackend = iota
	// JSONBackendStdlib 使用 Go 标准库 encoding/json
	JSONBackendStdlib
)

type KeyValue

type KeyValue[K any] struct {
	Key   string
	Value K
}

type LocalizeFunc added in v2.5.5

type LocalizeFunc func(id string, args ...map[string]any) string

LocalizeFunc is the i18n localization function type

var DefaultLocalizeFunc LocalizeFunc = func(id string, args ...map[string]any) string {
	return id
}

DefaultLocalizeFunc is the default localization function (returns id directly)

type LogContext

type LogContext = LogEntry

func NewLogContext

func NewLogContext(generateNewTraceId bool) LogContext

type LogEntry

type LogEntry = *plog.Entry

type Logger

type Logger = *LoggerT

func NewDiscardLogger

func NewDiscardLogger() Logger

func NewLogger

func NewLogger(console io.Writer, config LoggerConfig, fileName string) (Logger, error)

/ verbose: log to console if true

func NewLoggerP

func NewLoggerP(console io.Writer, config LoggerConfig, fileName string) Logger

func (Logger) Close

func (me Logger) Close()

func (Logger) Error

func (me Logger) Error(err any) LogEntry

func (Logger) NewSubLogger

func (me Logger) NewSubLogger(lctx LogContext) Logger

func (Logger) Parent

func (me Logger) Parent() Logger

type LoggerConfig

type LoggerConfig = *LoggerConfigT

type LoggerConfigT

type LoggerConfigT struct {
	MaxSize    int  `json:"max_size" yaml:"maxsize"`
	MaxAge     int  `json:"max_age" yaml:"maxage"`
	MaxBackups int  `json:"max_backups" yaml:"maxbackups"`
	LocalTime  bool `json:"local_time" yaml:"localtime"`
	Compress   bool `json:"compress" yaml:"compress"`
}

see lumberjack.Logger

type LoggerT

type LoggerT struct {
	plog.Logger
	// contains filtered or unexported fields
}

type MatchMode added in v2.6.13

type MatchMode int

MatchMode 表示匹配模式

const (
	// MatchGlob 通配符匹配 (使用 filepath.Match)
	MatchGlob MatchMode = iota
	// MatchExact 精确匹配
	MatchExact
	// MatchRegex 正则表达式匹配
	MatchRegex
)

type OrderedMap

type OrderedMap[K any] struct {
	// contains filtered or unexported fields
}

func NewOrderedMap

func NewOrderedMap[K any](nilValue K) *OrderedMap[K]

func (*OrderedMap[K]) Delete

func (me *OrderedMap[K]) Delete(key string)

func (*OrderedMap[K]) Entries

func (me *OrderedMap[K]) Entries() []*KeyValue[K]

func (*OrderedMap[K]) Find

func (me *OrderedMap[K]) Find(key string) (K, bool)

func (*OrderedMap[K]) Get

func (me *OrderedMap[K]) Get(key string) K

func (*OrderedMap[K]) Has

func (me *OrderedMap[K]) Has(key string) bool

func (*OrderedMap[K]) Keys

func (me *OrderedMap[K]) Keys() *hashset.Set

func (*OrderedMap[K]) Len

func (me *OrderedMap[K]) Len() int

func (*OrderedMap[K]) MarshalJSON

func (me *OrderedMap[K]) MarshalJSON() ([]byte, error)

func (*OrderedMap[K]) Put

func (me *OrderedMap[K]) Put(key string, value K)

func (*OrderedMap[K]) PutAll

func (me *OrderedMap[K]) PutAll(nameResolver func(v K) string, values []K)

func (*OrderedMap[K]) PutIfAbsent

func (me *OrderedMap[K]) PutIfAbsent(key string, value K) bool

func (*OrderedMap[K]) SortByKey

func (me *OrderedMap[K]) SortByKey(revert bool)

func (*OrderedMap[K]) ToMap added in v2.4.1

func (me *OrderedMap[K]) ToMap() map[string]K

func (*OrderedMap[K]) UnmarshalJSON

func (me *OrderedMap[K]) UnmarshalJSON(bytes []byte) error

func (*OrderedMap[K]) Values

func (me *OrderedMap[K]) Values() []K

type Plugin added in v2.5.0

type Plugin interface {
	Name() string
	Kind() PluginKind
	Start(logger Logger)
	Stop(logger Logger)
	Version() (major int, minor int)
}

type PluginKind added in v2.5.0

type PluginKind = string

type PluginLang added in v2.5.0

type PluginLang = string

type PluginLoader added in v2.5.0

type PluginLoader interface {
	Namespace() string
	Plugins() map[string]Plugin
	Start(logger Logger) error
	Stop(logger Logger) error
}

func NewFsPluginLoader added in v2.5.0

func NewFsPluginLoader(logger Logger, fs afero.Fs, dir string, namespace string) PluginLoader

func NewLocalPluginLoader added in v2.5.0

func NewLocalPluginLoader(logger Logger, fs afero.Fs, dir string) PluginLoader

func NewRemotePluginLoader added in v2.5.0

func NewRemotePluginLoader(logger Logger, fs afero.Fs, dir string) PluginLoader

type PluginManifest added in v2.5.0

type PluginManifest = *PluginManifestT

func PluginManifestWithJsonFile added in v2.5.0

func PluginManifestWithJsonFile(fs afero.Fs, manifestJsonFile string) PluginManifest

func PluginManifestWithMap added in v2.5.0

func PluginManifestWithMap(manifestMap map[string]any) PluginManifest

func PluginManifestWithYamlFile added in v2.5.0

func PluginManifestWithYamlFile(fs afero.Fs, manifestYamlFile string) PluginManifest

type PluginManifestT added in v2.5.0

type PluginManifestT struct {
	Kind         PluginKind `mapstructure:"kind" yaml:"kind"`
	Name         string     `mapstructure:"name" yaml:"name"`
	VersionMajor int        `mapstructure:"version_major" yaml:"version_major"`
	VersionMinor int        `mapstructure:"version_minor" yaml:"version_minor"`
}

type PluginRegistry added in v2.5.0

type PluginRegistry = *PluginRegistryT

func NewPluginRegistry added in v2.5.0

func NewPluginRegistry(supportedMajorVersion int, supportedKinds ...PluginKind) PluginRegistry

func (PluginRegistry) ByKind added in v2.5.0

func (me PluginRegistry) ByKind(kind PluginKind) map[string]Plugin

func (PluginRegistry) Destroy added in v2.5.0

func (me PluginRegistry) Destroy(logger Logger)

func (PluginRegistry) HasNamespace added in v2.5.0

func (me PluginRegistry) HasNamespace(ns string) bool

func (PluginRegistry) Init added in v2.5.0

func (me PluginRegistry) Init(logger Logger)

func (PluginRegistry) IsSupportedPluginKind added in v2.5.0

func (me PluginRegistry) IsSupportedPluginKind(kind PluginKind) bool

func (PluginRegistry) Register added in v2.5.0

func (me PluginRegistry) Register(loader PluginLoader)

func (PluginRegistry) SupportedMajorVersion added in v2.5.0

func (me PluginRegistry) SupportedMajorVersion() int

func (PluginRegistry) ValidatePlugin added in v2.5.0

func (me PluginRegistry) ValidatePlugin(namespace string, plugin Plugin) error

type PluginRegistryT added in v2.5.0

type PluginRegistryT struct {
	// contains filtered or unexported fields
}

type ProgressReader added in v2.5.5

type ProgressReader = *ProgressReaderT

func NewProgressReader added in v2.5.5

func NewProgressReader(reader io.Reader, total int64, onProgress func(transferred, total int64, speed float64)) ProgressReader

NewProgressReader 创建进度读取器 reader: 要包装的io.Reader total: 总大小(如果未知则为0) onProgress: 进度回调函数,参数为(已传输字节数, 总字节数, 传输速度bytes/s)

func (ProgressReader) Finish added in v2.5.5

func (p ProgressReader) Finish()

Finish 完成传输,触发最后一次进度报告

func (ProgressReader) GetStatistics added in v2.5.5

func (p ProgressReader) GetStatistics() (transferred int64, total int64, avgSpeed float64, duration time.Duration)

GetStatistics 获取传输统计信息

func (ProgressReader) Read added in v2.5.5

func (p ProgressReader) Read(buf []byte) (int, error)

type ProgressReaderT added in v2.5.5

type ProgressReaderT struct {
	// contains filtered or unexported fields
}

ProgressReader 进度读取器,包装io.Reader并报告读取进度

type ProgressWriter added in v2.5.5

type ProgressWriter = *ProgressWriterT

func NewProgressWriter added in v2.5.5

func NewProgressWriter(writer io.Writer, total int64, onProgress func(transferred, total int64, speed float64)) ProgressWriter

NewProgressWriter 创建进度写入器

func (ProgressWriter) Finish added in v2.5.5

func (p ProgressWriter) Finish()

Finish 完成传输,触发最后一次进度报告

func (ProgressWriter) GetStatistics added in v2.5.5

func (p ProgressWriter) GetStatistics() (transferred int64, total int64, avgSpeed float64, duration time.Duration)

GetStatistics 获取传输统计信息

func (ProgressWriter) Write added in v2.5.5

func (p ProgressWriter) Write(buf []byte) (int, error)

type ProgressWriterT added in v2.5.5

type ProgressWriterT struct {
	// contains filtered or unexported fields
}

ProgressWriter 进度写入器,包装io.Writer并报告写入进度

type QlogLoggerAdapter added in v2.7.7

type QlogLoggerAdapter struct {
	Logger Logger
}

QlogLoggerAdapter 将 comm.Logger 适配为 qgin.Logger 接口

func NewQlogLoggerAdapter added in v2.7.7

func NewQlogLoggerAdapter(logger Logger) *QlogLoggerAdapter

NewQlogLoggerAdapter 创建适配器

func (*QlogLoggerAdapter) Debug added in v2.7.7

func (a *QlogLoggerAdapter) Debug(msg string, fields ...any)

Debug 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) Error added in v2.7.7

func (a *QlogLoggerAdapter) Error(msg string, fields ...any)

Error 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) Fatal added in v2.7.7

func (a *QlogLoggerAdapter) Fatal(msg string, fields ...any)

Fatal 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) Info added in v2.7.7

func (a *QlogLoggerAdapter) Info(msg string, fields ...any)

Info 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) Panic added in v2.7.7

func (a *QlogLoggerAdapter) Panic(msg string, fields ...any)

Panic 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) Trace added in v2.7.7

func (a *QlogLoggerAdapter) Trace(msg string, fields ...any)

Trace 实现 qgin.Logger 接口 phuslu/log 没有 Trace 级别,使用 Debug 代替

func (*QlogLoggerAdapter) Warn added in v2.7.7

func (a *QlogLoggerAdapter) Warn(msg string, fields ...any)

Warn 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) WithField added in v2.7.7

func (a *QlogLoggerAdapter) WithField(key string, value any) any

WithField 实现 qgin.Logger 接口

func (*QlogLoggerAdapter) WithFields added in v2.7.7

func (a *QlogLoggerAdapter) WithFields(fields map[string]any) any

WithFields 实现 qgin.Logger 接口

type RemoteFile

type RemoteFile = *RemoteFileT

func NewRemoteFile

func NewRemoteFile(url string, credentials Credentials, timeout time.Duration) (RemoteFile, error)

func NewRemoteFileP

func NewRemoteFileP(url string, credentials Credentials, timeout time.Duration) RemoteFile

func (RemoteFile) Credentials

func (me RemoteFile) Credentials() Credentials

func (RemoteFile) Dir

func (me RemoteFile) Dir() string

filepath

func (RemoteFile) Download

func (me RemoteFile) Download() (Content, error)

func (RemoteFile) DownloadP

func (me RemoteFile) DownloadP() Content

func (RemoteFile) Name

func (me RemoteFile) Name() string

func (RemoteFile) Protocol

func (me RemoteFile) Protocol() string

remote protocol. May be used to explicitly tell what protocol to use (i.e. "http", "ftp", "etc").

func (RemoteFile) Timeout

func (me RemoteFile) Timeout() time.Duration

func (RemoteFile) URL

func (me RemoteFile) URL() *url.URL

func (RemoteFile) Url

func (me RemoteFile) Url() string

remote file/dir url

type RemoteFileT

type RemoteFileT struct {
	// contains filtered or unexported fields
}

type SSHConfig added in v2.5.7

type SSHConfig struct {
	// contains filtered or unexported fields
}

SSHConfig represents the parsed SSH configuration

func LoadSSHConfig added in v2.5.7

func LoadSSHConfig() (*SSHConfig, error)

LoadSSHConfig loads SSH configuration from ~/.ssh/config

func LoadSSHConfigFromFile added in v2.5.7

func LoadSSHConfigFromFile(path string) (*SSHConfig, error)

LoadSSHConfigFromFile loads SSH configuration from specified file

func NewSSHConfig added in v2.5.7

func NewSSHConfig() *SSHConfig

NewSSHConfig creates a new SSHConfig

func (*SSHConfig) GetHostConfig added in v2.5.7

func (c *SSHConfig) GetHostConfig(host string) *SSHHostConfig

GetHostConfig returns SSH configuration for the specified host

type SSHHostConfig added in v2.5.7

type SSHHostConfig struct {
	Host                 string
	HostName             string
	User                 string
	Port                 int
	IdentityFile         string
	IdentityFiles        []string
	PreferredAuth        []string
	ProxyJump            string
	ProxyCommand         string
	ForwardAgent         bool
	Compression          bool
	ServerAliveInterval  int
	ServerAliveCountMax  int
	StrictHostKeyCheck   string
	UserKnownHostsFile   string
	ConnectTimeout       int
	PasswordAuth         bool
	PubkeyAuth           bool
	KbdInteractiveAuth   bool
	RekeyLimit           string
	SendEnv              []string
	SetEnv               map[string]string
	RequestTTY           string
	RemoteCommand        string
	LocalForward         []string
	RemoteForward        []string
	DynamicForward       []string
	ExitOnForwardFailure bool
	ControlMaster        string
	ControlPath          string
	ControlPersist       string
}

SSHHostConfig represents SSH configuration for a specific host

type SecurityCheckError added in v2.6.13

type SecurityCheckError = *SecurityCheckErrorT

SecurityCheckError 是 SecurityCheckErrorT 的指针别名

func GetSecurityCheckError added in v2.6.13

func GetSecurityCheckError(err error) SecurityCheckError

GetSecurityCheckError 获取安全检查错误详情

func (SecurityCheckError) Error added in v2.6.13

func (e SecurityCheckError) Error() string

Error 实现 error 接口

type SecurityCheckErrorT added in v2.6.13

type SecurityCheckErrorT struct {
	// Command 触发错误的命令
	Command ExtractedCommand
	// Rule 触发错误的规则 (可能为 nil)
	Rule CommandRule
	// Message 错误消息
	Message string
	// ViolationType 违规类型
	ViolationType string
}

SecurityCheckErrorT 安全检查错误

type SecurityChecker added in v2.6.13

type SecurityChecker = *SecurityCheckerT

SecurityChecker 是 SecurityCheckerT 的指针别名

func NewSecurityChecker added in v2.6.13

func NewSecurityChecker() SecurityChecker

NewSecurityChecker 创建安全检查器

func (SecurityChecker) Check added in v2.6.13

func (me SecurityChecker) Check(cmds []ExtractedCommand) error

Check 检查命令列表是否通过安全检查

func (SecurityChecker) WithBlacklist added in v2.6.13

func (me SecurityChecker) WithBlacklist(rules ...CommandRule) SecurityChecker

WithBlacklist 添加黑名单规则

func (SecurityChecker) WithWhitelist added in v2.6.13

func (me SecurityChecker) WithWhitelist(rules ...CommandRule) SecurityChecker

WithWhitelist 添加白名单规则

func (SecurityChecker) WithWhitelistMode added in v2.6.13

func (me SecurityChecker) WithWhitelistMode(enabled bool) SecurityChecker

WithWhitelistMode 设置白名单模式

type SecurityCheckerT added in v2.6.13

type SecurityCheckerT struct {
	// contains filtered or unexported fields
}

SecurityCheckerT 安全检查器

type SlogLogger added in v2.6.15

type SlogLogger = *SlogLoggerT

func (SlogLogger) Enabled added in v2.6.15

func (me SlogLogger) Enabled(_ context.Context, level slog.Level) bool

func (SlogLogger) Handle added in v2.6.15

func (me SlogLogger) Handle(_ context.Context, r slog.Record) error

func (SlogLogger) WithAttrs added in v2.6.15

func (me SlogLogger) WithAttrs(attrs []slog.Attr) slog.Handler

func (SlogLogger) WithGroup added in v2.6.15

func (me SlogLogger) WithGroup(name string) slog.Handler

type SlogLoggerT added in v2.6.19

type SlogLoggerT struct {
	// contains filtered or unexported fields
}

SlogLoggerT 将 comm.Logger 包装为 slog.Logger

func NewSlogLogger added in v2.6.15

func NewSlogLogger(logger Logger) *SlogLoggerT

NewSlogLogger 创建 slog.Logger

type SonicAPI deprecated added in v2.7.2

type SonicAPI = qgin.SonicAPI

SonicAPI 是 qgin.SonicAPI 的别名

Deprecated: 请使用 qgin.SonicAPI

type SystemDetector added in v2.5.5

type SystemDetector = *SystemDetectorT

func NewSystemDetector added in v2.5.5

func NewSystemDetector() SystemDetector

NewSystemDetector 创建系统检测器

func (SystemDetector) GetSystemInfo added in v2.5.5

func (d SystemDetector) GetSystemInfo() SystemInfo

GetSystemInfo 获取系统信息

func (SystemDetector) IsLinux added in v2.5.5

func (d SystemDetector) IsLinux() bool

IsLinux 是否为Linux系统

func (SystemDetector) IsMacOS added in v2.5.5

func (d SystemDetector) IsMacOS() bool

IsMacOS 是否为macOS系统

func (SystemDetector) IsWindows added in v2.5.5

func (d SystemDetector) IsWindows() bool

IsWindows 是否为Windows系统

func (SystemDetector) MatchSystem added in v2.5.5

func (d SystemDetector) MatchSystem(os, dist, version, arch string) bool

MatchSystem 检查系统是否匹配指定条件 支持逗号或空格分隔的多个值

type SystemDetectorT added in v2.5.5

type SystemDetectorT struct {
	// contains filtered or unexported fields
}

SystemDetector 系统检测器

type SystemInfo added in v2.5.5

type SystemInfo struct {
	OS      string // 操作系统: linux, windows, macos
	Dist    string // Linux发行版: ubuntu, debian, centos, fedora等
	Version string // 发行版版本
	Arch    string // 架构: x86, amd64, arm64, armhf
}

SystemInfo 系统信息

type ToMap added in v2.3.1

type ToMap interface {
	ToMap() map[string]any
}

Directories

Path Synopsis
playground
file command
zenity command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址