expr

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: May 2, 2026 License: BSD-3-Clause Imports: 17 Imported by: 1

Documentation

Overview

Package expr provides conventions for command line expressions, which are flag-like arguments which are ordered and processed using pipe and filter semantics.

Evaluators

Evaluators support the binding pattern.

Say that you have an expression that has an operand "-name TEXT", and you have a function SetName(string)cli.Evaluator that can produce the evaluator that is actually used. You can use the following to simplify the binding of the string argument.

&cli.Arg {
    Name: "expression",
    Value: expr.Expression{
        Exprs: []*expr.Expr{
            {
                Name: "name",
                Args: cli.Args(cli.String()),
                Evaluator: expr.BindEvaluator(SetName, bind.String()),
            }
        }
    }
}

Notice that the bind.String() call doesn't require you to name the argument from which to obtain the value. When unspecified, it uses the first argument in the argument list for the Expr.

Index

Constants

View Source
const (
	AlwaysTrue  = Invariant(true)
	AlwaysFalse = Invariant(false)
)

Always or never yield the input value

View Source
const (
	// ParseAllowInlineValues is placed in the Uses pipeline of the Arg that contains
	// the expression and when present allows expressions to parse with inline arguments
	// when either (a) the short alias is an uppercase letter or (b) the inline
	// arguments have the equal sign. For example, if an expression -filter has
	// the alias -l, then it is acceptable to parse -lKEY=VALUE because an
	// equal sign is present. If the alias -L were present, then -LVALUE could
	// be parsed. These rules are designed to avoid ambiguity because in general,
	// ordinary expression names shouldn't use uppercase names and the equal sign
	// is a common delimiter in arguments.
	ParseAllowInlineValues cli.Option = cli.ReservedOption1
)

Variables

This section is empty.

Functions

func AddExpr

func AddExpr(e *Expr) cli.Action

AddExpr will add an expression operator to the containing Expression

func AddExprs

func AddExprs(exprs ...*Expr) cli.Action

AddExprs will add multiple expression operators to the containing Expression

func SetEvaluator

func SetEvaluator(e Evaluator) cli.Action

SetEvaluator provides an action used in the Uses pipeline of the Expr which updates its evaluator

Types

type ActionEvaluator added in v0.14.0

type ActionEvaluator interface {
	Evaluator
	cli.Action
}

ActionEvaluator provides an evaluator which can also be used as an action

func NewActionEvaluator added in v0.14.0

func NewActionEvaluator(action cli.Action, eval Evaluator) ActionEvaluator

NewActionEvaluator provides an evaluator which also provides an action. The typical use is to implement an initializer within the action that sets up the required flags and actions that the evaluator depends on.

type BindingEvaluator added in v0.14.0

type BindingEvaluator interface {
	Evaluator
	cli.Lookup

	// Expr retrieves the expression operator if it is available
	Expr() *Expr
}

BindingEvaluator provides the relationship between an evaluator and the evaluation context. Optionally, the original Expr is made available. A binding can support being reset if it exposes a method Reset(). Resetting a binding occurs when an expression is evaluated multiple times.

func NewBindingEvaluator added in v0.14.0

func NewBindingEvaluator(ev Evaluator, exprlookup ...any) BindingEvaluator

NewBindingEvaluator creates an expression binding evaluator. The ev parameter is how the expression is evaluated. The remaining arguments specify the *Expr expression operator to use and optionally a Lookup. The main use case for this function is to create a custom evaluation step that is appended to the expression pipeline

type Evaluator

type Evaluator interface {
	// Evaluate performs the evaluation.  The v argument is the value of the prior
	// expression operator.  The yield argument is used to pass one or more additional
	// values to the next expression operator.
	Evaluate(c context.Context, v any, yield func(any) error) error
}

Evaluator provides the evaluation function for an expression operator.

func BindEvaluator added in v0.10.0

func BindEvaluator[T any, E Evaluator](factory func(T) E, t bind.Binder[T]) Evaluator

BindEvaluator produces an evaluator from the bound values.

func BindEvaluator2 added in v0.10.0

func BindEvaluator2[T, U any, E Evaluator](eval func(T, U) E, t bind.Binder[T], u bind.Binder[U]) Evaluator

BindEvaluator2 produces an evaluator from the bound values.

func BindEvaluator3 added in v0.10.0

func BindEvaluator3[T, U, V any, E Evaluator](eval func(T, U, V) E, t bind.Binder[T], u bind.Binder[U], v bind.Binder[V]) Evaluator

BindEvaluator3 produces an evaluator from the bound values.

func ComposeEvaluator

func ComposeEvaluator(e ...Evaluator) Evaluator

ComposeEvaluator produces an evaluator which considers each evaluator in turn. If any evaluator yields the value, evaluation stops. If any evaluator returns an error, the evaluation stops and returns the error. This evaluator can be thought of as a logical conjunction in the case where evaluators work like Boolean predicates. Indeed, Predicate is often the type of the evaluators passed this function.

func Do added in v0.13.0

func Do(a cli.Action) Evaluator

Do converts action to an evaluator

func Error

func Error(err error) Evaluator

Error provides an evaluator which yields an error. The zero value is also useful, returning a generic error

func EvaluatorOf

func EvaluatorOf(v any) Evaluator

EvaluatorOf creates an expression evaluator for a given value. The value must be bool or a function. If a bool, then it works as a predicate for the corresponding invariant (i.e. false filters out all values, and true includes all values). If an error value, then it always returns such an error. If a function, the signature must match either the Evaluator.Evaluate function signature or a variation that excludes the context and/or yielder. You can also use bool as a return type as in the same signature used by Predicate. These are valid signatures:

  • func(*cli.Context, any, func(any)error) error
  • func(*cli.Context, any) error
  • func(*cli.Context, any) bool
  • func(*cli.Context, any)
  • func(*cli.Context) error
  • func(*cli.Context) bool
  • func(*cli.Context)
  • func(context.Context, any, func(any)error) error
  • func(context.Context, any) error
  • func(context.Context, any) bool
  • func(context.Context, any)
  • func(context.Context) error
  • func(context.Context) bool
  • func(context.Context)
  • func(any, func(any)error) error
  • func(any) bool
  • func(any) error
  • func(any)
  • func() bool
  • func() error
  • func()

type EvaluatorFunc

type EvaluatorFunc func(*cli.Context, any, func(any) error) error

EvaluatorFunc provides the basic function for an Evaluator

func (EvaluatorFunc) Evaluate

func (e EvaluatorFunc) Evaluate(c context.Context, v any, yield func(any) error) error

Evaluate provides the evaluation of the function and implements the Evaluator interface

type Expr

type Expr struct {
	// Name provides the name of the expression operator. This value must be set, and it is used to access
	// the expression operator's value via the context
	Name string

	// Aliases provides a list of alternative names for the expression operator.  In general, Name should
	// be used for the long name of the expression operator, 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

	// Args contains each of the arguments that are processed for the expression operators.  Expression
	// operators don't contain values directly; they process one or more arguments.
	Args []*cli.Arg

	// HelpText contains text which briefly describes the usage of the expression operator.
	// 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 expression operator 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 expression operator.  If left blank, a succinct synopsis
	// is generated from the type of the expression operator's arguments
	UsageText string

	// Category specifies the expression operator category.  When categories are used, operators are grouped
	// together on the help screen
	Category string

	// Description provides a long description.  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

	// Evaluate provides the evaluation behavior for the expression.  The value should
	// implement Evaluator or support runtime conversion to that interface via
	// the rules provided by the cli.EvaluatorOf function.
	Evaluate any

	// Before executes before the expression is evaluated.  Refer to cli.Action about the correct
	// function signature to use.
	Before any

	// After executes after the expression is evaluated.  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

	// Options sets various options about how to treat the expression operator.  For example, options can
	// hide the expression operator.
	Options cli.Option
	// contains filtered or unexported fields
}

Expr represents an operator in an expression. An expression is composed of an ordered series of operators meant to describe how to process one or more values. A well-known implementation of an expression is in the Unix `find` command where each file is processed through a series of operands to filter a list of files.

func (*Expr) Arg

func (e *Expr) Arg(name any) (*cli.Arg, bool)

Arg gets the expression operator by name

func (*Expr) LocalArgs

func (e *Expr) LocalArgs() []*cli.Arg

LocalArgs retrieves the arguments

func (*Expr) LookupData

func (e *Expr) LookupData(name string) (any, bool)

LookupData obtains the data if it exists

func (*Expr) Names

func (e *Expr) Names() []string

Names obtains the name of the expression operator and its aliases

func (*Expr) SetAliases

func (e *Expr) SetAliases(a []string)

SetAliases adds additional aliases

func (*Expr) SetCategory

func (e *Expr) SetCategory(name string)

SetCategory sets the category of the expression

func (*Expr) SetData

func (e *Expr) SetData(name string, v any)

SetData sets the specified metadata on the expression operator

func (*Expr) SetDescription

func (e *Expr) SetDescription(value string)

SetDescription sets the description of the expression

func (*Expr) SetHelpText

func (e *Expr) SetHelpText(name string)

SetHelpText sets the help text of the expression

func (*Expr) SetHidden

func (e *Expr) SetHidden(value bool)

SetHidden changes the visibility of the expression

func (*Expr) SetLocalArgs

func (e *Expr) SetLocalArgs(args []*cli.Arg) error

SetLocalArgs sets arguments

func (*Expr) SetManualText

func (e *Expr) SetManualText(name string)

SetManualText sets the manual text of the expression

func (*Expr) SetName

func (e *Expr) SetName(name string)

SetName sets the name of the expression

func (*Expr) SetUsageText

func (e *Expr) SetUsageText(value string)

SetUsageText sets the usage text of the expression

func (*Expr) Synopsis

func (e *Expr) Synopsis() string

Synopsis retrieves the synopsis for the expression operator.

type Expression

type Expression struct {

	// Exprs identifies the expression operators that are allowed
	Exprs []*Expr
	// contains filtered or unexported fields
}

Expression provides the parsed result of the expression that can be evaluated with the given inputs.

func FromContext

func FromContext(c context.Context, name string) *Expression

FromContext obtains the expression from the context

func (*Expression) Append

func (e *Expression) Append(expr BindingEvaluator)

func (*Expression) BindingEvaluators added in v0.14.0

func (e *Expression) BindingEvaluators() iter.Seq[BindingEvaluator]

BindingEvaluators enumerates all the binding evaluators on the expression

func (*Expression) Evaluate

func (e *Expression) Evaluate(ctx context.Context, items ...any) error

func (*Expression) ExecuteParallel added in v0.14.0

func (e *Expression) ExecuteParallel(ctx context.Context, jobs int, items ...any) error

ExecuteParallel evaluates the expression pipeline in parallel for multiple items. The jobs parameter controls the maximum number of concurrent evaluations. When jobs is zero or negative, the method uses runtime.NumCPU() as the default. Context propagation allows goroutines to be canceled or to time out. All errors are joined and returned together.

func (*Expression) Initializer

func (e *Expression) Initializer() cli.Action

Initializer is an action that binds expression handling to an argument. This is set up automatically when a command defines any expression operators. The exprFunc argument is used to determine which expressions to used. If nil, the default behavior is used which is to lookup Command.Exprs from the context

func (*Expression) Prepend

func (e *Expression) Prepend(expr BindingEvaluator)

func (*Expression) Set

func (e *Expression) Set(arg string) error

func (*Expression) String

func (e *Expression) String() string

func (*Expression) VisibleExprs

func (e *Expression) VisibleExprs() []*Expr

VisibleExprs filters all expression operators by whether they are not hidden

func (*Expression) Walk

func (e *Expression) Walk(fn func(BindingEvaluator) error) error

type Invariant

type Invariant bool

Invariant provides an evaluator which either always or never yields the input value

func (Invariant) Evaluate

func (i Invariant) Evaluate(_ context.Context, v any, y func(any) error) error

Evaluate implements the Evaluator interface for Invariant

type Predicate

type Predicate func(v any) bool

Predicate provides a simple predicate which filters values. The function takes the prior operand and returns true or false depending upon whether the operand should be yielded to the next step in the expression pipeline.

func (Predicate) Evaluate

func (p Predicate) Evaluate(_ context.Context, v any, yield func(any) error) error

Evaluate implements the Evaluator interface for Predicate

type Yielder

type Yielder func(any) error

Yielder provides the signature of the function used to yield values to the expression pipeline

Directories

Path Synopsis
Package expander provides an extension for representing expandable expressions in command line arguments.
Package expander provides an extension for representing expandable expressions in command line arguments.
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