Documentation ¶
Overview ¶
Package cmdr is a golang library to interpret/parse the command-line input with POSIX-compliant mode
Index ¶
- Constants
- Variables
- func AddOnConfigLoadedListener(c ConfigReloaded)
- func AsJSON() (b []byte)
- func AsJSONExt(prettyFormat bool) (b []byte, err error)
- func AsToml() (b []byte)
- func AsTomlExt() (b []byte, err error)
- func AsYaml() (b []byte)
- func AsYamlExt() (b []byte, err error)
- func AttachLiveArgsTo(err error, liveArgs ...interface{}) error
- func CheckpointSize() int
- func ClearCheckpoints()
- func Clone(from, to typ.Any) typ.Any
- func DebugOutputTildeInfo(showType bool)
- func DeleteKey(key string)
- func DottedPathToCommandOrFlag(dottedPath string, anyCmd *Command) (cc *Command, ff *Flag)
- func DumpAsString() (str string)
- func EnableShellPager(enabled bool)
- func Exec(rootCmd *RootCommand, opts ...ExecOption) (err error)
- func Get(key string) interface{}
- func GetAlterConfigWriteBackMode() bool
- func GetBool(key string, defaultVal ...bool) bool
- func GetBoolP(prefix, key string, defaultVal ...bool) bool
- func GetBoolR(key string, defaultVal ...bool) bool
- func GetBoolRP(prefix, key string, defaultVal ...bool) bool
- func GetComplex128(key string, defaultVal ...complex128) complex128
- func GetComplex128P(prefix, key string, defaultVal ...complex128) complex128
- func GetComplex128R(key string, defaultVal ...complex128) complex128
- func GetComplex128RP(prefix, key string, defaultVal ...complex128) complex128
- func GetComplex64(key string, defaultVal ...complex64) complex64
- func GetComplex64P(prefix, key string, defaultVal ...complex64) complex64
- func GetComplex64R(key string, defaultVal ...complex64) complex64
- func GetComplex64RP(prefix, key string, defaultVal ...complex64) complex64
- func GetDebugMode() bool
- func GetDebugModeHitCount() int
- func GetDuration(key string, defaultVal ...time.Duration) time.Duration
- func GetDurationP(prefix, key string, defaultVal ...time.Duration) time.Duration
- func GetDurationR(key string, defaultVal ...time.Duration) time.Duration
- func GetDurationRP(prefix, key string, defaultVal ...time.Duration) time.Duration
- func GetFlagHitCount(longName string) int
- func GetFlagHitCountRecursively(longName string) int
- func GetFloat32(key string, defaultVal ...float32) float32
- func GetFloat32P(prefix, key string, defaultVal ...float32) float32
- func GetFloat32R(key string, defaultVal ...float32) float32
- func GetFloat32RP(prefix, key string, defaultVal ...float32) float32
- func GetFloat64(key string, defaultVal ...float64) float64
- func GetFloat64P(prefix, key string, defaultVal ...float64) float64
- func GetFloat64R(key string, defaultVal ...float64) float64
- func GetFloat64RP(prefix, key string, defaultVal ...float64) float64
- func GetHierarchyList() map[string]interface{}
- func GetHitCountByDottedPath(dottedPath string) int
- func GetInt(key string, defaultVal ...int) int
- func GetInt64(key string, defaultVal ...int64) int64
- func GetInt64P(prefix, key string, defaultVal ...int64) int64
- func GetInt64R(key string, defaultVal ...int64) int64
- func GetInt64RP(prefix, key string, defaultVal ...int64) int64
- func GetInt64Slice(key string, defaultVal ...int64) []int64
- func GetInt64SliceP(prefix, key string, defaultVal ...int64) []int64
- func GetInt64SliceR(key string, defaultVal ...int64) []int64
- func GetInt64SliceRP(prefix, key string, defaultVal ...int64) []int64
- func GetIntP(prefix, key string, defaultVal ...int) int
- func GetIntR(key string, defaultVal ...int) int
- func GetIntRP(prefix, key string, defaultVal ...int) int
- func GetIntSlice(key string, defaultVal ...int) []int
- func GetIntSliceP(prefix, key string, defaultVal ...int) []int
- func GetIntSliceR(key string, defaultVal ...int) []int
- func GetIntSliceRP(prefix, key string, defaultVal ...int) []int
- func GetKibibytes(key string, defaultVal ...uint64) uint64
- func GetKibibytesP(prefix, key string, defaultVal ...uint64) uint64
- func GetKibibytesR(key string, defaultVal ...uint64) uint64
- func GetKibibytesRP(prefix, key string, defaultVal ...uint64) uint64
- func GetKilobytes(key string, defaultVal ...uint64) uint64
- func GetKilobytesP(prefix, key string, defaultVal ...uint64) uint64
- func GetKilobytesR(key string, defaultVal ...uint64) uint64
- func GetKilobytesRP(prefix, key string, defaultVal ...uint64) uint64
- func GetMap(key string) map[string]interface{}
- func GetMapR(key string) map[string]interface{}
- func GetNoColorMode() bool
- func GetNoColorModeHitCount() int
- func GetPredefinedAlterLocations() []string
- func GetPredefinedLocations() []string
- func GetQuietMode() bool
- func GetQuietModeHitCount() int
- func GetR(key string) interface{}
- func GetRemainArgs() []string
- func GetSecondaryLocations() []string
- func GetSectionFrom(sectionKeyPath string, holder interface{}) (err error)
- func GetStrictMode() bool
- func GetString(key string, defaultVal ...string) string
- func GetStringNoExpand(key string, defaultVal ...string) string
- func GetStringNoExpandP(prefix, key string, defaultVal ...string) string
- func GetStringNoExpandR(key string, defaultVal ...string) string
- func GetStringNoExpandRP(prefix, key string, defaultVal ...string) string
- func GetStringP(prefix, key string, defaultVal ...string) string
- func GetStringR(key string, defaultVal ...string) string
- func GetStringRP(prefix, key string, defaultVal ...string) string
- func GetStringSlice(key string, defaultVal ...string) []string
- func GetStringSliceP(prefix, key string, defaultVal ...string) []string
- func GetStringSliceR(key string, defaultVal ...string) []string
- func GetStringSliceRP(prefix, key string, defaultVal ...string) []string
- func GetTraceMode() bool
- func GetTraceModeHitCount() int
- func GetUint(key string, defaultVal ...uint) uint
- func GetUint64(key string, defaultVal ...uint64) uint64
- func GetUint64P(prefix, key string, defaultVal ...uint64) uint64
- func GetUint64R(key string, defaultVal ...uint64) uint64
- func GetUint64RP(prefix, key string, defaultVal ...uint64) uint64
- func GetUint64Slice(key string, defaultVal ...uint64) []uint64
- func GetUint64SliceP(prefix, key string, defaultVal ...uint64) []uint64
- func GetUint64SliceR(key string, defaultVal ...uint64) []uint64
- func GetUint64SliceRP(prefix, key string, defaultVal ...uint64) []uint64
- func GetUintP(prefix, key string, defaultVal ...uint) uint
- func GetUintR(key string, defaultVal ...uint) uint
- func GetUintRP(prefix, key string, defaultVal ...uint) uint
- func GetUsedAlterConfigFile() string
- func GetUsedConfigFile() string
- func GetUsedConfigSubDir() string
- func GetUsedSecondaryConfigFile() string
- func GetUsedSecondaryConfigSubDir() string
- func GetUsingConfigFiles() []string
- func GetVerboseMode() bool
- func GetVerboseModeHitCount() int
- func GetWatchingConfigFiles() []string
- func HasKey(key string) (ok bool)
- func InDevelopingTime() (status bool)
- func InTesting() bool
- func InvokeCommand(dottedCommandPath string, extraArgs ...string) (err error)
- func IsIgnorableError(err error) bool
- func LoadConfigFile(file string) (mainFile, subDir string, err error)
- func MergeWith(m map[string]interface{}) (err error)
- func NewErrorForCmdr(msg string, args ...interface{}) error
- func NewLoggerConfig() *log.LoggerConfig
- func NewLoggerConfigWith(enabled bool, backend, level string) *log.LoggerConfig
- func Parsed() bool
- func PartialContains(names []string, partialNeedle string) (index int, matched string, contains bool)
- func RemoveAllOnConfigLoadedListeners()
- func RemoveOnConfigLoadedListener(c ConfigReloaded)
- func ResetOptions()
- func RestoreCheckpoint(n ...int) (err error)
- func SaveAsJSON(filename string) (err error)
- func SaveAsJSONExt(filename string, prettyFormat bool) (err error)
- func SaveAsToml(filename string) (err error)
- func SaveAsYaml(filename string) (err error)
- func SaveCheckpoint() (err error)
- func SaveObjAsToml(obj interface{}, filename string) (err error)
- func Set(key string, val interface{})
- func SetAlterConfigWriteBackMode(enabled bool)
- func SetAsAnIgnorableError(err error, ignorable bool) error
- func SetDebugMode(b bool)
- func SetLogger(l log.Logger)
- func SetNoColorMode(b bool)
- func SetNx(key string, val interface{})
- func SetNxOverwrite(key string, val interface{})
- func SetOnConfigLoadedListener(c ConfigReloaded, enabled bool)
- func SetOverwrite(key string, val interface{})
- func SetQuietMode(b bool)
- func SetRaw(key string, val interface{})
- func SetTraceMode(b bool)
- func SetVerboseMode(b bool)
- func SignalQuitSignal()
- func SignalTermSignal()
- func SignalToSelf(sig os.Signal) (err error)
- func StripHTMLTags(s string) string
- func StripLeftTabs(s string) string
- func StripLeftTabsOnly(s string) string
- func ToBool(val interface{}, defaultVal ...bool) (ret bool)
- func TrapSignals(onTrapped func(s os.Signal), signals ...os.Signal) (waiter func())
- func TrapSignalsEnh(done chan bool, onTrapped func(s os.Signal), signals ...os.Signal) (waiter func())
- func WalkAllCommands(walk func(cmd *Command, index, level int) (err error)) (err error)
- func WrapWithRxxtPrefix(key string) string
- type BaseOpt
- func (s *BaseOpt) GetDescZsh() (desc string)
- func (s *BaseOpt) GetHitStr() string
- func (s *BaseOpt) GetLongTitleNamesArray() []string
- func (s *BaseOpt) GetShortTitleNamesArray() []string
- func (s *BaseOpt) GetTitleName() string
- func (s *BaseOpt) GetTitleNames() string
- func (s *BaseOpt) GetTitleNamesArray() []string
- func (s *BaseOpt) GetTitleNamesArrayMainly() []string
- func (s *BaseOpt) GetTitleNamesBy(delimChar string) string
- func (s *BaseOpt) GetTitleZshNames() string
- func (s *BaseOpt) GetTitleZshNamesBy(delimChar string) (str string)
- func (s *BaseOpt) HasParent() bool
- type ColorTranslator
- type Command
- func DottedPathToCommand(dottedPath string, anyCmd *Command) (cc *Command)
- func FindSubCommand(longName string, cmd *Command) (res *Command)
- func FindSubCommandRecursive(longName string, cmd *Command) (res *Command)
- func GetHitCommands() []*Command
- func MatchAndTest(inputCommandlineWithoutArg0 string, opts ...ExecOption) (last *Command, err error)
- func (c *Command) Delete()
- func (c *Command) EqualTo(rh *Command) (ok bool)
- func (c *Command) FindFlag(longName string) (res *Flag)
- func (c *Command) FindFlagRecursive(longName string) (res *Flag)
- func (c *Command) FindSubCommand(longName string) (res *Command)
- func (c *Command) FindSubCommandRecursive(longName string) (res *Command)
- func (c *Command) GetDottedNamePath() string
- func (c *Command) GetExpandableNames() string
- func (c *Command) GetExpandableNamesArray() []string
- func (c *Command) GetName() string
- func (c *Command) GetOwner() *Command
- func (c *Command) GetParentName() string
- func (c *Command) GetQuotedGroupName() string
- func (c *Command) GetRoot() *RootCommand
- func (c *Command) GetSubCommandNamesBy(delimChar string) string
- func (c *Command) GetTriggeredTimes() int
- func (c *Command) IsRoot() bool
- func (c *Command) Match(title string) (ok bool)
- func (c *Command) PrintBuildInfo()
- func (c *Command) PrintHelp(justFlags bool)
- func (c *Command) PrintVersion()
- type ConfigReloaded
- type ErrorForCmdr
- func (w *ErrorForCmdr) As(target interface{}) bool
- func (w *ErrorForCmdr) Attach(errs ...error)
- func (w *ErrorForCmdr) Cause() error
- func (w *ErrorForCmdr) Error() string
- func (w *ErrorForCmdr) FormatNew(ignorable bool, livedArgs ...interface{}) *errors.WithStackInfo
- func (w *ErrorForCmdr) Is(target error) bool
- func (w *ErrorForCmdr) Unwrap() error
- type ExecOption
- func WithAfterArgsParsed(hookFunc Handler) ExecOption
- func WithAlterConfigAutoWriteBack(writeChanges bool) ExecOption
- func WithAlterLocations(locations ...string) ExecOption
- func WithAutomaticEnvHooks(hook HookOptsFunc) ExecOption
- func WithBuiltinCommands(versionsCmds, helpCmds, verboseCmds, generateCmds, generalCmdrCmds bool) ExecOption
- func WithCommandSystemCustomizing(customizer HookFunc) ExecOption
- func WithConfigFileLoadingHooks(before, after HookFunc) ExecOption
- func WithConfigLoadedListener(c ConfigReloaded) ExecOption
- func WithConfigSubDirAutoName(folderName string) ExecOption
- func WithCustomShowBuildInfo(fn func()) ExecOption
- func WithCustomShowVersion(fn func()) ExecOption
- func WithEnvPrefix(prefix ...string) ExecOption
- func WithEnvVarMap(varToValue map[string]func() string) ExecOption
- func WithExtensionsLocations(locations ...string) ExecOption
- func WithGlobalPostActions(fns ...Invoker) ExecOption
- func WithGlobalPreActions(fns ...Handler) ExecOption
- func WithHelpPainter(painter Painter) ExecOption
- func WithHelpScreenHooks(before, after HookHelpScreenFunc) ExecOption
- func WithHelpTabStop(tabStop int) ExecOption
- func WithHelpTailLine(line string) ExecOption
- func WithIIfOpt(condition bool, yes, no func() ExecOption) ExecOption
- func WithIfOpt(condition bool, yes func() ExecOption) ExecOption
- func WithIgnoreWrongEnumValue(ignored bool) ExecOption
- func WithInternalDefaultAction(useInternalDefaultAction bool, userDefinedActionHandler ...Handler) ExecOption
- func WithInternalOutputStreams(out, err *bufio.Writer) ExecOption
- func WithLogx(logger log.Logger) ExecOption
- func WithLogxShort(enabled bool, backend, level string) ExecOption
- func WithNoColor(b bool) ExecOption
- func WithNoCommandAction(b bool) ExecOption
- func WithNoDefaultHelpScreen(b bool) ExecOption
- func WithNoEnvOverrides(b bool) ExecOption
- func WithNoLoadConfigFiles(b bool) ExecOption
- func WithNoWarnings(b bool) ExecOption
- func WithNoWatchConfigFiles(b bool) ExecOption
- func WithOnPassThruCharHit(fn func(parsed *Command, switchChar string, args []string) (err error)) ExecOption
- func WithOnSwitchCharHit(fn func(parsed *Command, switchChar string, args []string) (err error)) ExecOption
- func WithOptionMergeModifying(onMergingSet func(keyPath string, value, oldVal interface{})) ExecOption
- func WithOptionModifying(onOptionSet func(keyPath string, value, oldVal interface{})) ExecOption
- func WithOptionsPrefix(prefix ...string) ExecOption
- func WithPagerEnabled(enabled ...bool) ExecOption
- func WithPluginLocations(locations ...string) ExecOption
- func WithPredefinedLocations(locations ...string) ExecOption
- func WithRxxtPrefix(prefix ...string) ExecOption
- func WithSearchAlterConfigFiles(b bool) ExecOption
- func WithSecondaryLocations(locations ...string) ExecOption
- func WithShellCompletionCommandEnabled(b bool) ExecOption
- func WithSimilarThreshold(similarThreshold float64) ExecOption
- func WithStrictMode(b bool) ExecOption
- func WithToggleGroupChoicerNewStyle(style, trueChoicer, falseChoicer string) ExecOption
- func WithToggleGroupChoicerStyle(style string) ExecOption
- func WithUnhandledErrorHandler(handler UnhandledErrorHandler) ExecOption
- func WithUnknownOptionHandler(handler UnknownOptionHandler) ExecOption
- func WithWarnForUnknownCommand(b bool) ExecOption
- func WithWatchMainConfigFileToo(b bool) ExecOption
- func WithXrefBuildingHooks(beforeXrefBuildingX, afterXrefBuiltX HookFunc) ExecOption
- type ExecWorker
- type Flag
- func (f *Flag) Delete()
- func (f *Flag) EqualTo(rh *Flag) (ok bool)
- func (f *Flag) GetDescZsh() (desc string)
- func (f *Flag) GetDottedNamePath() string
- func (f *Flag) GetDottedNamePathEx() string
- func (f *Flag) GetTitleFlagNames() string
- func (f *Flag) GetTitleFlagNamesBy(delimChar string) string
- func (f *Flag) GetTitleFlagNamesByMax(delimChar string, maxShort int) string
- func (f *Flag) GetTitleZshFlagName() (str string)
- func (f *Flag) GetTitleZshFlagNamesArray() (ary []string)
- func (f *Flag) GetTitleZshFlagShortName() (str string)
- func (f *Flag) GetTitleZshNamesBy(delimChar string, allowPrefix, quoted bool) (str string)
- func (f *Flag) GetTitleZshNamesExtBy(delimChar string, allowPrefix, quoted, shortTitleOnly, longTitleOnly bool) (str string)
- func (f *Flag) GetTriggeredTimes() int
- type Handler
- type HookFunc
- type HookHelpScreenFunc
- type HookOptsFunc
- type Invoker
- type Level
- type OnOptionSetCB
- type OnPassThruCharHitCB
- type OnSet
- type OnSwitchCharHitCB
- type OptCmd
- type OptFlag
- func NewAny(defaultValue ...any) (opt OptFlag)
- func NewBool(defaultValue ...bool) (opt OptFlag)
- func NewComplex128(defaultValue ...complex128) (opt OptFlag)
- func NewComplex64(defaultValue ...complex64) (opt OptFlag)
- func NewDuration(defaultValue ...time.Duration) (opt OptFlag)
- func NewDurationFrom(flg *Flag) (opt OptFlag)
- func NewFloat32(defaultValue ...float32) (opt OptFlag)
- func NewFloat64(defaultValue ...float64) (opt OptFlag)
- func NewInt(defaultValue ...int) (opt OptFlag)
- func NewInt64(defaultValue ...int64) (opt OptFlag)
- func NewIntSlice(defaultValue ...int) (opt OptFlag)
- func NewString(defaultValue ...string) (opt OptFlag)
- func NewStringSlice(defaultValue ...string) (opt OptFlag)
- func NewTextVar(defaultValue ...TextVar) (opt OptFlag)
- func NewUint(defaultValue ...uint) (opt OptFlag)
- func NewUint64(defaultValue ...uint64) (opt OptFlag)
- func NewUintSlice(defaultValue ...uint) (opt OptFlag)
- type OptFlagType
- type Options
- func (s *Options) CheckpointSize() int
- func (s *Options) ClearCheckpoints()
- func (s *Options) Delete(key string)
- func (s *Options) DumpAsString(showType bool) (str string)
- func (s *Options) Flush()
- func (s *Options) FromKibiBytes(sz string) (ir64 uint64)
- func (s *Options) FromKilobytes(sz string) (ir64 uint64)
- func (s *Options) Get(key string) (ret interface{})
- func (s *Options) GetBoolEx(key string, defaultVal ...bool) (ret bool)
- func (s *Options) GetComplex128(key string, defaultVal ...complex128) (ir complex128)
- func (s *Options) GetComplex64(key string, defaultVal ...complex64) (ir complex64)
- func (s *Options) GetDuration(key string, defaultVal ...time.Duration) (ir time.Duration)
- func (s *Options) GetFloat32Ex(key string, defaultVal ...float32) (ir float32)
- func (s *Options) GetFloat64Ex(key string, defaultVal ...float64) (ir float64)
- func (s *Options) GetHierarchyList() map[string]interface{}
- func (s *Options) GetInt64Ex(key string, defaultVal ...int64) (ir int64)
- func (s *Options) GetInt64Slice(key string, defaultVal ...int64) (ir []int64)
- func (s *Options) GetIntEx(key string, defaultVal ...int) (ir int)
- func (s *Options) GetIntSlice(key string, defaultVal ...int) (ir []int)
- func (s *Options) GetKibibytesEx(key string, defaultVal ...uint64) (ir64 uint64)
- func (s *Options) GetKilobytesEx(key string, defaultVal ...uint64) (ir64 uint64)
- func (s *Options) GetMap(key string) map[string]interface{}
- func (s *Options) GetString(key string, defaultVal ...string) (ret string)
- func (s *Options) GetStringNoExpand(key string, defaultVal ...string) (ret string)
- func (s *Options) GetStringSlice(key string, defaultVal ...string) (ir []string)
- func (s *Options) GetTextVar(key string, defaultVal ...TextVar) (ir TextVar)
- func (s *Options) GetUint64Ex(key string, defaultVal ...uint64) (ir uint64)
- func (s *Options) GetUint64Slice(key string, defaultVal ...uint64) (ir []uint64)
- func (s *Options) GetUintEx(key string, defaultVal ...uint) (ir uint)
- func (s *Options) Has(key string) (ok bool)
- func (s *Options) LoadConfigFile(file string, cft configFileType) (mainFile, subDir string, err error)
- func (s *Options) MergeWith(m map[string]interface{}) (err error)
- func (s *Options) Reset()
- func (s *Options) RestoreCheckpoint(n ...int) (err error)
- func (s *Options) SaveCheckpoint() (err error)
- func (s *Options) Set(key string, val interface{})
- func (s *Options) SetNx(key string, val interface{})
- func (s *Options) SetNxOverwrite(key string, val interface{})
- func (s *Options) SetOverwrite(key string, val interface{})
- func (s *Options) SetRaw(key string, val interface{})
- func (s *Options) SetRawOverwrite(key string, val interface{})
- func (s *Options) Wrap(key string) string
- type Painter
- type RootCmdOpt
- func (s *RootCmdOpt) Action(action Handler) (opt OptCmd)
- func (s *RootCmdOpt) AddCommand(cmd *Command)
- func (s *RootCmdOpt) AddFlag(flag *Flag)
- func (s *RootCmdOpt) AddGlobalPostAction(post Invoker) *RootCmdOpt
- func (s *RootCmdOpt) AddGlobalPreAction(pre Handler) *RootCmdOpt
- func (s *RootCmdOpt) AddOptCmd(opt OptCmd)
- func (s *RootCmdOpt) AddOptFlag(flag OptFlag)
- func (s *RootCmdOpt) Aliases(aliases ...string) (opt OptCmd)
- func (s *RootCmdOpt) AppendPostActions(fns ...func(cmd *Command, args []string))
- func (s *RootCmdOpt) AppendPreActions(fns ...func(cmd *Command, args []string) (err error))
- func (s *RootCmdOpt) AttachTo(parentOpt OptCmd) (opt OptCmd)
- func (s *RootCmdOpt) AttachToCommand(cmd *Command) (opt OptCmd)
- func (s *RootCmdOpt) AttachToRoot(root *RootCommand) (opt OptCmd)
- func (s *RootCmdOpt) Bool() (opt OptFlag)
- func (s *RootCmdOpt) Complex128() (opt OptFlag)
- func (s *RootCmdOpt) Complex64() (opt OptFlag)
- func (s *RootCmdOpt) Copyright(copyright, author string) *RootCmdOpt
- func (s *RootCmdOpt) Deprecated(deprecation string) (opt OptCmd)
- func (s *RootCmdOpt) Description(oneLine string, long ...string) (opt OptCmd)
- func (s *RootCmdOpt) Duration() (opt OptFlag)
- func (s *RootCmdOpt) Examples(examples string) (opt OptCmd)
- func (s *RootCmdOpt) Float32() (opt OptFlag)
- func (s *RootCmdOpt) Float64() (opt OptFlag)
- func (s *RootCmdOpt) Group(group string) (opt OptCmd)
- func (s *RootCmdOpt) Header(header string) *RootCmdOpt
- func (s *RootCmdOpt) Hidden(hidden bool) (opt OptCmd)
- func (s *RootCmdOpt) Int() (opt OptFlag)
- func (s *RootCmdOpt) Int64() (opt OptFlag)
- func (s *RootCmdOpt) IntSlice() (opt OptFlag)
- func (s *RootCmdOpt) Long(long string) (opt OptCmd)
- func (s *RootCmdOpt) Name(name string) (opt OptCmd)
- func (s *RootCmdOpt) NewFlag(typ OptFlagType) (opt OptFlag)
- func (s *RootCmdOpt) NewFlagV(defaultValue interface{}, titles ...string) (opt OptFlag)
- func (s *RootCmdOpt) OwnerCommand() (opt OptCmd)
- func (s *RootCmdOpt) PostAction(post Invoker) (opt OptCmd)
- func (s *RootCmdOpt) PreAction(pre Handler) (opt OptCmd)
- func (s *RootCmdOpt) RootCmdOpt() (root *RootCmdOpt)
- func (s *RootCmdOpt) RootCommand() (root *RootCommand)
- func (s *RootCmdOpt) RunAsSubCommand(dottedPathToSubCommand string) *RootCmdOpt
- func (s *RootCmdOpt) SetOwner(opt OptCmd)
- func (s *RootCmdOpt) Sets(cb func(cmd OptCmd)) (opt OptCmd)
- func (s *RootCmdOpt) Short(short string) (opt OptCmd)
- func (s *RootCmdOpt) String() (opt OptFlag)
- func (s *RootCmdOpt) StringSlice() (opt OptFlag)
- func (s *RootCmdOpt) TailPlaceholder(placeholders ...string) (opt OptCmd)
- func (s *RootCmdOpt) Titles(long, short string, aliases ...string) (opt OptCmd)
- func (s *RootCmdOpt) ToCommand() *Command
- func (s *RootCmdOpt) Uint() (opt OptFlag)
- func (s *RootCmdOpt) Uint64() (opt OptFlag)
- func (s *RootCmdOpt) VendorHidden(hidden bool) (opt OptCmd)
- type RootCommand
- type TextVar
- type UnhandledErrorHandler
- type UnknownOptionHandler
Constants ¶
const ( // UnsortedGroup for commands and flags UnsortedGroup = "zzzg.unsorted" // AddonsGroup for commands and flags AddonsGroup = "zzzh.Addons" // ExtGroup for commands and flags ExtGroup = "zzzi.Extensions" // AliasesGroup for commands and flags AliasesGroup = "zzzj.Aliases" // SysMgmtGroup for commands and flags SysMgmtGroup = "zzz9.Misc" // DefaultEditor is 'vim' DefaultEditor = "vim" // ExternalToolEditor environment variable name, EDITOR is fit for most of shells. ExternalToolEditor = "EDITOR" // ExternalToolPasswordInput enables secure password input without echo. ExternalToolPasswordInput = "PASSWD" )
const ( // AppName const AppName = "cmdr" // Version const Version = "1.11.26" // VersionInt const VersionInt = 0x010b1a )
const ( // FgBlack terminal color code FgBlack = 30 // FgRed terminal color code FgRed = 31 // FgGreen terminal color code FgGreen = 32 // FgYellow terminal color code FgYellow = 33 // FgBlue terminal color code FgBlue = 34 // FgMagenta terminal color code FgMagenta = 35 // FgCyan terminal color code FgCyan = 36 // FgLightGray terminal color code FgLightGray = 37 // FgDarkGray terminal color code FgDarkGray = 90 // FgLightRed terminal color code FgLightRed = 91 // FgLightGreen terminal color code FgLightGreen = 92 // FgLightYellow terminal color code FgLightYellow = 93 // FgLightBlue terminal color code FgLightBlue = 94 // FgLightMagenta terminal color code FgLightMagenta = 95 // FgLightCyan terminal color code FgLightCyan = 96 // FgWhite terminal color code FgWhite = 97 // BgNormal terminal color code BgNormal = 0 // BgBoldOrBright terminal color code BgBoldOrBright = 1 // BgDim terminal color code BgDim = 2 // BgItalic terminal color code BgItalic = 3 // BgUnderline terminal color code BgUnderline = 4 // BgUlink terminal color code BgUlink = 5 // BgInverse _ BgInverse = 7 // BgHidden terminal color code BgHidden = 8 // BgStrikeout terminal color code BgStrikeout = 9 // DarkColor terminal color code DarkColor = FgLightGray )
Variables ¶
var ( // CurrentHiddenColor the print color for left part of a hidden opt CurrentHiddenColor = FgDarkGray // CurrentDeprecatedColor the print color for deprecated opt line CurrentDeprecatedColor = FgDarkGray // CurrentDescColor the print color for description line CurrentDescColor = FgDarkGray // CurrentDefaultValueColor the print color for default value line CurrentDefaultValueColor = FgDarkGray // CurrentGroupTitleColor the print color for titles CurrentGroupTitleColor = DarkColor )
var ( // ErrShouldBeStopException tips `Exec()` canceled the following actions after `PreAction()` ErrShouldBeStopException = SetAsAnIgnorableError(newErrorWithMsg("stop me right now"), true) // ErrNotImpl requests cmdr launch the internal default action (see defaultAction) after returning from user's action. // // There's 3 ways to make default impl: set action to nil; use envvar `FORCE_DEFAULT_ACTION=1`; return `cmdr.ErrNotImpl` in your action handler: // “`go // listCmd := cmdr.NewSubCmd().Titles("list", "ls"). // Description("list projects in .poi.yml"). // Action(func(cmd *cmdr.Command, args []string) (err error) { // err = cmdr.ErrNotImpl // notify caller fallback to defaultAction // return // }). // AttachTo(root) // “` ErrNotImpl = errorsStd.New("not implements") // ErrBadArg is a generic error for user ErrBadArg = newErrorWithMsg("bad argument") )
var AllLevels = []Level{ PanicLevel, FatalLevel, ErrorLevel, WarnLevel, InfoLevel, DebugLevel, TraceLevel, OffLevel, }
AllLevels is a constant exposing all logging levels
var Logger = log.NewDummyLogger()
Logger for cmdr
Functions ¶
func AddOnConfigLoadedListener ¶
func AddOnConfigLoadedListener(c ConfigReloaded)
AddOnConfigLoadedListener adds a functor on config loaded and merged
func AsJSON ¶ added in v1.1.1
func AsJSON() (b []byte)
AsJSON returns a json string bytes about all options
func AsToml ¶ added in v1.1.1
func AsToml() (b []byte)
AsToml returns a toml string bytes about all options
func AsYaml ¶ added in v1.1.1
func AsYaml() (b []byte)
AsYaml returns a yaml string bytes about all options
func AsYamlExt ¶ added in v1.6.13
AsYamlExt returns a yaml string bytes about all options Indent with 2 spaces
func AttachLiveArgsTo ¶ added in v1.10.27
AttachLiveArgsTo wraps liveArgs into err if it's a *ErrorForCmdr as a container.
func CheckpointSize ¶ added in v1.10.0
func CheckpointSize() int
CheckpointSize returns how many snapshots made see also SaveCheckpoint
func ClearCheckpoints ¶ added in v1.10.0
func ClearCheckpoints()
ClearCheckpoints removes all checkpoints from snapshot history see also SaveCheckpoint
func DebugOutputTildeInfo ¶ added in v1.9.8
func DebugOutputTildeInfo(showType bool)
DebugOutputTildeInfo prints debug information like `~~debug`
func DeleteKey ¶ added in v1.6.3
func DeleteKey(key string)
DeleteKey deletes a key from cmdr options store
func DottedPathToCommandOrFlag ¶ added in v1.10.0
DottedPathToCommandOrFlag searches the matched Command or Flag with the specified dotted-path. The searching will start from root if anyCmd is nil.
func EnableShellPager ¶ added in v1.7.27
func EnableShellPager(enabled bool)
EnableShellPager transfer cmdr stdout to OS pager. The environment variable `PAGER` will be checkout, otherwise `less`.
func Exec ¶
func Exec(rootCmd *RootCommand, opts ...ExecOption) (err error)
Exec is main entry of `cmdr`.
func Get ¶
func Get(key string) interface{}
Get returns the generic value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.Get("app.logger.level") => 'DEBUG',... ```
func GetAlterConfigWriteBackMode ¶ added in v1.10.13
func GetAlterConfigWriteBackMode() bool
GetAlterConfigWriteBackMode return the state of writeBackAlterConfigs
func GetBool ¶
GetBool returns the bool value of an `Option` key. Such as: ```golang cmdr.GetBool("app.logger.enable", false) => true,... ```
func GetBoolP ¶ added in v0.2.3
GetBoolP returns the bool value of an `Option` key. Such as: ```golang cmdr.GetBoolP("app.logger", "enable", false) => true,... ```
func GetBoolR ¶ added in v0.2.23
GetBoolR returns the bool value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.GetBoolR("logger.enable", false) => true,... ```
func GetBoolRP ¶ added in v0.2.23
GetBoolRP returns the bool value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.GetBoolRP("logger", "enable", false) => true,... ```
func GetComplex128 ¶ added in v1.6.21
func GetComplex128(key string, defaultVal ...complex128) complex128
GetComplex128 returns the complex128 value of an `Option` key.
func GetComplex128P ¶ added in v1.6.21
func GetComplex128P(prefix, key string, defaultVal ...complex128) complex128
GetComplex128P returns the complex128 value of an `Option` key.
func GetComplex128R ¶ added in v1.6.21
func GetComplex128R(key string, defaultVal ...complex128) complex128
GetComplex128R returns the complex128 value of an `Option` key with WrapWithRxxtPrefix.
func GetComplex128RP ¶ added in v1.6.21
func GetComplex128RP(prefix, key string, defaultVal ...complex128) complex128
GetComplex128RP returns the complex128 value of an `Option` key with WrapWithRxxtPrefix.
func GetComplex64 ¶ added in v1.6.21
GetComplex64 returns the complex64 value of an `Option` key.
func GetComplex64P ¶ added in v1.6.21
GetComplex64P returns the complex64 value of an `Option` key.
func GetComplex64R ¶ added in v1.6.21
GetComplex64R returns the complex64 value of an `Option` key with WrapWithRxxtPrefix.
func GetComplex64RP ¶ added in v1.6.21
GetComplex64RP returns the complex64 value of an `Option` key with WrapWithRxxtPrefix.
func GetDebugMode ¶ added in v0.2.5
func GetDebugMode() bool
GetDebugMode returns the flag value of `--debug`/`-D`
NOTE
log.GetDebugMode()/SetDebugMode() have higher universality
the flag value of `--debug` or `-D` is always stored in cmdr Option Store, so you can retrieved it by GetBoolR("debug") and set it by Set("debug", true). You could also set it with SetDebugMode(b bool).
func GetDebugModeHitCount ¶ added in v1.10.0
func GetDebugModeHitCount() int
GetDebugModeHitCount returns how many times `--debug`/`-D` specified
func GetDuration ¶ added in v0.2.19
GetDuration returns the int slice value of an `Option` key.
func GetDurationP ¶ added in v0.2.19
GetDurationP returns the int slice value of an `Option` key.
func GetDurationR ¶ added in v1.0.0
GetDurationR returns the int slice value of an `Option` key.
func GetDurationRP ¶ added in v1.0.0
GetDurationRP returns the int slice value of an `Option` key.
func GetFlagHitCount ¶ added in v1.10.0
GetFlagHitCount return how manu times a top-level Flag was specified from command-line.
func GetFlagHitCountRecursively ¶ added in v1.10.0
GetFlagHitCountRecursively return how manu times a Flag was specified from command-line. longName will be search recursively.
func GetFloat32 ¶ added in v1.0.1
GetFloat32 returns the float32 value of an `Option` key.
func GetFloat32P ¶ added in v1.0.1
GetFloat32P returns the float32 value of an `Option` key.
func GetFloat32R ¶ added in v1.0.1
GetFloat32R returns the float32 value of an `Option` key with WrapWithRxxtPrefix.
func GetFloat32RP ¶ added in v1.0.1
GetFloat32RP returns the float32 value of an `Option` key with WrapWithRxxtPrefix.
func GetFloat64 ¶ added in v1.0.1
GetFloat64 returns the float64 value of an `Option` key.
func GetFloat64P ¶ added in v1.0.1
GetFloat64P returns the float64 value of an `Option` key.
func GetFloat64R ¶ added in v1.0.1
GetFloat64R returns the float64 value of an `Option` key with WrapWithRxxtPrefix.
func GetFloat64RP ¶ added in v1.0.1
GetFloat64RP returns the float64 value of an `Option` key with WrapWithRxxtPrefix.
func GetHierarchyList ¶ added in v1.1.1
func GetHierarchyList() map[string]interface{}
GetHierarchyList returns the hierarchy data
func GetHitCountByDottedPath ¶ added in v1.10.0
GetHitCountByDottedPath return how manu times a Flag or a Command was specified from command-line.
func GetInt64R ¶ added in v0.2.23
GetInt64R returns the int64 value of an `Option` key with WrapWithRxxtPrefix.
func GetInt64RP ¶ added in v0.2.23
GetInt64RP returns the int64 value of an `Option` key with WrapWithRxxtPrefix.
func GetInt64Slice ¶ added in v1.6.3
GetInt64Slice returns the int slice value of an `Option` key.
func GetInt64SliceP ¶ added in v1.6.3
GetInt64SliceP returns the int slice value of an `Option` key.
func GetInt64SliceR ¶ added in v1.6.3
GetInt64SliceR returns the int slice value of an `Option` key with WrapWithRxxtPrefix.
func GetInt64SliceRP ¶ added in v1.6.3
GetInt64SliceRP returns the int slice value of an `Option` key with WrapWithRxxtPrefix.
func GetIntR ¶ added in v0.2.23
GetIntR returns the int value of an `Option` key with WrapWithRxxtPrefix.
func GetIntRP ¶ added in v0.2.23
GetIntRP returns the int value of an `Option` key with WrapWithRxxtPrefix.
func GetIntSlice ¶ added in v0.2.19
GetIntSlice returns the int slice value of an `Option` key.
func GetIntSliceP ¶ added in v0.2.19
GetIntSliceP returns the int slice value of an `Option` key.
func GetIntSliceR ¶ added in v0.2.23
GetIntSliceR returns the int slice value of an `Option` key with WrapWithRxxtPrefix.
func GetIntSliceRP ¶ added in v0.2.23
GetIntSliceRP returns the int slice value of an `Option` key with WrapWithRxxtPrefix.
func GetKibibytes ¶ added in v1.6.19
GetKibibytes returns the uint64 value of an `Option` key.
kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes
See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKibibytesP ¶ added in v1.6.19
GetKibibytesP returns the uint64 value of an `Option` key.
kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes
See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKibibytesR ¶ added in v1.6.19
GetKibibytesR returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.
kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes
See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKibibytesRP ¶ added in v1.6.19
GetKibibytesRP returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.
kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes
See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKilobytes ¶ added in v1.6.19
GetKilobytes returns the uint64 value of an `Option` key.
kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes
See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKilobytesP ¶ added in v1.6.19
GetKilobytesP returns the uint64 value of an `Option` key.
kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes
See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKilobytesR ¶ added in v1.6.19
GetKilobytesR returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.
kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes
See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetKilobytesRP ¶ added in v1.6.19
GetKilobytesRP returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.
kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes
See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func GetMapR ¶ added in v1.0.0
GetMapR an `Option` by key string with WrapWithRxxtPrefix, it returns a hierarchy map or nil
func GetNoColorMode ¶ added in v1.6.3
func GetNoColorMode() bool
GetNoColorMode return the flag value of `--no-color`/`-nc`
func GetNoColorModeHitCount ¶ added in v1.10.0
func GetNoColorModeHitCount() int
GetNoColorModeHitCount returns how many times `--no-color`/`-nc` specified
func GetPredefinedAlterLocations ¶ added in v1.10.8
func GetPredefinedAlterLocations() []string
GetPredefinedAlterLocations return the alternative searching locations. The alter config file will be merged into main config store after secondary config merged. The most different things are the alter config file can be written back when cmdr
func GetPredefinedLocations ¶ added in v0.2.5
func GetPredefinedLocations() []string
GetPredefinedLocations return the primary searching locations for loading the main config files. cmdr finds these location to create the main config store.
func GetQuietMode ¶ added in v0.2.5
func GetQuietMode() bool
GetQuietMode returns the flag value of `--quiet`/`-q`
func GetQuietModeHitCount ¶ added in v1.10.0
func GetQuietModeHitCount() int
GetQuietModeHitCount returns how many times `--quiet`/`-q` specified
func GetR ¶ added in v0.2.23
func GetR(key string) interface{}
GetR returns the generic value of an `Option` key with WrapWithRxxtPrefix. Such as: ```golang cmdr.GetR("logger.level") => 'DEBUG',... ```
func GetRemainArgs ¶ added in v1.7.27
func GetRemainArgs() []string
GetRemainArgs returns the remain arguments after command line parsed
func GetSecondaryLocations ¶ added in v1.10.9
func GetSecondaryLocations() []string
GetSecondaryLocations return the secondary searching locations, and these configs will be merged into main config store.
func GetSectionFrom ¶ added in v1.0.1
GetSectionFrom returns error while cannot yaml Marshal and Unmarshal `cmdr.GetSectionFrom(sectionKeyPath, &holder)` could load all sub-tree nodes from sectionKeyPath and transform them into holder structure, such as: ```go
type ServerConfig struct { Port int HttpMode int EnableTls bool } var serverConfig = new(ServerConfig) cmdr.GetSectionFrom("server", &serverConfig) assert serverConfig.Port == 7100
```
func GetStrictMode ¶ added in v0.2.5
func GetStrictMode() bool
GetStrictMode enables error when opt value missed. such as: xxx a b --prefix” => error: prefix opt has no value specified. xxx a b --prefix'/' => ok.
ENV: use `CMDR_APP_STRICT_MODE=true` to enable strict-mode. NOTE: `CMDR_APP_` prefix could be set by user (via: `EnvPrefix` && `RxxtPrefix`).
the flag value of `--strict-mode`.
func GetStringNoExpand ¶ added in v1.6.7
GetStringNoExpand returns the string value of an `Option` key.
func GetStringNoExpandP ¶ added in v1.6.7
GetStringNoExpandP returns the string value of an `Option` key.
func GetStringNoExpandR ¶ added in v1.6.7
GetStringNoExpandR returns the string value of an `Option` key with WrapWithRxxtPrefix.
func GetStringNoExpandRP ¶ added in v1.6.7
GetStringNoExpandRP returns the string value of an `Option` key with WrapWithRxxtPrefix.
func GetStringP ¶ added in v0.2.3
GetStringP returns the string value of an `Option` key.
func GetStringR ¶ added in v0.2.23
GetStringR returns the string value of an `Option` key with WrapWithRxxtPrefix.
func GetStringRP ¶ added in v0.2.23
GetStringRP returns the string value of an `Option` key with WrapWithRxxtPrefix.
func GetStringSlice ¶
GetStringSlice returns the string slice value of an `Option` key.
func GetStringSliceP ¶ added in v0.2.3
GetStringSliceP returns the string slice value of an `Option` key.
func GetStringSliceR ¶ added in v0.2.23
GetStringSliceR returns the string slice value of an `Option` key with WrapWithRxxtPrefix.
func GetStringSliceRP ¶ added in v0.2.23
GetStringSliceRP returns the string slice value of an `Option` key with WrapWithRxxtPrefix.
func GetTraceMode ¶ added in v1.7.0
func GetTraceMode() bool
GetTraceMode returns the flag value of `--trace`/`-tr`
NOTE
log.GetTraceMode()/SetTraceMode() have higher universality
the flag value of `--trace` or `-tr` is always stored in cmdr Option Store, so you can retrieved it by GetBoolR("trace") and set it by Set("trace", true). You could also set it with SetTraceMode(b bool).
The `--trace` is not enabled in default, so you have to add it manually:
import "github.com/hedzr/cmdr-addons/pkg/plugins/trace" cmdr.Exec(buildRootCmd(), trace.WithTraceEnable(true), )
func GetTraceModeHitCount ¶ added in v1.10.0
func GetTraceModeHitCount() int
GetTraceModeHitCount returns how many times `--trace`/`-tr` specified
func GetUint64P ¶ added in v0.2.3
GetUint64P returns the uint64 value of an `Option` key.
func GetUint64R ¶ added in v0.2.23
GetUint64R returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.
func GetUint64RP ¶ added in v0.2.23
GetUint64RP returns the uint64 value of an `Option` key with WrapWithRxxtPrefix.
func GetUint64Slice ¶ added in v1.6.3
GetUint64Slice returns the int slice value of an `Option` key.
func GetUint64SliceP ¶ added in v1.6.3
GetUint64SliceP returns the int slice value of an `Option` key.
func GetUint64SliceR ¶ added in v1.6.3
GetUint64SliceR returns the int slice value of an `Option` key with WrapWithRxxtPrefix.
func GetUint64SliceRP ¶ added in v1.6.3
GetUint64SliceRP returns the int slice value of an `Option` key with WrapWithRxxtPrefix.
func GetUintR ¶ added in v0.2.23
GetUintR returns the uint value of an `Option` key with WrapWithRxxtPrefix.
func GetUintRP ¶ added in v0.2.23
GetUintRP returns the uint value of an `Option` key with WrapWithRxxtPrefix.
func GetUsedAlterConfigFile ¶ added in v1.10.8
func GetUsedAlterConfigFile() string
GetUsedAlterConfigFile returns the alternative config filename
func GetUsedConfigFile ¶ added in v0.2.3
func GetUsedConfigFile() string
GetUsedConfigFile returns the main config filename (generally it's `<appname>.yml`)
func GetUsedConfigSubDir ¶ added in v0.2.3
func GetUsedConfigSubDir() string
GetUsedConfigSubDir returns the sub-directory `conf.d` of config files. Note that it be always normalized now. Sometimes it might be empty string ("") if `conf.d` have not been found.
func GetUsedSecondaryConfigFile ¶ added in v1.10.9
func GetUsedSecondaryConfigFile() string
GetUsedSecondaryConfigFile returns the secondary config filename
func GetUsedSecondaryConfigSubDir ¶ added in v1.10.9
func GetUsedSecondaryConfigSubDir() string
GetUsedSecondaryConfigSubDir returns the subdirectory `conf.d` of secondary config files.
func GetUsingConfigFiles ¶ added in v1.6.9
func GetUsingConfigFiles() []string
GetUsingConfigFiles returns all loaded config files, includes the main config file and children in sub-directory `conf.d`.
func GetVerboseMode ¶ added in v0.2.5
func GetVerboseMode() bool
GetVerboseMode returns the flag value of `--verbose`/`-v`
func GetVerboseModeHitCount ¶ added in v1.10.0
func GetVerboseModeHitCount() int
GetVerboseModeHitCount returns how many times `--verbose`/`-v` specified
func GetWatchingConfigFiles ¶ added in v1.7.31
func GetWatchingConfigFiles() []string
GetWatchingConfigFiles returns all config files being watched.
func InDevelopingTime ¶ added in v1.7.28
func InDevelopingTime() (status bool)
InDevelopingTime detects whether is in developing time.
If the main program has been built as a executable binary, we would assumed which is not in developing time. If GetDebugMode() is true, that's in developing time too.
func InvokeCommand ¶ added in v1.10.1
InvokeCommand invokes a sub-command internally.
func IsIgnorableError ¶ added in v1.10.27
IsIgnorableError tests if an error is a *ErrorForCmdr and its Ignorable field is true
func LoadConfigFile ¶
LoadConfigFile loads a yaml config file and merge the settings into `rxxtOptions` and load files in the `conf.d` child directory too.
func MergeWith ¶ added in v1.1.4
MergeWith will merge a map into Option Store recursively. You could merge a yaml/json/toml options into cmdr Hierarchy Options.
func NewErrorForCmdr ¶ added in v1.10.27
NewErrorForCmdr creates a *ErrorForCmdr object with ignorable field supports.
For examples:
err := cmdr.NewErrorForCmdr("error here") cmdr.SetAsAnIgnorableError(err, true) if cmdr.IsIgnorable(err) { // do jump out and ignore it }
func NewLoggerConfig ¶ added in v1.7.2
func NewLoggerConfig() *log.LoggerConfig
NewLoggerConfig returns a default LoggerConfig
func NewLoggerConfigWith ¶ added in v1.7.28
func NewLoggerConfigWith(enabled bool, backend, level string) *log.LoggerConfig
NewLoggerConfigWith returns a default LoggerConfig
func PartialContains ¶ added in v1.11.5
func PartialContains(names []string, partialNeedle string) (index int, matched string, contains bool)
PartialContains checks if one of names has partialNeedle as a part.
func RemoveAllOnConfigLoadedListeners ¶ added in v1.11.11
func RemoveAllOnConfigLoadedListeners()
RemoveAllOnConfigLoadedListeners remove a functor on config loaded and merged
func RemoveOnConfigLoadedListener ¶
func RemoveOnConfigLoadedListener(c ConfigReloaded)
RemoveOnConfigLoadedListener remove a functor on config loaded and merged
func ResetOptions ¶ added in v0.2.19
func ResetOptions()
ResetOptions to reset the current `Options Store`, so that you could follow a `LoadConfigFile()` with it.
func RestoreCheckpoint ¶ added in v1.10.0
RestoreCheckpoint restore 1 or n checkpoint(s) from snapshots history. see also SaveCheckpoint
func SaveAsJSON ¶ added in v0.2.17
SaveAsJSON to Save all config entries as a json file
func SaveAsJSONExt ¶ added in v1.10.19
SaveAsJSONExt to Save all config entries as a json file
func SaveAsToml ¶ added in v0.2.17
SaveAsToml to Save all config entries as a toml file
func SaveAsYaml ¶ added in v0.2.17
SaveAsYaml to Save all config entries as a yaml file
func SaveCheckpoint ¶ added in v1.10.0
func SaveCheckpoint() (err error)
SaveCheckpoint make a snapshot of the current Option Store
You may ResetOptions after SaveCheckpoint:
func x(aMap map[string]interface{}){ defer cmdr.RestoreCheckpoint() cmdr.SaveCheckpoint() cmdr.ResetOptions() cmdr.MergeWith(map[string]interface{}{ "app": map[string]interface{}{ conf.AppName: map[string]interface{}{ "a-map": aMap, } } } cmdr.SaveAsYaml("a-setting.yml") }
func SaveObjAsToml ¶ added in v0.2.19
SaveObjAsToml to Save an object as a toml file
func Set ¶ added in v0.2.3
func Set(key string, val interface{})
Set sets the value of an `Option` key (with prefix auto-wrap). The key MUST not have an `app` prefix. eg:
cmdr.Set("logger.level", "DEBUG") cmdr.Set("ms.tags.port", 8500) ... cmdr.Set("debug", true) cmdr.GetBool("app.debug") => true
func SetAlterConfigWriteBackMode ¶ added in v1.10.13
func SetAlterConfigWriteBackMode(enabled bool)
SetAlterConfigWriteBackMode enables writing the runtime changes back to alter config file, or disable it
func SetAsAnIgnorableError ¶ added in v1.10.27
SetAsAnIgnorableError checks err is a *ErrorForCmdr object and set its Ignorable field.
func SetDebugMode ¶ added in v1.7.28
func SetDebugMode(b bool)
SetDebugMode setup the debug mode status in Option Store
func SetNoColorMode ¶ added in v1.11.11
func SetNoColorMode(b bool)
func SetNx ¶ added in v0.2.3
func SetNx(key string, val interface{})
SetNx but without prefix auto-wrapped. `rxxtPrefix` is a string slice to define the prefix string array, default is ["app"]. So, cmdr.Set("debug", true) will put a real entry with (`debug`, true).
func SetNxOverwrite ¶ added in v1.10.19
func SetNxOverwrite(key string, val interface{})
SetNxOverwrite likes SetOverwrite but without prefix auto-wrapped. It replaces the old value on a slice, instead of the default append mode.
func SetOnConfigLoadedListener ¶
func SetOnConfigLoadedListener(c ConfigReloaded, enabled bool)
SetOnConfigLoadedListener enable/disable a functor on config loaded and merged
func SetOverwrite ¶ added in v1.10.19
func SetOverwrite(key string, val interface{})
SetOverwrite sets the value of an `Option` key. The key MUST not have an `app` prefix. It replaces the old value on a slice, instead of the default append mode.
SetOverwrite(key, newSlice) will replace the original value with newSlice.
func SetQuietMode ¶ added in v1.11.11
func SetQuietMode(b bool)
func SetRaw ¶ added in v1.9.4
func SetRaw(key string, val interface{})
SetRaw but without prefix auto-wrapped. So, cmdr.SetRaw("debug", true) will put a real entry with (`debug`, true).
cmdr.Set("debug", true) cmdr.GetBool("debug") => true
func SetTraceMode ¶ added in v1.7.28
func SetTraceMode(b bool)
SetTraceMode setup the tracing mode status in Option Store
func SetVerboseMode ¶ added in v1.11.11
func SetVerboseMode(b bool)
func SignalQuitSignal ¶ added in v1.6.7
func SignalQuitSignal()
SignalQuitSignal post a SIGQUIT signal to the current process
func SignalTermSignal ¶ added in v1.6.7
func SignalTermSignal()
SignalTermSignal post a SIGTERM signal to the current process
func SignalToSelf ¶ added in v1.6.7
SignalToSelf trigger the sig signal to the current process
func StripHTMLTags ¶ added in v1.10.19
StripHTMLTags aggressively strips HTML tags from a string. It will only keep anything between `>` and `<`.
func StripLeftTabs ¶ added in v1.10.19
StripLeftTabs strips the least left side tab chars from lines. StripLeftTabs strips html tags too.
func StripLeftTabsOnly ¶ added in v1.10.19
StripLeftTabsOnly strips the least left side tab chars from lines.
func TrapSignals ¶ added in v1.1.7
TrapSignals is a helper for simplify your infinite loop codes.
Usage
func enteringLoop() { waiter := cmdr.TrapSignals(func(s os.Signal) { cmdr.Logger.Debugf("receive signal '%v' in onTrapped()", s) }) go waiter() }
func TrapSignalsEnh ¶ added in v1.6.7
func TrapSignalsEnh(done chan bool, onTrapped func(s os.Signal), signals ...os.Signal) (waiter func())
TrapSignalsEnh is a helper for simplify your infinite loop codes.
Usage
func enteringLoop() { done := make(chan bool, 1) go func(done chan bool){ // your main serve loop done <- true // to end the TrapSignalsEnh waiter by manually, instead of os signals caught. }(done) waiter := cmdr.TrapSignalsEnh(done, func(s os.Signal) { cmdr.Logger.Debugf("receive signal '%v' in onTrapped()", s) }) go waiter() }
func WalkAllCommands ¶ added in v0.2.9
WalkAllCommands loops for all commands, starting from root.
func WrapWithRxxtPrefix ¶ added in v0.2.23
WrapWithRxxtPrefix wrap an key with [RxxtPrefix], for [GetXxx(key)] and [GetXxxP(prefix,key)]
Types ¶
type BaseOpt ¶
type BaseOpt struct { // Name is reserved for internal purpose. Name string `yaml:"name,omitempty" json:"name,omitempty"` // Short 'rune' string. short option/command name. // single char. example for flag: "a" -> "-a" Short string `yaml:"short-name,omitempty" json:"short-name,omitempty"` // Full is a full/long form flag/command title name. // word string. example for flag: "addr" -> "--addr" Full string `yaml:"title,omitempty" json:"title,omitempty"` // Aliases are the more synonyms Aliases []string `yaml:"aliases,flow,omitempty" json:"aliases,omitempty"` // Group specify a group name, // A special prefix could sort it, has a form like `[0-9a-zA-Z]+\.`. // The prefix will be removed from help screen. // // Some examples are: // "A001.Host Params" // "A002.User Params" // // If ToggleGroup specified, Group field can be omitted because we will copy // from there. Group string `yaml:"group,omitempty" json:"group,omitempty"` Description string `yaml:"desc,omitempty" json:"desc,omitempty"` LongDescription string `yaml:"long-desc,omitempty" json:"long-desc,omitempty"` Examples string `yaml:"examples,omitempty" json:"examples,omitempty"` Hidden bool `yaml:"hidden,omitempty" json:"hidden,omitempty"` VendorHidden bool `yaml:"vendor-hidden,omitempty" json:"vendor-hidden,omitempty"` // Deprecated is a version string just like '0.5.9' or 'v0.5.9', that // means this command/flag was/will be deprecated since `v0.5.9`. Deprecated string `yaml:"deprecated,omitempty" json:"deprecated,omitempty"` // Action is callback for the last recognized command/sub-command. // return: ErrShouldBeStopException will break the following flow and exit right now // cmd 是 flag 被识别时已经得到的子命令 Action Handler `yaml:"-" json:"-"` // contains filtered or unexported fields }
BaseOpt is base of `Command`, `Flag`
func (*BaseOpt) GetLongTitleNamesArray ¶ added in v0.2.3
GetLongTitleNamesArray returns long name and aliases as an array
func (*BaseOpt) GetShortTitleNamesArray ¶ added in v0.2.3
GetShortTitleNamesArray returns short name as an array
func (*BaseOpt) GetTitleName ¶
GetTitleName returns name/full/short string
func (*BaseOpt) GetTitleNames ¶
GetTitleNames return the joint string of short,full,aliases names
func (*BaseOpt) GetTitleNamesArray ¶
GetTitleNamesArray returns short,full,aliases names
func (*BaseOpt) GetTitleNamesArrayMainly ¶ added in v1.9.4
GetTitleNamesArrayMainly returns short,full names
func (*BaseOpt) GetTitleNamesBy ¶
GetTitleNamesBy returns the joint string of short,full,aliases names
func (*BaseOpt) GetTitleZshNames ¶ added in v1.9.4
GetTitleZshNames temp
func (*BaseOpt) GetTitleZshNamesBy ¶ added in v1.9.4
GetTitleZshNamesBy temp
type ColorTranslator ¶ added in v1.10.19
ColorTranslator _
type Command ¶
type Command struct { BaseOpt `yaml:",inline"` Flags []*Flag `yaml:"flags,omitempty" json:"flags,omitempty"` SubCommands []*Command `yaml:"subcmds,omitempty" json:"subcmds,omitempty"` // return: ErrShouldBeStopException will break the following flow and exit right now PreAction Handler `yaml:"-" json:"-"` // PostAction will be run after Action() invoked. PostAction Invoker `yaml:"-" json:"-"` // TailPlaceHolder contains the description text of positional // arguments of a command. // It will be shown at tail of command usages line. Suppose there's // a TailPlaceHolder with"<host-fqdn> <ipv4/6>", they will be // painted in help screen just like: // // austr dns add <host-fqdn> <ipv4/6> [Options] [Parent/Global Options] // // Deprecated since v1.10.36+, use TailPlaceHolders is recommended TailPlaceHolder string `yaml:"tail-placeholder,omitempty" json:"tail-placeholder,omitempty"` // TailPlaceHolders gives two places to place the placeholders. // It looks like the following form: // // austr dns add <placeholder1st> [Options] [Parent/Global Options] <placeholders more...> // // As shown, you may specify at: // // - before '[Options] [Parent/Global Options]' // - after '[Options] [Parent/Global Options]' // // In TailPlaceHolders slice, [0] is `placeholder1st“, and others // are `placeholders more“. // // Others: // TailArgsText string [no plan] // TailArgsDesc string [no plan] TailPlaceHolders []string `` // Invoke is a space-separated string which takes Command (name) and extra // remain args to be invoked. // It invokes a command from the command tree in this app. // Invoke field is available for Invoke string `yaml:"invoke,omitempty" json:"invoke,omitempty"` // InvokeProc is just for cmdr aliases commands // invoke the external commands (via: executable) InvokeProc string `yaml:"invoke-proc,omitempty" json:"invoke-proc,omitempty"` // InvokeShell is just for cmdr aliases commands // invoke the external commands (via: shell) InvokeShell string `yaml:"invoke-sh,omitempty" json:"invoke-sh,omitempty"` // Shell is just for cmdr aliases commands // invoke a command under this shell, or /usr/bin/env bash|zsh|... Shell string `yaml:"shell,omitempty" json:"shell,omitempty"` // contains filtered or unexported fields }
Command holds the structure of commands and sub-commands
func DottedPathToCommand ¶ added in v1.10.0
DottedPathToCommand searches the matched Command with the specified dotted-path. The searching will start from root if anyCmd is nil.
func FindSubCommand ¶ added in v0.2.17
FindSubCommand find sub-command with `longName` from `cmd` if cmd == nil: finding from root command
func FindSubCommandRecursive ¶ added in v0.2.17
FindSubCommandRecursive find sub-command with `longName` from `cmd` recursively if cmd == nil: finding from root command
func GetHitCommands ¶ added in v1.10.27
func GetHitCommands() []*Command
GetHitCommands returns all matched sub-commands from commandline
func MatchAndTest ¶ added in v1.10.19
func MatchAndTest(inputCommandlineWithoutArg0 string, opts ...ExecOption) (last *Command, err error)
MatchAndTest _
func (*Command) Delete ¶ added in v1.10.0
func (c *Command) Delete()
Delete removes myself from the command hierarchy system.
func (*Command) FindFlagRecursive ¶ added in v1.5.1
FindFlagRecursive find flag with `longName` from `cmd` recursively
func (*Command) FindSubCommand ¶ added in v1.5.1
FindSubCommand find sub-command with `longName` from `cmd`
func (*Command) FindSubCommandRecursive ¶ added in v1.5.1
FindSubCommandRecursive find sub-command with `longName` from `cmd` recursively
func (*Command) GetDottedNamePath ¶ added in v1.6.19
GetDottedNamePath return the dotted key path of this command in the options store. For example, the returned string just like: 'server.start'. NOTE that there is no OptiontPrefixes in this key path. For more information about Option Prefix, refer to WithOptionsPrefix
func (*Command) GetExpandableNames ¶
GetExpandableNames returns the names comma splitted string.
func (*Command) GetExpandableNamesArray ¶
GetExpandableNamesArray returns the names array of command, includes short name and long name.
func (*Command) GetParentName ¶
GetParentName returns the owner command name
func (*Command) GetQuotedGroupName ¶
GetQuotedGroupName returns the group name quoted string.
func (*Command) GetRoot ¶
func (c *Command) GetRoot() *RootCommand
GetRoot returns the `RootCommand`
func (*Command) GetSubCommandNamesBy ¶
GetSubCommandNamesBy returns the joint string of subcommands
func (*Command) GetTriggeredTimes ¶ added in v1.10.0
GetTriggeredTimes returns the matched times
func (*Command) PrintBuildInfo ¶ added in v1.5.0
func (c *Command) PrintBuildInfo()
PrintBuildInfo print building information
func (*Command) PrintVersion ¶
func (c *Command) PrintVersion()
PrintVersion prints versions information
type ConfigReloaded ¶
type ConfigReloaded interface {
OnConfigReloaded()
}
ConfigReloaded for config reloaded
type ErrorForCmdr ¶ added in v1.0.2
type ErrorForCmdr struct { Ignorable bool // contains filtered or unexported fields }
ErrorForCmdr structure
func UnwrapError ¶ added in v1.10.27
func UnwrapError(err error) (e *ErrorForCmdr, ignorable, ok bool)
UnwrapError try extracting the *ErrorForCmdr object from a given error object even if it'd been wrapped deeply.
func UnwrapLiveArgsFromCmdrError ¶ added in v1.10.27
func UnwrapLiveArgsFromCmdrError(err error) (liveArgs []interface{}, e *ErrorForCmdr, ok bool)
UnwrapLiveArgsFromCmdrError try extracting the *ErrorForCmdr object from a given error object, and return the liveArgs field for usages.
func (*ErrorForCmdr) As ¶ added in v1.6.21
func (w *ErrorForCmdr) As(target interface{}) bool
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
func (*ErrorForCmdr) Attach ¶ added in v1.6.9
func (w *ErrorForCmdr) Attach(errs ...error)
Attach appends errs. For ErrorForCmdr, only one last error will be kept.
func (*ErrorForCmdr) Cause ¶ added in v1.6.21
func (w *ErrorForCmdr) Cause() error
Cause returns the underlying cause of the error recursively, if possible.
func (*ErrorForCmdr) Error ¶ added in v1.0.2
func (w *ErrorForCmdr) Error() string
func (*ErrorForCmdr) FormatNew ¶ added in v1.6.21
func (w *ErrorForCmdr) FormatNew(ignorable bool, livedArgs ...interface{}) *errors.WithStackInfo
FormatNew creates a new error object based on this error template 'w'.
Example:
errTmpl1001 := BUG1001.NewTemplate("something is wrong %v") err4 := errTmpl1001.FormatNew("ok").Attach(errBug1) fmt.Println(err4) fmt.Printf("%+v\n", err4)
func (*ErrorForCmdr) Is ¶ added in v1.6.21
func (w *ErrorForCmdr) Is(target error) bool
Is reports whether any error in err's chain matches target.
func (*ErrorForCmdr) Unwrap ¶ added in v1.6.21
func (w *ErrorForCmdr) Unwrap() error
Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.
type ExecOption ¶ added in v1.5.0
type ExecOption func(w *ExecWorker)
ExecOption is the functional option for Exec()
func WithAfterArgsParsed ¶ added in v1.6.3
func WithAfterArgsParsed(hookFunc Handler) ExecOption
WithAfterArgsParsed sets a callback point after command-line args parsed by cmdr internal exec().
Your callback func will be invoked before invoking the matched command `cmd`. At this time, all command-line args parsed and a command found.
If program was launched with empty or wrong arguments, your callback func won't be triggered.
When empty argument or `--help` found, cmdr will display help screen. To customize it see also cmdr.WithCustomShowVersion and cmdr.WithCustomShowBuildInfo.
When any wrong/warn arguments found, cmdr will display some tip messages. To customize it see also cmdr.WithUnknownOptionHandler.
func WithAlterConfigAutoWriteBack ¶ added in v1.10.13
func WithAlterConfigAutoWriteBack(writeChanges bool) ExecOption
WithAlterConfigAutoWriteBack enables writing the runtime changes back to alter config file.
func WithAlterLocations ¶ added in v1.7.37
func WithAlterLocations(locations ...string) ExecOption
WithAlterLocations sets the alter config file locations.
Default is:
alterLocations: []string{ "/ci/etc/$APPNAME/alter/$APPNAME.yml", "/etc/$APPNAME/alter/$APPNAME.yml", "/usr/local/etc/$APPNAME/alter/$APPNAME.yml", "./bin/$APPNAME.yml", // for developer, current bin directory "/var/lib/$APPNAME/.$APPNAME.yml", // "$THIS/.$APPNAME.yml", // executable's directory },
NOTE that just one config file will be loaded, the child `conf.d` folder not supports.
cmdr will SAVE the changes in this alter config file automatically once loaded.
func WithAutomaticEnvHooks ¶ added in v1.5.1
func WithAutomaticEnvHooks(hook HookOptsFunc) ExecOption
WithAutomaticEnvHooks sets the hook after building automatic environment.
At this point, you could override the option default values.
func WithBuiltinCommands ¶ added in v1.5.0
func WithBuiltinCommands(versionsCmds, helpCmds, verboseCmds, generateCmds, generalCmdrCmds bool) ExecOption
WithBuiltinCommands enables/disables those builtin predefined commands. Such as:
- versionsCmds / EnableVersionCommands supports injecting the default `--version` flags and commands
- helpCmds / EnableHelpCommands supports injecting the default `--help` flags and commands
- verboseCmds / EnableVerboseCommands supports injecting the default `--verbose` flags and commands
- generalCmdrCmds / EnableCmdrCommands support these flags: `--strict-mode`, `--no-env-overrides`, and `--no-color`
- generateCmds / EnableGenerateCommands supports injecting the default `generate` commands and sub-commands
func WithCommandSystemCustomizing ¶ added in v1.10.0
func WithCommandSystemCustomizing(customizer HookFunc) ExecOption
WithCommandSystemCustomizing provides a shortcut to allow plugin/addon can customize the whole command/sub-command hierarchy structure.
For example, suppose you're planning to hide the 'generate' internal command from help screen:
opt := cmdr.WithCommandSystemCustomizing( func(root *cmdr.RootCommand, args []string) { root.FindSubCommand("generate").Delete() }) opts := append(opts, opt) err := cmdr.Exec(buildMyCommands(), opts...)
And, you may attach more sub-commands into the current command system from your plugin/addon:
func WithColorTableCommand(dottedCommand ...string) cmdr.ExecOption { return cmdr.WithCommandSystemCustomizing( func(root *cmdr.RootCommand, args []string) { cmd := &root.Command for _, d := range dottedCommand { cmd = cmdr.DottedPathToCommand(d, cmd) break } rr := cmdr.NewCmdFrom(cmd) addTo(rr, cmdr.RootFrom(root)) }) } func addTo(rr cmdr.OptCmd, root *cmdr.RootCmdOpt) { c := cmdr.NewSubCmd() c.Titles("color-table", "ct"). Description("print shell escape sequence table", ""). Group(cmdr.SysMgmtGroup). Hidden(hidden). Action(printColorTable). AttachTo(rr) //... }
func WithConfigFileLoadingHooks ¶ added in v1.7.43
func WithConfigFileLoadingHooks(before, after HookFunc) ExecOption
WithConfigFileLoadingHooks adds the hook function to the front and back of trying to load config files.
These two hooks always are triggered whatever WithNoLoadConfigFiles is enabled or not.
func WithConfigLoadedListener ¶ added in v1.5.0
func WithConfigLoadedListener(c ConfigReloaded) ExecOption
WithConfigLoadedListener adds a functor on config loaded and merged
func WithConfigSubDirAutoName ¶ added in v1.7.31
func WithConfigSubDirAutoName(folderName string) ExecOption
WithConfigSubDirAutoName specify an alternate folder name instead `conf.d`.
By default, cmdr watches all files in the sub-directory `conf.d` of which folder contains the main config file.
func WithCustomShowBuildInfo ¶ added in v1.5.0
func WithCustomShowBuildInfo(fn func()) ExecOption
WithCustomShowBuildInfo supports your `ShowBuildInfo()` instead of internal `showBuildInfo()`
func WithCustomShowVersion ¶ added in v1.5.0
func WithCustomShowVersion(fn func()) ExecOption
WithCustomShowVersion supports your `ShowVersion()` instead of internal `showVersion()`
func WithEnvPrefix ¶ added in v1.5.0
func WithEnvPrefix(prefix ...string) ExecOption
WithEnvPrefix sets the environment variable text prefixes. cmdr will lookup envvars for a key. Default env-prefix is array ["CMDR"], ie 'CMDR_'
func WithEnvVarMap ¶ added in v1.6.3
func WithEnvVarMap(varToValue map[string]func() string) ExecOption
WithEnvVarMap adds a (envvar-name, value) map, which will be applied to string option value, string-slice option values, .... For example, you could define a key-value entry in your `<app>.yml` file:
app: test-value: "$THIS/$APPNAME.yml" home-dir: "$HOME"
it will be expanded by mapping to OS environment and this map (WithEnvVarMap). That is, $THIS will be expanded to the directory path of this executable, $APPNAME to the app name. And of course, $HOME will be mapped to os home directory path.
func WithExtensionsLocations ¶ added in v1.7.23
func WithExtensionsLocations(locations ...string) ExecOption
WithExtensionsLocations sets the extension locations.
A extension is an executable (shell scripts, binary executable, ,,,).
Default locations are:
[]string{ "./ci/local/share/$APPNAME/ext", "$HOME/.local/share/$APPNAME/ext", "$HOME/.$APPNAME/ext", "/usr/local/share/$APPNAME/ext", "/usr/share/$APPNAME/ext", },
See also internalResetWorkerNoLock()
func WithGlobalPostActions ¶ added in v1.7.46
func WithGlobalPostActions(fns ...Invoker) ExecOption
WithGlobalPostActions adds the post-action for each command invoked
func WithGlobalPreActions ¶ added in v1.7.46
func WithGlobalPreActions(fns ...Handler) ExecOption
WithGlobalPreActions adds the pre-action for every command invoking
func WithHelpPainter ¶ added in v1.5.0
func WithHelpPainter(painter Painter) ExecOption
WithHelpPainter allows to change the behavior and facade of help screen.
func WithHelpScreenHooks ¶ added in v1.7.27
func WithHelpScreenHooks(before, after HookHelpScreenFunc) ExecOption
WithHelpScreenHooks adds the hook function to the front and back of printing help screen
func WithHelpTabStop ¶ added in v1.5.0
func WithHelpTabStop(tabStop int) ExecOption
WithHelpTabStop sets the tab-stop position in the help screen Default tabstop is 48
Deprecated since v1.7.8 because the tab-stop position will be autosize from then on.
func WithHelpTailLine ¶ added in v1.6.11
func WithHelpTailLine(line string) ExecOption
WithHelpTailLine setup the tail line in help screen
Default line is:
"\nType '-h' or '--help' to get command help screen."
Tiny html codes are supported, such as:
b/strong, i/cite, u, code/kbd, mark, del, font
These tags are parsed but ignored:
html, head, body
func WithIIfOpt ¶ added in v1.11.9
func WithIIfOpt(condition bool, yes, no func() ExecOption) ExecOption
func WithIfOpt ¶ added in v1.11.9
func WithIfOpt(condition bool, yes func() ExecOption) ExecOption
func WithIgnoreWrongEnumValue ¶ added in v1.5.0
func WithIgnoreWrongEnumValue(ignored bool) ExecOption
WithIgnoreWrongEnumValue will be put into `cmdrError.Ignorable` while wrong enumerable value found in parsing command-line options. The default is true.
Main program might decide whether it's a warning or error.
See also ¶
[Flag.ValidArgs]
func WithInternalDefaultAction ¶ added in v1.10.27
func WithInternalDefaultAction(useInternalDefaultAction bool, userDefinedActionHandler ...Handler) ExecOption
WithInternalDefaultAction provides a default command action to which hasn't been defined.
func WithInternalOutputStreams ¶ added in v1.5.0
func WithInternalOutputStreams(out, err *bufio.Writer) ExecOption
WithInternalOutputStreams sets the internal output streams for debugging
func WithLogx ¶ added in v1.7.6
func WithLogx(logger log.Logger) ExecOption
WithLogx enables github.com/hedzr/logex,log integration
Sample 1:
WithLogx(log.NewDummyLogger()), // import "github.com/hedzr/log" WithLogx(log.NewStdLogger()), // import "github.com/hedzr/log" WithLogx(logrus.New()), // import "github.com/hedzr/logex/logx/logrus" WithLogx(sugar.New()), // import "github.com/hedzr/logex/logx/zap/sugar" WithLogx(zap.New()), // import "github.com/hedzr/logex/logx/zap"
Sample 2:
WithLogx(build.New(loggerConfig)), // import "github.com/hedzr/logex/build" WithLogx(build.New(build.NewLoggerConfigWith(true, "zap", "debug")),
func WithLogxShort ¶ added in v1.7.43
func WithLogxShort(enabled bool, backend, level string) ExecOption
WithLogxShort enables github.com/hedzr/logex,log integration
func WithNoColor ¶ added in v1.6.3
func WithNoColor(b bool) ExecOption
WithNoColor make console outputs plain and without ANSI escape colors
Since v1.6.2+
func WithNoCommandAction ¶ added in v1.6.17
func WithNoCommandAction(b bool) ExecOption
WithNoCommandAction do NOT run the action of the matched command.
func WithNoDefaultHelpScreen ¶ added in v1.6.0
func WithNoDefaultHelpScreen(b bool) ExecOption
WithNoDefaultHelpScreen true to disable printing help screen if without any arguments
func WithNoEnvOverrides ¶ added in v1.6.3
func WithNoEnvOverrides(b bool) ExecOption
WithNoEnvOverrides enables the internal no-env-overrides mode
Since v1.6.2+
In this mode, cmdr do NOT find and transfer equivalent envvar value into cmdr options store.
func WithNoLoadConfigFiles ¶ added in v1.5.0
func WithNoLoadConfigFiles(b bool) ExecOption
WithNoLoadConfigFiles true means no loading config files
func WithNoWarnings ¶ added in v1.11.11
func WithNoWarnings(b bool) ExecOption
WithNoWarnings disable internal warnings
func WithNoWatchConfigFiles ¶ added in v1.6.9
func WithNoWatchConfigFiles(b bool) ExecOption
WithNoWatchConfigFiles true means no watching the config files
func WithOnPassThruCharHit ¶ added in v1.6.18
func WithOnPassThruCharHit(fn func(parsed *Command, switchChar string, args []string) (err error)) ExecOption
WithOnPassThruCharHit handle the passthrough char(s) (i.e. '--') matched For example, type `bin/fluent mx -d -- --help` will trigger this callback at the 2nd flag '--'.
func WithOnSwitchCharHit ¶ added in v1.6.18
func WithOnSwitchCharHit(fn func(parsed *Command, switchChar string, args []string) (err error)) ExecOption
WithOnSwitchCharHit handle the exact single switch-char (such as '-', '/', '~') matched. For example, type `bin/fluent mx -d - --help` will trigger this callback at the 2nd flag '-'.
func WithOptionMergeModifying ¶ added in v1.6.12
func WithOptionMergeModifying(onMergingSet func(keyPath string, value, oldVal interface{})) ExecOption
WithOptionMergeModifying adds a callback which invoked on new configurations was merging into, typically on loading the modified external config file(s). NOTE that MergeWith(...) can make it triggered too. A onMergingSet callback will be enabled after first loaded any external configuration files and environment variables merged.
func WithOptionModifying ¶ added in v1.6.12
func WithOptionModifying(onOptionSet func(keyPath string, value, oldVal interface{})) ExecOption
WithOptionModifying adds a callback which invoked at each time any option was modified. It will be triggered after any external config files first loaded and the env variables had been merged.
func WithOptionsPrefix ¶ added in v1.5.0
func WithOptionsPrefix(prefix ...string) ExecOption
WithOptionsPrefix create a top-level namespace, which contains all normalized `Flag`s. =WithRxxtPrefix Default Options Prefix is array ["app"], ie 'app.xxx'
func WithPagerEnabled ¶ added in v1.6.41
func WithPagerEnabled(enabled ...bool) ExecOption
WithPagerEnabled transfer cmdr stdout to OS pager. The environment variable `PAGER` will be checkout, otherwise `less`.
NOTICE ONLY the outputs of cmdr (such as help screen) will be paged.
func WithPluginLocations ¶ added in v1.7.23
func WithPluginLocations(locations ...string) ExecOption
WithPluginLocations sets the addon locations.
An addon is a golang plugin for cmdr.
Default locations are:
[]string{ "./ci/local/share/$APPNAME/addons", "$HOME/.local/share/$APPNAME/addons", "$HOME/.$APPNAME/addons", "/usr/local/share/$APPNAME/addons", "/usr/share/$APPNAME/addons", },
See also internalResetWorkerNoLock()
func WithPredefinedLocations ¶ added in v1.5.0
func WithPredefinedLocations(locations ...string) ExecOption
WithPredefinedLocations sets the main config file locations.
Default is:
[]string{ "./ci/etc/$APPNAME/$APPNAME.yml", // for developer "/etc/$APPNAME/$APPNAME.yml", // regular location "/usr/local/etc/$APPNAME/$APPNAME.yml", // regular macOS HomeBrew location "/opt/etc/$APPNAME/$APPNAME.yml", // regular location "/var/lib/etc/$APPNAME/$APPNAME.yml", // regular location "$HOME/.config/$APPNAME/$APPNAME.yml", // per user "$THIS/$APPNAME.yml", // executable's directory "$APPNAME.yml", // current directory },
See also internalResetWorkerNoLock()
func WithRxxtPrefix ¶ added in v1.5.0
func WithRxxtPrefix(prefix ...string) ExecOption
WithRxxtPrefix create a top-level namespace, which contains all normalized `Flag`s. cmdr will lookup envvars for a key. Default Options Prefix is array ["app"], ie 'app.xxx'
func WithSearchAlterConfigFiles ¶ added in v1.7.31
func WithSearchAlterConfigFiles(b bool) ExecOption
WithSearchAlterConfigFiles adds CURR_DIR/.<appname>.yml and CURR_DIR/.<appname>/*.yml to the assumed config files and folders
func WithSecondaryLocations ¶ added in v1.10.9
func WithSecondaryLocations(locations ...string) ExecOption
WithSecondaryLocations sets the secondary config file locations.
Default is:
secondaryLocations: []string{ "/ci/etc/$APPNAME/conf/$APPNAME.yml", "/etc/$APPNAME/conf/$APPNAME.yml", "/usr/local/etc/$APPNAME/conf/$APPNAME.yml", "$HOME/.$APPNAME/$APPNAME.yml", // ext location per user },
The child `conf.d` folder will be loaded too.
func WithShellCompletionCommandEnabled ¶ added in v1.10.27
func WithShellCompletionCommandEnabled(b bool) ExecOption
WithShellCompletionCommandEnabled enables __complete command for internal usage in fish, ps, etc..
func WithSimilarThreshold ¶ added in v1.5.5
func WithSimilarThreshold(similarThreshold float64) ExecOption
WithSimilarThreshold defines a threshold for command/option similar detector. Default threshold is 0.6666666666666666. See also JaroWinklerDistance
func WithStrictMode ¶ added in v1.6.3
func WithStrictMode(b bool) ExecOption
WithStrictMode enables the internal strict mode
Since v1.6.2+
In this mode, any warnings will be treat as an error and cause app fatal exit.
In normal mode, these cases are assumed as warnings: - flag name not found - command or sub-command name not found - value extracting failed - ...
func WithToggleGroupChoicerNewStyle ¶ added in v1.9.2
func WithToggleGroupChoicerNewStyle(style, trueChoicer, falseChoicer string) ExecOption
WithToggleGroupChoicerNewStyle enables customizable choicer characters with your own style name.
For `ToggleGroup Choicer` and its style, see also: https://github.com/hedzr/cmdr/issues/1#issuecomment-968247546
func WithToggleGroupChoicerStyle ¶ added in v1.9.2
func WithToggleGroupChoicerStyle(style string) ExecOption
WithToggleGroupChoicerStyle allows user-defined choicer style.
The valid styles are: hexagon, triangle-right.
For `ToggleGroup Choicer` and its style, see also: https://github.com/hedzr/cmdr/issues/1#issuecomment-968247546
func WithUnhandledErrorHandler ¶ added in v1.6.13
func WithUnhandledErrorHandler(handler UnhandledErrorHandler) ExecOption
WithUnhandledErrorHandler handle the panics or exceptions generally
func WithUnknownOptionHandler ¶ added in v1.5.5
func WithUnknownOptionHandler(handler UnknownOptionHandler) ExecOption
WithUnknownOptionHandler enables your customized wrong command/flag processor. internal processor supports smart suggestions for those wrong commands and flags.
func WithWarnForUnknownCommand ¶ added in v1.7.32
func WithWarnForUnknownCommand(b bool) ExecOption
WithWarnForUnknownCommand warns the end user if unknown command found.
By default, cmdr ignore the first unknown command and treat them as remained arguments.
func WithWatchMainConfigFileToo ¶ added in v1.6.9
func WithWatchMainConfigFileToo(b bool) ExecOption
WithWatchMainConfigFileToo enables the watcher on main config file.
By default, cmdr watches all files in the sub-directory `conf.d` of which folder contains the main config file. But as a feature, cmdr ignore the changes in main config file.
WithWatchMainConfigFileToo can switch this feature.
envvars:
CFG_DIR: will be set to the folder contains the main config file no-watch-conf-dir: if set true, the watcher will be disabled.
func WithXrefBuildingHooks ¶ added in v1.5.0
func WithXrefBuildingHooks(beforeXrefBuildingX, afterXrefBuiltX HookFunc) ExecOption
WithXrefBuildingHooks sets the hook before and after building xref indices. It's replacers for AddOnBeforeXrefBuilding, and AddOnAfterXrefBuilt.
By using beforeXrefBuildingX, you could append, modify, or remove the builtin commands and options.
type ExecWorker ¶ added in v1.5.0
type ExecWorker struct {
// contains filtered or unexported fields
}
ExecWorker is a core logic worker and holder
func (*ExecWorker) AddOnAfterXrefBuilt ¶ added in v1.5.0
func (w *ExecWorker) AddOnAfterXrefBuilt(cb HookFunc)
AddOnAfterXrefBuilt add hook func daemon plugin needed
func (*ExecWorker) AddOnBeforeXrefBuilding ¶ added in v1.5.0
func (w *ExecWorker) AddOnBeforeXrefBuilding(cb HookFunc)
AddOnBeforeXrefBuilding add hook func daemon plugin needed
func (*ExecWorker) InternalExecFor ¶ added in v1.5.0
func (w *ExecWorker) InternalExecFor(rootCmd *RootCommand, args []string) (last *Command, err error)
InternalExecFor is an internal helper, esp for debugging
type Flag ¶
type Flag struct { BaseOpt `yaml:",inline"` // ToggleGroup for Toggle Group ToggleGroup string `yaml:"toggle-group,omitempty" json:"toggle-group,omitempty"` // DefaultValuePlaceholder for flag DefaultValuePlaceholder string `yaml:"default-placeholder,omitempty" json:"default-placeholder,omitempty"` // DefaultValue default value for flag DefaultValue interface{} `yaml:"default,omitempty" json:"default,omitempty"` // DefaultValueType is a string to indicate the data-type of DefaultValue. // It's only available in loading flag definition from a config-file (yaml/json/...). // Never used in writing your codes manually. DefaultValueType string `yaml:"type,omitempty" json:"type,omitempty"` // ValidArgs for enum flag ValidArgs []string `yaml:"valid-args,omitempty" json:"valid-args,omitempty"` // Required to-do Required bool `yaml:"required,omitempty" json:"required,omitempty"` // ExternalTool to get the value text by invoking external tool. // It's an environment variable name, such as: "EDITOR" (or cmdr.ExternalToolEditor) ExternalTool string `yaml:"external-tool,omitempty" json:"external-tool,omitempty"` // EnvVars give a list to bind to environment variables manually // it'll take effects since v1.6.9 EnvVars []string `yaml:"envvars,flow,omitempty" json:"envvars,omitempty"` // HeadLike enables a free-hand option like `head -3`. // // When a free-hand option presents, it'll be treated as a named option with an integer value. // // For example, option/flag = `{{Full:"line",Short:"l"},HeadLike:true}`, the command line: // `app -3` // is equivalent to `app -l 3`, and so on. // // HeadLike assumed an named option with an integer value, that means, Min and Max can be applied on it too. // NOTE: Only one head-like option can be defined in a command/sub-command chain. HeadLike bool `yaml:"head-like,omitempty" json:"head-like,omitempty"` // Min minimal value of a range. Min int64 `yaml:"min,omitempty" json:"min,omitempty"` // Max maximal value of a range. Max int64 `yaml:"max,omitempty" json:"max,omitempty"` // contains filtered or unexported fields }
Flag means a flag, a option, or a opt.
func FindFlag ¶ added in v0.2.17
FindFlag find flag with `longName` from `cmd` if cmd == nil: finding from root command
func FindFlagRecursive ¶ added in v0.2.17
FindFlagRecursive find flag with `longName` from `cmd` recursively if cmd == nil: finding from root command
func GetHitFlags ¶ added in v1.10.27
func GetHitFlags() []*Flag
GetHitFlags returns all matched flags from commandline
func (*Flag) Delete ¶ added in v1.10.0
func (f *Flag) Delete()
Delete removes myself from the command owner.
func (*Flag) GetDescZsh ¶ added in v0.2.13
GetDescZsh temp
func (*Flag) GetDottedNamePath ¶ added in v1.10.13
GetDottedNamePath return the dotted key path of this flag in the options store.
func (*Flag) GetDottedNamePathEx ¶ added in v1.11.23
GetDottedNamePathEx return the dotted key path of this flag in the options store.
func (*Flag) GetTitleFlagNames ¶ added in v0.2.13
GetTitleFlagNames temp
func (*Flag) GetTitleFlagNamesBy ¶ added in v0.2.13
GetTitleFlagNamesBy temp
func (*Flag) GetTitleFlagNamesByMax ¶ added in v0.2.13
GetTitleFlagNamesByMax temp
func (*Flag) GetTitleZshFlagName ¶ added in v0.2.13
GetTitleZshFlagName temp
func (*Flag) GetTitleZshFlagNamesArray ¶ added in v0.2.13
GetTitleZshFlagNamesArray temp
func (*Flag) GetTitleZshFlagShortName ¶ added in v1.9.4
GetTitleZshFlagShortName temp
func (*Flag) GetTitleZshNamesBy ¶ added in v1.9.4
GetTitleZshNamesBy temp
func (*Flag) GetTitleZshNamesExtBy ¶ added in v1.9.4
func (f *Flag) GetTitleZshNamesExtBy(delimChar string, allowPrefix, quoted, shortTitleOnly, longTitleOnly bool) (str string)
GetTitleZshNamesExtBy temp
func (*Flag) GetTriggeredTimes ¶ added in v1.5.1
GetTriggeredTimes returns the matched times
type HookFunc ¶ added in v1.5.1
type HookFunc func(root *RootCommand, args []string)
HookFunc the hook function prototype for SetBeforeXrefBuilding and SetAfterXrefBuilt
type HookHelpScreenFunc ¶ added in v1.7.27
type HookHelpScreenFunc func(w *ExecWorker, p Painter, cmd *Command, justFlags bool)
HookHelpScreenFunc the hook function prototype
type HookOptsFunc ¶ added in v1.5.1
type HookOptsFunc func(root *RootCommand, opts *Options)
HookOptsFunc the hook function prototype
type Level ¶ added in v1.6.25
type Level uint32
Level type
const ( // PanicLevel level, highest level of severity. Logs and then calls panic with the // message passed to Debug, Info, ... PanicLevel Level = iota // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the // logging level is set to Panic. FatalLevel // ErrorLevel level. Logs. Used for errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. ErrorLevel // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel // InfoLevel level. General operational entries about what's going on inside the // application. InfoLevel // DebugLevel level. Usually only enabled when debugging. Very verbose logging. DebugLevel // TraceLevel level. Designates finer-grained informational events than the Debug. TraceLevel // OffLevel level. The logger will be shutdown. OffLevel )
These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `log.NewDummyLogger()`/`log.NewStdLogger()`.
func GetLoggerLevel ¶ added in v1.6.25
func GetLoggerLevel() Level
GetLoggerLevel returns the current logger level after parsed.
func ParseLevel ¶ added in v1.6.25
ParseLevel takes a string level and returns the hedzr/log logging level constant.
func (Level) MarshalText ¶ added in v1.6.25
MarshalText convert Level to string and []byte
func (Level) String ¶ added in v1.6.25
Convert the Level to a string. E.g. PanicLevel becomes "panic".
func (*Level) UnmarshalText ¶ added in v1.6.25
UnmarshalText implements encoding.TextUnmarshaler.
type OnOptionSetCB ¶ added in v1.7.27
type OnOptionSetCB func(keyPath string, value, oldVal interface{})
OnOptionSetCB is a callback function while an option is being set (or merged)
type OnPassThruCharHitCB ¶ added in v1.7.27
OnPassThruCharHitCB is a callback function ...
type OnSet ¶ added in v1.6.8
type OnSet interface { // OnSet will be callback'd once the flag parsed OnSet(f func(keyPath string, value interface{})) (opt OptFlag) }
OnSet interface
type OnSwitchCharHitCB ¶ added in v1.7.27
OnSwitchCharHitCB is a callback function ...
type OptCmd ¶ added in v0.2.15
type OptCmd interface { // Titles broken API since v1.6.39 // // If necessary, an order prefix can be attached to the long title. // The title with prefix will be set to Name field and striped to Long field. // // An order prefix is a dotted string with multiple alphabet and digit. Such as: // "zzzz.", "0001.", "700.", "A1." ... // Titles(long, short string, aliases ...string) (opt OptCmd) // Short gives a short form sub-command title in string representation. // // A short command title is often one char, sometimes it can be // two chars, but even more is allowed. Short(short string) (opt OptCmd) // Long gives a long form sub-command title, we call it 'Full Title' too. // // A long title should be one or more words in english, separated // by short hypen ('-'), for example 'create-new-account'. // // Of course, in a multiple-level command system, a better // hierarchical command structure might be: // // ROOT // account // create // edit // suspend // destroy // Long(long string) (opt OptCmd) // Name is an internal identity, and an order prefix is optional // // An ordered prefix is a dotted string with multiple alphabets // and digits. Such as: // "zzzz.", "0001.", "700.", "A1." ... Name(name string) (opt OptCmd) // Aliases gives more choices for a command. Aliases(ss ...string) (opt OptCmd) // Description gives normal and long form description of a command. // // Tiny html codes are supported, such as: // b/strong, i/cite, u, code/kbd, mark, del, font // These tags are parsed but ignored: // html, head, body Description(oneLine string, long ...string) (opt OptCmd) // Examples gives text to be shown in a section in the help screen. // // Tiny html codes are supported, such as: // b/strong, i/cite, u, code/kbd, mark, del, font // These tags are parsed but ignored: // html, head, body Examples(examples string) (opt OptCmd) // Group provides command group name. // // All commands with same group name will be agreegated in // one group. // // An order prefix is a dotted string with multiple alphabet // and digit. Such as: // "zzzz.", "0001.", "700.", "A1." ... Group(group string) (opt OptCmd) // Hidden command will not be shown in help screen, expect user // entered 'app --help -vvv'. // // NOTE -v is a builtin flag, -vvv means be triggered 3rd // times. // // And the triggered times of a flag can be retrieved by // flag.GetTriggeredTimes(), or via cmdr Option Store API: // cmdr.GetFlagHitCount("verbose") / cmdr.GetVerboseHitCount(). Hidden(hidden bool) (opt OptCmd) // VendorHidden command will never be shown in help screen, even // if user was entering 'app --help -vvv'. // // NOTE -v is a builtin flag, -vvv means be triggered 3rd times. // // And the triggered times of a flag can be retrieved by // flag.GetTriggeredTimes(), or via cmdr Option Store API: // cmdr.GetFlagHitCount("verbose") / cmdr.GetVerboseHitCount(). VendorHidden(hidden bool) (opt OptCmd) // Deprecated gives a tip to users to encourage them to move // up to some new API/commands/operations. // // A tip is starting by 'Since v....' typically, for instance: // // Since v1.10.36, PlaceHolder is deprecated, use PlaceHolders // is recommended for more abilities. Deprecated(deprecation string) (opt OptCmd) // Action will be triggered after all command-line arguments parsed. // // Action might be the most important entry for a command. // // For a nest command system, parent command shouldn't get a // valid Action handler because we need to get a chance to // step into its children for parsing command-line. Action(action Handler) (opt OptCmd) // PreAction will be invoked before running Action // NOTE that RootCommand.PreAction will be invoked too. PreAction(pre Handler) (opt OptCmd) // PostAction will be invoked after run Action // NOTE that RootCommand.PostAction will be invoked too. PostAction(post Invoker) (opt OptCmd) // TailPlaceholder gives two places to place the placeholders. // It looks like the following form: // // austr dns add <placeholder-1st> [Options] [Parent/Global Options] <placeholders-more...> // // As shown, you may specify at: // // - before '[Options] [Parent/Global Options]' // - after '[Options] [Parent/Global Options]' // // In TailPlaceHolders slice, [0] is `placeholder-1st“, and others // are `placeholders-more`. // // Others: // TailArgsText string [no plan] // TailArgsDesc string [no plan] TailPlaceholder(placeholders ...string) (opt OptCmd) // Sets _ // // Reserved API. Sets(func(cmd OptCmd)) (opt OptCmd) // OwnerCommand returns the parent command in OptCmd form. // // It's available for building time. OwnerCommand() (opt OptCmd) // SetOwner just work for internal purpose SetOwner(opt OptCmd) RootCommand() *RootCommand RootCmdOpt() (root *RootCmdOpt) ToCommand() *Command // AddOptFlag _ // // Deprecated since v1.10.36 AddOptFlag(flag OptFlag) // AddFlag _ // // Deprecated since v1.10.36 AddFlag(flag *Flag) // AddOptCmd adds 'opt' OptCmd as a sub-command. // // Deprecated since v1.10.36 AddOptCmd(opt OptCmd) // AddCommand adds a *Command as a sub-command. // // Deprecated since v1.10.36 AddCommand(cmd *Command) // AttachTo attaches itself as a sub-command of 'opt' OptCmd object AttachTo(parentOpt OptCmd) (opt OptCmd) // AttachToCommand attaches itself as a sub-command of *Command object AttachToCommand(cmd *Command) (opt OptCmd) // AttachToRoot attaches itself as a sub-command of *RootCommand object AttachToRoot(root *RootCommand) (opt OptCmd) }
OptCmd to support fluent api of cmdr. see also: cmdr.Root().NewSubCommand()/.NewFlag()
func NewCmd ¶ added in v0.2.17
func NewCmd() (opt OptCmd)
NewCmd creates a wrapped Command object as OptCmd
func NewCmdFrom ¶ added in v0.2.17
NewCmdFrom creates a wrapped Command object as OptCmd, and make it as the current working item.
type OptFlag ¶ added in v0.2.15
type OptFlag interface { // Titles broken API since v1.6.39. // // If necessary, an ordered prefix can be attached to the long // title. The title with prefix will be set to Name field and // striped to Long field. // // An ordered prefix is a dotted string with multiple alphabets // and digits. Such as: // "zzzz.", "0001.", "700.", "A1." ... Titles(long, short string, aliases ...string) (opt OptFlag) // Short gives a short form sub-command title in string representation. // // A short command title is often one char, sometimes it can be // two chars, but even more is allowed. Short(short string) (opt OptFlag) // Long gives a long form flag title, we call it 'Full Title' too. // // A long title should be one or more words in english, separated // by short hypen ('-'), for example 'auto-increment'. // Long(long string) (opt OptFlag) // Name is an internal identity, and an order prefix is optional // // An ordered prefix is a dotted string with multiple alphabets // and digits. Such as: // "zzzz.", "0001.", "700.", "A1." ... Name(name string) (opt OptFlag) // Aliases give more choices for a command. Aliases(ss ...string) (opt OptFlag) // Description gives normal and long form description of a flag. // // Tiny html codes are supported, such as: // b/strong, i/cite, u, code/kbd, mark, del, font // These tags are parsed but ignored: // html, head, body Description(oneLineDesc string, longDesc ...string) (opt OptFlag) // Examples gives text to be shown in a section in the help screen. // // Tiny html codes are supported, such as: // b/strong, i/cite, u, code/kbd, mark, del, font // These tags are parsed but ignored: // html, head, body Examples(examples string) (opt OptFlag) // Group provides flag group name. // // All flags with same group name will be agreegated in // one group. // // An order prefix is a dotted string with multiple alphabet // and digit. Such as: // "zzzz.", "0001.", "700.", "A1." ... Group(group string) (opt OptFlag) // Hidden flag will not be shown in help screen, expect user // entered 'app --help -vvv'. // // NOTE -v is a builtin flag, -vvv means be triggered 3rd times. // // And the triggered times of a flag can be retrieved by // flag.GetTriggeredTimes(), or via cmdr Option Store API: // cmdr.GetFlagHitCount("verbose") / cmdr.GetVerboseHitCount(). Hidden(hidden bool) (opt OptFlag) // VendorHidden flag will never be shown in help screen, even // if user was entering 'app --help -vvv'. // // NOTE -v is a builtin flag, -vvv means be triggered 3rd times. // // And the triggered times of a flag can be retrieved by // flag.GetTriggeredTimes(), or via cmdr Option Store API: // cmdr.GetFlagHitCount("verbose") / cmdr.GetVerboseHitCount(). VendorHidden(hidden bool) (opt OptFlag) // Deprecated gives a tip to users to encourage them to move // up to some new API/commands/operations. // // A tip is starting by 'Since v....' typically, for instance: // // Since v1.10.36, PlaceHolder is deprecated, use PlaceHolders // is recommended for more abilities. Deprecated(deprecation string) (opt OptFlag) // Action will be triggered once being parsed ok Action(action Handler) (opt OptFlag) // ToggleGroup provides the RADIO BUTTON model for a set of // flags. // // The flags with same toggle group name will be agreegated // into one group. // // One of them are set will clear all of others flags in same // toggle group. // In programmtically, you may retrieve the final choice by its // name, see also toggle-group example (at our cmdr-examples repo). // // NOTE When the ToggleGroup specified, Group can be ignored. // // func tg(root cmdr.OptCmd) { // // toggle-group // // c := cmdr.NewSubCmd().Titles("toggle-group", "tg"). // Description("soundex test"). // Group("Test"). // TailPlaceholder("[text1, text2, ...]"). // Action(func(cmd *cmdr.Command, args []string) (err error) { // selectedMuxType := cmdr.GetStringR("toggle-group.mux-type") // fmt.Printf("Flag 'echo' = %v\n", cmdr.GetBoolR("toggle-group.echo")) // fmt.Printf("Flag 'gin' = %v\n", cmdr.GetBoolR("toggle-group.gin")) // fmt.Printf("Flag 'gorilla' = %v\n", cmdr.GetBoolR("toggle-group.gorilla")) // fmt.Printf("Flag 'iris' = %v\n", cmdr.GetBoolR("toggle-group.iris")) // fmt.Printf("Flag 'std' = %v\n", cmdr.GetBoolR("toggle-group.std")) // fmt.Printf("Toggle Group 'mux-type' = %v\n", selectedMuxType) // return // }). // AttachTo(root) // // cmdr.NewBool(false).Titles("echo", "echo").Description("using 'echo' mux").ToggleGroup("mux-type").Group("Mux").AttachTo(c) // cmdr.NewBool(false).Titles("gin", "gin").Description("using 'gin' mux").ToggleGroup("mux-type").Group("Mux").AttachTo(c) // cmdr.NewBool(false).Titles("gorilla", "gorilla").Description("using 'gorilla' mux").ToggleGroup("mux-type").Group("Mux").AttachTo(c) // cmdr.NewBool(true).Titles("iris", "iris").Description("using 'iris' mux").ToggleGroup("mux-type").Group("Mux").AttachTo(c) // cmdr.NewBool(false).Titles("std", "std").Description("using standardlib http mux mux").ToggleGroup("mux-type").Group("Mux").AttachTo(c) // } // ToggleGroup(group string) (opt OptFlag) // DefaultValue needs an exact typed 'val'. // // IMPORTANT: cmdr interprets value-type of an option based // on the underlying default value set. DefaultValue(val interface{}, placeholder string) (opt OptFlag) // Placeholder _ // Deprecated since v1.10.40 Placeholder(placeholder string) (opt OptFlag) // CompletionActionStr for zsh completion CompletionActionStr(s string) (opt OptFlag) // CompletionMutualExclusiveFlags is a slice of flag full/long titles CompletionMutualExclusiveFlags(flags ...string) (opt OptFlag) // CompletionPrerequisitesFlags is a slice of flag full/long titles CompletionPrerequisitesFlags(flags ...string) (opt OptFlag) // CompletionJustOnce for zsh completion CompletionJustOnce(once bool) (opt OptFlag) // CompletionCircuitBreak for zsh completion CompletionCircuitBreak(once bool) (opt OptFlag) // DoubleTildeOnly requests only the form is okay when the // double tilde chars ('~~') leads the flag. // // So, short form (-f) and long form (--flag) will be interpreted as // unknown flag found. DoubleTildeOnly(once bool) (opt OptFlag) // ExternalTool provides a OS-environment variable name, // which identify the position of an external tool. // When cmdr parsed command-line ok, the external tool // will be invoked at first. // // For example: // // 'git commit -m' will wake up EDITOR to edit a commit message. // ExternalTool(envKeyName string) (opt OptFlag) // ValidArgs gives a constrained list for input value of // a flag. // // ValidArgs provides ENUM type on command-line. ValidArgs(list ...string) (opt OptFlag) // HeadLike enables `head -n` mode. // // 'min', 'max' will be ignored at this version, its might be // impl in the future. // // There's only one head-like flag in one command and its parent // and children commands. HeadLike(enable bool, min, max int64) (opt OptFlag) // EnvKeys is a list of env-var names of binding on this flag. EnvKeys(keys ...string) (opt OptFlag) // Required flag is MUST BE supplied by user entering from // command-line. // // NOTE Required() sets the required flag to true while // it was been invoking with empty params. Required(required ...bool) (opt OptFlag) // OwnerCommand returns the parent command in OptCmd form. // // It's available for building time. OwnerCommand() (opt OptCmd) // SetOwner just work for internal purpose SetOwner(opt OptCmd) RootCommand() *RootCommand ToFlag() *Flag // AttachTo attaches itself as a flag of `opt` OptCmd object AttachTo(parent OptCmd) (opt OptFlag) // AttachToCommand attaches itself as a flag of *Command object AttachToCommand(cmd *Command) (opt OptFlag) // AttachToRoot attaches itself as a flag of *RootCommand object AttachToRoot(root *RootCommand) (opt OptFlag) OnSet }
OptFlag to support fluent api of cmdr. see also: cmdr.Root().NewSubCommand()/.NewFlag()
For an option, its default value must be declared with exact type as is
func NewAny ¶ added in v1.10.49
NewAny creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewBool ¶ added in v0.2.17
NewBool creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewComplex128 ¶ added in v1.6.21
func NewComplex128(defaultValue ...complex128) (opt OptFlag)
NewComplex128 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewComplex64 ¶ added in v1.6.21
NewComplex64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewDuration ¶ added in v0.2.17
NewDuration creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewDurationFrom ¶ added in v1.0.3
NewDurationFrom creates a wrapped OptFlag, and append it into the current working item.
func NewFloat32 ¶ added in v1.0.1
NewFloat32 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewFloat64 ¶ added in v1.0.1
NewFloat64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewInt ¶ added in v0.2.17
NewInt creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewInt64 ¶ added in v0.2.17
NewInt64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewIntSlice ¶ added in v0.2.17
NewIntSlice creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
Sample:
cmdr.NewIntSlice(1, 2, 3).Titles("int-slice", "is").Group(""). AttachTo(parentCmdOpt)
func NewString ¶ added in v0.2.17
NewString creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewStringSlice ¶ added in v0.2.17
NewStringSlice creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
Sample:
cmdr.NewStringSlice("quick", "fox", "jumps").Titles("int-slice", "is").Group(""). AttachTo(parentCmdOpt)
func NewTextVar ¶ added in v1.10.49
NewTextVar creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewUint ¶ added in v0.2.17
NewUint creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewUint64 ¶ added in v0.2.17
NewUint64 creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
func NewUintSlice ¶ added in v1.6.47
NewUintSlice creates a wrapped OptFlag, you can connect it to a OptCmd via OptFlag.AttachXXX later.
Sample:
cmdr.NewUintSlice(1, 2, 3).Titles("uint-slice", "us").Group(""). AttachTo(parentCmdOpt)
type OptFlagType ¶ added in v0.2.15
type OptFlagType int
OptFlagType to support fluent api of cmdr. see also: OptCmd.NewFlag(OptFlagType)
Usage
root := cmdr.Root() co := root.NewSubCommand() co.NewFlag(cmdr.OptFlagTypeUint)
See also those short-hand constructors: Bool(), Int(), ....
const ( // OptFlagTypeBool to create a new bool flag OptFlagTypeBool OptFlagType = iota // OptFlagTypeInt to create a new int flag OptFlagTypeInt OptFlagType = iota + 1 // OptFlagTypeUint to create a new uint flag OptFlagTypeUint OptFlagType = iota + 2 // OptFlagTypeInt64 to create a new int64 flag OptFlagTypeInt64 OptFlagType = iota + 3 // OptFlagTypeUint64 to create a new uint64 flag OptFlagTypeUint64 OptFlagType = iota + 4 // OptFlagTypeFloat32 to create a new int float32 flag OptFlagTypeFloat32 OptFlagType = iota + 8 // OptFlagTypeFloat64 to create a new int float64 flag OptFlagTypeFloat64 OptFlagType = iota + 9 // OptFlagTypeComplex64 to create a new int complex64 flag OptFlagTypeComplex64 OptFlagType = iota + 10 // OptFlagTypeComplex128 to create a new int complex128 flag OptFlagTypeComplex128 OptFlagType = iota + 11 // OptFlagTypeString to create a new string flag OptFlagTypeString OptFlagType = iota + 12 // OptFlagTypeStringSlice to create a new string slice flag OptFlagTypeStringSlice OptFlagType = iota + 13 // OptFlagTypeIntSlice to create a new int slice flag OptFlagTypeIntSlice OptFlagType = iota + 14 // OptFlagTypeInt64Slice to create a new int slice flag OptFlagTypeInt64Slice OptFlagType = iota + 15 // OptFlagTypeUint64Slice to create a new int slice flag OptFlagTypeUint64Slice OptFlagType = iota + 16 // OptFlagTypeDuration to create a new duration flag OptFlagTypeDuration OptFlagType = iota + 17 // OptFlagTypeHumanReadableSize to create a new human readable size flag OptFlagTypeHumanReadableSize OptFlagType = iota + 18 )
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options is a holder of all options
func CurrentOptions ¶ added in v1.10.19
func CurrentOptions() *Options
CurrentOptions returns the global options instance (rxxtOptions), i.e. cmdr Options Store
func (*Options) CheckpointSize ¶ added in v1.10.0
CheckpointSize returns how many snapshots made see also SaveCheckpoint
func (*Options) ClearCheckpoints ¶ added in v1.10.0
func (s *Options) ClearCheckpoints()
ClearCheckpoints removes all checkpoints from snapshot history see also SaveCheckpoint
func (*Options) DumpAsString ¶
DumpAsString for debugging.
func (*Options) Flush ¶ added in v1.7.37
func (s *Options) Flush()
Flush writes all changes back to the alternative config file
func (*Options) FromKibiBytes ¶ added in v1.7.27
FromKibiBytes convert string to the uint64 value based kibibyte format.
kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes
See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func (*Options) FromKilobytes ¶ added in v1.6.19
FromKilobytes convert string to the uint64 value based kilobyte format.
kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes
See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func (*Options) Get ¶
Get an `Option` by key string, eg: ```golang cmdr.Get("app.logger.level") => 'DEBUG',... ```
func (*Options) GetComplex128 ¶ added in v1.6.21
func (s *Options) GetComplex128(key string, defaultVal ...complex128) (ir complex128)
GetComplex128 returns the complex128 value of an `Option` key.
func (*Options) GetComplex64 ¶ added in v1.6.21
GetComplex64 returns the complex64 value of an `Option` key.
func (*Options) GetDuration ¶ added in v0.2.11
GetDuration returns the time duration value of an `Option` key.
func (*Options) GetFloat32Ex ¶ added in v1.6.3
GetFloat32Ex returns the float32 value of an `Option` key.
func (*Options) GetFloat64Ex ¶ added in v1.6.3
GetFloat64Ex returns the float64 value of an `Option` key.
func (*Options) GetHierarchyList ¶ added in v0.2.17
GetHierarchyList returns the hierarchy data for dumping
func (*Options) GetInt64Ex ¶ added in v1.6.3
GetInt64Ex returns the int64 value of an `Option` key.
func (*Options) GetInt64Slice ¶ added in v1.5.5
GetInt64Slice returns the string slice value of an `Option` key.
func (*Options) GetIntSlice ¶ added in v0.2.11
GetIntSlice returns the string slice value of an `Option` key.
func (*Options) GetKibibytesEx ¶ added in v1.6.19
GetKibibytesEx returns the uint64 value of an `Option` key based kibibyte format.
kibibyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kibibyte is based 1024. That means: 1 KiB = 1k = 1024 bytes
See also: https://en.wikipedia.org/wiki/Kibibyte Its related word is kilobyte, refer to: https://en.wikipedia.org/wiki/Kilobyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func (*Options) GetKilobytesEx ¶ added in v1.6.19
GetKilobytesEx returns the uint64 value of an `Option` key with kilobyte format.
kilobyte format is for human readable. In this format, number presentations are: 2k, 8m, 3g, 5t, 6p, 7e. optional 'b' can be appended, such as: 2kb, 5tb, 7EB. All of them is case-insensitive.
kilobyte is based 1000. That means: 1 KB = 1k = 1000 bytes
See also: https://en.wikipedia.org/wiki/Kilobyte Its related word is kibibyte, refer to: https://en.wikipedia.org/wiki/Kibibyte
The pure number part can be golang presentation, such as 0x99, 0001b, 0700.
func (*Options) GetMap ¶ added in v1.0.0
GetMap an `Option` by key string, it returns a hierarchy map or nil
func (*Options) GetStringNoExpand ¶ added in v1.6.7
GetStringNoExpand returns the string value of an `Option` key.
func (*Options) GetStringSlice ¶
GetStringSlice returns the string slice value of an `Option` key.
func (*Options) GetTextVar ¶ added in v1.10.49
GetTextVar returns the time duration value of an `Option` key.
func (*Options) GetUint64Ex ¶ added in v1.6.3
GetUint64Ex returns the uint64 value of an `Option` key.
func (*Options) GetUint64Slice ¶ added in v1.5.5
GetUint64Slice returns the string slice value of an `Option` key.
func (*Options) LoadConfigFile ¶
func (s *Options) LoadConfigFile(file string, cft configFileType) (mainFile, subDir string, err error)
LoadConfigFile loads a yaml config file and merge the settings into `rxxtOptions` and load files in the `conf.d` child directory too.
func (*Options) Reset ¶
func (s *Options) Reset()
Reset the exists `Options`, so that you could follow a `LoadConfigFile()` with it.
func (*Options) RestoreCheckpoint ¶ added in v1.10.0
RestoreCheckpoint restore 1 or n checkpoint(s) from snapshots history. see also SaveCheckpoint
func (*Options) SaveCheckpoint ¶ added in v1.10.0
SaveCheckpoint make a snapshot of the current Option Store
You may ResetOptions after SaveCheckpoint:
func x(aMap map[string]interface{}){ defer cmdr.RestoreCheckpoint() cmdr.SaveCheckpoint() cmdr.ResetOptions() cmdr.MergeWith(map[string]interface{}{ "app": map[string]interface{}{ conf.AppName: map[string]interface{}{ "a-map": aMap, } } } cmdr.SaveAsYaml("a-setting.yml") }
func (*Options) Set ¶
Set sets the value of an `Option` key. The key MUST not have an `app` prefix.
For example: ```golang cmdr.Set("debug", true) cmdr.GetBool("app.debug") => true ```
Set runs in slice appending mode: for a slice, Set(key, newSlice) will append newSlice into original slice.
func (*Options) SetNx ¶
SetNx likes Set but without prefix auto-wrapped. `rxxtPrefix` is a string slice to define the prefix string array, default is ["app"]. So, cmdr.SetNx("debug", true) will put a real entry with (`debug`, true).
func (*Options) SetNxOverwrite ¶ added in v1.10.19
SetNxOverwrite likes SetOverwrite but without prefix auto-wrapped. It replaces the old value on a slice, instead of the default append mode.
func (*Options) SetOverwrite ¶ added in v1.10.19
SetOverwrite sets the value of an `Option` key. The key MUST not have an `app` prefix. It replaces the old value on a slice, instead of the default append mode.
SetOverwrite(key, newSlice) will replace the original value with newSlice.
func (*Options) SetRaw ¶ added in v1.9.4
SetRaw but without prefix auto-wrapped. So, cmdr.SetRaw("debug", true) will put a real entry with (`debug`, true).
func (*Options) SetRawOverwrite ¶ added in v1.10.49
SetRawOverwrite likes SetOverwrite but without prefix auto-wrapped. It replaces the old value on a slice, instead of the default append mode.
type Painter ¶ added in v0.2.9
type Painter interface { Printf(fmtStr string, args ...interface{}) Print(fmtStr string, args ...interface{}) FpPrintHeader(command *Command) FpPrintHelpTailLine(command *Command) FpUsagesTitle(command *Command, title string) FpUsagesLine(command *Command, fmt, appName, cmdList, cmdsTitle, tailPlaceHolder string) FpDescTitle(command *Command, title string) FpDescLine(command *Command) FpExamplesTitle(command *Command, title string) FpExamplesLine(command *Command) FpCommandsTitle(command *Command) FpCommandsGroupTitle(group string) FpCommandsLine(command *Command) (bufL, bufR bytes.Buffer) FpFlagsTitle(command *Command, flag *Flag, title string) FpFlagsGroupTitle(group string, isToggleGroup bool) FpFlagsLine(command *Command, flag *Flag, maxShort int, defValStr string) (bufL, bufR bytes.Buffer) Flush() Results() []byte // Reset does clear any internal states and reset itself Reset() }
Painter to support the genManual, genMarkdown, printHelpScreen.
type RootCmdOpt ¶ added in v0.2.15
type RootCmdOpt struct {
// contains filtered or unexported fields
}
RootCmdOpt for fluent api
func Root ¶ added in v0.2.15
func Root(appName, version string) (opt *RootCmdOpt)
Root for fluent api, to create a new *RootCmdOpt object.
func RootFrom ¶ added in v1.0.3
func RootFrom(root *RootCommand) (opt *RootCmdOpt)
RootFrom for fluent api, to create the new *RootCmdOpt object from an existed RootCommand
func (*RootCmdOpt) AddCommand ¶ added in v1.6.7
func (s *RootCmdOpt) AddCommand(cmd *Command)
func (*RootCmdOpt) AddGlobalPostAction ¶ added in v1.7.0
func (s *RootCmdOpt) AddGlobalPostAction(post Invoker) *RootCmdOpt
AddGlobalPostAction attaches your post handler to the global Post-Actions list
func (*RootCmdOpt) AddGlobalPreAction ¶ added in v1.7.0
func (s *RootCmdOpt) AddGlobalPreAction(pre Handler) *RootCmdOpt
AddGlobalPreAction attaches your pre handler to the global Pre-Actions list
func (*RootCmdOpt) AddOptFlag ¶ added in v1.6.7
func (s *RootCmdOpt) AddOptFlag(flag OptFlag)
func (*RootCmdOpt) AppendPostActions ¶ added in v1.7.46
func (s *RootCmdOpt) AppendPostActions(fns ...func(cmd *Command, args []string))
AppendPostActions adds the global post-action to cmdr system
func (*RootCmdOpt) AppendPreActions ¶ added in v1.7.46
func (s *RootCmdOpt) AppendPreActions(fns ...func(cmd *Command, args []string) (err error))
AppendPreActions adds the global pre-action to cmdr system
func (*RootCmdOpt) AttachToCommand ¶ added in v1.6.7
func (*RootCmdOpt) AttachToRoot ¶ added in v1.6.7
func (s *RootCmdOpt) AttachToRoot(root *RootCommand) (opt OptCmd)
func (*RootCmdOpt) Complex128 ¶ added in v1.6.21
func (s *RootCmdOpt) Complex128() (opt OptFlag)
func (*RootCmdOpt) Copyright ¶ added in v0.2.15
func (s *RootCmdOpt) Copyright(copyright, author string) *RootCmdOpt
Copyright for fluent api
func (*RootCmdOpt) Deprecated ¶ added in v0.2.15
func (*RootCmdOpt) Description ¶ added in v0.2.15
func (*RootCmdOpt) Header ¶ added in v0.2.15
func (s *RootCmdOpt) Header(header string) *RootCmdOpt
Header for fluent api
func (*RootCmdOpt) NewFlag ¶ added in v0.2.15
func (s *RootCmdOpt) NewFlag(typ OptFlagType) (opt OptFlag)
func (*RootCmdOpt) OwnerCommand ¶ added in v0.2.15
func (s *RootCmdOpt) OwnerCommand() (opt OptCmd)
func (*RootCmdOpt) PostAction ¶ added in v0.2.15
func (*RootCmdOpt) RootCmdOpt ¶ added in v1.7.46
func (s *RootCmdOpt) RootCmdOpt() (root *RootCmdOpt)
func (*RootCmdOpt) RootCommand ¶ added in v0.2.15
func (s *RootCmdOpt) RootCommand() (root *RootCommand)
func (*RootCmdOpt) RunAsSubCommand ¶ added in v1.10.19
func (s *RootCmdOpt) RunAsSubCommand(dottedPathToSubCommand string) *RootCmdOpt
RunAsSubCommand set RootCommand.RunAsSubCommand field. NOTE that when it's valid, RootCommand.Command.Action handler will be ignored.
func (*RootCmdOpt) StringSlice ¶ added in v0.2.15
func (s *RootCmdOpt) StringSlice() (opt OptFlag)
func (*RootCmdOpt) TailPlaceholder ¶ added in v0.2.15
func (*RootCmdOpt) VendorHidden ¶ added in v1.10.19
type RootCommand ¶
type RootCommand struct { Command `yaml:",inline"` AppName string `yaml:"appname,omitempty" json:"appname,omitempty"` Version string `yaml:"version,omitempty" json:"version,omitempty"` VersionInt uint32 `yaml:"version-int,omitempty" json:"version-int,omitempty"` Copyright string `yaml:"copyright,omitempty" json:"copyright,omitempty"` Author string `yaml:"author,omitempty" json:"author,omitempty"` Header string `yaml:"header,omitempty" json:"header,omitempty"` // using `Header` for header and ignore built with `Copyright` and `Author`, and no usage lines too. // RunAsSubCommand give a subcommand and will be invoked // while app enter without any subcommands. // // For example, RunAsSubCommand is set to "build", and // entering "app" will equal to entering "app build ...". // // NOTE that when it's valid, RootCommand.Command.Action handler will be ignored. RunAsSubCommand string `yaml:"run-as,omitempty" json:"run-as,omitempty"` // PreActions lists all global pre-actions. They will be launched before // any command hit would has been invoking. PreActions []Handler `yaml:"-" json:"-"` PostActions []Invoker `yaml:"-" json:"-"` // contains filtered or unexported fields }
RootCommand holds some application information
func (*RootCommand) AppendPostActions ¶ added in v1.6.22
func (c *RootCommand) AppendPostActions(fns ...func(cmd *Command, args []string))
AppendPostActions adds the global post-action to cmdr system
func (*RootCommand) AppendPreActions ¶ added in v1.7.46
func (c *RootCommand) AppendPreActions(fns ...func(cmd *Command, args []string) (err error))
AppendPreActions adds the global pre-action to cmdr system
type TextVar ¶ added in v1.10.49
type TextVar interface { encoding.TextMarshaler encoding.TextUnmarshaler }
TextVar _
func GetTextVar ¶ added in v1.10.49
GetTextVar returns the text-var value of an `Option` key.
func GetTextVarP ¶ added in v1.10.49
GetTextVarP returns the text-var value of an `Option` key.
func GetTextVarR ¶ added in v1.10.49
GetTextVarR returns the text-var value of an `Option` key.
func GetTextVarRP ¶ added in v1.10.49
GetTextVarRP returns the text-var value of an `Option` key.
A 'text-var' is a type which implements these interfaces:
encoding.TextMarshaler and encoding.TextUnmarshaler
The types typically are: net.IPv4, or time.Time.
type UnhandledErrorHandler ¶ added in v1.6.13
type UnhandledErrorHandler func(err interface{})
UnhandledErrorHandler for WithUnhandledErrorHandler
Source Files ¶
- base_opt.go
- build_xref.go
- command.go
- def.go
- def_errors.go
- doc.go
- exec.go
- exec_match.go
- exec_unknown.go
- exec_withopts.go
- exec_worker.go
- find.go
- flag.go
- fs_wrap.go
- gensh.go
- gensh_bash.go
- gensh_fish.go
- gensh_powershell.go
- gensh_query.go
- gensh_zsh.go
- handlers.go
- logex.go
- logex.lvl.go
- opt.go
- opt_command_impl.go
- opt_flag_impl.go
- opt_ops.go
- options.go
- options_cvt.go
- options_go1.18.go
- options_go1.19_and_any_ver.go
- options_impl.go
- options_watch.go
- predefined_locations.go
- print.go
- print_colors.go
- print_painter.go
- print_painter_help.go
- print_painter_man.go
- print_painter_mkd.go
- print_tree.go
- ptpkg.go
- replaceall_go1.12.go
- sbom.go
- sc_wrap.go
- types.go
- walk.go
Directories ¶
Path | Synopsis |
---|---|
Package conf are used to store the app-level constants (app name/vaersion) for cmdr and your app.
|
Package conf are used to store the app-level constants (app name/vaersion) for cmdr and your app. |
examples
|
|
Package flag is used to wrap some APIs from go stdlib flag
|
Package flag is used to wrap some APIs from go stdlib flag |
plugin
|
|
pprof
Package pprof provides the profiling command-line options and adapts to go tool pprof.
|
Package pprof provides the profiling command-line options and adapts to go tool pprof. |