minicli

package
v0.0.0-...-81ce8a9 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2022 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

The minicli package implements a simple command line interface for minimega. During startup, minimega initializers will register callbacks with minicli. Each registration consists of a pattern that the user's input should match, and a function pointer that should be invoked when there's a match.

Patterns consist of required text, required and optional fields, multiple choice arguments, and variable number of arguments. The pattern syntax is as follows:

foo bar     literal required text, as in "capture netflow"
<foo>       a required string, returned in the arg map with key "foo"
<foo bar>   a required string, still returned in the arg map with key "foo".
            The extra text is just documentation
<foo,bar>   a required multiple choice argument. Returned as whichever choice
            is made in the argmap (the argmap key is simply created).
[foo]       an optional string, returned in the arg map with key "foo".
            There can be only one optional arg and it must be at the end of
            the pattern.
[foo,bar]   an optional multiple choice argument. Must be at the end of
            pattern.
<foo>...    a required list of strings, one or more, with the key "foo" in
            the argmap. Must be at the end of the pattern.
[foo]...    an optional list of strings, zero or more, with the key "foo" in
            the argmap. This is the only way to support multiple optional
            fields. Must be at the end of the pattern.
(foo)       a nested subcommand consuming all items to the end of the input
            string. Must be at the end of pattern.

minicli also supports multiple output rendering modes and stream and tabular compression.

Index

Constants

View Source
const (
	CommentLeader = "#"
)

Variables

View Source
var HistoryLen = 10000

HistoryLen is the length of the history of commands that minicli stores. This may be increased or decreased as needed. If set to 0 or less, the history will grow unbounded and may cause an OOM crash.

View Source
var Preprocessor func(*Command) error

Preprocessor may be set to perform actions immediately before commands run.

Functions

func ClearHistory

func ClearHistory()

ClearHistory clears the command history.

func Doc

func Doc() (string, error)

Doc generate CLI documentation, in JSON format.

func ExpandAliases

func ExpandAliases(input string) string

ExpandAliases finds the first alias match in input and replaces it with it's expansion.

func Help

func Help(input string) string

func History

func History() string

History returns a newline-separated string of all the commands that have been run by minicli since it started or the last time that ClearHistory was called.

func MustRegister

func MustRegister(h *Handler)

MustRegister calls Register for a handler and panics if the handler has an error registering.

func ProcessCommand

func ProcessCommand(c *Command) <-chan Responses

Process a prepopulated Command

func ProcessString

func ProcessString(input string, record bool) (<-chan Responses, error)

Process raw input text. An error is returned if parsing the input text failed.

func Register

func Register(h *Handler) error

Register a new API based on pattern. See package documentation for details about supported patterns.

func Reset

func Reset()

Reset minicli state including all registered handlers.

func Suggest

func Suggest(input string) []string

func Validate

func Validate() error

Validate checks for ambiguous patterns

Types

type CLIFunc

type CLIFunc func(*Command, chan<- Responses)

type Command

type Command struct {
	Original string // original raw input

	StringArgs map[string]string
	BoolArgs   map[string]bool
	ListArgs   map[string][]string

	Subcommand *Command // parsed command

	Call CLIFunc `json:"-"`

	// Record command in history (or not). Checked after the command is
	// executed so the CLIFunc can set Record according to its own logic.
	Record bool

	// Preprocess controls whether the Preprocessor is run for this command or
	// not. Must be set before the Command is executed.
	Preprocess bool

	// Set when the command is intentionally a No-op (the original string
	// contains just a comment). This was added to ensure that lines containing
	// only a comment are recorded in the history.
	Nop bool

	// Source allows developers to keep track of where the command originated
	// from. Setting and using this is entirely up to developers using minicli.
	Source string
	// contains filtered or unexported fields
}

func Compile

func Compile(input string) (*Command, error)

Create a command from raw input text. An error is returned if parsing the input text failed.

func Compilef

func Compilef(format string, args ...interface{}) (*Command, error)

Compilef wraps fmt.Sprintf and Compile

func MustCompile

func MustCompile(input string) *Command

MustCompile compiles the string, calling log.Fatal if the string is not a valid command. Should be used when providing a known command rather than processing user input.

func MustCompilef

func MustCompilef(format string, args ...interface{}) *Command

MustCompilef wraps fmt.Sprintf and MustCompile

func (*Command) SetPreprocess

func (c *Command) SetPreprocess(v bool)

SetPreprocess sets the Preprocess field for a command and all nested subcommands.

func (*Command) SetRecord

func (c *Command) SetRecord(record bool)

SetRecord sets the Record field for a command and all nested subcommands.

func (*Command) SetSource

func (c *Command) SetSource(source string)

SetSource sets the Source field for a command and all nested subcommands.

func (Command) String

func (c Command) String() string

type Flags

type Flags struct {
	Annotate   bool
	Compress   bool
	Headers    bool
	Sort       bool
	Preprocess bool
	Mode       int
	Record     bool
}

type Handler

type Handler struct {
	HelpShort string   `json:"help_short"` // a brief (one line) help message
	HelpLong  string   `json:"help_long"`  // a descriptive help message
	Patterns  []string `json:"patterns"`   // the pattern that the input should match

	// Call to invoke when the raw input matches the pattern
	Call CLIFunc `json:"-"`

	// SharedPrefix is a prefix shared by all patterns. Populated by minicli
	// when the Handler is registered.
	SharedPrefix string `json:"shared_prefix"`

	// PatternItems are the processed patterns. Populated by minicli when the
	// Handler is registered.
	PatternItems [][]PatternItem `json:"parsed_patterns"`

	// Suggest provides suggestions for variable completion. For example, the
	// `vm stop` command might provide a listing of the currently running VM
	// names if the user tries to tab complete the "target". The function takes
	// three arguments: the raw input string, the variable name (e.g. "vm"),
	// and the user's input for the variable so far.
	Suggest SuggestFunc `json:"-"`
}

type Input

type Input struct {
	Original string
	// contains filtered or unexported fields
}

type PatternItem

type PatternItem struct {
	// The item type e.g. string literal, required string
	Type itemType `json:"type"`
	// Key is usually the first word, so "<foo bar>"->"foo"
	Key string `json:"key,omitempty"`
	// The original full text of the token
	Text string `json:"text,omitempty"`
	// A list of the options in the case of multiple choice
	Options []string `json:"options,omitempty"`
}

func (PatternItem) IsChoice

func (p PatternItem) IsChoice() bool

func (PatternItem) IsCommand

func (p PatternItem) IsCommand() bool

func (PatternItem) IsList

func (p PatternItem) IsList() bool

func (PatternItem) IsLiteral

func (p PatternItem) IsLiteral() bool

func (PatternItem) IsOptional

func (p PatternItem) IsOptional() bool

func (PatternItem) IsString

func (p PatternItem) IsString() bool

type PatternItems

type PatternItems []PatternItem

func (PatternItems) String

func (items PatternItems) String() string

type Response

type Response struct {
	Host     string      // Host this response was created on
	Response string      // Simple response
	Header   []string    // Optional header. If set, will be used for both Response and Tabular data.
	Tabular  [][]string  // Optional tabular data. If set, Response will be ignored
	Error    string      // Because you can't gob/json encode an error type
	Data     interface{} //`json:"-"` // Optional user data

	// Embedded output flags, overrides defaults if set for first response
	*Flags `json:"-"`
}

A response as populated by handler functions.

type Responses

type Responses []*Response

func (Responses) Error

func (r Responses) Error() string

Error returns a string containing all the errors in the responses

func (Responses) GoString

func (r Responses) GoString()

Return a verbose output representation for use with the %#v verb in pkg fmt

func (Responses) String

func (r Responses) String() string

Return a string representation using the current output mode

type SuggestFunc

type SuggestFunc func(string, string, string) []string

Jump to

Keyboard shortcuts

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