Documentation
¶
Overview ¶
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2023 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Package cli is a framework for command line applications. joe-cli is designed to be easy to use and to extend. It features a declarative model for organizing the app and a robust middleware/hook system to customize the app with reusable logic.
This is the minimal, useful application:
func main() { app := &cli.App{ Name: "greet", Action: func(c *cli.Context) error { fmt.Println("Hello, world!") return nil }, } app.Run(os.Args) }
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Copyright 2025 The Joe-cli Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Index ¶
- Constants
- Variables
- func BigFloat() **big.Float
- func BigInt() **big.Int
- func Bool() *bool
- func Bytes() *[]byte
- func Do(c context.Context, action Action) error
- func Duration() *time.Duration
- func Float32() *float32
- func Float64() *float64
- func IP() *net.IP
- func Int() *int
- func Int16() *int16
- func Int32() *int32
- func Int64() *int64
- func Int8() *int8
- func Join(args []string) string
- func List() *[]string
- func Map() *map[string]string
- func NameValues(namevalue ...string) *[]*NameValue
- func NewBuffer() *buffer
- func Quote(v any) string
- func ReadPasswordString(in io.Reader) (string, error)
- func ReadString(in io.Reader) (string, error)
- func Regexp() **regexp.Regexp
- func Set(dest any, args ...string) error
- func SetCurrentApp(a *App)
- func SetData(dest any, arg any) error
- func Shell() string
- func Split(s string) ([]string, error)
- func SplitList(s, sep string, n int) []string
- func SplitMap(s string) map[string]string
- func String() *string
- func URL() **url.URL
- func Uint() *uint
- func Uint16() *uint16
- func Uint32() *uint32
- func Uint64() *uint64
- func Uint8() *uint8
- func Wrap(w io.Writer, text string, indent string, width int)
- type Action
- func Accessory[T any, A Action](name string, fn func(T) A, actionopt ...Action) Action
- func Accessory0(name string, actionopt ...Action) Action
- func ActionOf(item any) Action
- func AddAlias(a string) Action
- func AddArg(a *Arg) Action
- func AddArgs(args ...*Arg) Action
- func AddCommand(c *Command) Action
- func AddCommands(commands ...*Command) Action
- func AddFlag(f *Flag) Action
- func AddFlags(flags ...*Flag) Action
- func After(a Action) Action
- func Alias(a ...string) Action
- func ApplyShellCompletion() Action
- func ArgSetup(fn func(*Arg)) Action
- func Assert(filter ContextFilter, a Action) Action
- func At(t Timing, a Action) Action
- func AutodetectColor() Action
- func Before(a Action) Action
- func Bind[V any](bind func(V) error, valopt ...V) Action
- func BindContext[T, V any](value func(context.Context) *T, bind func(*T, V) error, valopt ...V) Action
- func BindIndirect[T, V any](name any, bind func(*T, V) error, valopt ...V) Action
- func Category(name string) Action
- func CommandSetup(fn func(*Command)) Action
- func ContextValue(key, value any) Action
- func Customize(pattern string, a Action) Action
- func Data(name string, value any) Action
- func Description(v any) Action
- func DisplayHelpScreen(command ...string) Action
- func Enum(options ...string) Action
- func ExecuteSubcommand(interceptErr func(*Context, error) (*Command, error)) Action
- func ExecuteTemplate(name string, data func(*Context) any) Action
- func FlagSetup(fn func(*Flag)) Action
- func Fprint(w io.Writer, a ...any) Action
- func Fprintf(w io.Writer, format string, a ...any) Action
- func Fprintln(w io.Writer, a ...any) Action
- func FromEnv(vars ...string) Action
- func FromFilePath(f fs.FS, filePath string) Action
- func HandleCommandNotFound(fn func(*Context, error) (*Command, error)) Action
- func HandleSignal(s ...os.Signal) Action
- func HelpText(s string) Action
- func Hook(timing Timing, handler Action) Action
- func HookAfter(pattern string, handler Action) Action
- func HookBefore(pattern string, handler Action) Action
- func IfMatch(f ContextFilter, a Action) Action
- func ImplicitCommand(name string) Action
- func ImplicitValue(fn func(*Context) (string, bool)) Action
- func Implicitly(a Action) Action
- func Implies(name, value string) Action
- func Initializer(a Action) Action
- func ManualText(s string) Action
- func Mutex(names ...string) Action
- func Named(name string) Action
- func OptionalValue(v any) Action
- func Print(a ...any) Action
- func PrintLicense() Action
- func PrintVersion() Action
- func Printf(format string, a ...any) Action
- func Println(a ...any) Action
- func ProvideValueInitializer(v any, name string, actionopt ...Action) Action
- func Recover(a Action) Action
- func RegisterTemplate(name string, template string) Action
- func RegisterTemplateFunc(name string, fn any) Action
- func RemoveAlias(a string) Action
- func RemoveArg(name any) Action
- func RemoveCommand(name any) Action
- func RemoveFlag(name any) Action
- func SetColor(enabled bool) Action
- func SetCompletion(c Completion) Action
- func SetContext(ctx context.Context) Action
- func SetValue(v any) Action
- func ShellCompleteIntegration(name string, s ShellComplete) Action
- func SuppressError(a Action) Action
- func Timeout(timeout time.Duration) Action
- func Transform(fn TransformFunc) Action
- func UsageText(s string) Action
- func ValueTransform(valueFn TransformFunc) Action
- type ActionFunc
- type ActionPipeline
- type App
- func (a *App) Arg(name any) (*Arg, bool)
- func (a *App) Command(name string) (*Command, bool)
- func (a *App) Flag(name string) (*Flag, bool)
- func (a *App) Initialize(c context.Context) (context.Context, error)
- func (a *App) Run(args []string)
- func (a *App) RunContext(c context.Context, args []string) error
- func (a *App) SetData(name string, v any)
- func (a *App) Use(action Action) *App
- type Arg
- func (a *Arg) LookupData(name string) (any, bool)
- func (a *Arg) Occurrences() int
- func (a *Arg) Seen() bool
- func (a *Arg) Set(v any) error
- func (a *Arg) SetData(name string, v any)
- func (a *Arg) SetHidden(v bool)
- func (a *Arg) SetOccurrence(values ...string) error
- func (a *Arg) SetOccurrenceData(v any) error
- func (a *Arg) SetRequired(v bool)
- func (a *Arg) Synopsis() string
- func (a *Arg) Use(action Action) *Arg
- type ArgCounter
- type Binding
- type BindingLookup
- type BindingMap
- type BindingState
- type Color
- type Command
- func (c *Command) Arg(name any) (*Arg, bool)
- func (c *Command) Command(name string) (*Command, bool)
- func (c *Command) Flag(name string) (*Flag, bool)
- func (c *Command) LookupData(name string) (any, bool)
- func (c *Command) Names() []string
- func (c *Command) SetData(name string, v any)
- func (c *Command) SetHidden(value bool)
- func (c *Command) Synopsis() string
- func (c *Command) Use(action Action) *Command
- func (c *Command) VisibleArgs() []*Arg
- func (c *Command) VisibleFlags() []*Flag
- func (c *Command) VisibleSubcommands() []*Command
- type Completion
- type CompletionFunc
- type CompletionItem
- type CompletionRequest
- type CompletionType
- type Context
- func (c *Context) Action(action Action) error
- func (c *Context) AddAlias(aliases ...string) error
- func (c *Context) AddArg(v *Arg) error
- func (c *Context) AddArgs(args ...*Arg) (err error)
- func (c *Context) AddCommand(v *Command) error
- func (c *Context) AddCommands(commands ...*Command) (err error)
- func (c *Context) AddFlag(f *Flag) error
- func (c *Context) AddFlags(flags ...*Flag) (err error)
- func (c *Context) After(action Action) error
- func (c *Context) Aliases() []string
- func (c *Context) App() *App
- func (c *Context) Arg() *Arg
- func (c *Context) Args() []string
- func (c *Context) At(t Timing, v Action) error
- func (c *Context) AutodetectColor()
- func (c *Context) Before(action Action) error
- func (c *Context) BigFloat(name any) *big.Float
- func (c *Context) BigInt(name any) *big.Int
- func (c *Context) BindingLookup() BindingLookup
- func (c *Context) Bool(name any) bool
- func (c *Context) Bytes(name any) []byte
- func (c *Context) Category() string
- func (c *Context) Command() *Command
- func (c *Context) Complete(args []string, incomplete string) []CompletionItem
- func (c *Context) Completion() Completion
- func (c *Context) CompletionRequest() *CompletionRequest
- func (c *Context) Context() context.Context
- func (c *Context) ContextOf(target any) *Context
- func (c *Context) Customize(pattern string, a Action) error
- func (c *Context) Data() map[string]any
- func (c *Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) Description() any
- func (c *Context) Do(action Action) error
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Duration(name any) time.Duration
- func (c *Context) Err() error
- func (c *Context) Execute(args []string) error
- func (c *Context) ExecuteTemplate(name string, data func(*Context) any) error
- func (c *Context) File(name any) *File
- func (c *Context) FileSet(name any) *FileSet
- func (c *Context) FindTarget(path ContextPath) (res *Context, ok bool)
- func (c *Context) Flag() *Flag
- func (c *Context) Flags() []*Flag
- func (c *Context) Float32(name any) float32
- func (c *Context) Float64(name any) float64
- func (c *Context) Fprint(w io.Writer, a ...any) (n int, err error)
- func (c *Context) Fprintf(w io.Writer, format string, a ...any) (n int, err error)
- func (c *Context) Fprintln(w io.Writer, a ...any) (n int, err error)
- func (c *Context) HasValue() bool
- func (c *Context) HelpText() string
- func (c *Context) Hook(timing Timing, handler Action) error
- func (c *Context) HookAfter(pattern string, handler Action) error
- func (c *Context) HookBefore(pattern string, handler Action) error
- func (c *Context) IP(name any) net.IP
- func (c *Context) ImplicitlySet() bool
- func (c *Context) Int(name any) int
- func (c *Context) Int16(name any) int16
- func (c *Context) Int32(name any) int32
- func (c *Context) Int64(name any) int64
- func (c *Context) Int8(name any) int8
- func (c *Context) Interface(name any) (any, bool)
- func (c *Context) IsAction() bool
- func (c *Context) IsAfter() bool
- func (c *Context) IsArg() bool
- func (c *Context) IsBefore() bool
- func (c *Context) IsCommand() bool
- func (c *Context) IsFlag() bool
- func (c *Context) IsInitializing() bool
- func (c *Context) Lineage() []*Context
- func (c *Context) List(name any) []string
- func (c *Context) LocalArgs() []*Arg
- func (c *Context) LocalFlags() []*Flag
- func (c *Context) LookupArg(name any) (*Arg, bool)
- func (c *Context) LookupCommand(name any) (*Command, bool)
- func (c *Context) LookupData(name string) (any, bool)
- func (c *Context) LookupFlag(name any) (*Flag, bool)
- func (c *Context) LookupValueTarget(name string) (any, bool)
- func (c *Context) ManualText() string
- func (c *Context) Map(name any) map[string]string
- func (c *Context) Matches(f ContextFilter) bool
- func (c *Context) NValue() int
- func (c *Context) Name() string
- func (c *Context) NameValue(name any) *NameValue
- func (c *Context) NameValues(name any) []*NameValue
- func (c *Context) NewBuffer() *buffer
- func (c *Context) Occurrences(name any) int
- func (c *Context) Parent() *Context
- func (c *Context) Path() ContextPath
- func (c *Context) PersistentFlags() []*Flag
- func (c *Context) PreventSetup() error
- func (c *Context) Print(a ...any) (n int, err error)
- func (c *Context) Printf(format string, a ...any) (n int, err error)
- func (c *Context) Println(a ...any) (n int, err error)
- func (c *Context) ProvideValueInitializer(v any, name string, actionopt ...Action) error
- func (c *Context) Raw(name any) []string
- func (c *Context) RawOccurrences(name any) []string
- func (c *Context) ReadPasswordString(prompt string) (string, error)
- func (c *Context) ReadString(prompt string) (string, error)
- func (c *Context) Regexp(name any) *regexp.Regexp
- func (c *Context) RegisterTemplate(name string, tpl string) error
- func (c *Context) RegisterTemplateFunc(name string, fn any) error
- func (c *Context) RemoveAlias(a string) error
- func (c *Context) RemoveArg(name any) error
- func (c *Context) RemoveCommand(name any) error
- func (c *Context) RemoveFlag(name any) error
- func (c *Context) Root() *Context
- func (c *Context) Seen(name any) bool
- func (c *Context) SetCategory(name string) error
- func (c *Context) SetColor(v bool)
- func (c *Context) SetContext(ctx context.Context) error
- func (c *Context) SetContextValue(key, value any) error
- func (c *Context) SetData(name string, v any) error
- func (c *Context) SetDescription(v any) error
- func (c *Context) SetHelpText(s string) error
- func (c *Context) SetManualText(v string) error
- func (c *Context) SetName(name string) error
- func (c *Context) SetOptionalValue(v any) error
- func (c *Context) SetTransform(fn TransformFunc) error
- func (c *Context) SetUsageText(s string) error
- func (c *Context) SetValue(arg any) error
- func (c *Context) SkipImplicitSetup() bool
- func (c *Context) String(name any) string
- func (c *Context) Target() any
- func (c *Context) Template(name string) *Template
- func (c *Context) Timing() Timing
- func (c *Context) Trigger() error
- func (c *Context) URL(name any) *url.URL
- func (c *Context) Uint(name any) uint
- func (c *Context) Uint16(name any) uint16
- func (c *Context) Uint32(name any) uint32
- func (c *Context) Uint64(name any) uint64
- func (c *Context) Uint8(name any) uint8
- func (c *Context) UsageText() string
- func (c *Context) Use(action Action) error
- func (c *Context) Value(name any) any
- func (c *Context) ValueContextOf(name string, v any) *Context
- func (c *Context) Values() []any
- func (c *Context) Walk(fn WalkFunc) error
- type ContextFilter
- type ContextFilterFunc
- type ContextPath
- type ErrorCode
- type ExitCoder
- type FS
- type Feature
- type FeatureMap
- type File
- func (f *File) Base() string
- func (f *File) Chmod(mode fs.FileMode) error
- func (f *File) Chown(uid int, gid int) error
- func (f *File) Chtimes(atime, mtime time.Time) error
- func (f *File) Completion() Completion
- func (f *File) Create() (fs.File, error)
- func (f *File) Dir() string
- func (f *File) Exists() bool
- func (f *File) Ext() string
- func (f *File) Initializer() Action
- func (f *File) Mkdir(mode fs.FileMode) error
- func (f *File) MkdirAll(mode fs.FileMode) error
- func (f *File) Open() (fs.File, error)
- func (f *File) OpenContext(c context.Context) (fs.File, error)
- func (f *File) OpenFile(flag int, perm os.FileMode) (fs.File, error)
- func (f *File) Remove() error
- func (f *File) RemoveAll() error
- func (f *File) Rename(newpath string) error
- func (f *File) Set(arg string) error
- func (f *File) Stat() (fs.FileInfo, error)
- func (f *File) String() string
- func (*File) Synopsis() string
- func (f *File) Walk(fn fs.WalkDirFunc) error
- type FileSet
- func (f *FileSet) All() iter.Seq2[*File, error]
- func (f *FileSet) Completion() Completion
- func (f *FileSet) Do(fn func(*File, error) error) error
- func (f *FileSet) Exists() bool
- func (f *FileSet) Initializer() Action
- func (f *FileSet) NewCounter() ArgCounter
- func (f *FileSet) RecursiveFlag() Prototype
- func (f *FileSet) Reset()
- func (f *FileSet) Set(arg string) error
- func (f *FileSet) SetData(in io.Reader) error
- func (f *FileSet) SetRecursive(b bool) error
- func (f *FileSet) String() string
- func (*FileSet) Synopsis() string
- type FilterModes
- type Flag
- func (f *Flag) LongName() string
- func (f *Flag) LookupData(name string) (any, bool)
- func (f *Flag) Names() []string
- func (f *Flag) Occurrences() int
- func (f *Flag) Seen() bool
- func (f *Flag) Set(arg any) error
- func (f *Flag) SetData(name string, v any)
- func (f *Flag) SetHidden(v bool)
- func (f *Flag) SetOccurrence(values ...string) error
- func (f *Flag) SetOccurrenceData(v any) error
- func (f *Flag) SetRequired(v bool)
- func (f *Flag) ShortName() string
- func (f *Flag) Synopsis() string
- func (f *Flag) Use(action Action) *Flag
- type InternalError
- type Lookup
- type LookupFunc
- func (c LookupFunc) BigFloat(name any) *big.Float
- func (c LookupFunc) BigInt(name any) *big.Int
- func (c LookupFunc) Bool(name any) bool
- func (c LookupFunc) Bytes(name any) []byte
- func (c LookupFunc) Duration(name any) time.Duration
- func (c LookupFunc) File(name any) *File
- func (c LookupFunc) FileSet(name any) *FileSet
- func (c LookupFunc) Float32(name any) float32
- func (c LookupFunc) Float64(name any) float64
- func (c LookupFunc) IP(name any) net.IP
- func (c LookupFunc) Int(name any) int
- func (c LookupFunc) Int16(name any) int16
- func (c LookupFunc) Int32(name any) int32
- func (c LookupFunc) Int64(name any) int64
- func (c LookupFunc) Int8(name any) int8
- func (c LookupFunc) Interface(name any) (any, bool)
- func (c LookupFunc) List(name any) []string
- func (c LookupFunc) Map(name any) map[string]string
- func (c LookupFunc) NameValue(name any) *NameValue
- func (c LookupFunc) NameValues(name any) []*NameValue
- func (c LookupFunc) Regexp(name any) *regexp.Regexp
- func (c LookupFunc) String(name any) string
- func (c LookupFunc) URL(name any) *url.URL
- func (c LookupFunc) Uint(name any) uint
- func (c LookupFunc) Uint16(name any) uint16
- func (c LookupFunc) Uint32(name any) uint32
- func (c LookupFunc) Uint64(name any) uint64
- func (c LookupFunc) Uint8(name any) uint8
- func (c LookupFunc) Value(name any) any
- type LookupValues
- func (c LookupValues) BigFloat(name any) *big.Float
- func (c LookupValues) BigInt(name any) *big.Int
- func (c LookupValues) Bool(name any) bool
- func (c LookupValues) Bytes(name any) []byte
- func (c LookupValues) Duration(name any) time.Duration
- func (c LookupValues) File(name any) *File
- func (c LookupValues) FileSet(name any) *FileSet
- func (c LookupValues) Float32(name any) float32
- func (c LookupValues) Float64(name any) float64
- func (c LookupValues) IP(name any) net.IP
- func (c LookupValues) Int(name any) int
- func (c LookupValues) Int16(name any) int16
- func (c LookupValues) Int32(name any) int32
- func (c LookupValues) Int64(name any) int64
- func (c LookupValues) Int8(name any) int8
- func (c LookupValues) Interface(name any) (any, bool)
- func (c LookupValues) List(name any) []string
- func (c LookupValues) Map(name any) map[string]string
- func (c LookupValues) NameValue(name any) *NameValue
- func (c LookupValues) NameValues(name any) []*NameValue
- func (c LookupValues) Regexp(name any) *regexp.Regexp
- func (c LookupValues) String(name any) string
- func (c LookupValues) URL(name any) *url.URL
- func (c LookupValues) Uint(name any) uint
- func (c LookupValues) Uint16(name any) uint16
- func (c LookupValues) Uint32(name any) uint32
- func (c LookupValues) Uint64(name any) uint64
- func (c LookupValues) Uint8(name any) uint8
- func (c LookupValues) Value(name any) any
- type Middleware
- type NameValue
- func (v *NameValue) AllowFileReferencesFlag() Prototype
- func (v *NameValue) Copy() *NameValue
- func (v *NameValue) Initializer() Action
- func (v *NameValue) NewCounter() ArgCounter
- func (v *NameValue) Reset()
- func (v *NameValue) Set(arg string) error
- func (v *NameValue) SetAllowFileReference(val bool) error
- func (v *NameValue) String() string
- type Option
- type ParseError
- type Prototype
- type RawParseFlag
- type Setup
- type ShellComplete
- type StandardCompletion
- type Style
- type Template
- type Timing
- type TransformFunc
- type ValidatorFunc
- type Value
- type ValueReader
- type WalkFunc
- type Writer
Examples ¶
Constants ¶
const ( // TakeUnlessFlag is the value to use for Arg.NArg to indicate that an argument takes the // value unless it looks like a flag. This is the default TakeUnlessFlag = 0 // TakeRemaining is the value to use for Arg.NArg to indicate that an argument takes // all the remaining tokens from the command line TakeRemaining = -1 // TakeUntilNextFlag is the value to use for Arg.NArg to indicate that an argument takes // tokens from the command line until one looks like a flag. TakeUntilNextFlag = -2 // TakeExceptForFlags is the value to use for Arg.NArg to indicate that an argument can // be interspersed with values that look like flags. When the flag syntax is encountered, // a flag will be parsed and parsing the argument will resume. TakeExceptForFlags = -3 )
const ( // UnexpectedArgument provides the error when an unexpected argument is encountered UnexpectedArgument = ErrorCode(iota) // CommandNotFound provides the error when the command is not found CommandNotFound // UnknownOption occurs when the option is not recognized UnknownOption // MissingArgument means that the value is required for a flag MissingArgument // InvalidArgument error represents the value for a position argument or flag not being parsable InvalidArgument // ExpectedArgument occurs when a value must be specified to a positional argument or flag ExpectedArgument // UnknownExpr represents an expression name that was not recognized UnknownExpr // ArgsMustPrecedeExprs occurs in expression parsing for unexpected arguments ArgsMustPrecedeExprs // FlagUsedAfterArgs occurs when a flag is used after a positional arg, but not allowed FlagUsedAfterArgs // ExpectedRequiredOption occurs when a flag or option is required to be specified ExpectedRequiredOption )
const ( // Hidden causes the option to be Hidden Hidden = Option(1 << iota) // Required marks a flag as required. When set, an error is generated if the flag is not // specified Required // Exits marks a flag that causes the app to exit. This value is added to the options of flags // like --help and --version to indicate that they cause the app to exit when used. It implicitly // causes the action of the flag to return SuccessStatus if they return no other error. When this // option is set, it also causes the flag to be set apart visually on the help screen. Exits // MustExist indicates that when a File or Path value is used, it must represent a file // or path that exists. MustExist // SkipFlagParsing when applied to a Command causes everything submitted to the command // to be treated as if they are arguments. Generally with this option, you must either define // an Arg that is a list that takes all the values or you must parse manually from the context // args SkipFlagParsing // DisallowFlagsAfterArgs option when used on a Command prevents flags from being specified after args. // To ease ergonomics, flags can be specified after arguments by default; however, to stop this, this // option can be set, which causes the first occurrence of an argument to indicate that the rest of the // command line consists only of arguments. This option is implicitly set if any expressions or // sub-commands are defined. DisallowFlagsAfterArgs // WorkingDirectory labels a flag or argument as specifying the process working directory. // When used, the working directory will be changed to this path. WorkingDirectory // Optional makes the flag's value optional. When this is set, the value of a flag is optional, // and the following values are set when the flag is present but its value is omitted: // // integers (int, int32, int64, etc.) 1 // floats (float32, float64, etc.) 1.0 // time.Duration 1 second // bool true // string * // []string * // []byte * // other Value * // // * For string, []string, []byte, and any other Value implementation, using this option panics. // // For short options, no space can be between the flag and value (e.g. you need -sString to // specify a String to the -s option). // This option is available to but not useful for bool because this is the default behavior // for bool. If you need more customization, then you can use OptionalValue middleware. // Optional // No introduces a mirror flag to a Boolean flag that provides the false value. // When set as the option on a flag, this causes a mirror flag to be created with the // prefix no-. For example, for the flag --color, --no-color gets generated. In addition, // the mirror flag is hidden and the help screen provides a concise summary. The mirror // flag inherits the Before, After, and Action middleware pipelines; however, the Value // for the flag in the context always matches the original flag. No // NonPersistent marks a flag as being non-persistent. By default, any flag defined by an ancestor // command can be set by a sub-command. However, when present, the NonPersistent option causes this to // be treated as a usage error. NonPersistent // DisableSplitting disable splitting on commas. This affects List arguments and flags. // By default, commas are used as delimiters to split list values. // For example --planet Mars,Jupiter is equivalent to --planet Mars --planet Jupiter by default; // however, by enabling this option, such splitting is disabled. For custom implementations of // flag Value, you can implement this method DisableSplitting() to hook into this option. DisableSplitting // Merge when set, indicates that rather than overwrite values set in list, there should // be strategic merging. This pertains to strings, list, fileset, and map flags. By default, // the value that is used to initialize any of these flags is treated as a default which // is overwritten if the user specifies an environment variable or any value. To stop this, // the Merge option can be used Merge // RightToLeft causes arguments to bind right-to-left instead of left-to-right. // This option applies to commands and expressions, and it affects how optional args are // interpreted when there are fewer values than are optional. By default, with left-to-right binding, // in this situation, the leftmost optional args are filled first, leaving any subsequent args empty. // However, with right-to-left binding, we fill as many rightmost args as there are available // values. For example, if arg a and b are optional (as in, Arg.NArg set to 0) and a subsequent // arg r exists, then if there is one value passed to the command, only r will be set. If there // are two values, both b and r will be set. // Note that despite its name, args still bind in order. // RightToLeft // PreventSetup is used to opt-out of any setup actions. Typically, // reusable actions provide implicit setup such as choosing a good default // name or environment variables. To stop this, add PreventSetup to // the pipeline which will taint the implicit setup actions causing them // to be skipped. However, note that preventing setup could cause the // flag, arg, or command not to work properly if any required // configurations go missing. PreventSetup only applies in the Uses // pipeline and to actions in the Uses pipeline. The action is recursive to // the scope of the app, flag, arg, or command. PreventSetup // EachOccurrence causes the Action for a flag or arg to be called once for each occurrence // rather than just once for the winning value. This makes sense for flags or args // where each occurrence is treated as distinct whereas by default, clients are usually // only concerned with the last occurrence or the aggregated value. For example, for the // command "app -a first -a last", the value for -a is "last" (or "first last" if -a is set to Merge); // however, if EachOccurrence were specified, then the // Action associated with -a will be called twice with the context value set equal to the corresponding // occurrence. Note that only the default lookup will contain the occurrence; other lookups will // use the winning value. (i.e. for the example, String("") will vary as "first" and "last" in the // two corresponding Action calls; however String("a") will always be "last"). This also applies to // Raw(""). // // EachOccurrence can be used with built-in flag value types or any value which defines a method // named Copy with zero arguments, which is called after each occurrence EachOccurrence // FileReference indicates that the flag or argument is a reference to a file which is loaded // and whose contents provide the actual value of the flag. FileReference // AllowFileReference allows a flag or argument to use the special syntax @file to mean that // the value is obtained by loading the contents of a file rather than directly. When the // plain syntax without @ is used, the value is taken as the literal contents of an unnamed // file. AllowFileReference // SortedFlags causes flags to be sorted on the help screen generated for the command or app. SortedFlags // SortedCommands causes sub-commands to be sorted on the help screen generated for the command or app. SortedCommands // SortedExprs causes the expression listing to be sorted on the help screen generated for // the command or app. SortedExprs // ImpliedAction causes the Action for a flag or arg to be run if it was implicitly // set. By default, the Action for a flag or arg is only executed when it is // set explicitly. When this option is used, if the flag or arg has an implied value // set via an environment variable, loaded file, Implies, or any mechanism that modifies // it with ImplicitValueTiming, the action will also be run. Note that setting the value in // the initializer or an ordinary Before pipeline won't trigger the action. // The option can be set on the command to apply this behavior to all flags and args. ImpliedAction // Visible sets a flag or command as being visible in usage Visible // DisableAutoVisibility disables the default behavior of treating flags // and commands whose names start with underscores as hidden. This is typically // used on commands to prevent the behavior for sub-commands and flags. DisableAutoVisibility // Trigger marks a flag or arg action to be triggered. Generally, // a flag or arg Action is only triggered if it is set or if it or its // parent command is marked with ImpliedAction. To mark the Action to be triggered for some // other reason, you can use this action. Trigger // None represents no options None Option = 0 // Sorted causes flags and sub-commands to be sorted on the help screen generated for the command or app. Sorted = SortedExprs | SortedFlags | SortedCommands )
const ( RawRTL = RawParseFlag(1 << iota) RawDisallowFlagsAfterArgs RawSkipProgramName )
Raw flags used by the internal parser
const ( Bold Style = ansiterm.Bold Faint = ansiterm.Faint Italic = ansiterm.Italic Underline = ansiterm.Underline Blink = ansiterm.Blink Reverse = ansiterm.Reverse Strikethrough = ansiterm.Strikethrough Conceal = ansiterm.Conceal )
ANSI terminal styles
const ( Default = ansiterm.Default Black = ansiterm.Black Red = ansiterm.Red Green = ansiterm.Green Yellow = ansiterm.Yellow Blue = ansiterm.Blue Magenta = ansiterm.Magenta Cyan = ansiterm.Cyan Gray = ansiterm.Gray DarkGray = ansiterm.DarkGray BrightRed = ansiterm.BrightRed BrightGreen = ansiterm.BrightGreen BrightYellow = ansiterm.BrightYellow BrightBlue = ansiterm.BrightBlue BrightMagenta = ansiterm.BrightMagenta BrightCyan = ansiterm.BrightCyan White = ansiterm.White )
ANSI terminal colors
const (
// EndOfArguments signals no more arguments taken by this arg counter.
EndOfArguments
)
Variables ¶
var ( // ErrSkipCommand is used as a return value from WalkFunc to indicate that the command in the call is to be skipped. // This is also used to by ExecuteSubcommand (or HandleCommandNotFound) to indicate that no command should // be executed. ErrSkipCommand = errors.New("skip this command") // ErrTimingTooLate occurs when attempting to run an action in a pipeline // when the pipeline is later than requested by the action. ErrTimingTooLate = errors.New("too late for requested action timing") )
var ( // HelpTemplate provides the default help Go template that is rendered on the help // screen. The preferred way to customize the help screen is to override its constituent // templates. The template should otherwise define an entry point named "Help", which // you can use to define a from-scratch template. HelpTemplate = `` /* 2453-byte string literal not displayed */ // VersionTemplate specifies the Go template for what is printed when // the version flag or command is used. VersionTemplate = "{{ .App.Name }}, version {{ .App.Version }}\n" // LicenseTemplate specifies the Go template for what is printed when // the license flag or command is used. LicenseTemplate = "{{ .App.License | Wrap 4 }}\n" )
var ( // ErrImplicitValueAlreadySet occurs when the value for a flag // or arg is set multiple times within the implicit timing. ErrImplicitValueAlreadySet = errors.New("value already set implicitly") )
var ( // ExitHandler defines how to handle exiting the process. This function // takes the context, error message, and exit status. By default, text is // written to stderr and the exit status is returned via os.Exit ExitHandler func(*Context, string, int) )
Functions ¶
func BigFloat ¶
BigFloat creates a big float value. This is for convenience to obtain the right pointer.
func BigInt ¶
BigInt creates a big integer value. This is for convenience to obtain the right pointer.
func Bool ¶
func Bool() *bool
Bool creates a bool value. This is for convenience to obtain the right pointer.
func Bytes ¶
func Bytes() *[]byte
Bytes creates a slice of bytes. This is for convenience to obtain the right pointer.
func Duration ¶
Duration creates a time.Duration value. This is for convenience to obtain the right pointer.
func Float32 ¶
func Float32() *float32
Float32 creates a float32 value. This is for convenience to obtain the right pointer.
func Float64 ¶
func Float64() *float64
Float64 creates a float64 value. This is for convenience to obtain the right pointer.
func Int ¶
func Int() *int
Int creates an int value. This is for convenience to obtain the right pointer.
func Int16 ¶
func Int16() *int16
Int16 creates an int16 value. This is for convenience to obtain the right pointer.
func Int32 ¶
func Int32() *int32
Int32 creates an int32 value. This is for convenience to obtain the right pointer.
func Int64 ¶
func Int64() *int64
Int64 creates an int64 value. This is for convenience to obtain the right pointer.
func Int8 ¶
func Int8() *int8
Int8 creates an int8 value. This is for convenience to obtain the right pointer.
func List ¶
func List() *[]string
List creates a string slice value. This is for convenience to obtain the right pointer.
func NameValues ¶
NameValues creates a list of name-value pairs, optionally specifying the values to set
func NewBuffer ¶
func NewBuffer() *buffer
NewBuffer creates a buffer which is a Writer that can be used to accumulate text into a buffer. Color is enabled using auto-detection on stdout.
func ReadPasswordString ¶
ReadPasswordString securely gets a password, without the trailing '\n'. An error will be returned if the reader is not stdin connected to TTY.
func ReadString ¶
ReadString gets a line of text, without the trailing '\n'. An error will be returned if the reader is not stdin connected to TTY.
func Set ¶
Set will set the destination value if supported. If the destination value is not supported, this panics. See the overview for Value for which destination types are supported. No additional splitting is performed on arguments.
func SetCurrentApp ¶
func SetCurrentApp(a *App)
SetCurrentApp sets the current app directly so that tools, extensions, and plug-ins can discover which app to analyze.
func SetData ¶
SetData sets the value of a flag Value using the semantics of SetData(io.Reader), which is a convention that can be implemented by a value (see the summary on Value for information about conventions). In particular, in argument can be string, []byte, or io.Reader. If the method convention is not implemented, then ordinary Set(string) method on Value is called on the input.
func String ¶
func String() *string
String creates a string value. This is for convenience to obtain the right pointer.
func Uint ¶
func Uint() *uint
Uint creates an uint value. This is for convenience to obtain the right pointer.
func Uint16 ¶
func Uint16() *uint16
Uint16 creates an uint16 value. This is for convenience to obtain the right pointer.
func Uint32 ¶
func Uint32() *uint32
Uint32 creates an uint32 value. This is for convenience to obtain the right pointer.
func Uint64 ¶
func Uint64() *uint64
Uint64 creates an uint64 value. This is for convenience to obtain the right pointer.
Types ¶
type Action ¶
type Action interface { // Execute will execute the action. If the action returns an error, this // may cause subsequent actions in the pipeline not to be run and cause // the app to exit with an error exit status. Execute(context.Context) error }
Action represents the building block of the various actions to perform when an app, command, flag, or argument is being evaluated.
func Accessory ¶
Accessory provides an action which sets up an accessory flag for the current flag or argument. A common pattern is that a flag has a related sibling flag that can be used to refine the value. For example, you might define a --recursive flag next to a FileSet argument. When a Value supports an accessory flag prototype, you can use this action to activate it from its Uses pipeline.
The value of name determines the accessory flag name. There are two special cases. If it is blank, then the name from the prototype will be used. If it is "-", then it will be derived from the other flag. For example, in the case of the FileSet recursive flag as described earlier, if the FileSet flag were named "files", then the accessory flag would be named --files-recursive.
Example ¶
(&cli.App{ Name: "app", Args: []*cli.Arg{ { Name: "files", Value: new(cli.FileSet), Uses: cli.Accessory("recursive", (*cli.FileSet).RecursiveFlag), }, }, Action: func(c *cli.Context) { fmt.Println(c.Command().Synopsis()) }, }).Run([]string{"app"})
Output: app {--help | --version} [--recursive] [<files>]
func Accessory0 ¶
Accessory0 provides an action which sets up an accessory flag for the current flag or argument. A common pattern is that a flag has a related sibling flag that can be used to refine the value.
The value of name determines the accessory flag name. There are two special cases. If it is blank, then the name from the prototype will be used. If it is "-", then it will be derived from the other flag. For example, in the case of the FileSet recursive flag as described earlier, if the FileSet flag were named "files", then the accessory flag would be named --files-recursive.
func ActionOf ¶
ActionOf converts a value to an Action. Any of the following types can be converted:
- func(*Context) error
- func(*Context)
- func(context.Context) error (same signature as Action.Execute)
- func(context.Context)
- func() error
- func()
- Action
- error
You can also implement the legacy Action interface which used *Context instead of context.Context in the Execute method (i.e. Execute(*Context) error) As a special case, these signatures are allowed in order to provide middleware:
- func(Action)Action
- func(*Context, Action) error
Remember that the next action can be nil, and indeed the implementation of Execute (for implementing plain Action) the approach is to delegate to this function using a nil next action.
Any other type causes a panic.
func AddArg ¶
AddArg provides an action which adds an arg to the command or app Args can also be added to a value which has been provided to a value initializer (see ProvideValueInitializer)
func AddArgs ¶
AddArgs provides an action which adds the specified args to the command Args can also be added to a value which has been provided to a value initializer (see ProvideValueInitializer)
func AddCommand ¶
AddCommand provides an action which adds a sub-command to the command or app
func AddCommands ¶
AddCommands provides an action which adds the specified commands to the command
func After ¶
After revises the timing of the action so that it runs in the After pipeline. This function is used to wrap actions in the initialization pipeline that will be deferred until later.
func ApplyShellCompletion ¶
func ApplyShellCompletion() Action
ApplyShellCompletion detects whether a dynamic shell completion request has been added to the environment and activates the corresponding supported response.
func ArgSetup ¶
ArgSetup action is used to apply set-up to a Arg. This is typically used within the Uses pipeline for actions that provide some default setup. The setup function fn will only be called in the initialization timing and only if setup hasn't been blocked by PreventSetup.
func Assert ¶
func Assert(filter ContextFilter, a Action) Action
Assert provides an action that returns an error if the context filter does not match the context or otherwise runs the action. If the filter value has a method Describe() or String() that returns a string, it is consulted in order to produce the error message; otherwise, a generic error is returned. Compare to IfMatch.
func AutodetectColor ¶
func AutodetectColor() Action
AutodetectColor resets whether color output is used on stdout to use auto-detection
func Before ¶
Before revises the timing of the action so that it runs in the Before pipeline. This function is used to wrap actions in the initialization pipeline that will be deferred until later.
func Bind ¶
Bind invokes a function, either using the value specified or the value read from the flag or arg. The bind function is the function to execute, and valopt is optional, and if specified, indicates the value to set; otherwise, the value is read from the flag.
func BindContext ¶
func BindContext[T, V any](value func(context.Context) *T, bind func(*T, V) error, valopt ...V) Action
BindContext binds a value to a context value. The value function determines how to obtain the value from the context. Usually, this is a call to context/Context.Value. The bind function is the function to set the value, and valopt is optional, and if specified, indicates the value to set; otherwise, the value is read from the flag.
func BindIndirect ¶
BindIndirect binds a value to the specified option indirectly. For example, it is common to define a FileSet arg and a Boolean flag that controls whether or not the file set is enumerated recursively. You can use BindIndirect to update the arg indirectly by naming it and the bind function:
&cli.Arg{ Name: "files", Value: new(cli.FileSet), } &cli.Flag{ Name: "recursive", HelpText: "Whether files is recursively searched", Action: cli.BindIndirect("files", (*cli.FileSet).SetRecursive), }
The name parameter specifies the name of the flag or arg that is affected. The bind function is the function to set the value, and valopt is optional, and if specified, indicates the value to set; otherwise, the value is read from the flag.
func Category ¶
Category sets the category of a command, flag, or expression. This handler is generally set up inside a Uses pipeline.
func CommandSetup ¶
CommandSetup action is used to apply set-up to a Command. This is typically used within the Uses pipeline for actions that provide some default setup. It applies to the command in scope, so it can also be used within an arg or flag to affect the containing command. The setup function fn will only be called in the initialization timing and only if setup hasn't been blocked by PreventSetup.
func ContextValue ¶
ContextValue provides an action which updates the context with a value.
func Customize ¶
Customize matches a flag, arg, or command and runs additional pipeline steps. Customize is usually used to apply further customization after an extension has done setup of the defaults.
func Data ¶
Data sets metadata for a command, flag, arg, or expression. This handler is generally set up inside a Uses pipeline. When value is nil, the corresponding metadata is deleted
func Description ¶
Description sets the description of a command, flag, or expression. This handler is generally set up inside a Uses pipeline. The type should be string or fmt.Stringer Consider implementing a custom Stringer value that defers calculation of the description if the description is expensive to calculate. One convenient implementation is from Template.Bind or Template.BindFunc. The implementation can also provide:
- SortUsage() called when the option SortedExprs was used, which generally indicates that any expressions or other sub-details should be sorted.
func DisplayHelpScreen ¶
DisplayHelpScreen displays the help screen for the specified command. If the command is nested, each sub-command is named.
func Enum ¶
Enum provides validation that a particular flag or arg value matches a given set of legal values. The operation applies to the raw values in the occurrences. When used, it also sets the flag synopsis to a reasonable default derived from the values unless the flag provides its own specific synopsis. This enables completion on the enumerated values.
func ExecuteSubcommand ¶
ExecuteSubcommand finds and executes a sub-command. This action is intended to be used as the action on an argument. The argument should be a list of strings, which represent the sub-command to locate and execute and the arguments to use. If used within the Uses pipeline of an argument, a prototype applies these requirements for you and other good defaults to support completion and synopsis. If no sub-command matches, an error is generated, which you can intercept with custom handling using interceptErr. The interceptErr function should return a command to execute in lieu of returning the error. If the interceptErr command is nil, it is interpreted as the command not existing and the app will exit with a generic "command not found error" message. If it returns an error, then executing the sub-command fails with the error. However, if ErrSkipCommand is returned, then no command is executed, and no error is generated. It is uncommon to use this action because this action is implicitly bound to a synthetic argument when a command defines any sub-commands.
func ExecuteTemplate ¶
ExecuteTemplate provides an action that renders the specified template using the factory function that creates the data that is passed to the template
func FlagSetup ¶
FlagSetup action is used to apply set-up to a flag. This is typically used within the Uses pipeline for actions that provide some default setup. The setup function fn will only be called in the initialization timing and only if setup hasn't been blocked by PreventSetup.
func Fprint ¶
Fprint provides an action that formats using the default formats for its operands and writes to a file using the behavior of fmt.Fprint.
func Fprintf ¶
Fprintf provides an action that formats according to a format specifier and writes to a file using the behavior of fmt.Fprintf
func Fprintln ¶
Fprintln provides an action that formats using the default formats for its operands and writes to a file using the behavior of fmt.Fprintln
func FromEnv ¶
FromEnv loads the flag or arg value from the given environment variable(s). Alternatively, you can set the EnvVars field on Flag or Arg to achieve the same behavior.
The special pattern "{}" can be used to represent the long name of the flag transformed into uppercase, replacing internal dashes with underscores, and introducing an additional underscore to separate it from other text (hence, "APP{}" is an acceptable value to get env var APP_FLAG_NAME for the --flag-name flag.)
func FromFilePath ¶
FromFilePath loads the value from the given file path. If the file does not exist or fails to load, the error is silently ignored. Alternatively, you can set the Flag or Arg field FilePath.
func HandleCommandNotFound ¶
HandleCommandNotFound assigns a default function to invoke when a command cannot be found. The specified function is invoked if a command cannot be found. It contains the context of the parent attempting to invoke a command and the error previously encountered. It returns the command if any that can substitute. Composition occurs with functions registered to handle commands not found. They each get called until one returns a command.
func HandleSignal ¶
HandleSignal provides an action that provides simple handling of a signal, usually os.Interrupt. HandleSignal updates the Context to handle the signal by exposing the context Done() channel. Compare this behavior to os/signal.NotifyContext. Here's an example:
&cli.Command{ Name: "command", Uses: cli.HandleSignal(os.Interrupt), Action: func(c *cli.Context) error { for { select { case <-c.Done(): // Ctrl+C was called return nil default: // process another step, use return to exit } } } }
The signal handler is unregistered in the After pipeline. The recommended approach is therefore to place cleanup into After and consider using a timeout. The process will be terminated when the user presses ^C for the second time:
func HookAfter ¶
HookAfter registers a hook that runs for the matching elements. See ContextPath for the syntax of patterns and how they are matched.
func HookBefore ¶
HookBefore registers a hook that runs for the matching elements. See ContextPath for the syntax of patterns and how they are matched.
func IfMatch ¶
func IfMatch(f ContextFilter, a Action) Action
IfMatch provides an action that only runs on a matching context. If and only if the filter f matches will the corresponding action be run. If f is nil, this is a no-op.
func ImplicitCommand ¶
ImplicitCommand indicates the command which is implicit when no sub-command matches. The main use case for this is to allow a command to be invoked by default without being named. For example, you might have a sub-command called "exec" which can be omitted, making the following invocations equivalent:
- cloud exec tail -f /var/output/log
- cloud tail -f /var/output/log
func ImplicitValue ¶
ImplicitValue sets the implicit value, which is a value specified for the arg or flag when it was not specified from the command line arguments. Any errors setting the value are suppressed. In particular, note that the error ErrImplicitValueAlreadySet could be generated from setting value but it is also ignored.
func Implicitly ¶
Implicitly runs an action when there are zero occurrences (when an implicit value is set)
func Implies ¶
Implies is used to set the implied value of another flag. For example, an app might have two flags, --mode and --encryption-key, and you might allow --encryption-key to imply --mode=encrypt which saves power users from having to type both. Because it is an implied value, if the other flag is explicitly specified, the explicit value wins regardless of its position in the command line. If the name is the empty string, returns a no-op.
func Initializer ¶
Initializer marks an action handler as being for the initialization phase. When such a handler is added to the Uses pipeline, it will automatically be associated correctly with the initialization of the value. Otherwise, this handler is not special
func ManualText ¶
ManualText sets the manual text of a command, flag, arg, or expression.
func Mutex ¶
Mutex validates that explicit values are used mutually exclusively. When used on any flag in a mutex group, the other named flags are not allowed to be used.
func Named ¶
Named sets the name of a command, flag, or expression. This handler is generally set up inside a Uses pipeline.
func OptionalValue ¶
OptionalValue makes the flag's value optional, and when its value is not specified, the implied value is set to this value v. Say that a flag is defined as:
&Flag { Name: "secure", Value: cli.String(), Uses: cli.OptionalValue("TLS1.2"), }
This example implies that --secure without a value is set to the value TLS1.2 (presumably other versions are allowed). This example is a fair use case of this feature: making a flag opt-in to some sort of default configuration and allowing an expert configuration by using a value. For short options, no space can be between the flag and value (e.g. you need -sString to specify a String to the -s option). In general, making the value of a non-Boolean flag optional is not recommended when the command also allows arguments because it can make the syntax ambiguous.
func Print ¶
Print provides an action that formats using the default formats for its operands and writes to standard output using the behavior of fmt.Print.
func PrintLicense ¶
func PrintLicense() Action
PrintLicense displays the license. The LicenseTemplate provides the Go template
func PrintVersion ¶
func PrintVersion() Action
PrintVersion displays the version string. The VersionTemplate provides the Go template
func Printf ¶
Printf provides an action that formats according to a format specifier and writes to standard output using the behavior of fmt.Printf
func Println ¶
Println provides an action that formats using the default formats for its operands and writes to standard output using the behavior of fmt.Println
func ProvideValueInitializer ¶
ProvideValueInitializer causes an additional child context to be created which is used to initialize an arbitrary value. For more information, refer to the implementation provided by Context.ProvideValueInitializer.
func RegisterTemplate ¶
RegisterTemplate will register the specified template by name.
func RegisterTemplateFunc ¶
RegisterTemplateFunc will register the specified function for use in template rendering.
func RemoveAlias ¶
RemoveAlias removes the alias from the flag or command.
func RemoveArg ¶
RemoveArg provides an action which removes an arg from the command or app. The name specifies the name, index, or arg itself
func RemoveCommand ¶
RemoveCommand provides an action which removes a Command from the command or app. The name specifies the name, index, or Command itself
func RemoveFlag ¶
RemoveFlag provides an action which removes a flag from the command or app. The name specifies the name, index, or Flag itself
func SetCompletion ¶
func SetCompletion(c Completion) Action
SetCompletion sets completion for the command, flag, or arg.
func SetContext ¶
SetContext provides an action which sets the context
func ShellCompleteIntegration ¶
func ShellCompleteIntegration(name string, s ShellComplete) Action
ShellCompleteIntegration provides an action which renders the particular shell complete integration
func SuppressError ¶
SuppressError wraps an action to ignore its error.
func Transform ¶
func Transform(fn TransformFunc) Action
Transform defines how to interpret raw values passed to a flag or arg. The action is added to the Uses pipeline. The typical use of transforms is to interpret the value passed to an argument as instead a reference to a file which is loaded. The function fn can return string, []byte, or io.Reader. If the Value implements method SetData(io.Reader) error, then this is called instead when setting the Value. If it doesn't, then bytes or readers are read in and treated as a string and the usual Set method is used. See also: FileReference and AllowFileReference, which provide common transforms.
func ValueTransform ¶
func ValueTransform(valueFn TransformFunc) Action
ValueTransform sets the transform that applies to the syntax of the value in NameValue, NameValues, or Map. The first occurrence of an unescaped equal sign is treated as the delimiter between the name and value (as with any of the types just mentioned). The value portion is transformed using the logic of the transform function.
type ActionFunc ¶
ActionFunc provides the basic function for an Action
type ActionPipeline ¶
type ActionPipeline []Action
ActionPipeline represents an action composed of several steps. To create this value, use the Pipeline function
func Pipeline ¶
func Pipeline(actions ...any) ActionPipeline
Pipeline combines various actions into a single action. Compared to using ActionPipeline directly, the actions are flattened if any nested pipelines are present.
func (ActionPipeline) Append ¶
func (p ActionPipeline) Append(x ...Action) ActionPipeline
Append appends actions to the pipeline
func (ActionPipeline) Execute ¶
func (p ActionPipeline) Execute(c context.Context) (err error)
Execute the pipeline by calling each action successively
func (ActionPipeline) Prepend ¶
func (p ActionPipeline) Prepend(x ...Action) ActionPipeline
Prepend prepends actions to the pipeline
type App ¶
type App struct { // Name provides the name of the app. This value is inferred from the base name of the entry process if // it is explicitly not set. It will be displayed on the help screen and other templates. Name string // Version provides the version of the app. This value is typically used in templates, and otherwise // provides no special behavior. Version string // Description provides a description of the app. This value is typically used in templates, and otherwise // provides no special behavior. The type of Description should be string or // fmt.Stringer. Refer to func Description for details. Description any // BuildDate provides the time when the app was built. This value is typically used in templates, and otherwise // provides no special behavior. The default value is inferred by checking the last modification time of // the entry process. BuildDate time.Time // Author provides the author of the app. This value is typically used in templates, and otherwise // provides no special behavior. Author string // Copyright provides a copyright message for the app. This value is typically used in templates, and otherwise // provides no special behavior. Copyright string // Comment provides a short comment. This is // usually a few words to summarize the purpose of the app. Comment string // In corresponds to standard in Stdin io.Reader // In corresponds to standard out Stdout io.Writer // In corresponds to standard error Stderr io.Writer // Commands provides the list of commands in the app Commands []*Command // Flags supplies global flags for use with the app Flags []*Flag // Args will be bound for non-command arguments Args []*Arg // Action specifies the action to run for the app, assuming no other more specific command // has been selected. Refer to cli.Action about the correct function signature to use. Action any // Before executes before the app action or any sub-command action runs. // Refer to cli.Action about the correct function signature to use. Before any // After executes after the app action or any sub-command action runs. // Refer to cli.Action about the correct function signature to use. After any // Uses provides an action handler that is always executed during the initialization phase // of the app. Typically, hooks and other configuration actions are added to this handler. // Actions within the Uses and Before pipelines can modify the app Commands and Flags lists. Any // commands or flags added to the list will be initialized Uses any // Data provides an arbitrary mapping of additional data. This data can be used by // middleware and it is made available to templates Data map[string]any // Options sets common options for use with the app Options Option // FS specifies the file system that is used by default for Files. // If the FS implements func OpenContext(context.Context, string)(fs.File, error), note that // this will be called instead of Open in places where the Context is available. // For os.File this means that if the context has a Deadline, SetReadDeadline // and/or SetWriteDeadline will be set. Clients can implement similar functions in their // own fs.File implementations provided from an FS implementation. FS fs.FS // HelpText describes the help text displayed for the app HelpText string // ManualText provides the text shown in the manual. The default templates don't use this value ManualText string // UsageText provides the usage for the app. If left blank, a succinct synopsis // is generated that lists each visible flag and arg UsageText string // License sets the text of the app license. License string // contains filtered or unexported fields }
App provides the definition of an app, which is composed of commands, flags, and arguments.
func CurrentApp ¶
func CurrentApp() *App
CurrentApp contains the current app. If the app was run with Run or RunContext, this will contain the app.
func NewApp ¶
NewApp creates an app initialized from the specified command. The App struct can be used directly to create and run an App. It has the same set of exported fields; however, you can also initialize an app from a command directly using this function. This benefits from having a fully consistent model with Command and fewer hidden semantics.
func (*App) Arg ¶
Arg gets the argument by name, which can be either string, int, or the actual Arg.
func (*App) Command ¶
Command gets the command by name. If the name is the empty string, this refers to the command which backs the app once it has been initialized.
func (*App) Initialize ¶
Initialize sets up the app with the given context and arguments
func (*App) Run ¶
Run the application and exit using the exit handler. This function exits using the ExitHandler if an error occurs. If you want to process the error yourself, use RunContext.
func (*App) RunContext ¶
RunContext runs the application with the specified context and returns any error that occurred.
type Arg ¶
type Arg struct { // Name provides the name of the argument. This value must be set, and it is used to access // the argument's value via the context Name string // EnvVars specifies the name of environment variables that are read to provide the // default value of the argument. EnvVars []string // FilePath specifies a file that is loaded to provide the default value of the argument. FilePath string // HelpText contains text which briefly describes the usage of the argument. // For style, generally the usage text should be limited to about 40 characters. // Sentence case is recommended for the usage text. Uppercase is recommended for the // text of placeholders. The placeholder is used in the synopsis for the argument as well // as error messages. HelpText string // ManualText provides the text shown in the manual. The default templates don't use this value ManualText string // Description provides a long description for the flag. The long description is // not used in any templates by default. The type of Description should be string or // fmt.Stringer. Refer to func Description for details. Description any // Category specifies the arg category. Categories are not used by the help screen. Category string // UsageText provides the usage for the argument. If left blank, a succinct synopsis // is generated from the type of the argument's value UsageText string // Value provides the value of the argument. Any of the following types are valid for the // value: // // * *bool // * *time.Duration // * *float32 // * *float64 // * *int // * *int16 // * *int32 // * *int64 // * *int8 // * *net.IP // * *[]string // * *map[string]string // * **regexp.Regexp // * *string // * *uint // * *uint16 // * *uint32 // * *uint64 // * *uint8 // * **url.URL // * an implementation of Value interface // // If unspecified, the value will depend upon NArg if it is a number, in which case either // a pointer to a string or a string slice will be used depending upon the semantics of the // ArgCount function. For more information about Values, see the Value type Value any // DefaultText provides a description of the default value for the argument. This is displayed // on help screens but is otherwise unused DefaultText string // NArg describes how many values are passed to the argument. For a description, see // ArgCount function. By convention, if the flag Value provides the method NewCounter() ArgCounter, // this method is consulted to obtain the arg counter. NArg any // Options sets various options about how to treat the argument. Options Option // Before executes before the command runs. Refer to cli.Action about the correct // function signature to use. Before any // Action executes if the argument was set. Refer to cli.Action about the correct // function signature to use. Action any // After executes after the command runs. Refer to cli.Action about the correct // function signature to use. After any // Uses provides an action handler that is always executed during the initialization phase // of the app. Typically, hooks and other configuration actions are added to this handler. Uses any // Data provides an arbitrary mapping of additional data. This data can be used by // middleware and it is made available to templates Data map[string]any // Completion specifies a callback function that determines the auto-complete results Completion Completion // Transform defines how to interpret the text passed to the *Arg. This is generally used // when specialized syntax preprocesses the text, such as file references. Refer to the // overview in cli.Transform for information. Transform TransformFunc // contains filtered or unexported fields }
Arg provides the representation of a positional argument.
func Args ¶
Args provides a simple initializer for positional arguments. You specify each argument name and value in order to this function. It generates the corresponding list of required positional arguments. A panic occurs when this function is not called properly: when names and values are not arranged in pairs or when an unsupported type of value is used.
func (*Arg) LookupData ¶
LookupData obtains the data if it exists
func (*Arg) Occurrences ¶
Occurrences counts the number of times that the argument has occurred on the command line
func (*Arg) SetData ¶
SetData sets the specified metadata on the arg. When v is nil, the corresponding metadata is deleted
func (*Arg) SetOccurrence ¶
SetOccurrence will update the value of the arg
func (*Arg) SetOccurrenceData ¶
SetOccurrenceData will update the value of the arg
func (*Arg) SetRequired ¶
SetRequired will indicate that the argument is required.
type ArgCounter ¶
type ArgCounter interface { // Take considers the argument and determines whether it can be used. // If the special error value EndOfArguments is returned, then the // value is not consumed and the counting operation stops. // Other errors are treated as parse errors. When possibleFlag is // set, it signals that the argument could be a flag in such cases // that flags and args are interspersed on the command line. When this is // set to true, you may prefer to stop parsing and let the next argument be // parsed as a flag. // // The interface can optionally provide a method that describes // the synopsis for args used with the counter: // // - Usage() (optional, multi bool) called to query the usage of the // arg counter, whether the arg is possibly optional // and whether the arg may be multiple values. Take(arg string, possibleFlag bool) error // Done is invoked to signal the end of arguments Done() error }
ArgCounter provides the behavior of counting the values that are specified to an Arg. The method Take is called repeatedly to process each occurrence of a value until the special error EndOfArguments is returned. The method Done is used to finalize the counting operation.
func ArgCount ¶
func ArgCount(v any) ArgCounter
ArgCount gets the arg counter for the specified value. If the value is an int, it is interpreted as the discrete number of values in the argument if it is 1 or greater, but if it is < 0 it implies taking all arguments, or 0 means take it if it exists.
>= 1 take exactly n number of arguments, though if they look like flags treat as an error 0 take argument if it does not look like a flag ([TakeUnlessFlag]) -1 take all remaining arguments (even when they look like flags) ([TakeRemaining]) -2 take all remaining arguments but stop before taking one that looks like a flag ([TakeUntilNextFlag]) -3 take all remaining arguments except ones that look like flags ([TakeExceptForFlags])
Any other negative value uses the behavior of -1. As a special case, if v is an initialized *Arg or *Flag, it obtains the actual arg counter which will be used for it, or if v is nil, this is the same as TakeUnlessFlag. If the value is already ArgCounter, it is returned as-is.
func OptionalArg ¶
func OptionalArg(fn func(string) bool) ArgCounter
OptionalArg provides an argument counter which matches zero or one argument using the specified function.
type Binding ¶
type Binding interface { LookupOption(name string) (TransformFunc, ArgCounter, BindingState, bool) ResolveAlias(name string) (string, bool) PositionalArgNames() []string BehaviorFlags(name string) (optional bool) Reset() }
Binding provides the representation of how a flag set is bound to values. It defines the names and aliases of flags, order of args, and how values passed to an arg or flag are counted.
type BindingLookup ¶
type BindingLookup interface { Lookup // Raw obtains values which were specified for a flag or arg // including the flag or arg name Raw(name string) []string // Raw obtains values which were specified for a flag or arg // but not including the flag or arg name RawOccurrences(name string) []string // Bindings obtains values which were specified for a flag or arg // including the flag or arg name and grouped into occurrences. Bindings(name string) [][]string // BindingNames obtains the names of the flags/args which are available. // Even if it is available, the empty string "" is not returned from this list. BindingNames() []string }
BindingLookup can lookup values or their raw bindings
type BindingMap ¶
BindingMap contains the occurrences of the values passed to each flag and arg.
func RawParse ¶
func RawParse(arguments []string, b Binding, flags RawParseFlag) (bindings BindingMap, err error)
RawParse does low-level parsing that will parse from the given input arguments. (This is for advanced use.) The bindings parameter determines how to resolve flags and args. The return values are a map of data corresponding to the raw occurrences using the same names. An error, if it occurs is ParseError, which can provide more information about why the parse did not complete.
func (BindingMap) ApplyTo ¶
func (m BindingMap) ApplyTo(b Binding) error
ApplyTo uses the given binding to apply the values in the map
func (BindingMap) BindingNames ¶
func (m BindingMap) BindingNames() []string
BindingNames obtains the names of the flags/args which are available. Even if it is available, the empty string "" is not returned from this list.
func (BindingMap) Bindings ¶
func (m BindingMap) Bindings(name string) [][]string
Bindings obtains values which were specified for a flag or arg including the flag or arg name and grouped into occurrences.
func (BindingMap) Raw ¶
func (m BindingMap) Raw(name string) []string
Raw obtains values which were specified for a flag or arg including the flag or arg name
func (BindingMap) RawOccurrences ¶
func (m BindingMap) RawOccurrences(name string) []string
RawOccurrences obtains values which were specified for a flag or arg but not including the flag or arg name
type BindingState ¶
type BindingState interface { SetOccurrenceData(v any) error SetOccurrence(values ...string) error }
BindingState defines the state of the binding operation. This is generally *Arg or *Flag
type Command ¶
type Command struct { // Name of the command Name string // Subcommands provides sub-commands that compose the command. Subcommands []*Command // Flags that the command supports Flags []*Flag // Args that the command supports Args []*Arg // Aliases indicates alternate names that can be used Aliases []string // Action specifies the action to run for the command, assuming no other more specific command // has been selected. Refer to cli.Action about the correct function signature to use. Action any // Before executes before the app action or any sub-command action runs. Refer to // cli.Action about the correct function signature to use. Before any // After executes after the app action or any sub-command action runs. // Refer to cli.Action about the correct function signature to use. After any // Uses provides an action handler that is always executed during the initialization phase // of the app. Typically, hooks and other configuration actions are added to this handler. // Actions within the Uses and Before pipelines can modify the app Commands and Flags lists. Any // commands or flags added to the list will be initialized Uses any // Category places the command into a category. Categories are displayed on the default // help screen. Category string // Description provides a long description for the command. The long description is // displayed on the help screen. The type of Description should be string or // fmt.Stringer. Refer to func Description for details. Description any // Comment provides a short descriptive comment. This is // usually a few words to summarize the purpose of the command. Comment string // Data provides an arbitrary mapping of additional data. This data can be used by // middleware and it is made available to templates Data map[string]any // Options sets common options for use with the command Options Option // HelpText describes the help text displayed for commands HelpText string // ManualText provides the text shown in the manual. The default templates don't use this value ManualText string // UsageText provides the usage for the command. If left blank, a succinct synopsis // is generated that lists each visible flag and arg UsageText string // Completion provides the completion for use in the command. By default, the // completion detects whether a flag or arg is being used and then delegates to // the completion present there Completion Completion // contains filtered or unexported fields }
Command represents a command with arguments, flags, and expressions
By default, if a command name starts with an underscore, it is hidden. To stop this, either set Visible option explicitly or disable global behavior with the DisableAutoVisibility option.
Within a command, all args and flags must have unique names. The behavior is not defined if a flag alias is duplicative, but no flag can have the same name as one of the aliases. If a flag name is blank, this is an error; however, if an arg name is blank, it is implicitly given a name using its index.
func (*Command) LookupData ¶
LookupData obtains the data if it exists
func (*Command) Synopsis ¶
Synopsis returns the UsageText for the command or produces a succinct representation that names each flag and arg
func (*Command) VisibleArgs ¶
VisibleArgs filters all arguments in the command by whether they are not hidden
func (*Command) VisibleFlags ¶
VisibleFlags filters all flags in the command by whether they are not hidden
func (*Command) VisibleSubcommands ¶
VisibleSubcommands filters all sub-commands in the command by whether they are not hidden
type Completion ¶
type Completion interface {
Complete(context.Context) []CompletionItem
}
Completion is the shell auto-complete function for the flag, arg, or value
func CompletionValues ¶
func CompletionValues(values ...string) Completion
CompletionValues provides the context-specific completion values for the given strings. This can be specified as the Completion for flags or args. For flags, the name of the flag is automatically prefixed to the completion value using valid syntax.
type CompletionFunc ¶
type CompletionFunc func(*Context) []CompletionItem
CompletionFunc provide a function that can be used as a Completer
func (CompletionFunc) Complete ¶
func (f CompletionFunc) Complete(c context.Context) []CompletionItem
type CompletionItem ¶
type CompletionItem struct { Type CompletionType Value string HelpText string // PreventSpaceAfter disables the addition of a space after the completion token PreventSpaceAfter bool }
CompletionItem defines an item displayed in the completion results
type CompletionRequest ¶
type CompletionRequest struct { // Args that have been passed to the command so far Args []string // Incomplete the token that is incomplete being completed Incomplete string // Bindings gets the bindings that were partially parsed Bindings BindingMap // Err gets the error that occurred during parsing, likely *ParserError Err error }
CompletionRequest provides information about the completion request
type CompletionType ¶
type CompletionType int
CompletionType enumerates the supported kinds of completions
const ( CompletionTypeToken CompletionType = iota CompletionTypeFile CompletionTypeDirectory )
Completion types
type Context ¶
type Context struct { // Stdout is the output writer to Stdout Stdout Writer // Stderr is the output writer to Stderr Stderr Writer // Stdin is the input reader Stdin io.Reader // FS is the file system used by the context. // If the FS implements func OpenContext(context.Context, string)(fs.File, error), note that // this will be called instead of Open in places where the Context is available. // For os.File this means that if the context has a Deadline, SetReadDeadline // and/or SetWriteDeadline will be set. Clients can implement similar functions in their // own fs.File implementations provided from an FS implementation. FS fs.FS // contains filtered or unexported fields }
Context provides the context in which the app, command, or flag is executing or initializing. Context is used to facilitate interactions with the Joe-cli application context that is currently being initialized or executed. It wraps context.Context and can be obtained from FromContext
func FromContext ¶
FromContext obtains the Context, which faciliates interactions with the application that is initializing or running. If the argument is nil, the return value will be. Otherwise, if it can't be found, it panics
func (*Context) Action ¶
Action either stores or executes the action. When called from the initialization or before pipelines, this appends the action to the pipeline for the current flag, arg, or command/app. When called from the action pipeline, this simply causes the action to be invoked immediately.
func (*Context) AddAlias ¶
AddAlias adds one or more aliases to the current command or flag. For other targets, this operation is ignored. An error is returned if this is called after initialization.
func (*Context) AddArg ¶
AddArg provides a convenience method that adds an Arg to the current command or app. This is only valid during the initialization phase. An error is returned for other timings. Args can also be added to a value which has been provided to a value initializer (see ProvideValueInitializer)
func (*Context) AddArgs ¶
AddArgs provides a convenience method for adding args to the current command or app. Args can also be added to a value which has been provided to a value initializer (see ProvideValueInitializer)
func (*Context) AddCommand ¶
AddCommand provides a convenience method that adds a Command to the current command or app. This is only valid during the initialization phase. An error is returned for other timings.
func (*Context) AddCommands ¶
AddCommands provides a convenience method for adding commands to the current command or app.
func (*Context) AddFlag ¶
AddFlag provides a convenience method that adds a flag to the current command or app. This is only valid during the initialization phase. An error is returned for other timings.
func (*Context) AddFlags ¶
AddFlags provides a convenience method for adding flags to the current command or app.
func (*Context) After ¶
After either stores or executes the action. When called from the initialization, before, or action pipelines, this appends the action to the After pipeline for the current flag, arg, expression, or command/app. If called from the After pipeline itself, the action is invoked immediately
func (*Context) Aliases ¶
Aliases obtains the aliases for the current command or flag; otherwise, for args it is nill
func (*Context) Args ¶
Args retrieves the arguments. IF the context corresponds to a command, these represent the name of the command plus the arguments passed to it. For flags and arguments, this is the value passed to them
func (*Context) AutodetectColor ¶
func (c *Context) AutodetectColor()
AutodetectColor causes terminal color and styles to automatically detect support for stdout. Auto-detection is the default behavior, but this is provided to reset if SetColor has modified.
func (*Context) Before ¶
Before either stores or executes the action. When called from the initialization pipeline, this appends the action to the Before pipeline for the current flag, arg, expression, or command/app. If called from the Before pipeline, this causes the action to be invoked immediately. If called at any other time, this causes the action to be ignored and an error to be returned.
func (*Context) BigFloat ¶
BigFloat obtains a value by the name of the flag, arg, or other value in scope
func (*Context) BigInt ¶
BigInt obtains a value by the name of the flag, arg, or other value in scope
func (*Context) BindingLookup ¶
func (c *Context) BindingLookup() BindingLookup
BindingLookup returns the parse data for the context. Note that this lookup only applies to the current context and does not traverse inherited contexts. Compare Raw and RawOccurrences which perform this for you.
func (*Context) Command ¶
Command obtains the command. The command could be a synthetic command that was created to represent the root command of the app.
func (*Context) Complete ¶
func (c *Context) Complete(args []string, incomplete string) []CompletionItem
Complete considers the given arguments and completion request to determine completion items
func (*Context) Completion ¶
func (c *Context) Completion() Completion
Completion obtains the completion for the current target.
func (*Context) CompletionRequest ¶
func (c *Context) CompletionRequest() *CompletionRequest
CompletionRequest gets the completion request from the context if a completion is being requested.
func (*Context) ContextOf ¶
ContextOf creates a context for use with the given target, which must be a flag, arg, or sub-command, or it must be the name of a flag or arg (using the typing and rules of LookupFlag and LookupArg). This method does not check whether the target is actually in the scope of the current target. The result could be nil if the name or index does not exist.
func (*Context) Customize ¶
Customize matches a flag, arg, or command and runs additional pipeline steps. Customize is usually used to apply further customization after an extension has done setup of the defaults. As a special case, if pattern is the empty string, this is the same as calling Use, because it pertains to the current target.
During the initialization process, the customization action will be run for each matching flag, arg, or command. As a special case, if the flag or arg is created or changes its name during its own initialization process, customizations will be re-run on it.
func (*Context) Description ¶
Description obtains the description for the current target.
func (*Context) Do ¶
Do executes the specified actions in succession. If an action returns an error, that error is returned and the rest of the actions aren't run
func (*Context) Duration ¶
Duration obtains a value by the name of the flag, arg, or other value in scope
func (*Context) ExecuteTemplate ¶
ExecuteTemplate provides an action that renders the specified template using the factory function that creates the data that is passed to the template
func (*Context) FileSet ¶
FileSet obtains a value by the name of the flag, arg, or other value in scope
func (*Context) FindTarget ¶
func (c *Context) FindTarget(path ContextPath) (res *Context, ok bool)
FindTarget finds the given target corresponding to the context path.
func (*Context) Flags ¶
Flags obtains the flags from the command, including persistent flags which were defined by ancestor commands. If the current context is not a command, this is nil. Compare Flags, PersistentFlags, and LocalFlags.
func (*Context) Float32 ¶
Float32 obtains a value by the name of the flag, arg, or other value in scope
func (*Context) Float64 ¶
Float64 obtains a value by the name of the flag, arg, or other value in scope
func (*Context) Fprint ¶
Fprint formats using the default formats for its operands and writes to a file using the behavior of fmt.Fprint. As a special case, if writer is nil, [Context.Stderr] is used.
func (*Context) Fprintf ¶
Fprintf formats according to a format specifier and writes to a file using the behavior of fmt.Fprintf As a special case, if writer is nil, [Context.Stderr] is used.
func (*Context) Fprintln ¶
Fprintln formats using the default formats for its operands and writes to a file using the behavior of fmt.Fprintln As a special case, if writer is nil, [Context.Stderr] is used.
func (*Context) HookAfter ¶
HookAfter registers a hook that runs for the matching elements. See ContextPath for the syntax of patterns and how they are matched.
func (*Context) HookBefore ¶
HookBefore registers a hook that runs for the matching elements. See ContextPath for the syntax of patterns and how they are matched.
func (*Context) ImplicitlySet ¶
ImplicitlySet returns true if the flag or arg was implicitly set.
func (*Context) Interface ¶
Interface obtains a value by the name of the flag, arg, or other value in scope
func (*Context) IsAction ¶
IsAction returns true if the context represents actions running for the actual execution of the command
func (*Context) IsAfter ¶
IsAfter returns true if the context represents actions running after executing the command
func (*Context) IsBefore ¶
IsBefore returns true if the context represents actions running before executing the command
func (*Context) IsCommand ¶
IsCommand tests whether the last segment of the path represents a command
func (*Context) IsInitializing ¶
IsInitializing returns true if the context represents initialization
func (*Context) Lineage ¶
Lineage retrieves all of the ancestor contexts up to the root. The result contains the current context and all contexts up to the root.
func (*Context) LocalArgs ¶
LocalArgs obtains the args from the command or value target. If the current context is not a command or value target, this is nil.
func (*Context) LocalFlags ¶
LocalFlags obtains the flags from the command. If the current context is not a command, this is nil. Compare Flags, PersistentFlags, and LocalFlags.
func (*Context) LookupArg ¶
LookupArg finds the arg by name. The name can be a string, rune, or *Arg
func (*Context) LookupCommand ¶
LookupCommand finds the command by name. The name can be a string or *Command
func (*Context) LookupData ¶
LookupData gets the data matching the key, including recursive traversal up the lineage contexts
func (*Context) LookupFlag ¶
LookupFlag finds the flag by name. The name can be a string, rune, or *Flag
func (*Context) LookupValueTarget ¶
LookupValueTarget finds the value formerly provided to a value initializer by name.
func (*Context) ManualText ¶
ManualText obtains the manualText for the current target.
func (*Context) Matches ¶
func (c *Context) Matches(f ContextFilter) bool
Matches detects if the given context filter matches the current context
func (*Context) Name ¶
Name gets the name of the context, which is the name of the command, arg, flag, or expression operator in use
func (*Context) NameValue ¶
NameValue obtains a value by the name of the flag, arg, or other value in scope
func (*Context) NameValues ¶
NameValues obtains a value by the name of the flag, arg, or other value in scope
func (*Context) NewBuffer ¶
func (c *Context) NewBuffer() *buffer
NewBuffer creates a buffer which is a Writer that can be used to accumulate text into a buffer. Color is enabled depending upon whether it has been enabled for stdout.
func (*Context) Occurrences ¶
Occurrences returns the number of times the specified flag or argument has been used This is -1 in the context of commands.
func (*Context) Path ¶
func (c *Context) Path() ContextPath
Path retrieves all of the names on the context and its ancestors to the root. If the root command had no name, it is implied name from os.Args.
func (*Context) PersistentFlags ¶
PersistentFlags locates the nearest command and obtains flags from its parent and ancestor commands. If the current context is not a command, this is nil. Compare Flags, PersistentFlags, and LocalFlags.
func (*Context) PreventSetup ¶
PreventSetup causes implicit setup options to be skipped. The function returns an error if the timing is not initial timing.
func (*Context) Print ¶
Print formats using the default formats for its operands and writes to standard output using the behavior of fmt.Print.
func (*Context) Printf ¶
Printf formats according to a format specifier and writes to standard output using the behavior of fmt.Printf
func (*Context) Println ¶
Println formats using the default formats for its operands and writes to standard output using the behavior of fmt.Println
func (*Context) ProvideValueInitializer ¶
ProvideValueInitializer causes an additional child context to be created which is used to initialize an arbitrary value. Typically, the value is the value of the flag or arg. Indeed, a pattern is to expose this action as the return value of a method Initializer()Action (refer to the overview in Value about methods implemented by values by convention).
The value can also provide methods such as SetDescription(string), SetHelpText(string), SetManualText(string), SetLocalArgs([]*Arg)error, SetAliases([]string), etc. in order to operate with actions that set these values.
If the value has local args (a method LocalArgs() []*Arg), then their pipelines are triggered.
func (*Context) Raw ¶
Raw gets the exact value which was passed to the arg, flag including the name that was used. Value can be the empty string if no value was passed
func (*Context) RawOccurrences ¶
RawOccurrences gets the exact value which was passed to the arg, flag excluding the name that was used. Value can be the empty string if no value was passed
func (*Context) ReadPasswordString ¶
ReadPasswordString securely gets a password, without the trailing '\n'. An error will be returned if the reader is not stdin connected to TTY.
func (*Context) ReadString ¶
ReadString securely gets a password, without the trailing '\n'. An error will be returned if the reader is not stdin connected to TTY.
func (*Context) Regexp ¶
Regexp obtains a value by the name of the flag, arg, or other value in scope
func (*Context) RegisterTemplate ¶
RegisterTemplate will register the specified template by name. The nested templates defined within the template will also be registered, replacing any templates that were previously defined. If the template definition only contains nested template definitions, name should be left blank.
func (*Context) RegisterTemplateFunc ¶
RegisterTemplateFunc will register the specified function for use in template rendering. Templates are stored globally at the application level. Though part of its signature, this function never returns an error.
func (*Context) RemoveAlias ¶
RemoveAlias removes the given alias from the current command or flag. For other targets, this operation is ignored. An error is returned if this is caleld after initialization.
func (*Context) RemoveArg ¶
RemoveArg provides a convenience method that removes an Arg from the current command or app. The name specifies the name, index, or actual arg. This is only valid during the initialization phase. An error is returned for other timings. If the arg does not exist, if the name or index is out of bounds, the operation will still succeed.
func (*Context) RemoveCommand ¶
RemoveCommand provides a convenience method that removes a command from the current command or app. The name specifies the name or actual command. This is only valid during the initialization phase. An error is returned for other timings. If the Command does not exist, if the name or index is out of bounds, the operation will still succeed.
func (*Context) RemoveFlag ¶
RemoveFlag provides a convenience method that removes a Flag from the current command or app. The name specifies the name, index, or actual flag. This is only valid during the initialization phase. An error is returned for other timings. If the flag does not exist, if the name or index is out of bounds, the operation will still succeed.
func (*Context) Seen ¶
Seen returns true if the specified flag or argument has been used at least once. This is false in the context of commands.
func (*Context) SetCategory ¶
SetCategory sets the category on the current target
func (*Context) SetContext ¶
SetContext sets the context
func (*Context) SetContextValue ¶
SetContextValue updates the context with a value.
func (*Context) SetData ¶
SetData sets data on the current target. Despite the return value, this method never returns an error.
func (*Context) SetDescription ¶
SetDescription sets the description on the current target
func (*Context) SetHelpText ¶
SetHelpText sets the help text on the current target
func (*Context) SetManualText ¶
SetManualText sets the manualText on the current target
func (*Context) SetOptionalValue ¶
SetOptionalValue sets the optional value for the flag
func (*Context) SetTransform ¶
func (c *Context) SetTransform(fn TransformFunc) error
SetTransform sets the transform for the current flag or arg. For other targets, this operation is ignored. An error is returned if this is called after initialization.
func (*Context) SetUsageText ¶
SetUsageText sets the usage text on the current target
func (*Context) SetValue ¶
SetValue checks the timing and sets the value of the current flag or arg. This method can be called at any time to set the value; however, if the current timing is the ImplicitValueTiming, calling this method will return ErrImplicitValueAlreadySet for the second and subsequent invocations of this method. Clients typically ignore this error and don't bubble it up as a usage error, or they can check ImplicitlySet() to preempt it. Note that you can always set the value on the Arg or Flag directly with no checks for these timing semantics.
func (*Context) SkipImplicitSetup ¶
SkipImplicitSetup gets whether implicit setup steps should be skipped
func (*Context) String ¶
String obtains a value by the name of the flag, arg, or other value in scope
func (*Context) Target ¶
Target retrieves the target of the context, which is *App, *Command, *Flag, *Arg, or *Expr
func (*Context) Trigger ¶
Trigger marks a flag or arg action to be triggered. Generally, a flag or arg Action is only triggered if it is set or if it or its parent command is marked with ImpliedAction. To mark the Action to be triggered for some other reason, you can use this action.
func (*Context) Uint16 ¶
Uint16 obtains a value by the name of the flag, arg, or other value in scope
func (*Context) Uint32 ¶
Uint32 obtains a value by the name of the flag, arg, or other value in scope
func (*Context) Uint64 ¶
Uint64 obtains a value by the name of the flag, arg, or other value in scope
func (*Context) Use ¶
Use can only be used during initialization timing, in which case the action is just invoked. In other timings, this is an error
func (*Context) Value ¶
Value obtains the value of the flag or argument with the specified name. If name is the empty string or nil, this is interpreted as using the name of whatever is the current context flag or argument. The name can also be one of several other types:
- rune - corresponds to the short name of a flag
- int - obtain the argument by index
- *Arg - get value of the arg
- *Flag - get value of the flag
All other types are delegated to the underlying Context. This implies that you can only use your own (usually unexported) hashable type when setting up keys in the context.Context. (This is the recommended practice in any case, but it is made explicit by how this method works.)
func (*Context) ValueContextOf ¶
ValueContextOf creates a context for the use with values that may have initialization steps.
func (*Context) Walk ¶
Walk traverses the hierarchy of commands. The provided function fn is called once for each command that is encountered. If fn returns an error, the traversal stops and the error is returned; however, the specialized return value SkipCommand indicates that traversal skips the sub-commands of the current command and continues.
type ContextFilter ¶
ContextFilter is used to implement logic for filtering on matching contexts. The main use case is conditional actions using the IfMatch decorator.
func PatternFilter ¶
func PatternFilter(pat string) ContextFilter
PatternFilter parses a context pattern string and returns a filter which matches on it.
type ContextFilterFunc ¶
ContextFilterFunc provides a predicate function which detects whether the context applies.
type ContextPath ¶
type ContextPath []string
ContextPath provides a list of strings that name each one of the parent components in the context. Each string follows the form:
command a command matching the name "command" -flag a flag matching the flag name <arg> an argument matching the arg name
func (ContextPath) IsArg ¶
func (c ContextPath) IsArg() bool
IsArg tests whether the last segment of the path represents an argument
func (ContextPath) IsCommand ¶
func (c ContextPath) IsCommand() bool
IsCommand tests whether the last segment of the path represents a command
func (ContextPath) IsExpr ¶
func (c ContextPath) IsExpr() bool
IsExpr tests whether the last segment of the path represents an expression
func (ContextPath) IsFlag ¶
func (c ContextPath) IsFlag() bool
IsFlag tests whether the last segment of the path represents a flag
func (ContextPath) Match ¶
func (c ContextPath) Match(pattern string) bool
func (ContextPath) String ¶
func (c ContextPath) String() string
String converts the context path to a string
type ExitCoder ¶
ExitCoder is an error that knows how to convert to its exit code
func Exit ¶
Exit formats an error message using the default formats for each of the arguments, except the last one, which is interpreted as the desired exit code. The function provides similar semantics to fmt.Sprint in that all values are converted to text and joined together. Spaces are added between operands when neither is a string. If the last argument is an integer, it is interpreted as the exit code that will be generated when the program exits. If no integer is present, the value 1 is used.
type FS ¶
type FS interface { fs.FS fs.StatFS Chmod(name string, mode fs.FileMode) error Chown(name string, uid, gid int) error Create(name string) (fs.File, error) Mkdir(name string, perm fs.FileMode) error MkdirAll(path string, perm fs.FileMode) error OpenFile(name string, flag int, perm fs.FileMode) (fs.File, error) Remove(name string) error RemoveAll(path string) error Chtimes(name string, atime time.Time, mtime time.Time) error Rename(oldpath, newpath string) error OpenContext(context.Context, string) (fs.File, error) }
FS provides a read-write file system. In addition to the read-only behavior of io/fs.FS, it provides all the semantics available from the package os. To obtain an instance for the file system provided by package os, use DirFS. The io/fs.File value returned from any of the methods of this interface can also provide corresponding methods. For example, because FS defines Remove(string), the File implementation returned from Open or OpenFile can also implement the method Remove().
Though it implements fs.FS, implementers do not abide the restrictions for path name validations required by io/fs.FS.Open(). In particular, starting and trailing slashes in path names are allowed, which allows rooted files to be referenced. (These are the semantics of os.Open, etc.)
type FeatureMap ¶
FeatureMap provides a map from a feature identifier to an action. A common idiom within joe-cli is to define a bitmask representing
func (FeatureMap[T]) Pipeline ¶
func (m FeatureMap[T]) Pipeline(values T) Action
type File ¶
type File struct { // Name is the name of the file Name string // FS specifies the file system that is used for the file. If not specified, it provides a // default file system based upon the os package, which has the additional behavior that it treats the name "-" // specially as a file that reads and seeks from Stdin and writes to Stdout, FS fs.FS }
File provides a value that can be used to represent a file path in flags or arguments.
func (*File) Completion ¶
func (f *File) Completion() Completion
Completion gets the completion for files
func (*File) Initializer ¶
Initializer obtains the initializer for the File, which is used to setup the file system used
func (*File) OpenContext ¶
OpenContext is used to open the file with the given context
type FileSet ¶
type FileSet struct { // Recursive determines whether iteration over the file set by // Do or All recursively opens directories Recursive bool // Files provides the files named in the file set. These can be files or // directories Files []string // FS is the file system used to open files FS fs.FS }
FileSet provides a list of files and/or directories and whether the scope of the file set is recursive. A FileSet can also be read-in from a reader using the SetData method. The format is a list of file names, with blank lines or lines starting with comment characters being skipped. Comment characters are # and ;.
func (*FileSet) Completion ¶
func (f *FileSet) Completion() Completion
Completion gets the completion for files
func (*FileSet) Do ¶
Do will invoke the given function on each file in the set. If recursion is enabled, it will recurse directories and process on each file encountered.
func (*FileSet) Initializer ¶
Initializer obtains the initializer for the FileSet, which is used to setup the file system used
func (*FileSet) NewCounter ¶
func (f *FileSet) NewCounter() ArgCounter
NewCounter obtains the arg counter for file sets, which is implied to be TakeUntilNextFlag
func (*FileSet) RecursiveFlag ¶
RecursiveFlag obtains a conventions-based flag for making the file set recursive.
func (*FileSet) SetData ¶
SetData reads in a list of paths from a reader. Blank lines and comment lines (using ; or #) will be ignored. Whitespace is trimmed.
func (*FileSet) SetRecursive ¶
SetRecursive updates the file set Recursive field. This is generally meant to be used with BindIndirect. Never returns an error.
type FilterModes ¶
type FilterModes int
FilterModes enumerates common context filters. These are bitwise-combinable.
const ( // AnyFlag filters the context for any flag AnyFlag FilterModes = 1 << iota // AnyArg filters the context for any arg AnyArg // AnyCommand filters the context for any command AnyCommand // Seen filters the context to detect if the current flag or arg has been seen Seen // RootCommand filters the context to detect if the current command is the root command RootCommand // HasValue checks whether the target is an arg, flag, or value setup HasValue // Anything matches any kind of target Anything = AnyFlag | AnyArg | AnyCommand )
func (FilterModes) Describe ¶
func (f FilterModes) Describe() string
Describe produces a representation of the timing suitable for use in messages
func (FilterModes) MarshalText ¶
func (f FilterModes) MarshalText() ([]byte, error)
MarshalText provides the textual representation
func (FilterModes) String ¶
func (f FilterModes) String() string
String produces a textual representation of the timing
func (*FilterModes) UnmarshalText ¶
func (f *FilterModes) UnmarshalText(b []byte) error
UnmarshalText converts the textual representation
type Flag ¶
type Flag struct { // Name provides the name of the flag. This value must be set, and it is used to access // the flag's value via the context Name string // Aliases provides a list of alternative names for the flag. In general, Name should // be used for the long name of the flag, and Aliases should contain the short name. // If there are additional names for compatibility reasons, they should be included // with Aliases but listed after the preferred names. Note that only one short name // and one long name is displayed on help screens by default. Aliases []string // HelpText contains text which briefly describes the usage of the flag. If it contains // placeholders in the form {PLACEHOLDER}, then these name the purpose of the flag's // value. If a flag has multiple values, then placeholders can also specify the index of // the corresponding value using the syntax {0:PLACEHOLDER}; otherwise, the order is // inferred start to end. // For style, generally the usage text should be limited to about 40 characters. // Sentence case is recommended for the usage text. Uppercase is recommended for the // text of placeholders. The placeholder is used in the synopsis for the flag as well // as error messages. HelpText string // ManualText provides the text shown in the manual. The default templates don't use this value ManualText string // UsageText provides the usage for the flag. If left blank, a succinct synopsis // is generated from the type of the flag's value UsageText string // EnvVars specifies the name of environment variables that are read to provide the // default value of the flag. EnvVars []string // FilePath specifies a file that is loaded to provide the default value of the flag. FilePath string // Value provides the value of the flag. Any of the following types are valid for the // value: // // * *bool // * *time.Duration // * *float32 // * *float64 // * *int // * *int16 // * *int32 // * *int64 // * *int8 // * *net.IP // * *[]string // * *map[string]string // * **regexp.Regexp // * *string // * *uint // * *uint16 // * *uint32 // * *uint64 // * *uint8 // * **url.URL // * an implementation of Value interface // // If unspecified, the value will be a string pointer. // For more information about Values, see the Value type Value any // DefaultText provides a description of the default value for the flag. This is displayed // on help screens but is otherwise unused DefaultText string // Options sets various options about how to treat the flag. For example, options can // hide the flag or make its value optional. Options Option // Category specifies the flag category. When categories are used, flags are grouped // together on the help screen Category string // Description provides a long description for the flag. The long description is // not used in any templates by default. The type of Description should be string or // fmt.Stringer. Refer to func Description for details. Description any // Data provides an arbitrary mapping of additional data. This data can be used by // middleware and it is made available to templates Data map[string]any // Before executes before the command runs. Refer to cli.Action about the correct // function signature to use. Before any // After executes after the command runs. Refer to cli.Action about the correct // function signature to use. After any // Uses provides an action handler that is always executed during the initialization phase // of the app. Typically, hooks and other configuration actions are added to this handler. Uses any // Action executes if the flag was set. Refer to cli.Action about the correct // function signature to use. Action any // Completion specifies a callback function that determines the auto-complete results Completion Completion // Transform defines how to interpret the text passed to the *Flag. This is generally used // when specialized syntax preprocesses the text, such as file references. Refer to the // overview in cli.Transform for information. Transform TransformFunc // contains filtered or unexported fields }
Flag represents a command line flag. The only required attribute that must be set is Name. By default, the type of a flag is string; however, to use a more specific type you must either specify a pointer to a variable or use the built-in constants that identify the type to use:
&Flag{ Name: "age", Value: &age, // var age int -- defined somewhere in scope } &Flag{ Name: "age", Value: cli.Int(), // also sets int }
The corresponding, typed method to access the value of the flag by name is available from the Context. In this case, you can obtain value of the --age=21 flag using Context.Int("flag"), which may be necessary when you don't use your own variable.
By default, if a flag name starts with an underscore, it is hidden. To stop this, either set Visible option explicitly or disable global behavior with the DisableAutoVisibility option.
func (*Flag) LongName ¶
LongName gets the long name for the flag including the leading dashes. This is the Name of the flag if it contains more than one character, or this is the first alias which contains more than one character. If the Name and all Aliases have exactly one character, then the value of Name is returned even if it has exactly one character. Note that even in this case, the result starts with two leading dashes.
func (*Flag) LookupData ¶
LookupData obtains the data if it exists
func (*Flag) Names ¶
Names obtains the name of the flag and its aliases, including their leading dashes.
func (*Flag) Occurrences ¶
Occurrences returns the number of times the flag was specified on the command line
func (*Flag) SetData ¶
SetData sets the specified metadata on the flag. When v is nil, the corresponding metadata is deleted
func (*Flag) SetOccurrence ¶
SetOccurrence will update the value of the flag
func (*Flag) SetOccurrenceData ¶
SetOccurrenceData will update the value of the flag
func (*Flag) SetRequired ¶
SetRequired causes the flag to be required
func (*Flag) ShortName ¶
ShortName gets the short name for the flag including the leading dash. This is the Name of the flag if it contains exactly one character, or this is the first alias which contains exactly one character. This is the empty string if the name and all aliases are long names. The result starts with a dash.
type InternalError ¶
type InternalError struct { // Path describes the path where the internal error occurred Path ContextPath // Timing specifies when the error is occurring Timing Timing // Err returns the internal error Err error }
InternalError represents an error that has occurred because of the way the library is used rather than a user parse error. An example of this is ErrTimingTooLAte, which has occurred because an action was added to pipeline that wasn't acceptable.
func (*InternalError) Error ¶
func (i *InternalError) Error() string
func (*InternalError) Unwrap ¶
func (i *InternalError) Unwrap() error
type Lookup ¶
type Lookup interface { // Bool obtains the value and converts it to a bool Bool(name any) bool // File obtains the value and converts it to a File File(name any) *File // FileSet obtains the value and converts it to a FileSet FileSet(name any) *FileSet // Float32 obtains the value and converts it to a float32 Float32(name any) float32 // Float64 obtains the value and converts it to a float64 Float64(name any) float64 // Int obtains the value and converts it to a int Int(name any) int // Int16 obtains the value and converts it to a int16 Int16(name any) int16 // Int32 obtains the value and converts it to a int32 Int32(name any) int32 // Int64 obtains the value and converts it to a int64 Int64(name any) int64 // Int8 obtains the value and converts it to a int8 Int8(name any) int8 // Duration obtains the value and converts it to a Duration Duration(name any) time.Duration // List obtains the value and converts it to a slice of strings List(name any) []string // Map obtains the value and converts it to a map Map(name any) map[string]string // NameValue obtains the value and converts it to a name-value pair NameValue(name any) *NameValue // NameValues obtains the value and converts it to a list of name-value pairs NameValues(name any) []*NameValue // String obtains the value and converts it to a string String(name any) string // Uint obtains the value and converts it to a uint Uint(name any) uint // Uint16 obtains the value and converts it to a uint16 Uint16(name any) uint16 // Uint32 obtains the value and converts it to a uint32 Uint32(name any) uint32 // Uint64 obtains the value and converts it to a uint64 Uint64(name any) uint64 // Uint8 obtains the value and converts it to a uint8 Uint8(name any) uint8 // Value obtains the value and converts it to Value Value(name any) any // URL obtains the value and converts it to a URL URL(name any) *url.URL // Regexp obtains the value and converts it to a Regexp Regexp(name any) *regexp.Regexp // IP obtains the value and converts it to a IP IP(name any) net.IP // BigInt obtains the value and converts it to a BigInt BigInt(name any) *big.Int // BigFloat obtains the value and converts it to a BigFloat BigFloat(name any) *big.Float // Bytes obtains the value and converts it to a slice of bytes Bytes(name any) []byte // Interface returns the raw value without dereferencing and whether it exists Interface(name any) (any, bool) }
Lookup provides type conversion from the various built-in types supported by the framework. For each method, the name is either a string, rune, *Arg, or *Flag corresponding to the name of the argument or flag.
type LookupFunc ¶
LookupFunc provides a Lookup that converts from a name to a value.
func (LookupFunc) Bool ¶
func (c LookupFunc) Bool(name any) bool
func (LookupFunc) Bytes ¶
func (c LookupFunc) Bytes(name any) []byte
func (LookupFunc) File ¶
func (c LookupFunc) File(name any) *File
func (LookupFunc) FileSet ¶
func (c LookupFunc) FileSet(name any) *FileSet
func (LookupFunc) Float32 ¶
func (c LookupFunc) Float32(name any) float32
func (LookupFunc) Float64 ¶
func (c LookupFunc) Float64(name any) float64
func (LookupFunc) Int ¶
func (c LookupFunc) Int(name any) int
func (LookupFunc) Int16 ¶
func (c LookupFunc) Int16(name any) int16
func (LookupFunc) Int32 ¶
func (c LookupFunc) Int32(name any) int32
func (LookupFunc) Int64 ¶
func (c LookupFunc) Int64(name any) int64
func (LookupFunc) Int8 ¶
func (c LookupFunc) Int8(name any) int8
func (LookupFunc) List ¶
func (c LookupFunc) List(name any) []string
func (LookupFunc) NameValue ¶
func (c LookupFunc) NameValue(name any) *NameValue
func (LookupFunc) NameValues ¶
func (c LookupFunc) NameValues(name any) []*NameValue
func (LookupFunc) String ¶
func (c LookupFunc) String(name any) string
func (LookupFunc) Uint ¶
func (c LookupFunc) Uint(name any) uint
func (LookupFunc) Uint16 ¶
func (c LookupFunc) Uint16(name any) uint16
func (LookupFunc) Uint32 ¶
func (c LookupFunc) Uint32(name any) uint32
func (LookupFunc) Uint64 ¶
func (c LookupFunc) Uint64(name any) uint64
func (LookupFunc) Uint8 ¶
func (c LookupFunc) Uint8(name any) uint8
func (LookupFunc) Value ¶
func (c LookupFunc) Value(name any) any
type LookupValues ¶
LookupValues provides a Lookup backed by a map
func (LookupValues) BigFloat ¶
func (c LookupValues) BigFloat(name any) *big.Float
BigFloat obtains the BigFloat for the specified name
func (LookupValues) BigInt ¶
func (c LookupValues) BigInt(name any) *big.Int
BigInt obtains the BigInt for the specified name
func (LookupValues) Bool ¶
func (c LookupValues) Bool(name any) bool
Bool obtains the value and converts it to a bool
func (LookupValues) Bytes ¶
func (c LookupValues) Bytes(name any) []byte
Bytes obtains the bytes for the specified name
func (LookupValues) Duration ¶
func (c LookupValues) Duration(name any) time.Duration
Duration obtains the Duration for the specified name
func (LookupValues) File ¶
func (c LookupValues) File(name any) *File
File obtains the File for the specified name
func (LookupValues) FileSet ¶
func (c LookupValues) FileSet(name any) *FileSet
FileSet obtains the FileSet for the specified name
func (LookupValues) Float32 ¶
func (c LookupValues) Float32(name any) float32
Float32 obtains the float32 for the specified name
func (LookupValues) Float64 ¶
func (c LookupValues) Float64(name any) float64
Float64 obtains the float64 for the specified name
func (LookupValues) IP ¶
func (c LookupValues) IP(name any) net.IP
IP obtains the IP for the specified name
func (LookupValues) Int ¶
func (c LookupValues) Int(name any) int
Int obtains the int for the specified name
func (LookupValues) Int16 ¶
func (c LookupValues) Int16(name any) int16
Int16 obtains the int16 for the specified name
func (LookupValues) Int32 ¶
func (c LookupValues) Int32(name any) int32
Int32 obtains the int32 for the specified name
func (LookupValues) Int64 ¶
func (c LookupValues) Int64(name any) int64
Int64 obtains the int64 for the specified name
func (LookupValues) Int8 ¶
func (c LookupValues) Int8(name any) int8
Int8 obtains the int8 for the specified name
func (LookupValues) Interface ¶
func (c LookupValues) Interface(name any) (any, bool)
Interface obtains the raw value without dereferencing
func (LookupValues) List ¶
func (c LookupValues) List(name any) []string
List obtains the value and converts it to a string slice
func (LookupValues) Map ¶
func (c LookupValues) Map(name any) map[string]string
Map obtains the map for the specified name
func (LookupValues) NameValue ¶
func (c LookupValues) NameValue(name any) *NameValue
NameValue obtains the value and converts it to a name-value pair
func (LookupValues) NameValues ¶
func (c LookupValues) NameValues(name any) []*NameValue
NameValues obtains the value and converts it to a list of name-value pairs
func (LookupValues) Regexp ¶
func (c LookupValues) Regexp(name any) *regexp.Regexp
Regexp obtains the Regexp for the specified name
func (LookupValues) String ¶
func (c LookupValues) String(name any) string
String obtains the value and converts it to a string
func (LookupValues) URL ¶
func (c LookupValues) URL(name any) *url.URL
URL obtains the URL for the specified name
func (LookupValues) Uint ¶
func (c LookupValues) Uint(name any) uint
Uint obtains the uint for the specified name
func (LookupValues) Uint16 ¶
func (c LookupValues) Uint16(name any) uint16
Uint16 obtains the uint16 for the specified name
func (LookupValues) Uint32 ¶
func (c LookupValues) Uint32(name any) uint32
Uint32 obtains the uint32 for the specified name
func (LookupValues) Uint64 ¶
func (c LookupValues) Uint64(name any) uint64
Uint64 obtains the uint64 for the specified name
func (LookupValues) Uint8 ¶
func (c LookupValues) Uint8(name any) uint8
Uint8 obtains the uint8 for the specified name
func (LookupValues) Value ¶
func (c LookupValues) Value(name any) any
Value obtains the value and converts it to Value
type Middleware ¶
type Middleware interface { Action // ExecuteWithNext will execute the action and invoke Execute on the next // action ExecuteWithNext(context.Context, Action) error }
Middleware provides an action which controls how and whether the next action in the pipeline is executed
type NameValue ¶
type NameValue struct { // Name in the name-value pair Name string // Value in the name-value pair Value string // AllowFileReference indicates whether the @file syntax is allowed for the value, which // is automatically loaded as a value. AllowFileReference bool }
NameValue encapsulates a name-value pair. This is a flag value specified using the syntax name=value. When only the name is specified, this is interpreted as setting value to the constant true. This allows disambiguating the syntax name= explicitly setting value to blank.
func (*NameValue) AllowFileReferencesFlag ¶
AllowFileReferencesFlag obtains a flag configuration for setting the AllowFileReferences value
func (*NameValue) Initializer ¶
func (*NameValue) NewCounter ¶
func (v *NameValue) NewCounter() ArgCounter
func (*NameValue) SetAllowFileReference ¶
SetAllowFileReference sets whether file references are allowed. This function is for bindings
type Option ¶
type Option int
Option provides a built-in convenience configuration for flags, args, and commands.
func (Option) MarshalText ¶
MarshalText provides the textual representation
func (*Option) UnmarshalText ¶
UnmarshalText converts the textual representation
type ParseError ¶
type ParseError struct { // Code is the code to use. Code ErrorCode // Err is the internal error, if any Err error // Name specifies the name of the flag, arg, command, or expression that // caused the error Name string // Value is the value that caused the error Value string // Remaining contains arguments which could not be parsed Remaining []string }
ParseError provides the common representation of errors during parsing
func (*ParseError) Error ¶
func (e *ParseError) Error() string
type Prototype ¶
type Prototype struct { Aliases []string Category string Data map[string]any DefaultText string Description any EnvVars []string FilePath string HelpText string ManualText string Name string Options Option UsageText string Value any Setup Setup Completion Completion NArg any }
Prototype implements an action which sets up a flag, arg, or command. The prototype copies its values to the corresponding target if they have not already been set. Irrelevant fields are not set and do not cause errors; for example, setting FilePath, Value, and EnvVars, for a Command prototype has no effect. Some values are merged rather than overwritten: Data, Options, EnvVars, and Aliases. If setup has been prevented with the PreventSetup action, the prototype will do nothing. The main use of prototype is in extensions to provide reasonable defaults
type Setup ¶
type Setup struct { Uses any Before any Action any After any // Optional causes setup to ignore timing errors. By default, Setup depends upon the // timing, which means that an error will occur if Setup is used within a timing context // that is later than the corresponding pipelines. For example, if you have Setup.Uses set, // this implies that the Setup can only be itself added to a Uses pipeline; if you add it // to a Before, Action, or After pipeline, an error will occur because it is too late to process // the pipeline set in Setup.Uses. Setting Optional to true will prevent this error. // // The common use case for this is to allow defining new actions by simply returning a Setup, and letting // the user of the new action decide which parts of Setup get used by allowing them to specify the // setup in the pipeline of their choice. In the example, if the user // assigned the action in the Action pipeline, this would imply that they don't care about the // initialization behavior the action provides. If the initialization is genuinely optional // (and not a usage error of the new action), it is appropriate to set Optional to true. Optional bool }
Setup provides simple initialization, typically used in Uses pipeline. The Setup action will add the specified actions to the Before, main, and After action and run the Uses action immediately.
type ShellComplete ¶
type ShellComplete interface { GetCompletionRequest() (args []string, incomplete string) SetOptions(map[string]string) FormatCompletions([]CompletionItem) string GetSourceTemplate() *Template }
ShellComplete provides the implementation of the shell-specific completion handler
type StandardCompletion ¶
type StandardCompletion int
StandardCompletion enumerates standard completion results
const ( // FileCompletion generates a list of files in the completion response FileCompletion StandardCompletion = iota // DirectoryCompletion generations a list of directories in the completion response DirectoryCompletion )
func (StandardCompletion) Complete ¶
func (s StandardCompletion) Complete(ctx context.Context) []CompletionItem
type Template ¶
type Template struct { *template.Template // Debug when set will render errors to stderr. This value is typically activated via the // environment variable CLI_DEBUG_TEMPLATES=1 Debug bool }
Template provides a wrapper around text templates to support some additional configuration
func (*Template) Bind ¶
Bind the template to its data for later execution. This generates a Stringer which can be called to get the contents later. A common use of binding the template is an argument to an arg or flag description.
type Timing ¶
type Timing int
Timing enumerates the timing of an action
const ( // InitialTiming which occurs during the Uses pipeline InitialTiming Timing = iota // BeforeTiming which occurs before the command executes BeforeTiming // ActionTiming which occurs for the primary action ActionTiming // AfterTiming which occurs after the command executes AfterTiming // ValidatorTiming represents timing that happens when values are being validated // for an arg or flag. This timing can be set with the At function which affects // the sort order of actions so that validation occurs before all other actions in Before // pipeline. When the action runs, the actual timing will be BeforeTiming. ValidatorTiming // ImplicitValueTiming represents timing that happens when an implied value is being // computed for an arg or flag. This timing can be set with the At function // which affects the sort order of actions so that implied value timing occurs just before // the action. When the action runs, the actual timing will be BeforeTiming. ImplicitValueTiming )
func (Timing) Describe ¶
Describe produces a representation of the timing suitable for use in messages
func (Timing) MarshalText ¶
MarshalText provides the textual representation
func (*Timing) UnmarshalText ¶
UnmarshalText converts the textual representation
type TransformFunc ¶
TransformFunc implements a transformation from raw occurrences, which customizes the behavior of parsing. The function can return string, []byte, or io.Reader.
func TransformFileReference ¶
func TransformFileReference(f fs.FS) TransformFunc
TransformFileReference obtains the transform for the given file system.
func TransformOptionalFileReference ¶
func TransformOptionalFileReference(f fs.FS) TransformFunc
TransformOptionalFileReference obtains the transform for the given file system to treat the input as a file. When the prefix @ is specified, the file is loaded and its contents are returned by the transform. For other cases where the prefix is not present, it is interpretted as a literal value. When f is nil, the file system is determined from the Context.
type ValidatorFunc ¶
ValidatorFunc defines an Action that applies a validation rule to the explicit raw occurrence values for a flag or argument.
type Value ¶
Value provides the interface for custom handling of arg and flag values. This is the same as flag.Value. Values can implement additional methods by convention which are called on the first occurrence of a value being set
DisableSplitting() called when the option has set the DisableSplitting option, which indicates that commas shouldn't be treated as list separators
Reset() called on first occurrence of setting a value. This can be used to reset lists to empty when the Merge option has not been set
Copy() when used in addition to Reset(), can be used to copy into a new value
NewCounter() ArgCounter if provided, this method is consulted to obtain the arg counter if NArg is unset
Initializer() Action obtains an initialization action for the value which is called after initialization of the flag or arg
Value() T obtains the actual value to return from a lookup, useful when flag.Value is a wrapper. (the underlying value T is used)
Synopsis() string obtains the synopsis text
SetData(io.Reader)error read from a reader to set the value
Completion() Completion called to obtain the default completion for a value
type ValueReader ¶
ValueReader is a flag Value that can read from an input reader
type Writer ¶
type Writer interface { io.Writer io.StringWriter // ClearStyle removes the corresponding style ClearStyle(Style) // Reset will reset to the default style Reset() // SetColorCapable changes whether or not the writer should use color and style control codes SetColorCapable(bool) // ResetColorCapable uses auto detect to apply the default ResetColorCapable() // ColorCapable gets whether the writer is capable of writing color and style ColorCapable() bool // SetBackground updates the background color SetBackground(Color) // SetForeground updates the foreground color SetForeground(Color) // SetStyle updates the style SetStyle(Style) // Underline writes values in underline (if available) Underline(...any) (int, error) // Bold writes values in bold (if available) Bold(...any) (int, error) // Styled writes values in corresponding style (if available) Styled(Style, ...any) (int, error) }
Writer provides a terminal output writer which can provide access to color and styles
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
_examples
|
|
joefind
command
|
|
joegit
command
|
|
joeopen
command
|
|
cmd
|
|
joe
command
|
|
min
command
|
|
extensions
|
|
expr/exprfakes
Code generated by counterfeiter.
|
Code generated by counterfeiter. |
template/templatefakes
Code generated by counterfeiter.
|
Code generated by counterfeiter. |
internal
|
|
Code generated by counterfeiter.
|
Code generated by counterfeiter. |