Documentation
¶
Overview ¶
Package zcli 是一个基于cobra的命令行应用框架,提供了更友好的命令行界面和系统服务管理功能。
ZCli的主要特性包括:
友好的命令行界面:
- 支持彩色输出,自动检测终端颜色支持
- 自定义Logo显示
- 分组显示命令(普通命令和系统命令)
- 优化的帮助信息展示
- 支持命令补全
系统服务集成:
- 一键集成系统服务管理功能
- 支持服务的安装、卸载、启动、停止、重启和状态查询
- 支持服务配置的自定义(工作目录、环境变量等)
- 跨平台支持 (Windows, Linux, macOS)
国际化支持:
- 内置中文和英文支持
- 可扩展的语言包系统
- 支持自定义语言包和错误消息
版本信息管理:
- 详细的版本信息展示
- 支持构建信息的自定义
- 支持调试/发布模式切换
使用示例:
package main
import (
"log/slog"
"os"
"time"
"github.com/darkit/zcli"
)
var isRunning = true
func main() {
workDir, _ := os.UserHomeDir()
app := zcli.NewBuilder("zh").
WithName("myapp").
WithDisplayName("我的应用").
WithDescription("这是一个示例应用").
WithVersion("1.0.0").
WithWorkDir(workDir).
WithSystemService(run, stop).
Build()
// 执行应用
if err := app.Execute(); err != nil {
slog.Error(err.Error())
}
}
func run() {
slog.Info("服务已启动")
isRunning = true
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
if !isRunning {
break
}
slog.Info("服务正在运行...")
}
}
func stop() {
slog.Warn("服务停止中...")
isRunning = false
slog.Info("服务已停止")
}
主要结构:
Builder: CLI构建器,使用链式调用方式配置应用
app := zcli.NewBuilder("zh").
WithName("myapp").
WithSystemService(run, stop).
Build()
Cli: 命令行应用对象,封装了cobra.Command
// 添加命令 app.AddCommand(myCommand) // 执行应用 app.Execute()
Config: 应用配置,包含基本信息、运行时配置和服务配置
Language: 语言包定义,支持多语言
Command: 命令定义,等同于cobra.Command
最低Go版本要求: 1.19 (使用了atomic.Bool等特性)
更多信息和示例请参考: https://github.com/darkit/zcli
Package zcli 提供命令行工具构建功能,包括增强的错误处理机制。 本包实现了结构化错误处理、错误聚合和详细的错误追踪功能。
Index ¶
- Variables
- func CombineErrors(errs ...error) error
- func GetText(path string) string
- func IsErrorCode(err error, code ErrorCode) bool
- func IsServiceError(err error) bool
- func RegisterLanguage(lang *Language) error
- func SetLanguage(langCode string) error
- type BaseService
- type Basic
- type BuildError
- type Builder
- func (b *Builder) Build() *Cli
- func (b *Builder) BuildWithError() (*Cli, error)
- func (b *Builder) MustBuild() *Cli
- func (b *Builder) WithBuildTime(buildTime string) *Builder
- func (b *Builder) WithCommand(cmd *Command) *Builder
- func (b *Builder) WithContext(ctx context.Context) *Builder
- func (b *Builder) WithCustomService(fn func(*Config)) *Builder
- func (b *Builder) WithDebug(debug bool) *Builder
- func (b *Builder) WithDefaultConfig() *Builder
- func (b *Builder) WithDefaults() *Builder
- func (b *Builder) WithDependencies(deps ...string) *Builder
- func (b *Builder) WithDescription(desc string) *Builder
- func (b *Builder) WithDisplayName(name string) *Builder
- func (b *Builder) WithEnvVar(key, value string) *Builder
- func (b *Builder) WithGitInfo(commitID, branch, tag string) *Builder
- func (b *Builder) WithLanguage(lang string) *Builder
- func (b *Builder) WithLogo(logo string) *Builder
- func (b *Builder) WithName(name string) *Builder
- func (b *Builder) WithQuickConfig(name, displayName, description, version string) *Builder
- func (b *Builder) WithRuntime(rt *Runtime) *Builder
- func (b *Builder) WithService(run RunFunc, stop ...StopFunc) *Builder
- func (b *Builder) WithServiceOptions(workDir string, envVars map[string]string, deps ...string) *Builder
- func (b *Builder) WithServiceRunner(service ServiceRunner) *Builder
- func (b *Builder) WithShutdownTimeouts(initial, grace time.Duration) *Builder
- func (b *Builder) WithValidator(validator func(*Config) error) *Builder
- func (b *Builder) WithVersion(version string) *Builder
- func (b *Builder) WithWorkDir(dir string) *Builder
- type Cli
- func (c *Cli) AddCommand(cmds ...*Command)
- func (c *Cli) AddGroup(groups ...*Group)
- func (c *Cli) AllChildCommandsHaveGroup() bool
- func (c *Cli) ArgsLenAtDash() int
- func (c *Cli) CalledAs() string
- func (c *Cli) Command() *cobra.Command
- func (c *Cli) CommandPath() string
- func (c *Cli) CommandPathPadding() int
- func (c *Cli) Commands() []*Command
- func (c *Cli) Config() Config
- func (c *Cli) ContainsGroup(groupID string) bool
- func (c *Cli) Context() context.Context
- func (c *Cli) Done() <-chan struct{}
- func (c *Cli) Execute() error
- func (c *Cli) ExecuteC() (*Command, error)
- func (c *Cli) ExecuteContext(ctx context.Context) error
- func (c *Cli) ExecuteContextC(ctx context.Context) (*Command, error)
- func (c *Cli) ExportFlagsForViper(excludeFlags ...string) []*FlagSet
- func (c *Cli) Flag(name string) *Flag
- func (c *Cli) FlagErrorFunc() func(*Command, error) error
- func (c *Cli) Flags() *FlagSet
- func (c *Cli) GenBashCompletion(w io.Writer) error
- func (c *Cli) GenBashCompletionFile(filename string) error
- func (c *Cli) GenBashCompletionFileV2(filename string, includeDesc bool) error
- func (c *Cli) GenBashCompletionV2(w io.Writer, includeDesc bool) error
- func (c *Cli) GenFishCompletion(w io.Writer, includeDesc bool) error
- func (c *Cli) GenFishCompletionFile(filename string, includeDesc bool) error
- func (c *Cli) GenPowerShellCompletion(w io.Writer) error
- func (c *Cli) GenPowerShellCompletionFile(filename string) error
- func (c *Cli) GenPowerShellCompletionFileWithDesc(filename string) error
- func (c *Cli) GenPowerShellCompletionWithDesc(w io.Writer) error
- func (c *Cli) GenZshCompletion(w io.Writer) error
- func (c *Cli) GenZshCompletionFile(filename string) error
- func (c *Cli) GenZshCompletionFileNoDesc(filename string) error
- func (c *Cli) GenZshCompletionNoDesc(w io.Writer) error
- func (c *Cli) GetAllFlagSets() []*FlagSet
- func (c *Cli) GetBindableFlagSets(excludeFlags ...string) []*FlagSet
- func (c *Cli) GetFilteredFlagNames(excludeFlags ...string) []string
- func (c *Cli) GetFilteredFlags(excludeFlags ...string) *FlagSet
- func (c *Cli) GetFlagNames(includeInherited bool) []string
- func (c *Cli) GetSystemFlags() []string
- func (c *Cli) GlobalNormalizationFunc() func(f *FlagSet, name string) NormalizedName
- func (c *Cli) Groups() []*Group
- func (c *Cli) HasAlias(s string) bool
- func (c *Cli) HasAvailableFlags() bool
- func (c *Cli) HasAvailableInheritedFlags() bool
- func (c *Cli) HasAvailableLocalFlags() bool
- func (c *Cli) HasAvailablePersistentFlags() bool
- func (c *Cli) HasAvailableSubCommands() bool
- func (c *Cli) HasExample() bool
- func (c *Cli) HasFlags() bool
- func (c *Cli) HasHelpSubCommands() bool
- func (c *Cli) HasInheritedFlags() bool
- func (c *Cli) HasLocalFlags() bool
- func (c *Cli) HasParent() bool
- func (c *Cli) HasPersistentFlags() bool
- func (c *Cli) HasSubCommands() bool
- func (c *Cli) Help() error
- func (c *Cli) HelpFunc() func(*Command, []string)
- func (c *Cli) HelpTemplate() string
- func (c *Cli) InOrStdin() io.Reader
- func (c *Cli) InheritedFlags() *FlagSet
- func (c *Cli) InitDefaultCompletionCmd()
- func (c *Cli) InitDefaultHelpCmd()
- func (c *Cli) InitDefaultHelpFlag()
- func (c *Cli) InitDefaultVersionFlag()
- func (c *Cli) IsAdditionalHelpTopicCommand() bool
- func (c *Cli) IsAvailableCommand() bool
- func (c *Cli) IsSystemFlag(flagName string) bool
- func (c *Cli) LocalFlags() *FlagSet
- func (c *Cli) LocalNonPersistentFlags() *FlagSet
- func (c *Cli) MarkFlagCustom(name string, f string) error
- func (c *Cli) MarkFlagDirname(name string) error
- func (c *Cli) MarkFlagFilename(name string, extensions ...string) error
- func (c *Cli) MarkFlagRequired(name string) error
- func (c *Cli) MarkFlagsMutuallyExclusive(flagNames ...string)
- func (c *Cli) MarkFlagsOneRequired(flagNames ...string)
- func (c *Cli) MarkFlagsRequiredTogether(flagNames ...string)
- func (c *Cli) MarkPersistentFlagDirname(name string) error
- func (c *Cli) MarkPersistentFlagFilename(name string, extensions ...string) error
- func (c *Cli) MarkPersistentFlagRequired(name string) error
- func (c *Cli) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error
- func (c *Cli) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error
- func (c *Cli) Name() string
- func (c *Cli) NameAndAliases() string
- func (c *Cli) NamePadding() int
- func (c *Cli) NonInheritedFlags() *FlagSet
- func (c *Cli) OutOrStderr() io.Writer
- func (c *Cli) OutOrStdout() io.Writer
- func (c *Cli) Parent() *Command
- func (c *Cli) ParseFlags(args []string) error
- func (c *Cli) PersistentFlags() *FlagSet
- func (c *Cli) Print(i ...interface{})
- func (c *Cli) PrintErr(i ...interface{})
- func (c *Cli) PrintErrf(format string, i ...interface{})
- func (c *Cli) PrintErrln(i ...interface{})
- func (c *Cli) Printf(format string, i ...interface{})
- func (c *Cli) Println(i ...interface{})
- func (c *Cli) RegisterFlagCompletionFunc(flagName string, ...) error
- func (c *Cli) RemoveCommand(cmds ...*Command)
- func (c *Cli) ResetCommands()
- func (c *Cli) ResetFlags()
- func (c *Cli) Root() *Command
- func (c *Cli) Runnable() bool
- func (c *Cli) SetArgs(a []string)
- func (c *Cli) SetCompletionCommandGroupID(groupID string)
- func (c *Cli) SetContext(ctx context.Context)
- func (c *Cli) SetErr(newErr io.Writer)
- func (c *Cli) SetErrPrefix(s string)
- func (c *Cli) SetFlagErrorFunc(f func(*Command, error) error)
- func (c *Cli) SetGlobalNormalizationFunc(n func(f *FlagSet, name string) NormalizedName)
- func (c *Cli) SetHelpCommand(cmd *Command)
- func (c *Cli) SetHelpCommandGroupID(groupID string)
- func (c *Cli) SetHelpFunc(f func(*Command, []string))
- func (c *Cli) SetHelpTemplate(s string)
- func (c *Cli) SetIn(newIn io.Reader)
- func (c *Cli) SetOut(newOut io.Writer)
- func (c *Cli) SetOutput(output io.Writer)deprecated
- func (c *Cli) SetServiceRunning(running bool)
- func (c *Cli) SetUsageFunc(f func(*Command) error)
- func (c *Cli) SetUsageTemplate(s string)
- func (c *Cli) SetVersionTemplate(s string)
- func (c *Cli) SuggestionsFor(typedName string) []string
- func (c *Cli) Traverse(args []string) (*Command, []string, error)
- func (c *Cli) Usage() error
- func (c *Cli) UsageFunc() func(*Command) error
- func (c *Cli) UsagePadding() int
- func (c *Cli) UsageString() string
- func (c *Cli) UsageTemplate() string
- func (c *Cli) UseLine() string
- func (c *Cli) ValidateArgs(args []string) error
- func (c *Cli) ValidateFlagGroups() error
- func (c *Cli) ValidateRequiredFlags() error
- func (c *Cli) VersionTemplate() string
- func (c *Cli) VisitParents(fn func(*Command))
- type Command
- type CommandUI
- type CompletionOptions
- type Config
- type DefaultServiceFactory
- type ErrorAggregator
- type ErrorBuilder
- func (eb *ErrorBuilder) Build() *ServiceError
- func (eb *ErrorBuilder) Cause(cause error) *ErrorBuilder
- func (eb *ErrorBuilder) Context(key string, value any) *ErrorBuilder
- func (eb *ErrorBuilder) Message(message string) *ErrorBuilder
- func (eb *ErrorBuilder) Messagef(format string, args ...any) *ErrorBuilder
- func (eb *ErrorBuilder) Operation(operation string) *ErrorBuilder
- func (eb *ErrorBuilder) Service(service string) *ErrorBuilder
- func (eb *ErrorBuilder) Stack(stack []string) *ErrorBuilder
- type ErrorCode
- type ErrorDomain
- type ErrorHandler
- type FParseErrWhitelist
- type Flag
- type FlagSet
- type FormatDomain
- type FuncService
- type FuncServiceFactory
- type Group
- type HelpErrors
- type HelpUI
- type Language
- type LanguageManager
- type Logger
- type LoggingErrorHandler
- type ManagedService
- type NormalizedName
- type Option
- type PositionalArgs
- type RecoveryErrorHandler
- type RunFunc
- type Runtime
- type ServiceConfig
- type ServiceDomain
- type ServiceError
- func ErrConfigValidationFailed(details []error) *ServiceError
- func ErrPathNotExists(path string) *ServiceError
- func ErrPermissionDenied(path string, required, current string) *ServiceError
- func ErrServiceAlreadyRunning(service string) *ServiceError
- func ErrServiceAlreadyStopped(service string) *ServiceError
- func ErrServiceNotInstalled(service string) *ServiceError
- func ErrServiceStartTimeout(service string, timeout time.Duration) *ServiceError
- func ErrServiceStopTimeout(service string, timeout time.Duration) *ServiceError
- func GetServiceError(err error) (*ServiceError, bool)
- func NewServiceError(code ErrorCode, operation, service, message string) *ServiceError
- func WrapError(err error, code ErrorCode, operation string) *ServiceError
- func (se *ServiceError) Error() string
- func (se *ServiceError) GetCode() ErrorCode
- func (se *ServiceError) GetContext() map[string]any
- func (se *ServiceError) GetOperation() string
- func (se *ServiceError) GetService() string
- func (se *ServiceError) Is(target error) bool
- func (se *ServiceError) ToJSON() map[string]any
- func (se *ServiceError) Unwrap() error
- func (se *ServiceError) WithCause(cause error) *ServiceError
- func (se *ServiceError) WithContext(key string, value any) *ServiceError
- func (se *ServiceError) WithStack(stack []string) *ServiceError
- type ServiceErrors
- type ServiceFactory
- type ServiceLifecycle
- type ServiceLocalizer
- func (sl *ServiceLocalizer) FormatError(errorType string, args ...interface{}) string
- func (sl *ServiceLocalizer) FormatServiceStatus(serviceName, status string) string
- func (sl *ServiceLocalizer) GetError(errorType string) string
- func (sl *ServiceLocalizer) GetFormat(formatType string) string
- func (sl *ServiceLocalizer) GetOperation(operation string) string
- func (sl *ServiceLocalizer) GetStatus(status string) string
- func (sl *ServiceLocalizer) LogError(errorType string, err error)
- func (sl *ServiceLocalizer) LogInfo(serviceName, status string)
- func (sl *ServiceLocalizer) LogSuccess(serviceName, operation string)
- func (sl *ServiceLocalizer) LogWarning(message string, args ...interface{})
- type ServiceMessages
- type ServiceOperations
- type ServiceRunner
- type ServiceStatus
- type ShellCompDirective
- type StopFunc
- type SystemErrors
- type TimeoutService
- type UIDomain
- type ValidationError
- type VersionInfo
- type VersionUI
Constants ¶
This section is empty.
Variables ¶
var GlobalLanguageManager = NewLanguageManager("zh")
GlobalLanguageManager 全局语言包管理器
Functions ¶
func IsErrorCode ¶ added in v0.1.9
IsErrorCode 检查错误代码
func RegisterLanguage ¶ added in v0.1.9
RegisterLanguage 注册语言包到全局管理器
Types ¶
type BaseService ¶ added in v0.1.9
type BaseService struct {
// contains filtered or unexported fields
}
BaseService 提供默认的服务实现,用户可以嵌入此结构体
func NewBaseService ¶ added in v0.1.9
func NewBaseService(config ServiceConfig) (*BaseService, error)
NewBaseService 创建基础服务实例
func (*BaseService) AddStopHandler ¶ added in v0.1.9
func (bs *BaseService) AddStopHandler(handler func() error)
AddStopHandler 添加停止处理函数
func (*BaseService) IsRunning ¶ added in v0.1.9
func (bs *BaseService) IsRunning() bool
IsRunning 检查服务是否正在运行
func (*BaseService) Run ¶ added in v0.1.9
func (bs *BaseService) Run(ctx context.Context) error
Run 运行服务的默认实现,子类应该重写此方法
func (*BaseService) WaitForStop ¶ added in v0.1.9
func (bs *BaseService) WaitForStop() <-chan struct{}
WaitForStop 等待停止信号
type Basic ¶ added in v0.1.6
type Basic struct {
Name string // 服务名称
DisplayName string // 显示名称
Description string // 服务描述
Version string // 版本
Logo string // Logo 路径
Language string // 使用语言
NoColor bool // 禁用彩色输出
}
Basic 基础配置
type BuildError ¶ added in v0.1.9
type BuildError struct {
Errors []error
}
BuildError 构建错误
func (*BuildError) Error ¶ added in v0.1.9
func (be *BuildError) Error() string
func (*BuildError) Unwrap ¶ added in v0.1.9
func (be *BuildError) Unwrap() []error
type Builder ¶ added in v0.1.6
type Builder struct {
// contains filtered or unexported fields
}
Builder CLI构建器 - 增强版
func NewBuilder ¶ added in v0.1.6
NewBuilder 创建CLI构建器 lang参数可选,指定默认语言
func (*Builder) BuildWithError ¶ added in v0.1.9
BuildWithError 构建CLI实例,返回错误而不是panic
func (*Builder) WithBuildTime ¶ added in v0.1.8
WithBuildTime 设置构建时间
func (*Builder) WithCommand ¶ added in v0.1.6
WithCommand 添加命令
func (*Builder) WithContext ¶ added in v0.1.7
WithContext 设置名称
func (*Builder) WithCustomService ¶ added in v0.2.0
WithCustomService 配置服务(高级用法) 允许传入自定义配置函数来修改配置
func (*Builder) WithDefaultConfig ¶ added in v0.1.6
WithDefaultConfig 使用默认配置
func (*Builder) WithDefaults ¶ added in v0.1.9
WithDefaults 设置默认配置
func (*Builder) WithDependencies ¶ added in v0.1.6
WithDependencies 设置依赖
func (*Builder) WithDescription ¶ added in v0.1.6
WithDescription 设置描述
func (*Builder) WithDisplayName ¶ added in v0.1.6
WithDisplayName 设置显示名称
func (*Builder) WithEnvVar ¶ added in v0.1.6
WithEnvVar 设置环境变量
func (*Builder) WithGitInfo ¶ added in v0.1.6
WithGitInfo 设置Git信息
func (*Builder) WithLanguage ¶ added in v0.1.6
WithLanguage 设置语言
func (*Builder) WithQuickConfig ¶ added in v0.1.9
WithQuickConfig 快速配置基本信息
func (*Builder) WithRuntime ¶ added in v0.1.6
WithRuntime 设置运行时配置
func (*Builder) WithService ¶ added in v0.1.6
WithService 配置服务运行和停止函数(主入口) run: 服务运行函数,标准签名 func(ctx context.Context) error stop: 可选停止函数,标准签名 func() error
func (*Builder) WithServiceOptions ¶ added in v0.1.9
func (b *Builder) WithServiceOptions(workDir string, envVars map[string]string, deps ...string) *Builder
WithServiceOptions 配置服务选项
func (*Builder) WithServiceRunner ¶ added in v0.1.9
func (b *Builder) WithServiceRunner(service ServiceRunner) *Builder
WithServiceRunner 配置优雅的服务接口(推荐方式)
func (*Builder) WithShutdownTimeouts ¶ added in v0.2.0
WithShutdownTimeouts 配置优雅退出的分级超时时间 initial: 首次等待时长;grace: 调用停止函数后的额外等待时长
func (*Builder) WithValidator ¶ added in v0.1.9
WithValidator 添加配置验证器
func (*Builder) WithVersion ¶ added in v0.1.6
WithVersion 设置版本
func (*Builder) WithWorkDir ¶ added in v0.1.6
WithWorkDir 设置工作目录
type Cli ¶ added in v0.1.6
type Cli struct {
// contains filtered or unexported fields
}
Cli 是对 cobra.Command 的封装,提供更友好的命令行界面
func QuickService ¶ added in v0.1.9
QuickService 快速创建服务应用(新签名)
func QuickServiceWithStop ¶ added in v0.1.9
QuickServiceWithStop 快速创建带停止函数的服务应用
func (*Cli) AddCommand ¶ added in v0.1.6
AddCommand 添加一个或多个子命令到当前命令
func (*Cli) AllChildCommandsHaveGroup ¶ added in v0.1.6
AllChildCommandsHaveGroup 检查是否所有子命令都已分配到命令组中
func (*Cli) ArgsLenAtDash ¶ added in v0.1.6
ArgsLenAtDash 获取命令行中 "--" 之前的参数数量 用于区分命令参数和传递给外部命令的参数
func (*Cli) Command ¶ added in v0.2.0
Command 返回底层的 cobra.Command 指针 用于需要直接操作 Cobra 原生 API 的高级场景
示例:
cmd := app.Command()
cmd.AddCommand(customCmd)
cmd.PreRun = func(cmd *cobra.Command, args []string) {
// 自定义预运行逻辑
}
func (*Cli) CommandPath ¶ added in v0.1.6
CommandPath 返回从根命令到当前命令的完整路径
func (*Cli) CommandPathPadding ¶ added in v0.1.6
CommandPathPadding 返回命令路径的填充长度 用于格式化输出时对齐
func (*Cli) ContainsGroup ¶ added in v0.1.6
ContainsGroup 检查是否包含指定ID的命令组
func (*Cli) Done ¶ added in v0.1.9
func (c *Cli) Done() <-chan struct{}
Done 返回一个通道,当服务应该停止时会关闭 这为用户提供了优雅处理服务生命周期的方式
func (*Cli) ExecuteContext ¶ added in v0.1.6
ExecuteContext 在指定的上下文中执行命令 可用于传递取消信号或超时控制
func (*Cli) ExecuteContextC ¶ added in v0.1.6
ExecuteContextC 在指定上下文中执行命令并返回选中的命令
func (*Cli) ExportFlagsForViper ¶ added in v0.1.9
ExportFlagsForViper 导出适用于 Viper 绑定的标志集合 这是一个便捷方法,返回可以直接用于 WithBindPFlags 的标志数组
func (*Cli) FlagErrorFunc ¶ added in v0.1.6
FlagErrorFunc 返回处理标志错误的函数
func (*Cli) GenBashCompletion ¶ added in v0.1.6
GenBashCompletion 生成 Bash 补全脚本并写入指定的 Writer
func (*Cli) GenBashCompletionFile ¶ added in v0.1.6
GenBashCompletionFile 生成 Bash 补全脚本并保存到指定文件
func (*Cli) GenBashCompletionFileV2 ¶ added in v0.1.6
GenBashCompletionFileV2 生成新版本的 Bash 补全脚本并保存到文件 includeDesc 参数控制是否包含描述信息
func (*Cli) GenBashCompletionV2 ¶ added in v0.1.6
GenBashCompletionV2 生成新版本的 Bash 补全脚本并写入 Writer
func (*Cli) GenFishCompletion ¶ added in v0.1.6
GenFishCompletion 生成 Fish shell 补全脚本并写入 Writer
func (*Cli) GenFishCompletionFile ¶ added in v0.1.6
GenFishCompletionFile 生成 Fish shell 补全脚本并保存到文件
func (*Cli) GenPowerShellCompletion ¶ added in v0.1.6
GenPowerShellCompletion 生成 PowerShell 补全脚本并写入 Writer
func (*Cli) GenPowerShellCompletionFile ¶ added in v0.1.6
GenPowerShellCompletionFile 生成 PowerShell 补全脚本并保存到文件
func (*Cli) GenPowerShellCompletionFileWithDesc ¶ added in v0.1.6
GenPowerShellCompletionFileWithDesc 生成包含描述的 PowerShell 补全脚本并保存到文件
func (*Cli) GenPowerShellCompletionWithDesc ¶ added in v0.1.6
GenPowerShellCompletionWithDesc 生成包含描述的 PowerShell 补全脚本并写入 Writer
func (*Cli) GenZshCompletion ¶ added in v0.1.6
GenZshCompletion 生成 Zsh 补全脚本并写入 Writer
func (*Cli) GenZshCompletionFile ¶ added in v0.1.6
GenZshCompletionFile 生成 Zsh 补全脚本并保存到文件
func (*Cli) GenZshCompletionFileNoDesc ¶ added in v0.1.6
GenZshCompletionFileNoDesc 生成不包含描述的 Zsh 补全脚本并保存到文件
func (*Cli) GenZshCompletionNoDesc ¶ added in v0.1.6
GenZshCompletionNoDesc 生成不包含描述的 Zsh 补全脚本并写入 Writer
func (*Cli) GetAllFlagSets ¶ added in v0.1.9
GetAllFlagSets 返回所有标志集合的切片,便于传递给外部包 返回顺序:[本地标志, 持久标志, 继承标志]
func (*Cli) GetBindableFlagSets ¶ added in v0.1.9
GetBindableFlagSets 返回适用于绑定的标志集合,自动排除常见的系统标志 excludeFlags: 额外需要排除的标志名称
func (*Cli) GetFilteredFlagNames ¶ added in v0.1.9
GetFilteredFlagNames 返回过滤后的标志名称列表
func (*Cli) GetFilteredFlags ¶ added in v0.1.9
GetFilteredFlags 返回过滤后的单个标志集合,包含所有非排除的标志
func (*Cli) GetFlagNames ¶ added in v0.1.9
GetFlagNames 返回所有标志的名称列表
func (*Cli) GetSystemFlags ¶ added in v0.1.9
GetSystemFlags 返回当前被排除的系统标志列表(调试用)
func (*Cli) GlobalNormalizationFunc ¶ added in v0.1.6
func (c *Cli) GlobalNormalizationFunc() func(f *FlagSet, name string) NormalizedName
GlobalNormalizationFunc 返回全局标志名称规范化函数
func (*Cli) HasAvailableFlags ¶ added in v0.1.6
HasAvailableFlags 检查命令是否有可用的标志
func (*Cli) HasAvailableInheritedFlags ¶ added in v0.1.6
HasAvailableInheritedFlags 检查命令是否有可用的继承标志
func (*Cli) HasAvailableLocalFlags ¶ added in v0.1.6
HasAvailableLocalFlags 检查命令是否有可用的本地标志
func (*Cli) HasAvailablePersistentFlags ¶ added in v0.1.6
HasAvailablePersistentFlags 检查命令是否有可用的持久标志
func (*Cli) HasAvailableSubCommands ¶ added in v0.1.6
HasAvailableSubCommands 检查是否有可用的子命令
func (*Cli) HasHelpSubCommands ¶ added in v0.1.6
HasHelpSubCommands 检查是否有帮助子命令
func (*Cli) HasInheritedFlags ¶ added in v0.1.6
HasInheritedFlags 检查命令是否有继承的标志
func (*Cli) HasLocalFlags ¶ added in v0.1.6
HasLocalFlags 检查命令是否有本地标志
func (*Cli) HasPersistentFlags ¶ added in v0.1.6
HasPersistentFlags 检查命令是否有持久标志
func (*Cli) HasSubCommands ¶ added in v0.1.6
HasSubCommands 检查是否有子命令
func (*Cli) HelpTemplate ¶ added in v0.1.6
HelpTemplate 返回帮助信息模板
func (*Cli) InheritedFlags ¶ added in v0.1.6
InheritedFlags 返回命令的继承标志集
func (*Cli) InitDefaultCompletionCmd ¶ added in v0.1.6
func (c *Cli) InitDefaultCompletionCmd()
InitDefaultCompletionCmd 初始化默认的补全命令
func (*Cli) InitDefaultHelpCmd ¶ added in v0.1.6
func (c *Cli) InitDefaultHelpCmd()
InitDefaultHelpCmd 初始化默认的帮助命令
func (*Cli) InitDefaultHelpFlag ¶ added in v0.1.6
func (c *Cli) InitDefaultHelpFlag()
InitDefaultHelpFlag 初始化默认的帮助标志
func (*Cli) InitDefaultVersionFlag ¶ added in v0.1.6
func (c *Cli) InitDefaultVersionFlag()
InitDefaultVersionFlag 初始化默认的版本标志
func (*Cli) IsAdditionalHelpTopicCommand ¶ added in v0.1.6
IsAdditionalHelpTopicCommand 检查是否是额外的帮助主题命令
func (*Cli) IsAvailableCommand ¶ added in v0.1.6
IsAvailableCommand 检查命令是否可用
func (*Cli) IsSystemFlag ¶ added in v0.1.9
IsSystemFlag 检查指定标志是否为系统标志
func (*Cli) LocalNonPersistentFlags ¶ added in v0.1.6
LocalNonPersistentFlags 返回命令的非持久本地标志集
func (*Cli) MarkFlagCustom ¶ added in v0.1.6
MarkFlagCustom 为指定标志添加自定义补全函数
func (*Cli) MarkFlagDirname ¶ added in v0.1.6
MarkFlagDirname 标记指定标志接受目录名作为参数
func (*Cli) MarkFlagFilename ¶ added in v0.1.6
MarkFlagFilename 标记指定标志接受文件名作为参数
func (*Cli) MarkFlagRequired ¶ added in v0.1.6
MarkFlagRequired 标记指定标志为必需
func (*Cli) MarkFlagsMutuallyExclusive ¶ added in v0.1.6
MarkFlagsMutuallyExclusive 标记多个标志互斥
func (*Cli) MarkFlagsOneRequired ¶ added in v0.1.6
MarkFlagsOneRequired 标记多个标志中必须指定一个
func (*Cli) MarkFlagsRequiredTogether ¶ added in v0.1.6
MarkFlagsRequiredTogether 标记多个标志必须同时使用
func (*Cli) MarkPersistentFlagDirname ¶ added in v0.1.6
MarkPersistentFlagDirname 标记指定的持久标志接受目录名作为参数
func (*Cli) MarkPersistentFlagFilename ¶ added in v0.1.6
MarkPersistentFlagFilename 标记指定的持久标志接受文件名作为参数
func (*Cli) MarkPersistentFlagRequired ¶ added in v0.1.6
MarkPersistentFlagRequired 标记指定的持久标志为必需
func (*Cli) MarkZshCompPositionalArgumentFile ¶ added in v0.1.6
MarkZshCompPositionalArgumentFile 标记 Zsh 位置参数接受文件
func (*Cli) MarkZshCompPositionalArgumentWords ¶ added in v0.1.6
MarkZshCompPositionalArgumentWords 标记 Zsh 位置参数接受指定的词列表
func (*Cli) NameAndAliases ¶ added in v0.1.6
NameAndAliases 返回命令名称及其所有别名
func (*Cli) NonInheritedFlags ¶ added in v0.1.6
NonInheritedFlags 返回命令的非继承标志集
func (*Cli) OutOrStderr ¶ added in v0.1.6
OutOrStderr 返回命令的错误输出流,默认为标准错误
func (*Cli) OutOrStdout ¶ added in v0.1.6
OutOrStdout 返回命令的标准输出流,默认为标准输出
func (*Cli) ParseFlags ¶ added in v0.1.6
ParseFlags 解析命令行参数中的标志
func (*Cli) PersistentFlags ¶ added in v0.1.6
PersistentFlags 返回命令的持久标志集
func (*Cli) PrintErrln ¶ added in v0.1.6
func (c *Cli) PrintErrln(i ...interface{})
PrintErrln 打印到命令的错误输出并换行
func (*Cli) RegisterFlagCompletionFunc ¶ added in v0.1.6
func (c *Cli) RegisterFlagCompletionFunc(flagName string, f func(*Command, []string, string) ([]string, ShellCompDirective)) error
RegisterFlagCompletionFunc 注册标志的补全函数
func (*Cli) RemoveCommand ¶ added in v0.1.6
RemoveCommand 移除指定的子命令
func (*Cli) SetCompletionCommandGroupID ¶ added in v0.1.6
SetCompletionCommandGroupID 设置补全命令的组ID
func (*Cli) SetContext ¶ added in v0.1.6
SetContext 设置命令的上下文
func (*Cli) SetErrPrefix ¶ added in v0.1.6
SetErrPrefix 设置错误消息的前缀
func (*Cli) SetFlagErrorFunc ¶ added in v0.1.6
SetFlagErrorFunc 设置处理标志错误的自定义函数
func (*Cli) SetGlobalNormalizationFunc ¶ added in v0.1.6
func (c *Cli) SetGlobalNormalizationFunc(n func(f *FlagSet, name string) NormalizedName)
SetGlobalNormalizationFunc 设置全局标志名称规范化函数
func (*Cli) SetHelpCommand ¶ added in v0.1.6
SetHelpCommand 设置自定义的帮助命令
func (*Cli) SetHelpCommandGroupID ¶ added in v0.1.6
SetHelpCommandGroupID 设置帮助命令的组ID
func (*Cli) SetHelpFunc ¶ added in v0.1.6
SetHelpFunc 设置自定义的帮助函数
func (*Cli) SetHelpTemplate ¶ added in v0.1.6
SetHelpTemplate 设置帮助信息的模板
func (*Cli) SetServiceRunning ¶ added in v0.1.9
SetServiceRunning 设置服务运行状态(内部使用) 用于在服务启动时传递正确的上下文
func (*Cli) SetUsageFunc ¶ added in v0.1.6
SetUsageFunc 设置自定义的使用说明函数
func (*Cli) SetUsageTemplate ¶ added in v0.1.6
SetUsageTemplate 设置使用说明的模板
func (*Cli) SetVersionTemplate ¶ added in v0.1.6
SetVersionTemplate 设置版本信息的模板
func (*Cli) SuggestionsFor ¶ added in v0.1.6
SuggestionsFor 返回针对给定输入的建议
func (*Cli) UsagePadding ¶ added in v0.1.6
UsagePadding 返回使用说明的填充长度
func (*Cli) UsageTemplate ¶ added in v0.1.6
UsageTemplate 返回使用说明模板
func (*Cli) ValidateArgs ¶ added in v0.1.6
ValidateArgs 验证命令参数
func (*Cli) ValidateFlagGroups ¶ added in v0.1.6
ValidateFlagGroups 验证标志组
func (*Cli) ValidateRequiredFlags ¶ added in v0.1.6
ValidateRequiredFlags 验证必需的标志
func (*Cli) VersionTemplate ¶ added in v0.1.6
VersionTemplate 返回版本信息模板
func (*Cli) VisitParents ¶ added in v0.1.6
VisitParents 访问所有父命令
type CommandUI ¶ added in v0.1.9
type CommandUI struct {
Usage string // 用法
Options string // 选项
Examples string // 示例
Flags string // 参数
AvailableCommands string // 可用命令
SystemCommands string // 系统命令
DefaultValue string // 默认值格式: "(default: %s)"
}
CommandUI 命令界面相关文本
type CompletionOptions ¶ added in v0.1.6
type CompletionOptions = cobra.CompletionOptions
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config 统一配置结构 字段已私有化,通过 getter 方法访问以防止外部直接修改
func (*Config) Service ¶ added in v0.1.6
func (c *Config) Service() ServiceConfig
Service 返回服务配置的深拷贝,防止外部通过切片/map 修改内部状态
type DefaultServiceFactory ¶ added in v0.1.9
type DefaultServiceFactory struct{}
DefaultServiceFactory 默认服务工厂
func (*DefaultServiceFactory) CreateService ¶ added in v0.1.9
func (dsf *DefaultServiceFactory) CreateService(config ServiceConfig) (ServiceRunner, error)
CreateService 创建默认服务
type ErrorAggregator ¶ added in v0.1.9
type ErrorAggregator struct {
// contains filtered or unexported fields
}
ErrorAggregator 错误聚合器
func NewErrorAggregator ¶ added in v0.1.9
func NewErrorAggregator() *ErrorAggregator
NewErrorAggregator 创建错误聚合器
func (*ErrorAggregator) Error ¶ added in v0.1.9
func (ea *ErrorAggregator) Error() string
Error 返回聚合错误信息
func (*ErrorAggregator) Errors ¶ added in v0.1.9
func (ea *ErrorAggregator) Errors() []error
Errors 返回所有错误
func (*ErrorAggregator) HasErrors ¶ added in v0.1.9
func (ea *ErrorAggregator) HasErrors() bool
HasErrors 检查是否有错误
type ErrorBuilder ¶ added in v0.1.9
type ErrorBuilder struct {
// contains filtered or unexported fields
}
ErrorBuilder 错误构建器
func (*ErrorBuilder) Build ¶ added in v0.1.9
func (eb *ErrorBuilder) Build() *ServiceError
Build 构建错误
func (*ErrorBuilder) Cause ¶ added in v0.1.9
func (eb *ErrorBuilder) Cause(cause error) *ErrorBuilder
Cause 设置原因错误
func (*ErrorBuilder) Context ¶ added in v0.1.9
func (eb *ErrorBuilder) Context(key string, value any) *ErrorBuilder
Context 添加上下文信息
func (*ErrorBuilder) Message ¶ added in v0.1.9
func (eb *ErrorBuilder) Message(message string) *ErrorBuilder
Message 设置错误消息
func (*ErrorBuilder) Messagef ¶ added in v0.1.9
func (eb *ErrorBuilder) Messagef(format string, args ...any) *ErrorBuilder
Messagef 设置格式化错误消息
func (*ErrorBuilder) Operation ¶ added in v0.1.9
func (eb *ErrorBuilder) Operation(operation string) *ErrorBuilder
Operation 设置操作名称
func (*ErrorBuilder) Service ¶ added in v0.1.9
func (eb *ErrorBuilder) Service(service string) *ErrorBuilder
Service 设置服务名称
func (*ErrorBuilder) Stack ¶ added in v0.1.9
func (eb *ErrorBuilder) Stack(stack []string) *ErrorBuilder
Stack 添加堆栈信息
type ErrorCode ¶ added in v0.1.9
type ErrorCode string
ErrorCode 错误代码类型
const ( // 配置相关错误 ErrConfigValidation ErrorCode = "CONFIG_VALIDATION" ErrConfigMissing ErrorCode = "CONFIG_MISSING" ErrConfigInvalid ErrorCode = "CONFIG_INVALID" // 服务相关错误 ErrServiceCreate ErrorCode = "SERVICE_CREATE" ErrServiceStart ErrorCode = "SERVICE_START" ErrServiceStop ErrorCode = "SERVICE_STOP" ErrServiceRestart ErrorCode = "SERVICE_RESTART" ErrServiceNotFound ErrorCode = "SERVICE_NOT_FOUND" ErrServiceRunning ErrorCode = "SERVICE_ALREADY_RUNNING" ErrServiceStopped ErrorCode = "SERVICE_ALREADY_STOPPED" ErrServiceTimeout ErrorCode = "SERVICE_TIMEOUT" // 系统相关错误 ErrPermission ErrorCode = "PERMISSION_DENIED" ErrPathNotFound ErrorCode = "PATH_NOT_FOUND" ErrPathInvalid ErrorCode = "PATH_INVALID" ErrExecutableInvalid ErrorCode = "EXECUTABLE_INVALID" // 运行时错误 ErrRuntime ErrorCode = "RUNTIME_ERROR" ErrContextCancelled ErrorCode = "CONTEXT_CANCELLED" ErrTimeout ErrorCode = "TIMEOUT" // 网络和通信错误 ErrNetwork ErrorCode = "NETWORK_ERROR" ErrConnection ErrorCode = "CONNECTION_ERROR" )
type ErrorDomain ¶ added in v0.1.9
type ErrorDomain struct {
Prefix string // 错误前缀
Service ServiceErrors // 服务错误
System SystemErrors // 系统错误
Help HelpErrors // 帮助错误
}
ErrorDomain 错误域 - 集中管理所有错误信息
type ErrorHandler ¶ added in v0.1.9
ErrorHandler 错误处理器接口
type FParseErrWhitelist ¶ added in v0.1.6
type FParseErrWhitelist = cobra.FParseErrWhitelist
type FormatDomain ¶ added in v0.1.9
type FormatDomain struct {
ServiceStatus string // "Service %s: %s"
ErrorWithDetail string // "Error: %s"
TimeoutMessage string // "Timeout after %d seconds"
PermissionDenied string // "Required: %v, Current: %v"
PathError string // "Path error: %s"
}
FormatDomain 格式化域 - 提供格式化模板
type FuncService ¶ added in v0.1.9
type FuncService struct {
*BaseService
// contains filtered or unexported fields
}
FuncService 基于函数的服务实现,用于简单场景
func NewFuncService ¶ added in v0.1.9
func NewFuncService(config ServiceConfig, runFunc func(context.Context) error, stopFunc func() error) (*FuncService, error)
NewFuncService 创建函数式服务
type FuncServiceFactory ¶ added in v0.1.9
type FuncServiceFactory struct {
// contains filtered or unexported fields
}
FuncServiceFactory 函数式服务工厂
func NewFuncServiceFactory ¶ added in v0.1.9
func NewFuncServiceFactory(runFunc func(context.Context) error, stopFunc func() error) *FuncServiceFactory
NewFuncServiceFactory 创建函数式服务工厂
func (*FuncServiceFactory) CreateService ¶ added in v0.1.9
func (fsf *FuncServiceFactory) CreateService(config ServiceConfig) (ServiceRunner, error)
CreateService 创建函数式服务
type HelpErrors ¶ added in v0.1.9
type HelpErrors struct {
UnknownTopic string // 未知帮助主题
}
HelpErrors 帮助相关错误
type HelpUI ¶ added in v0.1.9
type HelpUI struct {
Command string // 帮助命令
Description string // 帮助描述
Usage string // 帮助使用说明格式: "Use '%s [command] --help' for more information"
}
HelpUI 帮助界面相关文本
type Language ¶ added in v0.1.6
type Language struct {
Code string // 语言代码 (如: "zh", "en")
Name string // 语言名称 (如: "中文", "English")
Service ServiceDomain // 服务域
UI UIDomain // 界面域
Error ErrorDomain // 错误域
Format FormatDomain // 格式化域
}
Language 新的层次化语言包结构
type LanguageManager ¶ added in v0.1.9
type LanguageManager struct {
// contains filtered or unexported fields
}
LanguageManager 智能语言包管理器
func GetLanguageManager ¶ added in v0.1.9
func GetLanguageManager() *LanguageManager
GetLanguageManager 获取全局语言包管理器
func NewLanguageManager ¶ added in v0.1.9
func NewLanguageManager(primaryLang string) *LanguageManager
NewLanguageManager 创建语言包管理器
func (*LanguageManager) GetPrimary ¶ added in v0.1.9
func (lm *LanguageManager) GetPrimary() *Language
GetPrimary 获取主要语言包
func (*LanguageManager) GetText ¶ added in v0.1.9
func (lm *LanguageManager) GetText(path string) string
GetText 智能获取文本,支持回退机制
func (*LanguageManager) RegisterLanguage ¶ added in v0.1.9
func (lm *LanguageManager) RegisterLanguage(lang *Language) error
RegisterLanguage 注册新的语言包
func (*LanguageManager) SetPrimary ¶ added in v0.1.9
func (lm *LanguageManager) SetPrimary(langCode string) error
SetPrimary 设置主要语言
type Logger ¶ added in v0.1.9
type Logger interface {
Error(msg string, fields ...any)
Warn(msg string, fields ...any)
Info(msg string, fields ...any)
}
Logger 日志接口
type LoggingErrorHandler ¶ added in v0.1.9
type LoggingErrorHandler struct {
// contains filtered or unexported fields
}
LoggingErrorHandler 日志记录错误处理器
func NewLoggingErrorHandler ¶ added in v0.1.9
func NewLoggingErrorHandler(logger Logger) *LoggingErrorHandler
NewLoggingErrorHandler 创建日志错误处理器
func (*LoggingErrorHandler) HandleError ¶ added in v0.1.9
func (leh *LoggingErrorHandler) HandleError(err error) error
HandleError 处理错误
type ManagedService ¶ added in v0.1.9
type ManagedService struct {
ServiceRunner
// contains filtered or unexported fields
}
ManagedService 带生命周期管理的服务
func NewManagedService ¶ added in v0.1.9
func NewManagedService(runner ServiceRunner, lifecycle ServiceLifecycle) *ManagedService
NewManagedService 创建带生命周期管理的服务
type NormalizedName ¶ added in v0.1.6
type NormalizedName = pflag.NormalizedName
type PositionalArgs ¶ added in v0.1.6
type PositionalArgs = cobra.PositionalArgs
type RecoveryErrorHandler ¶ added in v0.1.9
type RecoveryErrorHandler struct {
// contains filtered or unexported fields
}
RecoveryErrorHandler 恢复错误处理器
func NewRecoveryErrorHandler ¶ added in v0.1.9
func NewRecoveryErrorHandler(retryCount int, retryDelay time.Duration) *RecoveryErrorHandler
NewRecoveryErrorHandler 创建恢复错误处理器
func (*RecoveryErrorHandler) HandleError ¶ added in v0.1.9
func (reh *RecoveryErrorHandler) HandleError(err error) error
HandleError 处理错误并尝试恢复
type Runtime ¶ added in v0.1.6
type Runtime struct {
Run RunFunc // 启动函数,标准签名:func(ctx context.Context) error
Stop StopFunc // 停止函数,标准签名:func() error
BuildInfo *VersionInfo // 构建信息
// ShutdownInitial 优雅退出的初次等待时长,默认 3s
ShutdownInitial time.Duration
// ShutdownGrace 在调用停止函数后的额外等待时长,默认 2s
ShutdownGrace time.Duration
}
Runtime 运行时配置
type ServiceConfig ¶ added in v0.1.9
type ServiceConfig struct {
Name string `validate:"required,min=3,max=50"`
DisplayName string `validate:"required,max=100"`
Description string `validate:"max=500"`
Version string `validate:"semver"`
WorkDir string `validate:"dir_path"`
Username string `validate:"username"`
Dependencies []string `validate:"dive,required"`
EnvVars map[string]string `validate:"dive,keys,required,endkeys,required"`
Arguments []string
Executable string
ChRoot string
Options map[string]interface{}
}
ServiceConfig 服务配置结构,提供完整的类型安全
func (*ServiceConfig) Validate ¶ added in v0.1.9
func (sc *ServiceConfig) Validate() error
Validate 验证配置的有效性
type ServiceDomain ¶ added in v0.1.9
type ServiceDomain struct {
Operations ServiceOperations // 服务操作
Status ServiceStatus // 服务状态
Messages ServiceMessages // 服务消息
}
ServiceDomain 服务域 - 专注于服务相关的所有文本
type ServiceError ¶ added in v0.1.9
type ServiceError struct {
Code ErrorCode `json:"code"`
Operation string `json:"operation"`
Service string `json:"service"`
Message string `json:"message"`
Cause error `json:"cause,omitempty"`
Context map[string]any `json:"context,omitempty"`
Timestamp time.Time `json:"timestamp"`
Stack []string `json:"stack,omitempty"`
}
ServiceError 增强的服务错误类型
func ErrConfigValidationFailed ¶ added in v0.1.9
func ErrConfigValidationFailed(details []error) *ServiceError
ErrConfigValidationFailed configuration validation failed错误
func ErrPathNotExists ¶ added in v0.1.9
func ErrPathNotExists(path string) *ServiceError
ErrPathNotExists 路径不存在错误
func ErrPermissionDenied ¶ added in v0.1.9
func ErrPermissionDenied(path string, required, current string) *ServiceError
ErrPermissionDenied 权限被拒绝错误
func ErrServiceAlreadyRunning ¶ added in v0.1.9
func ErrServiceAlreadyRunning(service string) *ServiceError
ErrServiceAlreadyRunning 服务已在运行错误
func ErrServiceAlreadyStopped ¶ added in v0.1.9
func ErrServiceAlreadyStopped(service string) *ServiceError
ErrServiceAlreadyStopped service already stopped错误
func ErrServiceNotInstalled ¶ added in v0.1.9
func ErrServiceNotInstalled(service string) *ServiceError
ErrServiceNotInstalled service is not installed错误
func ErrServiceStartTimeout ¶ added in v0.1.9
func ErrServiceStartTimeout(service string, timeout time.Duration) *ServiceError
ErrServiceStartTimeout 服务启动超时错误
func ErrServiceStopTimeout ¶ added in v0.1.9
func ErrServiceStopTimeout(service string, timeout time.Duration) *ServiceError
ErrServiceStopTimeout 服务停止超时错误
func GetServiceError ¶ added in v0.1.9
func GetServiceError(err error) (*ServiceError, bool)
GetServiceError 获取服务错误
func NewServiceError ¶ added in v0.1.9
func NewServiceError(code ErrorCode, operation, service, message string) *ServiceError
NewServiceError 创建新的服务错误
func WrapError ¶ added in v0.1.9
func WrapError(err error, code ErrorCode, operation string) *ServiceError
WrapError 包装普通错误为服务错误
func (*ServiceError) GetCode ¶ added in v0.1.9
func (se *ServiceError) GetCode() ErrorCode
GetCode 获取错误代码
func (*ServiceError) GetContext ¶ added in v0.1.9
func (se *ServiceError) GetContext() map[string]any
GetContext 获取上下文信息
func (*ServiceError) GetOperation ¶ added in v0.1.9
func (se *ServiceError) GetOperation() string
GetOperation 获取操作名称
func (*ServiceError) GetService ¶ added in v0.1.9
func (se *ServiceError) GetService() string
GetService 获取服务名称
func (*ServiceError) ToJSON ¶ added in v0.1.9
func (se *ServiceError) ToJSON() map[string]any
ToJSON 转换为JSON格式
func (*ServiceError) WithCause ¶ added in v0.1.9
func (se *ServiceError) WithCause(cause error) *ServiceError
WithCause 添加原因错误
func (*ServiceError) WithContext ¶ added in v0.1.9
func (se *ServiceError) WithContext(key string, value any) *ServiceError
WithContext 添加上下文信息
func (*ServiceError) WithStack ¶ added in v0.1.9
func (se *ServiceError) WithStack(stack []string) *ServiceError
WithStack 添加堆栈信息
type ServiceErrors ¶ added in v0.1.9
type ServiceErrors struct {
CreateConfig string // 创建配置失败
CreateService string // 创建服务失败
GetStatus string // 获取状态失败
StartFailed string // 启动失败
StopFailed string // 停止失败
RestartFailed string // 重启失败
InstallFailed string // 安装失败
UninstallFailed string // 卸载失败
RunFailed string // 运行失败
NotFound string // 服务未找到
AlreadyRunning string // 服务已在运行
Timeout string // 操作超时
TimeoutWarning string // 超时警告
ForceTerminate string // 强制终止
}
ServiceErrors 服务相关错误
type ServiceFactory ¶ added in v0.1.9
type ServiceFactory interface {
CreateService(config ServiceConfig) (ServiceRunner, error)
}
ServiceFactory 服务工厂接口
type ServiceLifecycle ¶ added in v0.1.9
type ServiceLifecycle interface {
// BeforeStart 服务启动前调用
BeforeStart() error
// AfterStart 服务启动后调用
AfterStart() error
// BeforeStop 服务停止前调用
BeforeStop() error
// AfterStop 服务停止后调用
AfterStop() error
}
ServiceLifecycle 服务生命周期管理接口
type ServiceLocalizer ¶ added in v0.1.9
type ServiceLocalizer struct {
// contains filtered or unexported fields
}
ServiceLocalizer 服务本地化器,提供便利的API
func NewServiceLocalizer ¶ added in v0.1.9
func NewServiceLocalizer(manager *LanguageManager, colors *colors) *ServiceLocalizer
NewServiceLocalizer 创建服务本地化器
func (*ServiceLocalizer) FormatError ¶ added in v0.1.9
func (sl *ServiceLocalizer) FormatError(errorType string, args ...interface{}) string
FormatError 格式化错误消息
func (*ServiceLocalizer) FormatServiceStatus ¶ added in v0.1.9
func (sl *ServiceLocalizer) FormatServiceStatus(serviceName, status string) string
FormatServiceStatus 格式化服务状态
func (*ServiceLocalizer) GetError ¶ added in v0.1.9
func (sl *ServiceLocalizer) GetError(errorType string) string
GetError 获取错误文本
func (*ServiceLocalizer) GetFormat ¶ added in v0.1.9
func (sl *ServiceLocalizer) GetFormat(formatType string) string
GetFormat 获取格式化模板
func (*ServiceLocalizer) GetOperation ¶ added in v0.1.9
func (sl *ServiceLocalizer) GetOperation(operation string) string
GetOperation 获取操作文本
func (*ServiceLocalizer) GetStatus ¶ added in v0.1.9
func (sl *ServiceLocalizer) GetStatus(status string) string
GetStatus 获取状态文本
func (*ServiceLocalizer) LogError ¶ added in v0.1.9
func (sl *ServiceLocalizer) LogError(errorType string, err error)
LogError 记录错误日志
func (*ServiceLocalizer) LogInfo ¶ added in v0.1.9
func (sl *ServiceLocalizer) LogInfo(serviceName, status string)
LogInfo 记录信息日志
func (*ServiceLocalizer) LogSuccess ¶ added in v0.1.9
func (sl *ServiceLocalizer) LogSuccess(serviceName, operation string)
LogSuccess 记录成功日志
func (*ServiceLocalizer) LogWarning ¶ added in v0.1.9
func (sl *ServiceLocalizer) LogWarning(message string, args ...interface{})
LogWarning 记录警告日志
type ServiceMessages ¶ added in v0.1.6
type ServiceMessages struct {
Installing string // 正在安装...
Uninstalling string // 正在卸载...
Starting string // 正在启动...
Stopping string // 正在停止...
Restarting string // 正在重启...
CheckingStatus string // 正在检查状态...
TimeoutWarning string // 超时警告
ForceTerminate string // 强制终止
}
ServiceMessages 服务操作过程中的提示消息
type ServiceOperations ¶ added in v0.1.9
type ServiceOperations struct {
Install string // 安装
Uninstall string // 卸载
Start string // 启动
Stop string // 停止
Restart string // 重启
Run string // 运行
Status string // 查看状态
}
ServiceOperations 服务操作相关文本
type ServiceRunner ¶ added in v0.1.9
type ServiceRunner interface {
// Run 运行服务主逻辑,接收上下文用于优雅关闭
Run(ctx context.Context) error
// Stop 停止服务,执行清理工作
Stop() error
// Name 返回服务名称
Name() string
}
ServiceRunner 定义服务运行接口,提供类型安全的服务管理
func NewSimpleService ¶ added in v0.1.9
func NewSimpleService(name string, runFunc func(context.Context) error, stopFunc func() error) ServiceRunner
NewSimpleService 创建简单服务实现
type ServiceStatus ¶ added in v0.1.9
type ServiceStatus struct {
Running string // 正在运行
Stopped string // 已停止
Unknown string // 未知状态
NotInstalled string // 未安装
AlreadyExists string // 已存在
AlreadyRunning string // 已在运行
AlreadyStopped string // 已停止
Success string // 成功
}
ServiceStatus 服务状态相关文本
type ShellCompDirective ¶ added in v0.1.6
type ShellCompDirective = cobra.ShellCompDirective
type SystemErrors ¶ added in v0.1.9
type SystemErrors struct {
PathNotExist string // 路径不存在
GetPathInfo string // 获取路径信息失败
InsufficientPerm string // 权限不足
GetExecPath string // 获取可执行文件路径失败
ExecPermission string // 可执行文件权限检查失败
WorkDirPermission string // 工作目录权限检查失败
ChrootPermission string // chroot目录权限检查失败
}
SystemErrors 系统相关错误
type TimeoutService ¶ added in v0.1.9
type TimeoutService struct {
ServiceRunner
// contains filtered or unexported fields
}
TimeoutService 带超时的服务包装器
func NewTimeoutService ¶ added in v0.1.9
func NewTimeoutService(service ServiceRunner, startTimeout, stopTimeout time.Duration) *TimeoutService
NewTimeoutService 创建带超时的服务
type ValidationError ¶ added in v0.1.9
type ValidationError struct {
Errors []error
}
ValidationError 配置验证错误
func (*ValidationError) Error ¶ added in v0.1.9
func (ve *ValidationError) Error() string
func (*ValidationError) Unwrap ¶ added in v0.1.9
func (ve *ValidationError) Unwrap() []error
type VersionInfo ¶ added in v0.1.6
type VersionInfo struct {
Version string `json:"version"` // 版本号
GoVersion string `json:"goVersion"` // Go版本
GitCommit string `json:"gitCommit"` // Git提交哈希
GitBranch string `json:"gitBranch"` // Git分支
GitTag string `json:"gitTag"` // Git标签
Platform string `json:"platform"` // 运行平台
Architecture string `json:"architecture"` // 系统架构
Compiler string `json:"compiler"` // 编译器
Debug atomic.Bool `json:"debug"` // 调试模式
BuildTime time.Time `json:"buildTime"` // 构建时间
}
VersionInfo 构建信息
func (*VersionInfo) String ¶ added in v0.1.6
func (vi *VersionInfo) String() string
String 返回格式化的构建信息