builder

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2024 License: Apache-2.0 Imports: 37 Imported by: 5

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorDuplicatePlugin  = errors.New("duplicate plugin")
	ErrorUnknownPlugin    = errors.New("unknown plugin")
	ErrDefinitionNotfound = errors.New("definition not found")
	ErrConfigNotFound     = errors.New("config file not found")
	ErrCommandHasNoType   = errors.New("command has no type defined")
	ErrInvalidDefinition  = errors.New("invalid definition")

	Version = "development"
)
View Source
var ErrInvalidTransform = errors.New("invalid transform")

Functions

func CreateGenericCommand

func CreateGenericCommand(app KingpinCommand, sc *GenericCommand, arguments map[string]any, flags map[string]any, b *AppBuilder, cb fisk.Action) *fisk.CmdClause

CreateGenericCommand can be used to add all the typical flags and arguments etc if your command is based on GenericCommand. Values set in flags and arguments are created on the supplied maps, if flags or arguments is nil then this will not attempt to add defined flags. Use this if you wish to use GenericCommand as a base for your own commands while perhaps using an extended argument set

func MountAsCommand added in v0.7.2

func MountAsCommand(ctx context.Context, app KingpinCommand, definition []byte, log Logger) error

MountAsCommand takes the given definition and mounts it on app using name

func MustRegisterCommand

func MustRegisterCommand(kind string, constructor CommandConstructor)

MustRegisterCommand registers a command and panics if it cannot

func ParseStateTemplate

func ParseStateTemplate(body string, args map[string]any, flags map[string]any, cfg any) (string, error)

ParseStateTemplate parses body as a go text template with supplied values exposed to the user

func ParseStateTemplateWithFuncMap added in v0.6.2

func ParseStateTemplateWithFuncMap(body string, args map[string]any, flags map[string]any, cfg any, funcMap template.FuncMap) (string, error)

ParseStateTemplateWithFuncMap parses body as a go text template with supplied values exposed to the user with additional functions available to the template

func RegisterCommand

func RegisterCommand(kind string, constructor CommandConstructor) error

RegisterCommand adds a new kind of command

func RunBuilderCLI added in v0.0.5

func RunBuilderCLI(ctx context.Context, watchInterrupts bool, opts ...Option) error

func RunStandardCLI

func RunStandardCLI(ctx context.Context, name string, watchInterrupts bool, log Logger, opts ...Option) error

RunStandardCLI runs a standard command line instance with shutdown watchers etc. If log is nil a logger will be created

func RunTaskCLI added in v0.6.0

func RunTaskCLI(ctx context.Context, watchInterrupts bool, opts ...Option) error

func TemplateFuncs added in v0.7.0

func TemplateFuncs(all bool) template.FuncMap

Types

type AppBuilder

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

AppBuilder is the main runner and configuration handler

func New

func New(ctx context.Context, name string, opts ...Option) (*AppBuilder, error)

New creates a new CLI Builder

func (*AppBuilder) Configuration

func (b *AppBuilder) Configuration() map[string]any

Configuration is the loaded configuration, valid only after LoadConfig() is called, usually done during RunCommand()

func (*AppBuilder) Context

func (b *AppBuilder) Context() context.Context

Context gives access to the context used to control app execution and shutdown

func (*AppBuilder) CreateBuilderApp added in v0.0.5

func (b *AppBuilder) CreateBuilderApp(cmd KingpinCommand)

func (*AppBuilder) DefinitionDirectory added in v0.6.2

func (b *AppBuilder) DefinitionDirectory() string

DefinitionDirectory is the directory where the definition is stored

func (*AppBuilder) FiskApplication added in v0.2.0

func (b *AppBuilder) FiskApplication() (*fisk.Application, error)

FiskApplication loads the definition and returns a fisk application

func (*AppBuilder) HasDefinition

func (b *AppBuilder) HasDefinition() bool

HasDefinition determines if the named definition can be found on the node

func (*AppBuilder) LoadConfig

func (b *AppBuilder) LoadConfig() (map[string]any, error)

LoadConfig loads the configuration if possible, does not error if nothing is found only if loading fails

func (*AppBuilder) LoadDefinition

func (b *AppBuilder) LoadDefinition() (*Definition, error)

LoadDefinition loads the definition for the name from file, creates the command structure and validates everything

func (*AppBuilder) RunBuilderCLI added in v0.0.5

func (b *AppBuilder) RunBuilderCLI() error

RunBuilderCLI runs the builder command, used to validate apps and more

func (*AppBuilder) RunCommand

func (b *AppBuilder) RunCommand() error

RunCommand prepares the CLI and runs it, including parsing all flags etc

func (*AppBuilder) Stderr added in v0.2.0

func (b *AppBuilder) Stderr() io.Writer

Stderr is the target for writing errors

func (*AppBuilder) Stdout added in v0.2.0

func (b *AppBuilder) Stdout() io.Writer

Stdout is the target for writing errors

func (*AppBuilder) TemplateFuncs added in v0.7.1

func (b *AppBuilder) TemplateFuncs(all bool) template.FuncMap

TemplateFuncs returns standard template funcs, set all to also include sprig functions

func (*AppBuilder) UserWorkingDirectory added in v0.6.2

func (b *AppBuilder) UserWorkingDirectory() string

UserWorkingDirectory is the user is in when executing the command

type AppCheat added in v0.0.7

type AppCheat struct {
	Enabled bool     `json:"enabled,omitempty"`
	Tags    []string `json:"tags,omitempty"`

	GenericCommandCheat
}

type Command

type Command interface {
	// CreateCommand should add all the flags, sub commands, arguments and more to the app
	CreateCommand(app KingpinCommand) (*fisk.CmdClause, error)
	// SubCommands is the list of defined sub commands, nil if none
	SubCommands() []json.RawMessage
	// Validate should validate the properties of the command after creation
	Validate(Logger) error
	// String should describe the plugin, usually in the form 'name (kind)'
	String() string
}

Command is the interface a command plugin should implement

type CommandConstructor

type CommandConstructor func(*AppBuilder, json.RawMessage, Logger) (Command, error)

CommandConstructor should exist in any package that is used as a plugin

type Definition

type Definition struct {
	Name         string    `json:"name"`
	Description  string    `json:"description"`
	Version      string    `json:"version"`
	Author       string    `json:"author"`
	Cheats       *AppCheat `json:"cheat"`
	HelpTemplate string    `json:"help_template"`
	IncludeFile  string    `json:"include_file"`

	GenericSubCommands
	// contains filtered or unexported fields
}

Definition defines the entire application, it's the root of the app with all possible sub commands below it

func (*Definition) Validate

func (d *Definition) Validate(log Logger) error

Validate validates the top of the definition for validity

type GenericArgument

type GenericArgument struct {
	Name                 string   `json:"name"`
	Description          string   `json:"description"`
	Required             bool     `json:"required"`
	Enum                 []string `json:"enum"`
	Default              string   `json:"default"`
	ValidationExpression string   `json:"validate"`
}

GenericArgument is a standard command line argument

type GenericCommand

type GenericCommand struct {
	Name          string               `json:"name"`
	Description   string               `json:"description"`
	Aliases       []string             `json:"aliases"`
	Type          string               `json:"type"`
	Arguments     []GenericArgument    `json:"arguments,omitempty"`
	Flags         []GenericFlag        `json:"flags,omitempty"`
	ConfirmPrompt string               `json:"confirm_prompt"`
	Banner        string               `json:"banner"`
	Cheat         *GenericCommandCheat `json:"cheat,omitempty"`
}

GenericCommand is a typical command with the minimal options all supported

func (*GenericCommand) Validate

func (c *GenericCommand) Validate(logger Logger) error

Validate ensures the command is well-formed

type GenericCommandCheat added in v0.0.7

type GenericCommandCheat struct {
	Label string `json:"label,omitempty"`
	Cheat string `json:"cheat"`
}

type GenericFlag

type GenericFlag struct {
	Name                 string   `json:"name"`
	Description          string   `json:"description"`
	Required             bool     `json:"required"`
	PlaceHolder          string   `json:"placeholder"`
	Enum                 []string `json:"enum"`
	Default              any      `json:"default"`
	Bool                 bool     `json:"bool"`
	EnvVar               string   `json:"env"`
	Short                string   `json:"short"`
	ValidationExpression string   `json:"validate"`
}

GenericFlag is a standard command line flag

type GenericSubCommands

type GenericSubCommands struct {
	Commands []json.RawMessage `json:"commands"`
}

GenericSubCommands is the typical sub commands most commands support, custom plugins can choose to use this if they support sub commands

func (*GenericSubCommands) Validate

func (c *GenericSubCommands) Validate(logger Logger) error

Validate is a noop here

type KingpinCommand

type KingpinCommand interface {
	Flag(name, help string) *fisk.FlagClause
	Command(name, help string) *fisk.CmdClause
}

type Logger

type Logger interface {
	Debugf(format string, v ...any)
	Infof(format string, v ...any)
	Warnf(format string, v ...any)
	Errorf(format string, v ...any)
}

Logger is a pluggable logger interface

func NewDefaultLogger added in v0.7.0

func NewDefaultLogger() Logger

type NoopLogger added in v0.2.0

type NoopLogger struct{}

func (NoopLogger) Debugf added in v0.2.0

func (n NoopLogger) Debugf(format string, v ...any)

func (NoopLogger) Errorf added in v0.2.0

func (n NoopLogger) Errorf(format string, v ...any)

func (NoopLogger) Infof added in v0.2.0

func (n NoopLogger) Infof(format string, v ...any)

func (NoopLogger) Warnf added in v0.2.0

func (n NoopLogger) Warnf(format string, v ...any)

type Option

type Option func(*AppBuilder) error

Option configures the builder

func WithAppDefinitionBytes added in v0.7.2

func WithAppDefinitionBytes(def []byte) Option

WithAppDefinitionBytes uses a provided app definition rather than load one from disk

func WithAppDefinitionFile

func WithAppDefinitionFile(f string) Option

WithAppDefinitionFile sets a file where the definition should be loaded from

func WithConfigPaths

func WithConfigPaths(paths ...string) Option

WithConfigPaths overrides the path to the app configuration file, should be a full absolute path

func WithContextualUsageOnError added in v0.1.0

func WithContextualUsageOnError() Option

WithContextualUsageOnError handles application termination by showing contextual help rather than returning an error

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets a custom logger to use

func WithStderr added in v0.2.0

func WithStderr(w io.Writer) Option

WithStderr configures a standard error out handle to output

func WithStdout added in v0.2.0

func WithStdout(w io.Writer) Option

WithStdout configures a standard out handle to output

type TemplateState added in v0.7.0

type TemplateState struct {
	Arguments any
	Flags     any
	Config    any
	Input     any
}

func NewTemplateState added in v0.7.0

func NewTemplateState(args map[string]any, flags map[string]any, cfg any, input any) *TemplateState

type Transform added in v0.2.0

type Transform struct {
	// Query is a JQ query to process, deprecated for backwards compatibility only
	Query string `json:"query"`

	// JQ is a JQ query to process
	JQ *jqTransform `json:"jq,omitempty"`

	// LineGraph is an ascii line graph from a single json array of float64 or float64 per line
	LineGraph *lineGraphTransform `json:"line_graph,omitempty"`

	// BarGraph is a ascii bar graph from a json map[string]float64
	BarGraph *barGraphTransform `json:"bar_graph,omitempty"`

	// Pipeline is a series of transforms to pass the data through
	Pipeline []Transform `json:"pipeline,omitempty"`

	// Template parses input through Go templates
	Template *templateTransform `json:"template,omitempty"`

	// Report turns row orientated data into a paged report
	Report *reportTransform `json:"report,omitempty"`

	// WriteFile writes data to a file
	WriteFile *writeFileTransform `json:"write_file,omitempty"`

	// ToJSON converts from YAML or JSON into JSON
	ToJSON *toJSONTransform `json:"to_json,omitempty"`

	// ToYAML converts from JSON to YAML
	ToYAML *toYAMLTransform `json:"to_yaml,omitempty"`

	// Scaffold renders complex multi file output from an input data structure
	Scaffold *scaffoldTransform `json:"scaffold,omitempty"`
}

Transform is a generic transformation definition

func (*Transform) Transform added in v0.2.0

func (t *Transform) Transform(ctx context.Context, r io.Reader, args map[string]any, flags map[string]any, b *AppBuilder) (io.Reader, error)

func (*Transform) TransformBytes added in v0.2.0

func (t *Transform) TransformBytes(ctx context.Context, r []byte, args map[string]any, flags map[string]any, b *AppBuilder) ([]byte, error)

func (*Transform) Validate added in v0.2.0

func (t *Transform) Validate(log Logger) error

Jump to

Keyboard shortcuts

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