Documentation ¶
Index ¶
- Constants
- Variables
- func DottedPathToCommandOrFlag(dottedPath string, anyCmd *Command) (cc *Command, ff *Flag)
- func EraseAnyWSs(s string) string
- type App
- type BaseOpt
- func (c *BaseOpt) App() App
- func (c *BaseOpt) AppVersion() string
- func (c *BaseOpt) Deprecated() string
- func (c *BaseOpt) DeprecatedHelpString(trans func(ss string, clr color.Color) string, clr, clrDefault color.Color) (hs, plain string)
- func (c *BaseOpt) Desc() string
- func (c *BaseOpt) DescLong() string
- func (c *BaseOpt) Examples() string
- func (c *BaseOpt) GetCommandTitles() string
- func (c *BaseOpt) GetDescZsh() (desc string)
- func (c *BaseOpt) GetDottedPath() string
- func (c *BaseOpt) GetDottedPathFull() string
- func (c *BaseOpt) GetHitStr() string
- func (c *BaseOpt) GetLongTitleNamesArray() []string
- func (c *BaseOpt) GetName() string
- func (c *BaseOpt) GetShortTitleNamesArray() []string
- func (c *BaseOpt) GetTitleName() string
- func (c *BaseOpt) GetTitleNames() string
- func (c *BaseOpt) GetTitleNamesArray() []string
- func (c *BaseOpt) GetTitleNamesArrayMainly() []string
- func (c *BaseOpt) GetTitleNamesBy(delimiter string) string
- func (c *BaseOpt) GetTitleZshNames() string
- func (c *BaseOpt) GetTitleZshNamesBy(delimiter string) (str string)
- func (c *BaseOpt) GetTriggeredTimes() int
- func (c *BaseOpt) GroupHelpTitle() string
- func (c *BaseOpt) GroupTitle() string
- func (c *BaseOpt) HasParent() bool
- func (c *BaseOpt) Hidden() bool
- func (c *BaseOpt) Name() string
- func (c *BaseOpt) Owner() *Command
- func (c *BaseOpt) Root() *RootCommand
- func (c *BaseOpt) SafeGroup() string
- func (c *BaseOpt) Set() store.Store
- func (c *BaseOpt) SetDeprecated(deprecated string)
- func (c *BaseOpt) SetDescription(description string, longDescription ...string)
- func (c *BaseOpt) SetExamples(examples ...string)
- func (c *BaseOpt) SetGroup(group string)
- func (c *BaseOpt) SetHidden(hidden bool, vendorHidden ...bool)
- func (c *BaseOpt) SetName(name string)
- func (c *BaseOpt) SetShorts(shorts ...string)
- func (c *BaseOpt) Shorts() (shorts []string)
- func (c *BaseOpt) String() string
- func (c *BaseOpt) Title() string
- func (c *BaseOpt) VendorHidden() bool
- type CmdSlice
- type Command
- func (c *Command) AddFlag(child *Flag, callbacks ...func(ff *Flag))
- func (c *Command) AddSubCommand(child *Command, callbacks ...func(cc *Command))
- func (c *Command) AppendTailPlaceHolder(placeHolder ...string)
- func (c *Command) CanInvoke() bool
- func (c *Command) CountOfCommands() int
- func (c *Command) CountOfFlags() int
- func (c *Command) EnsureTree(app App, root *RootCommand)
- func (c *Command) EnsureXref(cb ...func(cc *Command, index, level int))
- func (c *Command) EqualTo(rh *Command) (ok bool)
- func (c *Command) FindFlag(longName string, wide bool) (res *Flag)
- func (c *Command) FindFlagBackwards(longName string) (res *Flag)
- func (c *Command) FindFlagRecursive(longName string, wide bool) (res *Flag)
- func (c *Command) FindSubCommand(longName string, wide bool) (res *Command)
- func (c *Command) FindSubCommandRecursive(longName string, wide bool) (res *Command)
- func (c *Command) Flags() []*Flag
- func (c *Command) ForeachFlags(cb func(f *Flag) (stop bool)) (stop bool)
- func (c *Command) ForeachGroupedFlags(cb func(group string, items []*Flag))
- func (c *Command) ForeachGroupedSubCommands(cb func(group string, items []*Command))
- func (c *Command) ForeachSubCommands(cb func(cc *Command) (stop bool)) (stop bool)
- func (c *Command) GetExpandableNames() string
- func (c *Command) GetExpandableNamesArray() []string
- func (c *Command) GetGroupedCommands(group string) (commands []*Command)
- func (c *Command) GetGroupedFlags(group string) (flags []*Flag)
- func (c *Command) GetQuotedGroupName() string
- func (c *Command) HasFlag(longTitle string) (f *Flag, ok bool)
- func (c *Command) HasOnAction() bool
- func (c *Command) Invoke(args []string) (err error)
- func (c *Command) IsRoot() bool
- func (c *Command) Match(title string) (short bool, cc *Command)
- func (c *Command) MatchFlag(vp *FlagValuePkg) (ff *Flag, err error)
- func (c *Command) MatchTitleNameFast(title string) (ok bool)
- func (c *Command) RedirectTo() (dottedPath string)
- func (c *Command) RunPreActions(cmd *Command, args []string) (deferAction func(errInvoked error), err error)
- func (c *Command) SelfAssert(root *RootCommand)
- func (c *Command) SetAction(fn OnInvokeHandler)
- func (c *Command) SetInvokeProc(str string)
- func (c *Command) SetInvokeShell(str string)
- func (c *Command) SetOnMatched(functions ...OnCommandMatchedHandler)
- func (c *Command) SetPostActions(functions ...OnPostInvokeHandler)
- func (c *Command) SetPreActions(functions ...OnPreInvokeHandler)
- func (c *Command) SetPresetCmdLines(args ...string)
- func (c *Command) SetRedirectTo(dottedPath string)
- func (c *Command) SetShell(str string)
- func (c *Command) SetTailPlaceHolder(placeHolders ...string)
- func (c *Command) String() string
- func (c *Command) SubCommands() []*Command
- func (c *Command) TailPlaceHolder() string
- func (c *Command) TryOnMatched(position int, hitState *MatchState) (handled bool, err error)
- func (c *Command) Walk(cb WalkCB)
- func (c *Command) WalkBackwards(cb WalkBackwardsCB)
- func (c *Command) WalkEverything(cb WalkEverythingCB)
- func (c *Command) WalkGrouped(cb WalkGroupedCB)
- type CommandBuilder
- type Config
- type Flag
- func (f *Flag) ActionStr() string
- func (f *Flag) AppendEnvVars(vars ...string)
- func (f *Flag) AppendValidArgs(validArgs ...string)
- func (f *Flag) CircuitBreak() bool
- func (f *Flag) DefaultValue() any
- func (f *Flag) DefaultValueHelpString(trans transFunc, clr, clrDefault color.Color) (hs, plain string)
- func (f *Flag) Delete()
- func (f *Flag) DoubleTildeOnly() bool
- func (f *Flag) EnvVars() []string
- func (f *Flag) EqualTo(rh *Flag) (ok bool)
- func (f *Flag) ExternalEditor() string
- func (f *Flag) GetDescZsh() (desc string)
- func (f *Flag) GetDottedNamePath() string
- func (f *Flag) GetTitleFlagNames() string
- func (f *Flag) GetTitleFlagNamesBy(delimiter string) string
- func (f *Flag) GetTitleFlagNamesByMax(delimiter 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(delimiter string, allowPrefix, quoted bool) (str string)
- func (f *Flag) GetTitleZshNamesExtBy(delimiter string, allowPrefix, quoted, shortTitleOnly, longTitleOnly bool) (str string)
- func (f *Flag) GetTriggeredTimes() int
- func (f *Flag) HeadLike() bool
- func (f *Flag) IsToggleGroup() bool
- func (f *Flag) JustOnce() bool
- func (f *Flag) MatchedTG() (tgm *ToggleGroupMatch)
- func (f *Flag) MutualExclusives() []string
- func (f *Flag) NeedParseValue() bool
- func (f *Flag) PlaceHolder() string
- func (f *Flag) Prerequisites() []string
- func (f *Flag) Range() (min, max int)
- func (f *Flag) Required() bool
- func (f *Flag) SetActionStr(action string)
- func (f *Flag) SetCircuitBreak(cb bool)
- func (f *Flag) SetDefaultValue(val any)
- func (f *Flag) SetDoubleTildeOnly(b bool)
- func (f *Flag) SetEnvVars(vars ...string)
- func (f *Flag) SetExternalEditor(externalEditor string)
- func (f *Flag) SetHeadLike(headLike bool)
- func (f *Flag) SetJustOnce(justOnce bool)
- func (f *Flag) SetMutualExclusives(ex ...string)
- func (f *Flag) SetOnChangedHandler(handler OnChangedHandler)
- func (f *Flag) SetOnChangingHandler(handler OnChangingHandler)
- func (f *Flag) SetOnMatchedHandler(handler OnMatchedHandler)
- func (f *Flag) SetOnParseValueHandler(handler OnParseValueHandler)
- func (f *Flag) SetOnSetHandler(handler OnSetHandler)
- func (f *Flag) SetPlaceHolder(placeHolder string)
- func (f *Flag) SetPrerequisites(flags ...string)
- func (f *Flag) SetRange(min, max int)
- func (f *Flag) SetRequired(required bool)
- func (f *Flag) SetToggleGroup(group string)
- func (f *Flag) SetValidArgs(validArgs ...string)
- func (f *Flag) String() string
- func (f *Flag) ToggleGroup() string
- func (f *Flag) ToggleGroupLeadHelpString() (lead string)
- func (f *Flag) TryOnChanged(oldVal, newVal any)
- func (f *Flag) TryOnChanging(oldVal, newVal any) (handled bool, err error)
- func (f *Flag) TryOnMatched(position int, hitState *MatchState) (handled bool, err error)
- func (f *Flag) TryOnParseValue(index int, hitCaption, hitValue string, args []string) (handled bool, newVal any, remainsPartInHitValue string, err error)
- func (f *Flag) TryOnSet(oldVal, newVal any)
- func (f *Flag) ValidArgs() []string
- type FlagBuilder
- type FlagValuePkg
- type FlgSlice
- type HelpWriter
- type Loader
- type MatchState
- type OnChangedHandler
- type OnChangingHandler
- type OnCommandMatchedHandler
- type OnInvokeHandler
- type OnMatchedHandler
- type OnParseValueHandler
- type OnPostInvokeHandler
- type OnPreInvokeHandler
- type OnSetHandler
- type Opt
- func WithArgs(args ...string) Opt
- func WithDebugScreenWriter(w HelpWriter) Opt
- func WithExternalLoaders(loaders ...Loader) Opt
- func WithForceDefaultAction(b bool) Opt
- func WithHelpScreenWriter(w HelpWriter) Opt
- func WithStore(op store.Store) Opt
- func WithTasksBeforeParse(tasks ...Task) Opt
- func WithTasksBeforeRun(tasks ...Task) Opt
- func WithUnmatchedAsError(b bool) Opt
- type RootCommand
- func (c *RootCommand) AppDescription() string
- func (c *RootCommand) AppLongDescription() string
- func (c *RootCommand) AppendPostActions(functions ...OnPostInvokeHandler)
- func (c *RootCommand) AppendPreActions(functions ...OnPreInvokeHandler)
- func (c *RootCommand) Attach(newRootCommand *Command)
- func (c *RootCommand) Footer() string
- func (c *RootCommand) Header() string
- func (c *RootCommand) SelfAssert()
- type Runner
- type Task
- type ToggleGroupMatch
- type WalkBackwardsCB
- type WalkCB
- type WalkEverythingCB
- type WalkGroupedCB
Constants ¶
const ( // UnsortedGroup for commands and flags UnsortedGroup = "!!!!.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" )
Variables ¶
var ( ErrMissedPrerequisite = errors.New("Flag %q needs %q was set at first") // flag need a prerequisite flag exists. ErrFlagJustOnce = errors.New("Flag %q MUST BE set once only") // flag cannot be set more than one time. )
var ( ErrShouldFallback = errors.New("fallback") // cmdr should fall back to the default internal impl, such as defaultAction, .... ErrShouldStop = errors.New("stop") // cmdr should end the parsing loop ASAP, instead old ErrShouldBeStopException. ErrEmptyRootCommand = errors.New("the RootCommand hasn't been built") // obs ErrCommandsNotReady = errors.New("the RootCommand hasn't been built, or InitGlobally() failed. Has builder.App.Build() called? ") // obs )
Functions ¶
func DottedPathToCommandOrFlag ¶
DottedPathToCommandOrFlag searches the matched Command or Flag with the specified dotted-path. The searching will start from root if anyCmd is nil.
func EraseAnyWSs ¶
EraseAnyWSs eats any whitespaces inside the giving string s.
Types ¶
type App ¶
type App interface { NewCommandBuilder(longTitle string, titles ...string) CommandBuilder // starts a closure to build a new sub-command and its children NewFlagBuilder(longTitle string, titles ...string) FlagBuilder // starts a closure to build a flag // Cmd is a shortcut to NewCommandBuilder and starts a stream building for a new sub-command Cmd(longTitle string, titles ...string) CommandBuilder // Flg is a shortcut to NewFlagBuilder and starts a stream building for a new flag Flg(longTitle string, titles ...string) FlagBuilder // AddCmd starts a closure to build a new sub-command and its children. // After the closure invoked, Build() will be called implicitly. AddCmd(func(b CommandBuilder)) App // AddFlg starts a closure to build a flag // After the closure invoked, Build() will be called implicitly. AddFlg(cb func(b FlagBuilder)) App // NewCmdFrom creates a CommandBuilder from 'from' Command. NewCmdFrom(from *Command, cb func(b CommandBuilder)) App // NewFlgFrom creates a CommandBuilder from 'from' Command. NewFlgFrom(from *Command, defaultValue any, cb func(b FlagBuilder)) App Runner Info(name, version string, desc ...string) App // setup basic information about this app Copyright(copy string) App // setup copyright declaration about this app Author(author string) App // setup author or team information Header(headerLine string) App // setup header line(s) instead of copyright+author fields WithRootCommand(root *RootCommand) App // setup root command RootCommand() *RootCommand // get root command Name() string // this app name Version() string // this app version Args() []string // command-line args }
type BaseOpt ¶
type BaseOpt struct { // Long is a full/long form flag/command title name. // word string. example for flag: "addr" -> "--addr" Long string // Short 'rune' string. short option/command name. // single char. example for flag: "a" -> "-a" Short string // Aliases are the more synonyms Aliases []string // contains filtered or unexported fields }
func (*BaseOpt) AppVersion ¶
func (*BaseOpt) Deprecated ¶
func (*BaseOpt) DeprecatedHelpString ¶
func (*BaseOpt) GetCommandTitles ¶
func (*BaseOpt) GetDottedPath ¶
GetDottedPath 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 OptionPrefixes in this key path. For more information about Option Prefix, refer to [WithOptionsPrefix]
func (*BaseOpt) GetDottedPathFull ¶
func (*BaseOpt) GetLongTitleNamesArray ¶
GetLongTitleNamesArray returns long name and aliases as an array
func (*BaseOpt) GetShortTitleNamesArray ¶
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 ¶
GetTitleNamesArrayMainly returns short,full names
func (*BaseOpt) GetTitleNamesBy ¶
GetTitleNamesBy returns the joint string of short,full,aliases names
func (*BaseOpt) GetTitleZshNames ¶
GetTitleZshNames temp
func (*BaseOpt) GetTitleZshNamesBy ¶
GetTitleZshNamesBy temp
func (*BaseOpt) GetTriggeredTimes ¶
GetTriggeredTimes returns the matched times
func (*BaseOpt) GroupHelpTitle ¶
GroupHelpTitle returns the group title or empty string if it's UnsortedGroup.
This func is used for printing help screen.
func (*BaseOpt) GroupTitle ¶
GroupTitle returns the group title without leading ordered pieces.
func (*BaseOpt) Name ¶
Name returns the identity string of this command/flag, long title or name only
func (*BaseOpt) Root ¶
func (c *BaseOpt) Root() *RootCommand
func (*BaseOpt) SetDeprecated ¶
func (*BaseOpt) SetDescription ¶
func (*BaseOpt) SetExamples ¶
func (*BaseOpt) VendorHidden ¶
type Command ¶
type Command struct { BaseOpt // contains filtered or unexported fields }
func (*Command) AddSubCommand ¶
func (*Command) AppendTailPlaceHolder ¶
func (*Command) CountOfCommands ¶
func (*Command) CountOfFlags ¶
func (*Command) EnsureTree ¶
func (c *Command) EnsureTree(app App, root *RootCommand)
EnsureTree associates owner and app between all subCommands and app/runner/rootCommand. EnsureTree links all commands as a tree (make root and owner linked).
func (*Command) EnsureXref ¶
EnsureXref builds the internal indexes and maps.
Called by worker.Worker in preparing time (preProcess).
ForeachSubCommands, ForeachFlags, ForeachGroupedSubCommands, and ForeachGroupedFlags needs EnsureXref called.
func (*Command) FindFlagBackwards ¶
func (*Command) FindFlagRecursive ¶
FindFlagRecursive find flag with `longName` from `cmd` recursively
func (*Command) FindSubCommand ¶
FindSubCommand find sub-command with `longName` from `cmd`.
If wide is true, FindSubCommand try to match long, short and aliases titles, If wide is false, only long title matched.
func (*Command) FindSubCommandRecursive ¶
FindSubCommandRecursive find sub-command with `longName` from `cmd` recursively
func (*Command) ForeachFlags ¶
ForeachFlags is another way to WalkEverything on all flags.
func (*Command) ForeachGroupedFlags ¶
ForeachGroupedFlags loops for all grouped flags.
This function works proper except EnsureXref called. EnsureXref will link the whole command tree and build all internal indexes and maps.
func (*Command) ForeachGroupedSubCommands ¶
ForeachGroupedSubCommands loops for all grouped commands.
This function works proper except EnsureXref called. EnsureXref will link the whole command tree and build all internal indexes and maps.
func (*Command) ForeachSubCommands ¶
ForeachSubCommands is another way to Walk on all commands.
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) GetGroupedCommands ¶
func (*Command) GetGroupedFlags ¶
func (*Command) GetQuotedGroupName ¶
GetQuotedGroupName returns the group name quoted string.
func (*Command) HasOnAction ¶
func (*Command) MatchFlag ¶
func (c *Command) MatchFlag(vp *FlagValuePkg) (ff *Flag, err error)
MatchFlag try matching command title with vp.Remains, and update the relevant states.
While a flag matched ok, returns vp.Matched != "" && ff != nil && err != nil
func (*Command) MatchTitleNameFast ¶
MatchTitleNameFast matches a given title string without indices built.
func (*Command) RedirectTo ¶
RedirectTo provides the real command target for current Command.
Suppose command [app build] is being redirected to [app gcc build]. There [app build] is a shortcut to its full commands [app gcc build].
func (*Command) RunPreActions ¶
func (*Command) SelfAssert ¶
func (c *Command) SelfAssert(root *RootCommand)
func (*Command) SetAction ¶
func (c *Command) SetAction(fn OnInvokeHandler)
SetAction adds the onInvoke action to a command
func (*Command) SetInvokeProc ¶
func (*Command) SetInvokeShell ¶
func (*Command) SetOnMatched ¶
func (c *Command) SetOnMatched(functions ...OnCommandMatchedHandler)
SetOnMatched adds the onMatched handler to a command
func (*Command) SetPostActions ¶
func (c *Command) SetPostActions(functions ...OnPostInvokeHandler)
SetPostActions adds the post-action to a command
func (*Command) SetPreActions ¶
func (c *Command) SetPreActions(functions ...OnPreInvokeHandler)
SetPreActions adds the pre-action to a command
func (*Command) SetPresetCmdLines ¶
func (*Command) SetRedirectTo ¶
func (*Command) SetTailPlaceHolder ¶
func (*Command) SubCommands ¶
func (*Command) TailPlaceHolder ¶
TailPlaceHolder is a string at end of usage line in help screen.
In help screen, a command's usage line generally has the following form:
<app-name> <sub-commands> [<options>] [<positional-args>...]
The text of <positional-args> is exact TailPlaceHolder. Set TailPlaceHolder to "files..." might be meaningful for "load" command, looks like:
<app> yaml-formatter load [<options>] files...
func (*Command) TryOnMatched ¶
func (c *Command) TryOnMatched(position int, hitState *MatchState) (handled bool, err error)
func (*Command) WalkBackwards ¶
func (c *Command) WalkBackwards(cb WalkBackwardsCB)
WalkBackwards is a simple way to loop for all commands.
func (*Command) WalkEverything ¶
func (c *Command) WalkEverything(cb WalkEverythingCB)
WalkEverything loops for all commands and its flags.
func (*Command) WalkGrouped ¶
func (c *Command) WalkGrouped(cb WalkGroupedCB)
WalkGrouped loops for all commands and its flags with grouped order.
type CommandBuilder ¶
type CommandBuilder interface { // Build connects the built command into the building command system. Build() // Titles should be specified with this form: // // longTitle, shortTitle, aliases... // // The Long-Title is must-required, and the others are optional. // // For Flag, Long-Title and Aliases are posix long parameters with the // leading double hyphen string '--'. And Short-Title has single // hyphen '-' as leading. // // For example, A flag with longTitle "debug" means that an end-user // should type "--debug" for it. // // For the multi-level command and subcommands, long, short and // aliases will be used as is. Titles(longTitle string, titles ...string) CommandBuilder // Description specifies the one-line description and a multi-line // description (optional) Description(description string, longDescription ...string) CommandBuilder // Examples can be a multi-line string. Examples(examples string) CommandBuilder // 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(group string) CommandBuilder // 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(deprecated string) CommandBuilder // Hidden command/flag won't be shown in help-screen and others output. // // The Hidden command/flag may be printed normally if very verbose mode // specified (typically '-vv' detected). // // The VendorHidden commands/flags will be hidden at any time even if // in vert verbose mode. Hidden(hidden bool, vendorHidden ...bool) CommandBuilder // ExtraShorts sets more short titles ExtraShorts(shorts ...string) CommandBuilder // 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(placeHolders ...string) CommandBuilder // RedirectTo gives the dotted-path to point to a subcommand. // // Thd target subcommand will be invoked while this command is being invoked. // // For example, if RootCommand.RedirectTo is set to "build", and // entering "app" will equal to entering "app build ...". // // NOTE: // // when redirectTo is valid, Command.OnInvoke handler will be ignored. RedirectTo(dottedPath string) CommandBuilder // OnAction is the main action or entry point when the command // was hit from parsing command-line arguments. OnAction(handler OnInvokeHandler) CommandBuilder // OnPreAction will be launched before running OnInvoke. // The return value obj.ErrShouldStop will cause the remained // following processing flow broken right away. OnPreAction(handlers ...OnPreInvokeHandler) CommandBuilder // OnPostAction will be launched after running OnInvoke. OnPostAction(handlers ...OnPostInvokeHandler) CommandBuilder // OnMatched _. OnMatched(handler OnCommandMatchedHandler) CommandBuilder // PresetCmdLines provides a set of args so that end-user can // type the command-line bypass its. PresetCmdLines(args ...string) CommandBuilder // InvokeProc specifies an executable path which will be launched // on this command hit and being invoked InvokeProc(executablePath string) CommandBuilder // InvokeShell specifies a shell command-line which will be launched // on this command hit and being invoked. // // NOTE the command-line string will be launched under the specified // shell environment, if it's defined by UseShell(). InvokeShell(commandLine string) CommandBuilder // UseShell specifies a shell environment. // // It should be a valid path to a shell, such as '/bin/bash', // '/bin/zsh', and so on. UseShell(shellPath string) CommandBuilder NewCommandBuilder(longTitle string, titles ...string) CommandBuilder // starts a closure to build a new sub-command and its children NewFlagBuilder(longTitle string, titles ...string) FlagBuilder // starts a closure to build a flag // Cmd is a shortcut to NewCommandBuilder and starts a stream building for a new sub-command Cmd(longTitle string, titles ...string) CommandBuilder // Flg is a shortcut to NewFlagBuilder and starts a stream building for a new flag Flg(longTitle string, titles ...string) FlagBuilder // AddCmd starts a closure to build a new sub-command and its children. // After the closure invoked, Build() will be called implicitly. AddCmd(func(b CommandBuilder)) CommandBuilder // AddFlg starts a closure to build a flag // After the closure invoked, Build() will be called implicitly. AddFlg(cb func(b FlagBuilder)) CommandBuilder }
type Config ¶
type Config struct { store.Store ForceDefaultAction bool UnmatchedAsError bool TasksBeforeParse []Task TasksBeforeRun []Task Loaders []Loader HelpScreenWriter HelpWriter DebugScreenWriter HelpWriter Args []string // for testing }
func DefaultConfig ¶
func DefaultConfig() *Config
type Flag ¶
type Flag struct { BaseOpt // contains filtered or unexported fields }
func (*Flag) AppendEnvVars ¶
func (*Flag) AppendValidArgs ¶
func (*Flag) CircuitBreak ¶
func (*Flag) DefaultValue ¶
func (*Flag) DefaultValueHelpString ¶
func (*Flag) DoubleTildeOnly ¶
func (*Flag) ExternalEditor ¶
func (*Flag) GetDottedNamePath ¶
GetDottedNamePath return the dotted key path of this flag in the options store.
func (*Flag) GetTitleFlagNamesBy ¶
GetTitleFlagNamesBy temp
func (*Flag) GetTitleFlagNamesByMax ¶
GetTitleFlagNamesByMax temp
func (*Flag) GetTitleZshFlagName ¶
GetTitleZshFlagName temp
func (*Flag) GetTitleZshFlagNamesArray ¶
GetTitleZshFlagNamesArray temp
func (*Flag) GetTitleZshFlagShortName ¶
GetTitleZshFlagShortName temp
func (*Flag) GetTitleZshNamesBy ¶
GetTitleZshNamesBy temp
func (*Flag) GetTitleZshNamesExtBy ¶
func (f *Flag) GetTitleZshNamesExtBy(delimiter string, allowPrefix, quoted, shortTitleOnly, longTitleOnly bool) (str string)
GetTitleZshNamesExtBy temp
func (*Flag) GetTriggeredTimes ¶
GetTriggeredTimes returns the matched times
func (*Flag) IsToggleGroup ¶
func (*Flag) MatchedTG ¶
func (f *Flag) MatchedTG() (tgm *ToggleGroupMatch)
func (*Flag) MutualExclusives ¶
func (*Flag) NeedParseValue ¶
func (*Flag) PlaceHolder ¶
func (*Flag) Prerequisites ¶
func (*Flag) SetActionStr ¶
func (*Flag) SetCircuitBreak ¶
func (*Flag) SetDefaultValue ¶
func (*Flag) SetDoubleTildeOnly ¶
func (*Flag) SetEnvVars ¶
func (*Flag) SetExternalEditor ¶
func (*Flag) SetHeadLike ¶
func (*Flag) SetJustOnce ¶
func (*Flag) SetMutualExclusives ¶
func (*Flag) SetOnChangedHandler ¶
func (f *Flag) SetOnChangedHandler(handler OnChangedHandler)
func (*Flag) SetOnChangingHandler ¶
func (f *Flag) SetOnChangingHandler(handler OnChangingHandler)
func (*Flag) SetOnMatchedHandler ¶
func (f *Flag) SetOnMatchedHandler(handler OnMatchedHandler)
func (*Flag) SetOnParseValueHandler ¶
func (f *Flag) SetOnParseValueHandler(handler OnParseValueHandler)
func (*Flag) SetOnSetHandler ¶
func (f *Flag) SetOnSetHandler(handler OnSetHandler)
func (*Flag) SetPlaceHolder ¶
func (*Flag) SetPrerequisites ¶
func (*Flag) SetRequired ¶
func (*Flag) SetToggleGroup ¶
func (*Flag) SetValidArgs ¶
func (*Flag) ToggleGroup ¶
func (*Flag) ToggleGroupLeadHelpString ¶
func (*Flag) TryOnChanged ¶
func (*Flag) TryOnChanging ¶
func (*Flag) TryOnMatched ¶
func (f *Flag) TryOnMatched(position int, hitState *MatchState) (handled bool, err error)
func (*Flag) TryOnParseValue ¶
type FlagBuilder ¶
type FlagBuilder interface { // Build connects the built command into the building command system. Build() // Titles should be specified with this form: // // longTitle, shortTitle, aliases... // // The Long-Title is must-required, and the others are optional. // // For Flag, Long-Title and Aliases are posix long parameters with the // leading double hyphen string '--'. And Short-Title has single // hyphen '-' as leading. // // For example, A flag with longTitle "debug" means that an end-user // should type "--debug" for it. // // For the multi-level command and subcommands, long, short and // aliases will be used as is. Titles(longTitle string, titles ...string) FlagBuilder // Default is a synonym to DefaultValue Default(defaultValue any) FlagBuilder // ExtraShorts sets more short titles ExtraShorts(shorts ...string) FlagBuilder // Description specifies the one-line description and a multi-line // description (optional) Description(description string, longDescription ...string) FlagBuilder // Examples can be a multi-line string. Examples(examples string) FlagBuilder // 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(group string) FlagBuilder // 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(deprecated string) FlagBuilder // Hidden command/flag won't be shown in help-screen and others output. // // The Hidden command/flag may be printed normally if very verbose mode // specified (typically '-vv' detected). // // The VendorHidden commands/flags will be hidden at any time even if // in vert verbose mode. Hidden(hidden bool, vendorHidden ...bool) FlagBuilder ToggleGroup(group string) FlagBuilder PlaceHolder(placeHolder string) FlagBuilder // DefaultValue specifies a binding value to the flag with explicit // datatype. DefaultValue(val any) FlagBuilder // EnvVars binds the environment variable onto the flag EnvVars(vars ...string) FlagBuilder // AppendEnvVars binds the environment variable onto the flag AppendEnvVars(vars ...string) FlagBuilder // ExternalEditor is an env-var name to identify an external program // which will be used to collect user-input as a string value. // // The input string value will be bound to this value finally. ExternalEditor(externalEditor string) FlagBuilder // ValidArgs provides the selectable choice from a set of values. // // As end-user inputs not in the preset values, an error will be threw up. ValidArgs(validArgs ...string) FlagBuilder // AppendValidArgs provides the selectable choice from a set of values. // // As end-user inputs not in the preset values, an error will be threw up. AppendValidArgs(validArgs ...string) FlagBuilder // Range _ // not yet Range(min, max int) FlagBuilder // HeadLike identifies this flag is head-like. HeadLike(headLike bool, bounds ...int) FlagBuilder // Required identifies this flag is must-required. // // As end-user input missed, an error will be threw up. Required(required bool) FlagBuilder // CompJustOnce is used for zsh completion. CompJustOnce(justOnce bool) FlagBuilder // CompActionStr is for zsh completion, see action of an optspec in _argument CompActionStr(action string) FlagBuilder // CompMutualExclusives is used for zsh completion. // // For the ToggleGroup group, mutualExclusives is implicit. CompMutualExclusives(ex ...string) FlagBuilder // CompPrerequisites flags for this one. // // In zsh completion, any of prerequisites flags must be present // so that user can complete this one. // // The prerequisites were not present and cmdr would report error // and stop parsing flow. CompPrerequisites(flags ...string) FlagBuilder // CompCircuitBreak is used for zsh completion. // // A flag can break cmdr parsing flow with return // ErrShouldBeStopException in its Action handler. // But you' better told zsh system with set circuitBreak // to true. At this case, cmdr will generate a suitable // completion script. CompCircuitBreak(cb bool) FlagBuilder // DoubleTildeOnly can be used for zsh completion. // // A DoubleTildeOnly Flag accepts '~~opt' only, so '--opt' is // invalid form and couldn't be used for other Flag // anymore. DoubleTildeOnly(b bool) FlagBuilder // OnParseValue allows user-defined value parsing, converting and validating. OnParseValue(handler OnParseValueHandler) FlagBuilder // OnMatched handler will be called when this flag matched. // // OnMatched handler is a cancellable notifier (a validator) // before a formal on-changed notification, // // OnMatched will be called after a flag matched and its value // extracted but not saved. // // = OnValidating // // You can capture it and validate the user input for this flag. // // If you're looking for a best hook point where the old value is // changing to new value, using OnChanging handler. // // The calling order in parsing command-line: // // OnParseValue (cancel ->) // OnMatched (cancel ->) // OnChanging (cancel ->) // OnChanged // // The calling order in parsing other sources (config file, ...): // // OnParseValue (cancel ->) // OnMatched (cancel ->) // OnChanging (cancel ->) // OnChanged // // The calling order if store.Set(dottedPath, value) calling: // // OnParseValue (cancel ->) // OnSet // OnMatched(handler OnMatchedHandler) FlagBuilder OnChanging(handler OnChangingHandler) FlagBuilder // OnChanged handler will be called when this flag is being // modified generally (programmatically, cmdline parsing, cfg file, ...) OnChanged(handler OnChangedHandler) FlagBuilder // OnSet handler will be called when this flag is being modified // programmatically. OnSet(handler OnSetHandler) FlagBuilder }
type FlagValuePkg ¶
type FlagValuePkg struct { Args []string AteArgs int SpecialTilde bool Short bool Matched string Remains string PartialMatched bool Flags []*Flag // matched flags, reserved. ValueOK bool Value any }
func NewFVP ¶
func NewFVP(args []string, remains string, short, plusSign, dblTilde bool) (vp *FlagValuePkg)
NewFVP gets a new FlagValuePkg done. A FlagValuePkg is a internal structure for tracing the flag's matching and parsing.
func (*FlagValuePkg) Reset ¶
func (s *FlagValuePkg) Reset()
type HelpWriter ¶
type HelpWriter interface { io.Writer io.StringWriter }
type MatchState ¶
type OnChangedHandler ¶
type OnChangingHandler ¶
OnChangingHandler handles when a flag is been setting by parsing command-line args, loading from external sources and other cases.
You can cancel the parsing before received a formal OnChanged event, for its validation.
type OnCommandMatchedHandler ¶
type OnCommandMatchedHandler func(c *Command, position int, hitState *MatchState) (err error)
type OnInvokeHandler ¶
type OnMatchedHandler ¶
type OnMatchedHandler func(f *Flag, position int, hitState *MatchState) (err error)
type OnParseValueHandler ¶
type OnParseValueHandler func( f *Flag, position int, hitCaption string, hitValue string, moreArgs []string, ) ( newVal any, remainPartInHitValue string, err error, )
OnParseValueHandler could be used for parsing value string as you want, and/or check the validation of the input value or flag, and so on.
return err == obj.ErrShouldFallback: let cmdr fallback to the default implementation; return err == obj.ErrShouldStop: let cmdr stop parsing action.
type OnPostInvokeHandler ¶
type OnPreInvokeHandler ¶
type OnSetHandler ¶
type Opt ¶
type Opt func(s *Config)
func WithDebugScreenWriter ¶
func WithDebugScreenWriter(w HelpWriter) Opt
func WithExternalLoaders ¶
func WithForceDefaultAction ¶
func WithHelpScreenWriter ¶
func WithHelpScreenWriter(w HelpWriter) Opt
func WithTasksBeforeParse ¶
func WithTasksBeforeRun ¶
func WithUnmatchedAsError ¶
type RootCommand ¶
type RootCommand struct { AppName string Version string // AppDescription string // AppLongDesc string Copyright string Author string HeaderLine string *Command // contains filtered or unexported fields }
func (*RootCommand) AppDescription ¶
func (c *RootCommand) AppDescription() string
func (*RootCommand) AppLongDescription ¶
func (c *RootCommand) AppLongDescription() string
func (*RootCommand) AppendPostActions ¶
func (c *RootCommand) AppendPostActions(functions ...OnPostInvokeHandler)
AppendPostActions adds the global post-action to cmdr system
func (*RootCommand) AppendPreActions ¶
func (c *RootCommand) AppendPreActions(functions ...OnPreInvokeHandler)
AppendPreActions adds the global pre-action to cmdr system
func (*RootCommand) Attach ¶
func (c *RootCommand) Attach(newRootCommand *Command)
Attach attaches new root command on it
func (*RootCommand) Footer ¶
func (c *RootCommand) Footer() string
func (*RootCommand) Header ¶
func (c *RootCommand) Header() string
func (*RootCommand) SelfAssert ¶
func (c *RootCommand) SelfAssert()
type Runner ¶
type Runner interface { // InitGlobally initialize all prerequisites, block itself until all // of them done and Ready signal changed. Some resources can be exceptions // if not required. InitGlobally() Ready() bool // the Runner is built and ready for Run? Run(opts ...Opt) (err error) // Run enter the main entry DumpErrors(wr io.Writer) // prints the errors Error() errors.Error // return the collected errors in parsing args and invoke actions Store() store.Store // app settings store, config set Name() string // app name Version() string // app version Root() *RootCommand // root command // Actions return a state map. // The states can be: // - show-version // - show-built-info // - show-help // - show-help-man // - show-tree // - show-debug // These states are produced by parsing the builtin flags // with user's command line arguments. // For examples, `~~tree` causes 'show-tree' state ON, // `--help` causes 'show-help' state ON. Actions() (ret map[string]bool) }
type ToggleGroupMatch ¶
type ToggleGroupMatch struct { Flags map[string]*Flag // key: flg.Long Matched *Flag MatchedTitle string }
func (*ToggleGroupMatch) MatchedFlag ¶
func (s *ToggleGroupMatch) MatchedFlag() *Flag