printer

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: BSD-3-Clause Imports: 13 Imported by: 0

Documentation

Overview

Package printer provides the expression operators which print the values which flow through an expression evaluation pipeline. These are the familiar operators from the Unix find command:

-fprint FILE
-fprint0 FILE
-fprintf FILE PATTERN
-print
-print0
-printf PATTERN

together with the operator -field (aliased as -F), which names the fields to print rather than spelling out a pattern:

-field NAMES

Each of these operators always yields the value it was given, which makes it possible to compose them with the rest of the pipeline.

The Printer does the actual work. It is a context service, which means that it is registered into the context when it is added to a pipeline and retrieved from the context with FromContext. Adding it to a pipeline also registers the expression operators listed above. A minimal app resembles:

app := &cli.App{
    Uses: printer.New(),
    Args: []*cli.Arg{
        {
            Name: "path",
            NArg: 1,
        },
        {
            Name:  "expression",
            Value: new(expr.Expression),
        },
    },
    Action: func(c *cli.Context) error {
        return expr.FromContext(c, "expression").Evaluate(c, time.Now())
    },
}

Invoking this app as

app . -fprintf test.txt %(year)/%(month)

writes the year and month of the value which was pushed into the pipeline to the file test.txt. Invoking it as

app . -field year,month

prints the same two fields to standard output, separated by the delimiter. The delimiter is a tab unless WithDelimiter sets another one, and SetDelimiter provides the action which lets the user choose it.

How the value is converted into the expander which resolves the names within a pattern is controlled by WithExpanderFactory; how patterns themselves are parsed is controlled by WithPatternOptions. Thxe operators which don't take a pattern print the value using the conversion which WithFormatter controls, and whether they imply a newline is controlled by WithNewline, which the flag that SetNoNewline defines also provides.

Index

Constants

View Source
const DefaultDelimiter = "\t"

DefaultDelimiter is the delimiter which the -field operator uses to separate the fields it prints when the printer has no other delimiter set.

Variables

View Source
var (
	// DefaultExpanderFactory provides the default conversion of a value from the
	// expression evaluation pipeline into the expander which expands patterns.  A
	// value which is itself an expander is used as-is; any other value uses the
	// reflection expander adapter [expander.Reflect], which resolves keys to the
	// fields and no-arg methods of the value.
	DefaultExpanderFactory ExpanderFactory = defaultExpanderFactory

	// DefaultFormatter provides the default conversion of a value from the
	// expression evaluation pipeline into the text which the operators that
	// don't take a pattern print.  The value is formatted with the default
	// format of the fmt package, which honors [fmt.Stringer].
	DefaultFormatter Formatter = defaultFormatter
)

Functions

func AddExprs

func AddExprs() cli.Action

AddExprs provides an action which registers each of the expression operators which the printer supports: -field, -fprint, -fprint0, -fprintf, -print, -print0, and -printf.

When this action is used within the Uses pipeline of the arg which defines the expression, the operators are added to it directly. Otherwise it adds a hook which will add it to any arg that has an Expression, which is what enables New to be useable at the level of the command or app.

func ContextValue

func ContextValue(v *Printer) cli.Action

ContextValue provides an action that sets the given value into the context. The only supported type is *Printer.

func Field added in v0.20.0

func Field(names []string) expr.Evaluator

Field provides an evaluator which prints the named fields of the value from the expression evaluation pipeline to standard output, separated by the delimiter.

func Fprint

func Fprint(file string) expr.Evaluator

Fprint provides an evaluator which prints the value from the expression evaluation pipeline to the named file followed by a newline.

func Fprint0

func Fprint0(file string) expr.Evaluator

Fprint0 provides an evaluator which prints the value from the expression evaluation pipeline to the named file followed by a null character.

func Fprintf

func Fprintf(file string, pattern *expander.Pattern) expr.Evaluator

Fprintf provides an evaluator which prints the value from the expression evaluation pipeline to the named file using the given pattern.

func Print

func Print() expr.Evaluator

Print provides an evaluator which prints the value from the expression evaluation pipeline to standard output followed by a newline.

func Print0

func Print0() expr.Evaluator

Print0 provides an evaluator which prints the value from the expression evaluation pipeline to standard output followed by a null character.

func Printf

func Printf(pattern *expander.Pattern) expr.Evaluator

Printf provides an evaluator which prints the value from the expression evaluation pipeline to standard output using the given pattern.

func SetDelimiter added in v0.20.0

func SetDelimiter(delimiteropt ...string) cli.Action

SetDelimiter returns an action that sets the delimiter which the -field operator uses to separate the fields it prints. If specified on a flag or argument, it provides the action for a string value that names the delimiter. The initializer sets *string if the value is unset. If the argument delimiteropt is specified, that value is used; otherwise, it is obtained from the context. The printer must be registered in the context, which is done by adding it to a pipeline (see New).

&cli.Flag{Name: "delimiter", Uses: printer.SetDelimiter()}

func SetNoNewline added in v0.20.0

func SetNoNewline(v ...bool) cli.Action

SetNoNewline sets up the --no-newline flag and provides reasonable defaults for initializing a flag. The flag applies WithNewline to the printer which is in the context, which stops -print and -fprint from implying a newline:

&cli.Flag{Uses: printer.SetNoNewline()}

func SourceAnnotation

func SourceAnnotation() (string, string)

SourceAnnotation gets the name and value of the annotation added to the Data of all expression operators that are initialized from this package

Types

type ExpanderFactory

type ExpanderFactory func(context.Context, any) expander.Interface

ExpanderFactory converts a value from the expression evaluation pipeline into the expander which is used to expand patterns.

type Formatter added in v0.20.0

type Formatter func(context.Context, any) string

Formatter converts a value from the expression evaluation pipeline into the text which is printed for it by the operators which don't take a pattern.

type Option

type Option interface {
	cli.Action
	// contains filtered or unexported methods
}

Option provides an option for configuring the printer. An option is also an action, which applies it to the printer which is in the context, making it possible to use an option from within a pipeline (see SetNoNewline for the idiomatic use).

func WithAction

func WithAction(a cli.Action) Option

WithAction sets the action to use with the printer.

func WithDefaultAction

func WithDefaultAction() Option

WithDefaultAction sets the action to the default, which sets the printer into the context, adds the expression operators, and closes any files which the printer opened.

func WithDelimiter added in v0.20.0

func WithDelimiter(delimiter string) Option

WithDelimiter sets the delimiter which the -field operator uses to separate the fields it prints. When unset, DefaultDelimiter is used. The delimiter can also be set while the app runs, which is what SetDelimiter does.

func WithExpanderFactory

func WithExpanderFactory(fn func(context.Context, any) expander.Interface) Option

WithExpanderFactory sets how a value from the expression evaluation pipeline is converted into the expander which is used to expand patterns. When unset, DefaultExpanderFactory is used.

func WithFS

func WithFS(f cli.FS) Option

WithFS sets the file system which is used to interpret the file names given to the expression operators. When unset, the file system from the cli context is used, which also provides the convention that the file named with a dash refers to standard output.

func WithFormatter added in v0.20.0

func WithFormatter(fn func(context.Context, any) string) Option

WithFormatter sets how a value from the expression evaluation pipeline is converted into the text which the operators that don't take a pattern print. When unset, DefaultFormatter is used.

func WithNewline added in v0.20.0

func WithNewline(v bool) Option

WithNewline sets whether a newline is implied by the -print and -fprint operators, which it is by default. The other operators are unaffected: the terminator of -print0 and -fprint0 is always the null character, and -printf and -fprintf only print what their pattern specifies. SetNoNewline provides the flag which sets this option to false.

func WithPatternOptions

func WithPatternOptions(opts ...expander.Option) Option

WithPatternOptions sets the options which are used when the patterns named by the expression operators are parsed. Refer to expander.Compile for the available options. This option is additive; each call appends to the options which are already present.

type Printer

type Printer struct {
	// Action provides the action to run when the printer is added to a
	// pipeline.
	cli.Action
	// contains filtered or unexported fields
}

Printer facilitates the fprint-style expression operators. It resolves the expander to use for each value in the expression evaluation pipeline, it compiles patterns, and it owns the files which the operators name. Use New to create one which registers itself as a context service and registers the expression operators.

A file is created the first time that it is named and it is held open for the remainder of the run, which causes each subsequent print to append to it. Use Printer.Close to close the files, which the default action does automatically in the After timing.

func FromContext

func FromContext(ctx context.Context) *Printer

FromContext retrieves the printer from the context. This panics if the printer has not been registered, which is done by adding it to a pipeline (see New) or by using ContextValue.

func New

func New(opts ...Option) *Printer

New creates a printer which uses the default action. The default action registers the printer as a context service, adds each of the expression operators via AddExprs, and closes any files which were opened when the app exits.

func (*Printer) Apply

func (p *Printer) Apply(opts ...Option)

Apply will apply the given options to the printer.

func (*Printer) Close

func (p *Printer) Close() error

Close closes each of the files which the printer opened and forgets them, which means that naming one of these files again re-creates it.

func (*Printer) Compile

func (p *Printer) Compile(pattern string) *expander.Pattern

Compile compiles the given pattern using the pattern options which were configured for the printer. Patterns are cached, so compiling the same pattern text obtains the same pattern.

func (*Printer) Delimiter added in v0.20.0

func (p *Printer) Delimiter() string

Delimiter obtains the delimiter which the -field operator uses to separate the fields it prints, which is DefaultDelimiter unless it has been set.

func (*Printer) Expander

func (p *Printer) Expander(ctx context.Context, v any) expander.Interface

Expander obtains the expander for the given value from the expression evaluation pipeline using the expander factory.

func (*Printer) Field added in v0.20.0

func (p *Printer) Field(ctx context.Context, names []string, v any) error

Field prints the named fields of the value to standard output. It is equivalent to Printer.Printf using the pattern which names each field in order and separates them with the delimiter (see Printer.Delimiter); the value is therefore expanded by the same expander that a pattern would use.

func (*Printer) File added in v0.20.0

func (p *Printer) File(ctx context.Context, name string) (io.Writer, error)

File obtains the file output writer by name. It will be opened on first request and cached for further use so that a pipeline of expressions will append to the file.

func (*Printer) Format added in v0.20.0

func (p *Printer) Format(ctx context.Context, v any) string

Format converts the given value from the expression evaluation pipeline into the text which the operators that don't take a pattern print, using the formatter which was configured with WithFormatter.

func (*Printer) Fprint

func (p *Printer) Fprint(ctx context.Context, file string, v any) error

Fprint prints the value to the named file followed by a newline unless WithNewline disabled it.

func (*Printer) Fprint0

func (p *Printer) Fprint0(ctx context.Context, file string, v any) error

Fprint0 prints the value to the named file followed by a null character.

func (*Printer) Fprintf

func (p *Printer) Fprintf(ctx context.Context, file string, pattern *expander.Pattern, v any) error

Fprintf prints the value to the named file after expanding the pattern with the expander which corresponds to the value.

func (*Printer) Pipeline

func (p *Printer) Pipeline() cli.Action

Pipeline obtains the pipeline which sets up the printer.

func (*Printer) Print

func (p *Printer) Print(ctx context.Context, v any) error

Print prints the value to standard output followed by a newline unless WithNewline disabled it.

func (*Printer) Print0

func (p *Printer) Print0(ctx context.Context, v any) error

Print0 prints the value to standard output followed by a null character.

func (*Printer) Printf

func (p *Printer) Printf(ctx context.Context, pattern *expander.Pattern, v any) error

Printf prints the value to standard output after expanding the pattern with the expander which corresponds to the value. The writer which is used understands the stdout and stderr control expressions (see expander.Renderer).

func (*Printer) SetDelimiter added in v0.20.0

func (p *Printer) SetDelimiter(delimiter string)

SetDelimiter sets the delimiter which the -field operator uses to separate the fields it prints. Unlike leaving it unset, setting it to the empty string causes the fields to run together.

Jump to

Keyboard shortcuts

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