cli

package module
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2025 License: BSD-3-Clause Imports: 39 Imported by: 7

README

cli

cli (tentative name) is another command line parsing and commander for Go.

Code of conduct

This project has adopted a Code of conduct.

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

Examples

Constants

View Source
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
)
View Source
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
)
View Source
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
)
View Source
const (
	RawRTL = RawParseFlag(1 << iota)
	RawDisallowFlagsAfterArgs
	RawSkipProgramName
)

Raw flags used by the internal parser

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

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

View Source
const (

	// EndOfArguments signals no more arguments taken by this arg counter.
	EndOfArguments
)

Variables

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

func BigFloat() **big.Float

BigFloat creates a big float value. This is for convenience to obtain the right pointer.

func BigInt

func BigInt() **big.Int

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 Do

func Do(c context.Context, action Action) error

Do invokes the actions with the given context

func Duration

func Duration() *time.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 IP

func IP() *net.IP

IP creates an IP 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 Join

func Join(args []string) string

Join together the arguments, wrapping each in quotes if necessary

func List

func List() *[]string

List creates a string slice value. This is for convenience to obtain the right pointer.

func Map

func Map() *map[string]string

Map creates a map value. This is for convenience to obtain the right pointer.

func NameValues

func NameValues(namevalue ...string) *[]*NameValue

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 Quote

func Quote(v any) string

Quote uses shell escaping rules if necessary to quote a value

func ReadPasswordString

func ReadPasswordString(in io.Reader) (string, error)

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

func ReadString(in io.Reader) (string, error)

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 Regexp

func Regexp() **regexp.Regexp

Regexp creates a Regexp value. This is for convenience to obtain the right pointer.

func Set

func Set(dest any, args ...string) error

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

func SetData(dest any, arg any) error

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 Shell

func Shell() string

Shell detects the shell which is running.

func Split

func Split(s string) ([]string, error)

Split splits the specified text using shell splitting rules

func SplitList

func SplitList(s, sep string, n int) []string

SplitList considers escape sequences when splitting. sep must not be empty string

func SplitMap

func SplitMap(s string) map[string]string

SplitMap considers escape sequences when splitting

func String

func String() *string

String creates a string value. This is for convenience to obtain the right pointer.

func URL

func URL() **url.URL

URL creates a URL 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.

func Uint8

func Uint8() *uint8

Uint8 creates an uint8 value. This is for convenience to obtain the right pointer.

func Wrap

func Wrap(w io.Writer, text string, indent string, width int)

Wrap wraps the given text using a maximum line width and indentation. Wrapping text using this method is aware of ANSI escape sequences.

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

func Accessory[T any, A Action](name string, fn func(T) A, actionopt ...Action) Action

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

func Accessory0(name string, actionopt ...Action) Action

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

func ActionOf(item any) Action

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 AddAlias

func AddAlias(a string) Action

AddAlias adds the specified alias to the flag or command.

func AddArg

func AddArg(a *Arg) Action

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

func AddArgs(args ...*Arg) Action

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

func AddCommand(c *Command) Action

AddCommand provides an action which adds a sub-command to the command or app

func AddCommands

func AddCommands(commands ...*Command) Action

AddCommands provides an action which adds the specified commands to the command

func AddFlag

func AddFlag(f *Flag) Action

AddFlag provides an action which adds a flag to the command or app

func AddFlags

func AddFlags(flags ...*Flag) Action

AddFlags provides an action which adds the specified flags to the command

func After

func After(a Action) Action

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 Alias

func Alias(a ...string) Action

Alias sets the given alias on the flag or command. For args, the action is ignored

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

func ArgSetup(fn func(*Arg)) Action

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 At

func At(t Timing, a Action) Action

At wraps an action and causes it to execute at the given timing.

func AutodetectColor

func AutodetectColor() Action

AutodetectColor resets whether color output is used on stdout to use auto-detection

func Before

func Before(a Action) Action

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

func Bind[V any](bind func(V) error, valopt ...V) Action

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

func BindIndirect[T, V any](name any, bind func(*T, V) error, valopt ...V) Action

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

func Category(name string) Action

Category sets the category of a command, flag, or expression. This handler is generally set up inside a Uses pipeline.

func CommandSetup

func CommandSetup(fn func(*Command)) Action

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

func ContextValue(key, value any) Action

ContextValue provides an action which updates the context with a value.

func Customize

func Customize(pattern string, a Action) Action

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

func Data(name string, value any) Action

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

func Description(v any) Action

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

func DisplayHelpScreen(command ...string) Action

DisplayHelpScreen displays the help screen for the specified command. If the command is nested, each sub-command is named.

func Enum

func Enum(options ...string) Action

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

func ExecuteSubcommand(interceptErr func(*Context, error) (*Command, error)) Action

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

func ExecuteTemplate(name string, data func(*Context) any) Action

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

func FlagSetup(fn func(*Flag)) Action

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

func Fprint(w io.Writer, a ...any) Action

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

func Fprintf(w io.Writer, format string, a ...any) Action

Fprintf provides an action that formats according to a format specifier and writes to a file using the behavior of fmt.Fprintf

func Fprintln

func Fprintln(w io.Writer, a ...any) Action

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

func FromEnv(vars ...string) Action

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

func FromFilePath(f fs.FS, filePath string) Action

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

func HandleCommandNotFound(fn func(*Context, error) (*Command, error)) Action

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

func HandleSignal(s ...os.Signal) Action

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 HelpText

func HelpText(s string) Action

HelpText sets the help text for the current target

func Hook

func Hook(timing Timing, handler Action) Action

Hook registers a hook that runs for any context in the given timing.

func HookAfter

func HookAfter(pattern string, handler Action) Action

HookAfter registers a hook that runs for the matching elements. See ContextPath for the syntax of patterns and how they are matched.

func HookBefore

func HookBefore(pattern string, handler Action) Action

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

func ImplicitCommand(name string) Action

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

func ImplicitValue(fn func(*Context) (string, bool)) Action

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

func Implicitly(a Action) Action

Implicitly runs an action when there are zero occurrences (when an implicit value is set)

func Implies

func Implies(name, value string) Action

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

func Initializer(a Action) Action

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

func ManualText(s string) Action

ManualText sets the manual text of a command, flag, arg, or expression.

func Mutex

func Mutex(names ...string) Action

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

func Named(name string) Action

Named sets the name of a command, flag, or expression. This handler is generally set up inside a Uses pipeline.

func OptionalValue

func OptionalValue(v any) Action

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

func Print(a ...any) Action

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

func Printf(format string, a ...any) Action

Printf provides an action that formats according to a format specifier and writes to standard output using the behavior of fmt.Printf

func Println

func Println(a ...any) Action

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

func ProvideValueInitializer(v any, name string, actionopt ...Action) Action

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 Recover

func Recover(a Action) Action

Recover wraps an action to recover from a panic

func RegisterTemplate

func RegisterTemplate(name string, template string) Action

RegisterTemplate will register the specified template by name.

func RegisterTemplateFunc

func RegisterTemplateFunc(name string, fn any) Action

RegisterTemplateFunc will register the specified function for use in template rendering.

func RemoveAlias

func RemoveAlias(a string) Action

RemoveAlias removes the alias from the flag or command.

func RemoveArg

func RemoveArg(name any) Action

RemoveArg provides an action which removes an arg from the command or app. The name specifies the name, index, or arg itself

func RemoveCommand

func RemoveCommand(name any) Action

RemoveCommand provides an action which removes a Command from the command or app. The name specifies the name, index, or Command itself

func RemoveFlag

func RemoveFlag(name any) Action

RemoveFlag provides an action which removes a flag from the command or app. The name specifies the name, index, or Flag itself

func SetColor

func SetColor(enabled bool) Action

SetColor enables or disables color output on stdout.

func SetCompletion

func SetCompletion(c Completion) Action

SetCompletion sets completion for the command, flag, or arg.

func SetContext

func SetContext(ctx context.Context) Action

SetContext provides an action which sets the context

func SetValue

func SetValue(v any) Action

SetValue provides an action which sets the value of the flag or argument.

func ShellCompleteIntegration

func ShellCompleteIntegration(name string, s ShellComplete) Action

ShellCompleteIntegration provides an action which renders the particular shell complete integration

func SuppressError

func SuppressError(a Action) Action

SuppressError wraps an action to ignore its error.

func Timeout

func Timeout(timeout time.Duration) Action

Timeout provides an action which adds a timeout to the context.

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 UsageText

func UsageText(s string) Action

UsageText sets the help text for the current target

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

type ActionFunc func(*Context) error

ActionFunc provides the basic function for an Action

func (ActionFunc) Execute

func (af ActionFunc) Execute(ctx context.Context) error

Execute the action by calling the function

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

func NewApp(cmd *Command) *App

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

func (a *App) Arg(name any) (*Arg, bool)

Arg gets the argument by name, which can be either string, int, or the actual Arg.

func (*App) Command

func (a *App) Command(name string) (*Command, bool)

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

func (a *App) Flag(name string) (*Flag, bool)

Flag gets the flag by name.

func (*App) Initialize

func (a *App) Initialize(c context.Context) (context.Context, error)

Initialize sets up the app with the given context and arguments

func (*App) Run

func (a *App) Run(args []string)

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

func (a *App) RunContext(c context.Context, args []string) error

RunContext runs the application with the specified context and returns any error that occurred.

func (*App) SetData

func (a *App) SetData(name string, v any)

SetData sets the specified metadata on the app

func (*App) Use

func (a *App) Use(action Action) *App

Use appends actions to Uses pipeline

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

func Args(namevalue ...any) []*Arg

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

func (a *Arg) LookupData(name string) (any, bool)

LookupData obtains the data if it exists

func (*Arg) Occurrences

func (a *Arg) Occurrences() int

Occurrences counts the number of times that the argument has occurred on the command line

func (*Arg) Seen

func (a *Arg) Seen() bool

Seen reports true if the argument is used at least once.

func (*Arg) Set

func (a *Arg) Set(v any) error

Set will set the value of the argument

func (*Arg) SetData

func (a *Arg) SetData(name string, v any)

SetData sets the specified metadata on the arg. When v is nil, the corresponding metadata is deleted

func (*Arg) SetHidden

func (a *Arg) SetHidden(v bool)

SetHidden causes the argument to be hidden from the help screen

func (*Arg) SetOccurrence

func (a *Arg) SetOccurrence(values ...string) error

SetOccurrence will update the value of the arg

func (*Arg) SetOccurrenceData

func (a *Arg) SetOccurrenceData(v any) error

SetOccurrenceData will update the value of the arg

func (*Arg) SetRequired

func (a *Arg) SetRequired(v bool)

SetRequired will indicate that the argument is required.

func (*Arg) Synopsis

func (a *Arg) Synopsis() string

Synopsis contains the value placeholder

func (*Arg) Use

func (a *Arg) Use(action Action) *Arg

Use appends actions to Uses pipeline

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 NoArgs

func NoArgs() ArgCounter

NoArgs provides an argument counter that takes no args.

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.

func NewBinding

func NewBinding(flags []*Flag, args []*Arg, parent interface{ Flags() []*Flag }) Binding

NewBinding creates a binding. This expert API is to provide a representation of the naming and parsing rules for flags, args, and the parent

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

type BindingMap map[string][][]string

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 Color

type Color = ansiterm.Color

Color of terminal output

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

func (c *Command) Arg(name any) (*Arg, bool)

Arg tries to obtain a arg by name or alias

func (*Command) Command

func (c *Command) Command(name string) (*Command, bool)

Command tries to obtain a sub-command by name or alias

func (*Command) Flag

func (c *Command) Flag(name string) (*Flag, bool)

Flag tries to obtain a flag by name or alias

func (*Command) LookupData

func (c *Command) LookupData(name string) (any, bool)

LookupData obtains the data if it exists

func (*Command) Names

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

Names obtains the name of the command and its aliases

func (*Command) SetData

func (c *Command) SetData(name string, v any)

SetData sets the specified metadata on the command

func (*Command) SetHidden

func (c *Command) SetHidden(value bool)

func (*Command) Synopsis

func (c *Command) Synopsis() string

Synopsis returns the UsageText for the command or produces a succinct representation that names each flag and arg

func (*Command) Use

func (c *Command) Use(action Action) *Command

Use appends actions to Uses pipeline

func (*Command) VisibleArgs

func (c *Command) VisibleArgs() []*Arg

VisibleArgs filters all arguments in the command by whether they are not hidden

func (*Command) VisibleFlags

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

VisibleFlags filters all flags in the command by whether they are not hidden

func (*Command) VisibleSubcommands

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

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

func (CompletionFunc) Execute

func (f CompletionFunc) Execute(ctx context.Context) error

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

func FromContext(ctx context.Context) *Context

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

func (c *Context) Action(action Action) error

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

func (c *Context) AddAlias(aliases ...string) error

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

func (c *Context) AddArg(v *Arg) error

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

func (c *Context) AddArgs(args ...*Arg) (err error)

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

func (c *Context) AddCommand(v *Command) error

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

func (c *Context) AddCommands(commands ...*Command) (err error)

AddCommands provides a convenience method for adding commands to the current command or app.

func (*Context) AddFlag

func (c *Context) AddFlag(f *Flag) error

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

func (c *Context) AddFlags(flags ...*Flag) (err error)

AddFlags provides a convenience method for adding flags to the current command or app.

func (*Context) After

func (c *Context) After(action Action) error

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

func (c *Context) Aliases() []string

Aliases obtains the aliases for the current command or flag; otherwise, for args it is nill

func (*Context) App

func (c *Context) App() *App

App obtains the app

func (*Context) Arg

func (c *Context) Arg() *Arg

Arg retrieves the argument in scope if any

func (*Context) Args

func (c *Context) Args() []string

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

func (c *Context) At(t Timing, v Action) error

At either stores or executes the action at the given timing.

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

func (c *Context) Before(action Action) error

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

func (c *Context) BigFloat(name any) *big.Float

BigFloat obtains a value by the name of the flag, arg, or other value in scope

func (*Context) BigInt

func (c *Context) BigInt(name any) *big.Int

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

func (c *Context) Bool(name any) bool

Bool obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Bytes

func (c *Context) Bytes(name any) []byte

Bytes obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Category

func (c *Context) Category() string

Category obtains the category for the current target.

func (*Context) Command

func (c *Context) Command() *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) Context

func (c *Context) Context() context.Context

func (*Context) ContextOf

func (c *Context) ContextOf(target any) *Context

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

func (c *Context) Customize(pattern string, a Action) error

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

func (c *Context) Data() map[string]any

Data obtains the data for the current target. This could be a nil map.

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) Description

func (c *Context) Description() any

Description obtains the description for the current target.

func (*Context) Do

func (c *Context) Do(action Action) error

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

func (c *Context) Done() <-chan struct{}

func (*Context) Duration

func (c *Context) Duration(name any) time.Duration

Duration obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Err

func (c *Context) Err() error

func (*Context) Execute

func (c *Context) Execute(args []string) error

Execute executes the context with the given arguments.

func (*Context) ExecuteTemplate

func (c *Context) ExecuteTemplate(name string, data func(*Context) any) error

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

func (c *Context) File(name any) *File

File obtains a value by the name of the flag, arg, or other value in scope

func (*Context) FileSet

func (c *Context) FileSet(name any) *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) Flag

func (c *Context) Flag() *Flag

Flag retrieves the flag in scope if any

func (*Context) Flags

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

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

func (c *Context) Float32(name any) float32

Float32 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Float64

func (c *Context) Float64(name any) float64

Float64 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Fprint

func (c *Context) Fprint(w io.Writer, a ...any) (n int, err error)

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

func (c *Context) Fprintf(w io.Writer, format string, a ...any) (n int, err error)

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

func (c *Context) Fprintln(w io.Writer, a ...any) (n int, err error)

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

func (c *Context) HasValue() bool

HasValue tests whether the target has a value

func (*Context) HelpText

func (c *Context) HelpText() string

HelpText obtains the helpText for the current target.

func (*Context) Hook

func (c *Context) Hook(timing Timing, handler Action) error

Hook registers a hook that runs for any context in the given timing.

func (*Context) HookAfter

func (c *Context) HookAfter(pattern string, handler Action) error

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

func (c *Context) HookBefore(pattern string, handler Action) error

HookBefore registers a hook that runs for the matching elements. See ContextPath for the syntax of patterns and how they are matched.

func (*Context) IP

func (c *Context) IP(name any) net.IP

IP obtains a value by the name of the flag, arg, or other value in scope

func (*Context) ImplicitlySet

func (c *Context) ImplicitlySet() bool

ImplicitlySet returns true if the flag or arg was implicitly set.

func (*Context) Int

func (c *Context) Int(name any) int

Int obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Int16

func (c *Context) Int16(name any) int16

Int16 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Int32

func (c *Context) Int32(name any) int32

Int32 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Int64

func (c *Context) Int64(name any) int64

Int64 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Int8

func (c *Context) Int8(name any) int8

Int8 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Interface

func (c *Context) Interface(name any) (any, bool)

Interface obtains a value by the name of the flag, arg, or other value in scope

func (*Context) IsAction

func (c *Context) IsAction() bool

IsAction returns true if the context represents actions running for the actual execution of the command

func (*Context) IsAfter

func (c *Context) IsAfter() bool

IsAfter returns true if the context represents actions running after executing the command

func (*Context) IsArg

func (c *Context) IsArg() bool

IsArg tests whether the last segment of the path represents an argument

func (*Context) IsBefore

func (c *Context) IsBefore() bool

IsBefore returns true if the context represents actions running before executing the command

func (*Context) IsCommand

func (c *Context) IsCommand() bool

IsCommand tests whether the last segment of the path represents a command

func (*Context) IsFlag

func (c *Context) IsFlag() bool

IsFlag tests whether the last segment of the path represents a flag

func (*Context) IsInitializing

func (c *Context) IsInitializing() bool

IsInitializing returns true if the context represents initialization

func (*Context) Lineage

func (c *Context) Lineage() []*Context

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

func (c *Context) List(name any) []string

List obtains a value by the name of the flag, arg, or other value in scope

func (*Context) LocalArgs

func (c *Context) LocalArgs() []*Arg

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

func (c *Context) LocalFlags() []*Flag

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

func (c *Context) LookupArg(name any) (*Arg, bool)

LookupArg finds the arg by name. The name can be a string, rune, or *Arg

func (*Context) LookupCommand

func (c *Context) LookupCommand(name any) (*Command, bool)

LookupCommand finds the command by name. The name can be a string or *Command

func (*Context) LookupData

func (c *Context) LookupData(name string) (any, bool)

LookupData gets the data matching the key, including recursive traversal up the lineage contexts

func (*Context) LookupFlag

func (c *Context) LookupFlag(name any) (*Flag, bool)

LookupFlag finds the flag by name. The name can be a string, rune, or *Flag

func (*Context) LookupValueTarget

func (c *Context) LookupValueTarget(name string) (any, bool)

LookupValueTarget finds the value formerly provided to a value initializer by name.

func (*Context) ManualText

func (c *Context) ManualText() string

ManualText obtains the manualText for the current target.

func (*Context) Map

func (c *Context) Map(name any) map[string]string

Map obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Matches

func (c *Context) Matches(f ContextFilter) bool

Matches detects if the given context filter matches the current context

func (*Context) NValue

func (c *Context) NValue() int

NValue gets the maximum number available, exclusive, as an argument Value.

func (*Context) Name

func (c *Context) Name() string

Name gets the name of the context, which is the name of the command, arg, flag, or expression operator in use

func (*Context) NameValue

func (c *Context) NameValue(name any) *NameValue

NameValue obtains a value by the name of the flag, arg, or other value in scope

func (*Context) NameValues

func (c *Context) NameValues(name any) []*NameValue

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

func (c *Context) Occurrences(name any) int

Occurrences returns the number of times the specified flag or argument has been used This is -1 in the context of commands.

func (*Context) Parent

func (c *Context) Parent() *Context

Parent obtains the parent context or nil if the root context

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

func (c *Context) PersistentFlags() []*Flag

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

func (c *Context) PreventSetup() error

PreventSetup causes implicit setup options to be skipped. The function returns an error if the timing is not initial timing.

func (*Context) Print

func (c *Context) Print(a ...any) (n int, err error)

Print formats using the default formats for its operands and writes to standard output using the behavior of fmt.Print.

func (*Context) Printf

func (c *Context) Printf(format string, a ...any) (n int, err error)

Printf formats according to a format specifier and writes to standard output using the behavior of fmt.Printf

func (*Context) Println

func (c *Context) Println(a ...any) (n int, err error)

Println formats using the default formats for its operands and writes to standard output using the behavior of fmt.Println

func (*Context) ProvideValueInitializer

func (c *Context) ProvideValueInitializer(v any, name string, actionopt ...Action) error

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

func (c *Context) Raw(name any) []string

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

func (c *Context) RawOccurrences(name any) []string

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

func (c *Context) ReadPasswordString(prompt string) (string, error)

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

func (c *Context) ReadString(prompt string) (string, error)

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

func (c *Context) Regexp(name any) *regexp.Regexp

Regexp obtains a value by the name of the flag, arg, or other value in scope

func (*Context) RegisterTemplate

func (c *Context) RegisterTemplate(name string, tpl string) error

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

func (c *Context) RegisterTemplateFunc(name string, fn any) error

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

func (c *Context) RemoveAlias(a string) error

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

func (c *Context) RemoveArg(name any) error

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

func (c *Context) RemoveCommand(name any) error

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

func (c *Context) RemoveFlag(name any) error

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

func (c *Context) Root() *Context

Root obtains the root command.

func (*Context) Seen

func (c *Context) Seen(name any) bool

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

func (c *Context) SetCategory(name string) error

SetCategory sets the category on the current target

func (*Context) SetColor

func (c *Context) SetColor(v bool)

SetColor sets whether terminal color and styles are enabled on stdout.

func (*Context) SetContext

func (c *Context) SetContext(ctx context.Context) error

SetContext sets the context

func (*Context) SetContextValue

func (c *Context) SetContextValue(key, value any) error

SetContextValue updates the context with a value.

func (*Context) SetData

func (c *Context) SetData(name string, v any) error

SetData sets data on the current target. Despite the return value, this method never returns an error.

func (*Context) SetDescription

func (c *Context) SetDescription(v any) error

SetDescription sets the description on the current target

func (*Context) SetHelpText

func (c *Context) SetHelpText(s string) error

SetHelpText sets the help text on the current target

func (*Context) SetManualText

func (c *Context) SetManualText(v string) error

SetManualText sets the manualText on the current target

func (*Context) SetName

func (c *Context) SetName(name string) error

SetName sets the name on the current target

func (*Context) SetOptionalValue

func (c *Context) SetOptionalValue(v any) error

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

func (c *Context) SetUsageText(s string) error

SetUsageText sets the usage text on the current target

func (*Context) SetValue

func (c *Context) SetValue(arg any) error

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

func (c *Context) SkipImplicitSetup() bool

SkipImplicitSetup gets whether implicit setup steps should be skipped

func (*Context) String

func (c *Context) String(name any) string

String obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Target

func (c *Context) Target() any

Target retrieves the target of the context, which is *App, *Command, *Flag, *Arg, or *Expr

func (*Context) Template

func (c *Context) Template(name string) *Template

Template retrieves a template by name

func (*Context) Timing

func (c *Context) Timing() Timing

Timing retrieves the timing

func (*Context) Trigger

func (c *Context) Trigger() error

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

func (c *Context) URL(name any) *url.URL

URL obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Uint

func (c *Context) Uint(name any) uint

Uint obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Uint16

func (c *Context) Uint16(name any) uint16

Uint16 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Uint32

func (c *Context) Uint32(name any) uint32

Uint32 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Uint64

func (c *Context) Uint64(name any) uint64

Uint64 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) Uint8

func (c *Context) Uint8(name any) uint8

Uint8 obtains a value by the name of the flag, arg, or other value in scope

func (*Context) UsageText

func (c *Context) UsageText() string

UsageText obtains the usageText for the current target.

func (*Context) Use

func (c *Context) Use(action Action) error

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

func (c *Context) Value(name any) any

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

func (c *Context) ValueContextOf(name string, v any) *Context

ValueContextOf creates a context for the use with values that may have initialization steps.

func (*Context) Values

func (c *Context) Values() []any

Values gets all the values from the context .

func (*Context) Walk

func (c *Context) Walk(fn WalkFunc) error

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

type ContextFilter interface {
	Matches(c context.Context) bool
}

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

type ContextFilterFunc func(*Context) bool

ContextFilterFunc provides a predicate function which detects whether the context applies.

func (ContextFilterFunc) Matches

func (f ContextFilterFunc) Matches(c context.Context) bool

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

func (c ContextPath) Last() string

Last gets the last name in the path

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 ErrorCode

type ErrorCode int

ErrorCode provides common error codes in the CLI framework.

func (ErrorCode) String

func (e ErrorCode) String() string

String produces a textual representation of error code

type ExitCoder

type ExitCoder interface {
	error

	// ExitCode obtains the exit code for the error
	ExitCode() int
}

ExitCoder is an error that knows how to convert to its exit code

func Exit

func Exit(message ...any) ExitCoder

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

func DirFS

func DirFS(dir string) FS

DirFS returns a file system for files rooted at the directory dir.

func NewFS

func NewFS(f fs.FS) FS

NewFS wraps the given FS for use as a CLI file system.

func NewSysFS

func NewSysFS(base FS, in io.Reader, out io.Writer) FS

NewSysFS wraps the given FS with the semantics for the special file named with a dash. Typically, the file named by dash reads from stdin and writes to stdout.

type Feature

type Feature interface {
	~int
}

type FeatureMap

type FeatureMap[T Feature] map[T]Action

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

func (f *File) Base() string

Base obtains the basename of the file

func (*File) Chmod

func (f *File) Chmod(mode fs.FileMode) error

Chmod to change mode

func (*File) Chown

func (f *File) Chown(uid int, gid int) error

Chown to change owner

func (*File) Chtimes

func (f *File) Chtimes(atime, mtime time.Time) error

Chtimes to change times

func (*File) Completion

func (f *File) Completion() Completion

Completion gets the completion for files

func (*File) Create

func (f *File) Create() (fs.File, error)

Create the file

func (*File) Dir

func (f *File) Dir() string

Dir obtains the directory

func (*File) Exists

func (f *File) Exists() bool

Exists tests whether the file exists

func (*File) Ext

func (f *File) Ext() string

Ext obtains the file extension

func (*File) Initializer

func (f *File) Initializer() Action

Initializer obtains the initializer for the File, which is used to setup the file system used

func (*File) Mkdir

func (f *File) Mkdir(mode fs.FileMode) error

Mkdir creates a directory

func (*File) MkdirAll

func (f *File) MkdirAll(mode fs.FileMode) error

MkdirAll creates a directory and all ancestors

func (*File) Open

func (f *File) Open() (fs.File, error)

Open the file

func (*File) OpenContext

func (f *File) OpenContext(c context.Context) (fs.File, error)

OpenContext is used to open the file with the given context

func (*File) OpenFile

func (f *File) OpenFile(flag int, perm os.FileMode) (fs.File, error)

OpenFile will open the file using the specified flags and permissions

func (*File) Remove

func (f *File) Remove() error

Remove file

func (*File) RemoveAll

func (f *File) RemoveAll() error

RemoveAll to remove file and all ancestors

func (*File) Rename

func (f *File) Rename(newpath string) error

Rename file

func (*File) Set

func (f *File) Set(arg string) error

Set will set the name of the file

func (*File) Stat

func (f *File) Stat() (fs.FileInfo, error)

Stat obtains information about the file

func (*File) String

func (f *File) String() string

func (*File) Synopsis

func (*File) Synopsis() string

func (*File) Walk

func (f *File) Walk(fn fs.WalkDirFunc) error

Walk walks the file tree, calling fn for each file or directory in the tree, including the root.

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

func (f *FileSet) All() iter.Seq2[*File, error]

func (*FileSet) Completion

func (f *FileSet) Completion() Completion

Completion gets the completion for files

func (*FileSet) Do

func (f *FileSet) Do(fn func(*File, error) error) error

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

func (f *FileSet) Exists() bool

Exists tests whether all files in the set exist

func (*FileSet) Initializer

func (f *FileSet) Initializer() Action

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

func (f *FileSet) RecursiveFlag() Prototype

RecursiveFlag obtains a conventions-based flag for making the file set recursive.

func (*FileSet) Reset

func (f *FileSet) Reset()

Reset will resets the file set to empty

func (*FileSet) Set

func (f *FileSet) Set(arg string) error

Set argument value; can call repeatedly

func (*FileSet) SetData

func (f *FileSet) SetData(in io.Reader) error

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

func (f *FileSet) SetRecursive(b bool) error

SetRecursive updates the file set Recursive field. This is generally meant to be used with BindIndirect. Never returns an error.

func (*FileSet) String

func (f *FileSet) String() string

func (*FileSet) Synopsis

func (*FileSet) Synopsis() string

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

func (f FilterModes) Matches(ctx context.Context) bool

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

func (f *Flag) LongName() string

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

func (f *Flag) LookupData(name string) (any, bool)

LookupData obtains the data if it exists

func (*Flag) Names

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

Names obtains the name of the flag and its aliases, including their leading dashes.

func (*Flag) Occurrences

func (f *Flag) Occurrences() int

Occurrences returns the number of times the flag was specified on the command line

func (*Flag) Seen

func (f *Flag) Seen() bool

Seen returns true if the flag was used on the command line at least once

func (*Flag) Set

func (f *Flag) Set(arg any) error

Set will update the value of the flag

func (*Flag) SetData

func (f *Flag) SetData(name string, v any)

SetData sets the specified metadata on the flag. When v is nil, the corresponding metadata is deleted

func (*Flag) SetHidden

func (f *Flag) SetHidden(v bool)

SetHidden causes the flag to be hidden

func (*Flag) SetOccurrence

func (f *Flag) SetOccurrence(values ...string) error

SetOccurrence will update the value of the flag

func (*Flag) SetOccurrenceData

func (f *Flag) SetOccurrenceData(v any) error

SetOccurrenceData will update the value of the flag

func (*Flag) SetRequired

func (f *Flag) SetRequired(v bool)

SetRequired causes the flag to be required

func (*Flag) ShortName

func (f *Flag) ShortName() string

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.

func (*Flag) Synopsis

func (f *Flag) Synopsis() string

Synopsis contains the name of the flag, its aliases, and the value placeholder. The text of synopsis is inferred from the HelpText. Up to one short and one long name will be used.

func (*Flag) Use

func (f *Flag) Use(action Action) *Flag

Use appends actions to Uses pipeline

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

type LookupFunc func(string) (any, bool)

LookupFunc provides a Lookup that converts from a name to a value.

func (LookupFunc) BigFloat

func (c LookupFunc) BigFloat(name any) *big.Float

func (LookupFunc) BigInt

func (c LookupFunc) BigInt(name any) *big.Int

func (LookupFunc) Bool

func (c LookupFunc) Bool(name any) bool

func (LookupFunc) Bytes

func (c LookupFunc) Bytes(name any) []byte

func (LookupFunc) Duration

func (c LookupFunc) Duration(name any) time.Duration

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

func (c LookupFunc) IP(name any) net.IP

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

func (c LookupFunc) Interface(name any) (any, bool)

func (LookupFunc) List

func (c LookupFunc) List(name any) []string

func (LookupFunc) Map

func (c LookupFunc) Map(name any) map[string]string

func (LookupFunc) NameValue

func (c LookupFunc) NameValue(name any) *NameValue

func (LookupFunc) NameValues

func (c LookupFunc) NameValues(name any) []*NameValue

func (LookupFunc) Regexp

func (c LookupFunc) Regexp(name any) *regexp.Regexp

func (LookupFunc) String

func (c LookupFunc) String(name any) string

func (LookupFunc) URL

func (c LookupFunc) URL(name any) *url.URL

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

type LookupValues map[string]any

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

func (v *NameValue) AllowFileReferencesFlag() Prototype

AllowFileReferencesFlag obtains a flag configuration for setting the AllowFileReferences value

func (*NameValue) Copy

func (v *NameValue) Copy() *NameValue

func (*NameValue) Initializer

func (v *NameValue) Initializer() Action

func (*NameValue) NewCounter

func (v *NameValue) NewCounter() ArgCounter

func (*NameValue) Reset

func (v *NameValue) Reset()

func (*NameValue) Set

func (v *NameValue) Set(arg string) error

func (*NameValue) SetAllowFileReference

func (v *NameValue) SetAllowFileReference(val bool) error

SetAllowFileReference sets whether file references are allowed. This function is for bindings

func (*NameValue) String

func (v *NameValue) String() string

String obtains the string representation of the name-value pair

type Option

type Option int

Option provides a built-in convenience configuration for flags, args, and commands.

func (Option) Execute

func (o Option) Execute(c context.Context) (err error)

Execute treats the options as if an action

func (Option) MarshalText

func (o Option) MarshalText() ([]byte, error)

MarshalText provides the textual representation

func (Option) String

func (o Option) String() string

func (*Option) UnmarshalText

func (o *Option) UnmarshalText(b []byte) error

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

func (*ParseError) ExitCode

func (e *ParseError) ExitCode() int

ExitCode always returns 2

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap returns the internal error

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

func (Prototype) Execute

func (p Prototype) Execute(ctx context.Context) error

func (Prototype) Use

func (p Prototype) Use(action Action) Prototype

type RawParseFlag

type RawParseFlag int

RawParseFlag enumerates rules for RawParse

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.

func (Setup) Execute

func (s Setup) Execute(ctx context.Context) error

Execute executes the Setup, which assigns the various parts to their pipelines

func (Setup) Use

func (s Setup) Use(action Action) Setup

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 (StandardCompletion) Execute

func (s StandardCompletion) Execute(ctx context.Context) error

type Style

type Style = ansiterm.Style

Style of terminal output

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

func (t *Template) Bind(data any) fmt.Stringer

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.

func (*Template) BindFunc

func (t *Template) BindFunc(data func() any) fmt.Stringer

BindFunc will 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.

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data any) error

Execute the template

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

func (t Timing) Describe() string

Describe produces a representation of the timing suitable for use in messages

func (Timing) MarshalText

func (t Timing) MarshalText() ([]byte, error)

MarshalText provides the textual representation

func (Timing) Matches

func (t Timing) Matches(ctx context.Context) bool

func (Timing) String

func (t Timing) String() string

String produces a textual representation of the timing

func (*Timing) UnmarshalText

func (t *Timing) UnmarshalText(b []byte) error

UnmarshalText converts the textual representation

type TransformFunc

type TransformFunc func(rawOccurrences []string) (any, error)

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.

func (TransformFunc) Execute

func (t TransformFunc) Execute(ctx context.Context) error

type ValidatorFunc

type ValidatorFunc func(s []string) error

ValidatorFunc defines an Action that applies a validation rule to the explicit raw occurrence values for a flag or argument.

func (ValidatorFunc) Execute

func (v ValidatorFunc) Execute(ctx context.Context) error

type Value

type Value = flag.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

type ValueReader interface {
	Value
	SetData(io.Reader) error
}

ValueReader is a flag Value that can read from an input reader

type WalkFunc

type WalkFunc func(cmd *Context) error

WalkFunc provides the callback for the Walk function

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

func NewWriter

func NewWriter(w io.Writer) Writer

NewWriter creates a new writer with support for color if TTY is detected

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
joe
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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