expr

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: BSD-3-Clause Imports: 21 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.

Compilers

When an expression is evaluated, the sequence of binding evaluators that was parsed is compiled into the evaluator which implements the evaluation pipeline. The default compiler, Compile, chains each binding evaluator to the next one. Setting Expression.Compiler replaces this behavior, which is typically used to rewrite the sequence of binding evaluators before delegating to Compile:

&expr.Expression{
    Compiler: func(items []expr.BindingEvaluator) (expr.Evaluator, error) {
        return expr.Compile(append(items, implicitPrint))
    },
}

Expression.Compile applies the compiler eagerly, producing a copy of the expression which evaluates using the pipeline that was compiled. When the compiler returns an error, the pipeline is an evaluator which fails with that error.

Parallelism

An evaluator makes work asynchronous by submitting it as a task using Go, yielding its result from within the task. With the default compiler, the task runs inline, so the evaluator behaves as though it were synchronous. The Parallel compiler provides a scheduler which runs at most a maximum number of tasks concurrently, and it serializes evaluators which aren't safe to evaluate concurrently. A simple, blocking evaluator can be made asynchronous by wrapping it with Async:

&expr.Expression{
    Compiler: expr.Parallel(8, nil),
    Exprs: []*expr.Expr{
        {
            Name:     "fetch",
            Evaluate: expr.Async(expr.NewEvaluator0(fetchURL)),
        },
    },
}

Operators

When the reserved option ParseOperators is set on the arg which contains the expression, the Unix find-style operators ( ) ! -and -a -or -o , are parsed and placed in the sequence of binding evaluators as Operator placeholders. The default compiler does not support operators, so a compiler which interprets them, such as operator.Compile, must also be set.

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 = reservedoptions.ExprParseAllowInlineValues

	// ParseOperators is placed in the Uses pipeline of the Arg that contains the
	// expression and when present allows expressions to contain the operators
	// ( ) ! -and -a -or -o ",", which are placed in the sequence of binding
	// evaluators as Operator.  A compiler which interprets operators, such as
	// operator.Compile, must be set on the expression.
	ParseOperators cli.Option = reservedoptions.ExprParseOperators
)

Variables

This section is empty.

Functions

func Go added in v0.24.0

func Go(ctx context.Context, task func(context.Context) error) error

Go submits a task to the scheduler from the context, which is how an evaluator makes work asynchronous. The task usually ends by yielding its result, which continues the expression pipeline:

func (h hashEval) Evaluate(ctx context.Context, v any, yield func(any) error) error {
    return expr.Go(ctx, func(ctx context.Context) error {
        sum, err := hashFile(ctx, v.(string))
        if err != nil {
            return err
        }
        return yield(sum)
    })
}

When the context has no scheduler, as with the default compiler, the task runs inline, so the evaluator behaves as though it were synchronous. With a scheduler such as the one provided by the Parallel compiler, the task can run concurrently and yield after Evaluate has returned. The values of the args of an expression operator must be obtained before calling Go because another use of the operator could change them afterwards.

func Sync added in v0.24.0

func Sync(ctx context.Context) context.Context

Sync provides a context in which tasks submitted using Go run inline. An evaluator which depends upon whether another evaluator yields a value should evaluate it with Sync so that yielding occurs before Evaluate returns. ComposeEvaluator does this for the evaluators it composes.

func WithScheduler added in v0.24.0

func WithScheduler(ctx context.Context, s Scheduler) context.Context

WithScheduler provides a context which uses the given scheduler for the tasks which are submitted using Go

Types

type Action added in v0.23.0

type Action = cli.Action

Action represents the building block of the various actions that the expr extension supports

func AddExpr

func AddExpr(e *Expr) Action

AddExpr will add an expression operator to the containing Expression

func AddExprs

func AddExprs(exprs ...*Expr) Action

AddExprs will add multiple expression operators to the containing Expression

func Evaluate added in v0.23.0

func Evaluate(items ...any) Action

Evaluate provides an action which evaluates the expression with the given input items. The expression is retrieved from the arg in scope.

func EvaluateParallel added in v0.23.0

func EvaluateParallel(items ...any) Action

EvaluateParallel provides an action which evaluates the expression with the given input items. The expression is retrieved from the arg in scope and runs in parallel. By convention, if this is present within the Uses pipeline, it registers a flag to configure the number of jobs.

func SetEvaluator

func SetEvaluator(e Evaluator) Action

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

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 Binding

type Binding interface {
	// ResolveAlias resolves an argument as it was written, including the leading dash
	// of an expression operator, to the canonical name that LookupExpr accepts.
	// Arguments which are operators, such as "(" or "-a", resolve to the canonical name of
	// the operator.
	ResolveAlias(arg string) (string, bool)

	// LookupExpr gets the BindingEvaluator by canonical name.  If the result implements
	// BindingState, then it represents one occurrence of an expression operator, so each
	// call must return a new one.
	LookupExpr(name string) (BindingEvaluator, bool)

	// Numeric gets the canonical name of the expression operator that handles numeric
	// syntax such as -1 and -2, or the empty string if there isn't one.
	Numeric() string
}

Binding provides the representation of how the arguments of an expression are bound to expression operators. It defines the names and aliases of expression operators and operators, and which expression operator handles the numeric syntax. It is analogous to cli.Binding, which does the same for the flags and args of a command.

Operators such as ( and -and are resolved the same as expression operators, but the BindingEvaluator they provide doesn't implement BindingState because they don't support bindings over args.

func NewBinding

func NewBinding(exprs []*Expr, options cli.Option) Binding

NewBinding creates a binding over the given expression operators. This expert API is to provide a representation of the naming rules for expression operators. The options can include ParseOperators, which has the same meaning as when set on the arg that contains the expression. (ParseAllowInlineValues is handled by the parser and has no effect on the binding.) The expression operator that is marked with Expr.SetNumeric handles the numeric syntax. The names, aliases, and numeric flag are read from the expression operators whenever they are resolved, so changes made to them during initialization, such as promoting optional aliases, are seen by the binding.

type BindingEvaluator added in v0.14.0

type BindingEvaluator interface {
	Evaluator

	// 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 BindingState added in v0.25.0

type BindingState interface {
	BindingEvaluator

	// Binding gets the binding used to parse the args that follow the name of the
	// expression operator, which ends at the first argument that the expression operator
	// doesn't take. If nil, there is nothing to parse nor apply.
	Binding() cli.Binding

	// Apply applies the result of parsing the args.  The state retains the result and
	// applies it again each time it is evaluated.
	Apply(*cli.BindingResult) error
}

BindingState defines the state of the binding operation for one occurrence of an expression operator within an expression. A BindingEvaluator returned by Binding.LookupExpr can implement this to have the args that follow it parsed. It is analogous to cli.BindingState, which is the state of the binding of an arg or flag.

type Compiler added in v0.22.0

type Compiler func([]BindingEvaluator) (Evaluator, error)

Compiler converts the sequence of binding evaluators within an expression into the evaluator which implements the evaluation pipeline. A compiler is set on Expression.Compiler, and when unset, the default compiler, Compile, is used. An error is returned when the sequence can't be compiled, such as when it contains operators which are not well-formed.

func Parallel added in v0.24.0

func Parallel(jobs int, next Compiler) Compiler

Parallel provides a compiler whose pipeline evaluates the tasks that evaluators submit using Go concurrently, running at most jobs tasks at once. When jobs is zero or negative, runtime.NumCPU() is used. The binding evaluators are compiled by next, or by Compile when next is nil.

Evaluate returns after all of the tasks complete, and it returns the first error from any of them, which also cancels the context of the others. If the context already has a scheduler other than the one provided by Sync, as within Expression.EvaluateParallel, that scheduler is used instead, jobs is ignored, and whatever provided the scheduler waits for the tasks. Values are yielded to the yielder passed to Evaluate one at a time, but their order is not guaranteed.

Unless its evaluator is safe to evaluate concurrently (see Evaluator), each binding evaluator is serialized from when it is evaluated until it first yields a value, submits a task, or returns. All uses of an Expr are serialized together because they share its args. Code which runs after that point can run concurrently with other evaluations, so it must not access shared state without synchronization.

Binding evaluators which next adds to the sequence are not serialized. To rewrite the sequence and have the result serialized, apply Parallel to the rewritten sequence:

&expr.Expression{
    Compiler: func(items []expr.BindingEvaluator) expr.Evaluator {
        return expr.Parallel(8, nil)(append(items, implicitPrint))
    },
}

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.

An evaluator can submit work as a task using Go, in which case yield can be called after Evaluate returns and from another goroutine. An evaluator which depends upon whether another evaluator yields a value should evaluate it using the context provided by Sync.

An evaluator can optionally implement the following method:

  • Concurrent() bool: when true, the evaluator is safe to evaluate concurrently, so the Parallel compiler need not serialize it

func Async added in v0.24.0

func Async(ev any) Evaluator

Async provides an evaluator which submits the evaluation of ev as a task using Go, which allows a simple, blocking evaluator to be evaluated concurrently by the Parallel compiler. The value of ev is converted using the rules of EvaluatorOf. Using Async asserts that ev is safe to evaluate concurrently.

When ev is provided by BindEvaluator, its values are bound before the task is submitted. Otherwise, ev is evaluated entirely within the task, so it must not obtain the values of the args of the expression operator from the context.

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 Compile added in v0.22.0

func Compile(items []BindingEvaluator) (Evaluator, error)

Compile provides the default compiler for an expression, which converts the sequence of binding evaluators into the evaluator that implements the evaluation pipeline. Each binding evaluator yields the values it produces to the next one in the sequence, and the last one yields to the yielder which is passed to the resulting evaluator's Evaluate method. Operators are not supported, and an error is returned when any are present.

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. The evaluators are evaluated using the context provided by Sync so that tasks they submit using Go run inline.

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

Each of these signatures can also name a type that is more specific than any for the value parameter, in which case reflection is used to invoke the function. For example, func(context.Context, string) bool is valid, and each value in the expression pipeline is passed to it as a string; a value which can't be used as a string causes evaluation to return an error. The yield function is not covariant, however: it must always be spelled func(any) error.

func NewEvaluator added in v0.22.0

func NewEvaluator[V any](fn func(context.Context, V, func(any) error) error) Evaluator

NewEvaluator creates an evaluator from a strongly typed function. The value flowing through the expression pipeline is converted to V before fn is invoked

func NewEvaluator0 added in v0.22.0

func NewEvaluator0[V any](fn func(context.Context, V) error) Evaluator

NewEvaluator0 creates an evaluator from a strongly typed function which does not yield values directly. The value flowing through the expression pipeline is converted to V before fn is invoked, and if fn returns no error, the value is yielded to continue the pipeline.

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. If the evaluator is also a
	// [cli.Action] or implements the method Initializer() cli.Action as a convention, then
	// the action will be invoked during the initialization of the Expression.
	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 any) (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) OccurrenceValue added in v0.16.0

func (s Expr) OccurrenceValue(name string, index int) any

func (Expr) OccurrenceValues added in v0.16.0

func (s Expr) OccurrenceValues(name string) []any

func (Expr) Raw added in v0.20.0

func (s Expr) Raw(name string) []string

Raw obtains the values which were specified for an arg. The empty name designates the expression itself, whose raw value is the args it was parsed from.

func (Expr) RawOccurrences added in v0.20.0

func (s Expr) RawOccurrences(name string) []string

RawOccurrences obtains the values which were specified for an arg, excluding the name that was used. The empty name designates the expression itself, whose occurrences are the args it was parsed from excluding the name of the expression.

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, v any)

SetData sets the specified metadata on the expression operator. Despite its signature, Expr does not

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) SetNumeric added in v0.18.0

func (e *Expr) SetNumeric(value bool)

SetNumeric marks the expression as handling the numeric syntax -0, -1, etc.

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

	// Binding provides the rules used to parse the arguments into binding
	// evaluators: how arguments resolve to expression operators and operators, and how
	// the arguments of each expression operator are bound.  When nil, the default
	// binding over Exprs is used, as created by NewBinding, which honors
	// ParseOperators and Expr.SetNumeric.  When set, the binding is responsible for
	// resolving arguments, and Exprs and ParseOperators don't affect parsing, though
	// Exprs is still used to generate help.  ParseAllowInlineValues applies
	// to any binding because the inline syntax is handled by the parser.
	Binding Binding

	// Compiler provides the function which converts the binding evaluators that
	// were parsed into the evaluator which is used as the evaluation pipeline.
	// When nil, the default behavior, which is implemented by Compile, is used.
	// A custom compiler is typically used to rewrite the sequence of binding
	// evaluators before delegating to Compile.  The sequence passed to the
	// compiler is a copy, so it is safe to rewrite it.
	Compiler Compiler
	// 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, nameopt ...string) *Expression

FromContext obtains the expression from the context. When nameopt is not specified or is the empty string, then the expression from the current arg or apparent from one of the args in the current command is returned.

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) Clone added in v0.22.0

func (e *Expression) Clone() *Expression

Clone provides a copy of the expression. The expression operators, the arguments which were parsed, and the binding evaluators are shallow copied, which makes it possible to rewrite or add to the binding evaluators of the copy without affecting the original expression.

func (*Expression) Compile added in v0.22.0

func (e *Expression) Compile() *Expression

Compile provides a copy of the expression with the compiler step applied. The resulting expression evaluates using the pipeline which was compiled from the binding evaluators as they exist now rather than compiling the pipeline when it is evaluated. Consequently, binding evaluators which are added to the copy using Append or Prepend take no part in its evaluation. When the compiler returns an error, the pipeline is the Error evaluator, which fails the evaluation immediately.

func (*Expression) Evaluate

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

Evaluate evaluates the expression pipeline for each of the items. The pipeline is obtained from the compiler, which is Expression.Compiler or the default compiler, Compile, when it is unset. If the expression was compiled using Expression.Compile, the pipeline that was compiled is used as-is.

func (*Expression) EvaluateParallel added in v0.16.0

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

EvaluateParallel 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. The tasks that evaluators submit using Go share the same limit (see NewJobs). Context propagation allows goroutines to be canceled or to time out. The first error cancels the remaining evaluations and is returned.

Unless the pipeline is compiled by Parallel, which serializes evaluators that aren't safe to evaluate concurrently, the evaluators must be safe to evaluate concurrently.

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) Concurrent added in v0.24.0

func (Invariant) Concurrent() bool

Concurrent indicates that Invariant is safe to evaluate concurrently

func (Invariant) Evaluate

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

Evaluate implements the Evaluator interface for Invariant

func (Invariant) Initializer added in v0.23.0

func (i Invariant) Initializer() cli.Action

type JobsScheduler added in v0.24.0

type JobsScheduler struct {
	// contains filtered or unexported fields
}

JobsScheduler provides a scheduler which runs at most a maximum number of tasks concurrently. When that many tasks are already running, a task which is submitted runs inline on the goroutine which submitted it, which bounds the number of goroutines and allows tasks to submit more tasks without deadlock. The first task that returns an error cancels the context provided by NewJobsScheduler.

func NewJobsScheduler added in v0.24.0

func NewJobsScheduler(ctx context.Context, max int) (*JobsScheduler, context.Context)

NewJobsScheduler creates a scheduler which runs at most max tasks concurrently. When max is zero or negative, runtime.NumCPU() is used. The context which is returned uses the scheduler and is canceled when a task returns an error or when Wait returns.

func (*JobsScheduler) Go added in v0.24.0

func (j *JobsScheduler) Go(ctx context.Context, task func(context.Context) error) error

Go submits a task, which runs concurrently when fewer than the maximum number of tasks are running, or otherwise inline. The error from a task which runs inline is returned.

func (*JobsScheduler) Wait added in v0.24.0

func (j *JobsScheduler) Wait() error

Wait waits for all tasks to complete and returns the first error from any of them

type Operator added in v0.23.0

type Operator rune

Operator provides an operator in the small predicate expression language. Though this implements BindingEvaluator, it is only meant as a placeholder for which a Compiler must interpret. Indeed, the default Compile function panics when they are present.

const (
	LParen Operator = '('
	RParen Operator = ')'
	Not    Operator = '!'
	And    Operator = '&'
	Or     Operator = '|'
	Comma  Operator = ','
)

Operators that can be parsed into expressions. Unlike other exprs, these are typically symbols. Indeed, the underlying type of this is rune which represents their common representation.

func (Operator) Evaluate added in v0.23.0

func (Operator) Evaluate(context.Context, any, func(any) error) error

Evaluate always returns nil. Operators are BindingEvaluators but are typically replaced by the Compiler

func (Operator) Expr added in v0.23.0

func (Operator) Expr() *Expr

Expr always returns nil.

func (Operator) String added in v0.24.0

func (o Operator) String() string

String provides the representation of the operator as it is parsed

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 PredicateContext added in v0.23.0

type PredicateContext func(ctx context.Context, v any) bool

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

func (PredicateContext) Evaluate added in v0.23.0

func (p PredicateContext) Evaluate(ctx context.Context, v any, yield func(any) error) error

Evaluate implements the Evaluator interface for PredicateContext

type Scheduler added in v0.24.0

type Scheduler interface {
	Go(ctx context.Context, task func(context.Context) error) error
}

Scheduler runs the tasks which evaluators submit using Go. A scheduler can run a task concurrently, in which case it returns before the task completes, and the task's error is reported by whatever waits for the scheduler (for example, JobsScheduler.Wait). Otherwise, the task runs inline, and its error is returned.

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.
Package operator provides the small predicate expression language.
Package operator provides the small predicate expression language.
Package printer provides the expression operators which print the values which flow through an expression evaluation pipeline.
Package printer provides the expression operators which print the values which flow through an expression evaluation pipeline.

Jump to

Keyboard shortcuts

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