cli

package
v2.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: Apache-2.0 Imports: 22 Imported by: 4

Documentation

Index

Constants

View Source
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

View Source
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.
)
View Source
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

func DottedPathToCommandOrFlag(dottedPath string, anyCmd *Command) (cc *Command, ff *Flag)

DottedPathToCommandOrFlag searches the matched Command or Flag with the specified dotted-path. The searching will start from root if anyCmd is nil.

func EraseAnyWSs

func EraseAnyWSs(s string) string

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
	Footer(footerLine string) App                  // setup footer line(s)

	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) App

func (c *BaseOpt) App() App

func (*BaseOpt) AppVersion

func (c *BaseOpt) AppVersion() string

func (*BaseOpt) Deprecated

func (c *BaseOpt) Deprecated() string

func (*BaseOpt) DeprecatedHelpString

func (c *BaseOpt) DeprecatedHelpString(trans func(ss string, clr color.Color) string, clr, clrDefault color.Color) (hs, plain string)

func (*BaseOpt) Desc

func (c *BaseOpt) Desc() string

func (*BaseOpt) DescLong

func (c *BaseOpt) DescLong() string

func (*BaseOpt) Examples

func (c *BaseOpt) Examples() string

func (*BaseOpt) GetCommandTitles

func (c *BaseOpt) GetCommandTitles() string

func (*BaseOpt) GetDescZsh

func (c *BaseOpt) GetDescZsh() (desc string)

GetDescZsh temp

func (*BaseOpt) GetDottedPath

func (c *BaseOpt) GetDottedPath() string

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 (c *BaseOpt) GetDottedPathFull() string

func (*BaseOpt) GetHitStr

func (c *BaseOpt) GetHitStr() string

GetHitStr returns the matched command string

func (*BaseOpt) GetLongTitleNamesArray

func (c *BaseOpt) GetLongTitleNamesArray() []string

GetLongTitleNamesArray returns long name and aliases as an array

func (*BaseOpt) GetName

func (c *BaseOpt) GetName() string

GetName returns the name of a `Command`.

func (*BaseOpt) GetShortTitleNamesArray

func (c *BaseOpt) GetShortTitleNamesArray() []string

GetShortTitleNamesArray returns short name as an array

func (*BaseOpt) GetTitleName

func (c *BaseOpt) GetTitleName() string

GetTitleName returns name/full/short string

func (*BaseOpt) GetTitleNames

func (c *BaseOpt) GetTitleNames() string

GetTitleNames return the joint string of short,full,aliases names

func (*BaseOpt) GetTitleNamesArray

func (c *BaseOpt) GetTitleNamesArray() []string

GetTitleNamesArray returns short,full,aliases names

func (*BaseOpt) GetTitleNamesArrayMainly

func (c *BaseOpt) GetTitleNamesArrayMainly() []string

GetTitleNamesArrayMainly returns short,full names

func (*BaseOpt) GetTitleNamesBy

func (c *BaseOpt) GetTitleNamesBy(delimiter string) string

GetTitleNamesBy returns the joint string of short,full,aliases names

func (*BaseOpt) GetTitleZshNames

func (c *BaseOpt) GetTitleZshNames() string

GetTitleZshNames temp

func (*BaseOpt) GetTitleZshNamesBy

func (c *BaseOpt) GetTitleZshNamesBy(delimiter string) (str string)

GetTitleZshNamesBy temp

func (*BaseOpt) GetTriggeredTimes

func (c *BaseOpt) GetTriggeredTimes() int

GetTriggeredTimes returns the matched times

func (*BaseOpt) GroupHelpTitle

func (c *BaseOpt) GroupHelpTitle() string

GroupHelpTitle returns the group title or empty string if it's UnsortedGroup.

This func is used for printing help screen.

func (*BaseOpt) GroupTitle

func (c *BaseOpt) GroupTitle() string

GroupTitle returns the group title without leading ordered pieces.

func (*BaseOpt) HasParent

func (c *BaseOpt) HasParent() bool

HasParent detects whether owner is available or not

func (*BaseOpt) Hidden

func (c *BaseOpt) Hidden() bool

func (*BaseOpt) Name

func (c *BaseOpt) Name() string

Name returns the identity string of this command/flag, long title or name only

func (*BaseOpt) Owner

func (c *BaseOpt) Owner() *Command

func (*BaseOpt) Root

func (c *BaseOpt) Root() *RootCommand

func (*BaseOpt) SafeGroup

func (c *BaseOpt) SafeGroup() string

func (*BaseOpt) Set

func (c *BaseOpt) Set() store.Store

func (*BaseOpt) SetDeprecated

func (c *BaseOpt) SetDeprecated(deprecated string)

func (*BaseOpt) SetDescription

func (c *BaseOpt) SetDescription(description string, longDescription ...string)

func (*BaseOpt) SetExamples

func (c *BaseOpt) SetExamples(examples ...string)

func (*BaseOpt) SetGroup

func (c *BaseOpt) SetGroup(group string)

func (*BaseOpt) SetHidden

func (c *BaseOpt) SetHidden(hidden bool, vendorHidden ...bool)

func (*BaseOpt) SetName

func (c *BaseOpt) SetName(name string)

func (*BaseOpt) SetShorts

func (c *BaseOpt) SetShorts(shorts ...string)

func (*BaseOpt) Shorts

func (c *BaseOpt) Shorts() (shorts []string)

func (*BaseOpt) String

func (c *BaseOpt) String() string

func (*BaseOpt) Title

func (c *BaseOpt) Title() string

func (*BaseOpt) VendorHidden

func (c *BaseOpt) VendorHidden() bool

type CmdSlice

type CmdSlice struct {
	A []*Command
}

type Command

type Command struct {
	BaseOpt
	// contains filtered or unexported fields
}

func (*Command) AddFlag

func (c *Command) AddFlag(child *Flag, callbacks ...func(ff *Flag))

func (*Command) AddSubCommand

func (c *Command) AddSubCommand(child *Command, callbacks ...func(cc *Command))

func (*Command) AppendTailPlaceHolder

func (c *Command) AppendTailPlaceHolder(placeHolder ...string)

func (*Command) CanInvoke

func (c *Command) CanInvoke() bool

func (*Command) CountOfCommands

func (c *Command) CountOfCommands() int

func (*Command) CountOfFlags

func (c *Command) CountOfFlags() int

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

func (c *Command) EnsureXref(cb ...func(cc *Command, index, level int))

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) EqualTo

func (c *Command) EqualTo(rh *Command) (ok bool)

EqualTo compares with another one based on its titles

func (*Command) FindFlag

func (c *Command) FindFlag(longName string, wide bool) (res *Flag)

FindFlag find flag with `longName` from `cmd`

func (*Command) FindFlagBackwards

func (c *Command) FindFlagBackwards(longName string) (res *Flag)

func (*Command) FindFlagRecursive

func (c *Command) FindFlagRecursive(longName string, wide bool) (res *Flag)

FindFlagRecursive find flag with `longName` from `cmd` recursively

func (*Command) FindSubCommand

func (c *Command) FindSubCommand(longName string, wide bool) (res *Command)

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

func (c *Command) FindSubCommandRecursive(longName string, wide bool) (res *Command)

FindSubCommandRecursive find sub-command with `longName` from `cmd` recursively

func (*Command) Flags

func (c *Command) Flags() []*Flag

func (*Command) ForeachFlags

func (c *Command) ForeachFlags(cb func(f *Flag) (stop bool)) (stop bool)

ForeachFlags is another way to WalkEverything on all flags.

func (*Command) ForeachGroupedFlags

func (c *Command) ForeachGroupedFlags(cb func(group string, items []*Flag))

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

func (c *Command) ForeachGroupedSubCommands(cb func(group string, items []*Command))

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

func (c *Command) ForeachSubCommands(cb func(cc *Command) (stop bool)) (stop bool)

ForeachSubCommands is another way to Walk on all commands.

func (*Command) GetExpandableNames

func (c *Command) GetExpandableNames() string

GetExpandableNames returns the names comma splitted string.

func (*Command) GetExpandableNamesArray

func (c *Command) GetExpandableNamesArray() []string

GetExpandableNamesArray returns the names array of command, includes short name and long name.

func (*Command) GetGroupedCommands

func (c *Command) GetGroupedCommands(group string) (commands []*Command)

func (*Command) GetGroupedFlags

func (c *Command) GetGroupedFlags(group string) (flags []*Flag)

func (*Command) GetQuotedGroupName

func (c *Command) GetQuotedGroupName() string

GetQuotedGroupName returns the group name quoted string.

func (*Command) HasFlag

func (c *Command) HasFlag(longTitle string) (f *Flag, ok bool)

func (*Command) HasOnAction

func (c *Command) HasOnAction() bool

func (*Command) Invoke

func (c *Command) Invoke(args []string) (err error)

func (*Command) IsRoot

func (c *Command) IsRoot() bool

func (*Command) Match

func (c *Command) Match(title string) (short bool, cc *Command)

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

func (c *Command) MatchTitleNameFast(title string) (ok bool)

MatchTitleNameFast matches a given title string without indices built.

func (*Command) RedirectTo

func (c *Command) RedirectTo() (dottedPath string)

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 (c *Command) RunPreActions(cmd *Command, args []string) (deferAction func(errInvoked error), err error)

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 (c *Command) SetInvokeProc(str string)

func (*Command) SetInvokeShell

func (c *Command) SetInvokeShell(str string)

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 (c *Command) SetPresetCmdLines(args ...string)

func (*Command) SetRedirectTo

func (c *Command) SetRedirectTo(dottedPath string)

func (*Command) SetShell

func (c *Command) SetShell(str string)

func (*Command) SetTailPlaceHolder

func (c *Command) SetTailPlaceHolder(placeHolders ...string)

func (*Command) String

func (c *Command) String() string

func (*Command) SubCommands

func (c *Command) SubCommands() []*Command

func (*Command) TailPlaceHolder

func (c *Command) TailPlaceHolder() string

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) Walk

func (c *Command) Walk(cb WalkCB)

Walk is a simple way to loop for all commands.

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

func NewConfig

func NewConfig(opts ...Opt) *Config

type Flag

type Flag struct {
	BaseOpt
	// contains filtered or unexported fields
}

func (*Flag) ActionStr

func (f *Flag) ActionStr() string

func (*Flag) AppendEnvVars

func (f *Flag) AppendEnvVars(vars ...string)

func (*Flag) AppendValidArgs

func (f *Flag) AppendValidArgs(validArgs ...string)

func (*Flag) CircuitBreak

func (f *Flag) CircuitBreak() bool

func (*Flag) DefaultValue

func (f *Flag) DefaultValue() any

func (*Flag) DefaultValueHelpString

func (f *Flag) DefaultValueHelpString(trans transFunc, clr, clrDefault color.Color) (hs, plain string)

func (*Flag) Delete

func (f *Flag) Delete()

Delete removes myself from the command owner.

func (*Flag) DoubleTildeOnly

func (f *Flag) DoubleTildeOnly() bool

func (*Flag) EnvVars

func (f *Flag) EnvVars() []string

func (*Flag) EqualTo

func (f *Flag) EqualTo(rh *Flag) (ok bool)

EqualTo _

func (*Flag) ExternalEditor

func (f *Flag) ExternalEditor() string

func (*Flag) GetDescZsh

func (f *Flag) GetDescZsh() (desc string)

GetDescZsh temp

func (*Flag) GetDottedNamePath

func (f *Flag) GetDottedNamePath() string

GetDottedNamePath return the dotted key path of this flag in the options store.

func (*Flag) GetTitleFlagNames

func (f *Flag) GetTitleFlagNames() string

GetTitleFlagNames temp

func (*Flag) GetTitleFlagNamesBy

func (f *Flag) GetTitleFlagNamesBy(delimiter string) string

GetTitleFlagNamesBy temp

func (*Flag) GetTitleFlagNamesByMax

func (f *Flag) GetTitleFlagNamesByMax(delimiter string, maxShort int) string

GetTitleFlagNamesByMax temp

func (*Flag) GetTitleZshFlagName

func (f *Flag) GetTitleZshFlagName() (str string)

GetTitleZshFlagName temp

func (*Flag) GetTitleZshFlagNamesArray

func (f *Flag) GetTitleZshFlagNamesArray() (ary []string)

GetTitleZshFlagNamesArray temp

func (*Flag) GetTitleZshFlagShortName

func (f *Flag) GetTitleZshFlagShortName() (str string)

GetTitleZshFlagShortName temp

func (*Flag) GetTitleZshNamesBy

func (f *Flag) GetTitleZshNamesBy(delimiter string, allowPrefix, quoted bool) (str string)

GetTitleZshNamesBy temp

func (*Flag) GetTitleZshNamesExtBy

func (f *Flag) GetTitleZshNamesExtBy(delimiter string, allowPrefix, quoted, shortTitleOnly, longTitleOnly bool) (str string)

GetTitleZshNamesExtBy temp

func (*Flag) GetTriggeredTimes

func (f *Flag) GetTriggeredTimes() int

GetTriggeredTimes returns the matched times

func (*Flag) HeadLike

func (f *Flag) HeadLike() bool

func (*Flag) IsToggleGroup

func (f *Flag) IsToggleGroup() bool

func (*Flag) JustOnce

func (f *Flag) JustOnce() bool

func (*Flag) MatchedTG

func (f *Flag) MatchedTG() (tgm *ToggleGroupMatch)

func (*Flag) MutualExclusives

func (f *Flag) MutualExclusives() []string

func (*Flag) NeedParseValue

func (f *Flag) NeedParseValue() bool

func (*Flag) PlaceHolder

func (f *Flag) PlaceHolder() string

func (*Flag) Prerequisites

func (f *Flag) Prerequisites() []string

func (*Flag) Range

func (f *Flag) Range() (min, max int)

func (*Flag) Required

func (f *Flag) Required() bool

func (*Flag) SetActionStr

func (f *Flag) SetActionStr(action string)

func (*Flag) SetCircuitBreak

func (f *Flag) SetCircuitBreak(cb bool)

func (*Flag) SetDefaultValue

func (f *Flag) SetDefaultValue(val any)

func (*Flag) SetDoubleTildeOnly

func (f *Flag) SetDoubleTildeOnly(b bool)

func (*Flag) SetEnvVars

func (f *Flag) SetEnvVars(vars ...string)

func (*Flag) SetExternalEditor

func (f *Flag) SetExternalEditor(externalEditor string)

func (*Flag) SetHeadLike

func (f *Flag) SetHeadLike(headLike bool)

func (*Flag) SetJustOnce

func (f *Flag) SetJustOnce(justOnce bool)

func (*Flag) SetMutualExclusives

func (f *Flag) SetMutualExclusives(ex ...string)

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 (f *Flag) SetPlaceHolder(placeHolder string)

func (*Flag) SetPrerequisites

func (f *Flag) SetPrerequisites(flags ...string)

func (*Flag) SetRange

func (f *Flag) SetRange(min, max int)

func (*Flag) SetRequired

func (f *Flag) SetRequired(required bool)

func (*Flag) SetToggleGroup

func (f *Flag) SetToggleGroup(group string)

func (*Flag) SetValidArgs

func (f *Flag) SetValidArgs(validArgs ...string)

func (*Flag) String

func (f *Flag) String() string

func (*Flag) ToggleGroup

func (f *Flag) ToggleGroup() string

func (*Flag) ToggleGroupLeadHelpString

func (f *Flag) ToggleGroupLeadHelpString() (lead string)

func (*Flag) TryOnChanged

func (f *Flag) TryOnChanged(oldVal, newVal any)

func (*Flag) TryOnChanging

func (f *Flag) TryOnChanging(oldVal, newVal any) (handled bool, err error)

func (*Flag) TryOnMatched

func (f *Flag) TryOnMatched(position int, hitState *MatchState) (handled bool, err error)

func (*Flag) TryOnParseValue

func (f *Flag) TryOnParseValue(index int, hitCaption, hitValue string, args []string) (
	handled bool, newVal any, remainsPartInHitValue string, err error,
)

func (*Flag) TryOnSet

func (f *Flag) TryOnSet(oldVal, newVal any)

func (*Flag) ValidArgs

func (f *Flag) ValidArgs() []string

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 FlgSlice

type FlgSlice struct {
	A []*Flag
}

type HelpWriter

type HelpWriter interface {
	io.Writer
	io.StringWriter
}

type Loader

type Loader interface {
	Load(app App) (err error)
}

type MatchState

type MatchState struct {
	Short, DblTilde bool
	HitStr          string
	HitTimes        int
	Value           any
}

type OnChangedHandler

type OnChangedHandler func(f *Flag, oldVal, newVal any)

type OnChangingHandler

type OnChangingHandler func(f *Flag, oldVal, newVal any) (err error)

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 OnInvokeHandler func(cmd *Command, args []string) (err error)

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 OnPostInvokeHandler func(cmd *Command, args []string, errInvoked error) (err error)

type OnPreInvokeHandler

type OnPreInvokeHandler func(cmd *Command, args []string) (err error)

type OnSetHandler

type OnSetHandler func(f *Flag, oldVal, newVal any)

type Opt

type Opt func(s *Config)

func WithArgs

func WithArgs(args ...string) Opt

func WithDebugScreenWriter

func WithDebugScreenWriter(w HelpWriter) Opt

func WithExternalLoaders

func WithExternalLoaders(loaders ...Loader) Opt

func WithForceDefaultAction

func WithForceDefaultAction(b bool) Opt

func WithHelpScreenWriter

func WithHelpScreenWriter(w HelpWriter) Opt

func WithStore

func WithStore(op store.Store) Opt

func WithTasksBeforeParse

func WithTasksBeforeParse(tasks ...Task) Opt

func WithTasksBeforeRun

func WithTasksBeforeRun(tasks ...Task) Opt

func WithUnmatchedAsError

func WithUnmatchedAsError(b bool) Opt

type RootCommand

type RootCommand struct {
	AppName string
	Version string
	// AppDescription string
	// AppLongDesc    string
	Copyright  string
	Author     string
	HeaderLine string
	FooterLine 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 Task

type Task func(root *RootCommand, runner Runner, extras ...any) (err error)

type ToggleGroupMatch

type ToggleGroupMatch struct {
	Flags        map[string]*Flag // key: flg.Long
	Matched      *Flag
	MatchedTitle string
}

func (*ToggleGroupMatch) MatchedFlag

func (s *ToggleGroupMatch) MatchedFlag() *Flag

type WalkBackwardsCB

type WalkBackwardsCB func(cc *Command, ff *Flag, index, count, level int)

type WalkCB

type WalkCB func(cc *Command, index, level int)

type WalkEverythingCB

type WalkEverythingCB func(cc, pp *Command, ff *Flag, cmdIndex, flgIndex, level int)

type WalkGroupedCB

type WalkGroupedCB func(cc, pp *Command, ff *Flag, group string, idx, level int)

Directories

Path Synopsis
Package atoa - converters for any to any
Package atoa - converters for any to any

Jump to

Keyboard shortcuts

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