commandline

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2021 License: GPL-3.0, GPL-3.0 Imports: 4 Imported by: 0

Documentation

Overview

Package commandline facilitates parsing of command line input. Given a command template, it can be used to tokenisze and validate user input. It also functions as a tab-completion engine, implementing the terminal.TabCompletion interface.

The Commands type is the base product of the package. To create an instance of Commands, use ParseCommandTemplate() with a suitable template. See the function documentation for syntax. An example template would be:

template := []string {
	"LIST",
	"PRINT [%s]",
	"SORT (RISING|FALLING)",
}

Once parsed, the resulting Commands instance can be used to validate input.

cmds, _ := ParseCommandTemplate(template)
toks := TokeniseInput("list")
err := cmds.ValidateTokens(toks)
if err != nil {
	panic("validation failed")
}

Note that all validation is case-insensitive. Once validated the tokens can be processed and acted upon. The commandline package proveds some useful functions to work on tokenised input. We've already seen TokeniseInput(). This function creates an instance of type Tokens. The Get() function can be used to retrieve the next token in line.

The beauty of validating tokens against the command template is that we can simplify and restrict our handling of Get() returned values to only those that we know have passed the validation. For example, using the above template, we can implement a switch very consisely:

option, _ := toks.Get()
switch strings.ToUpper(option) {
	case "LIST:
		list()
	case "PRINT:
		fmt.Println(toks.Get())
	case "SORT:
		rising = true
		if toks.Get() == "FALLING" {
			rising = false
		}
		sort(data, rising)
}

The TabCompletion type is used to transform input such that it more closely resemebles a valid command according to the supplied template. The NewTabCompletion() function expects an instance of Commands.

tbc := NewTabCompletion(cmds)

The Complete() function can then be used to transform user input:

inp := "LIS"
inp = tbc.Complete(inp)

In this instance the value of inp will be "LIST " (note the trailing space). Given a number of options to use for the completion, the first option will be returned first followed by the second, third, etc. on subsequent calls to Complete(). A tab completion session can be terminated with a call to Reset().

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Commands

type Commands struct {
	Index map[string]*node
	// contains filtered or unexported fields
}

Commands is the root of the node tree.

func ParseCommandTemplate

func ParseCommandTemplate(template []string) (*Commands, error)

ParseCommandTemplate turns a string representation of a command template into a machine friendly representation

Syntax

[ a ]	required keyword
( a )	optional keyword
[ a | b | ... ]	required selection
( a | b | ... )	optional selection

groups can be embedded in one another

Placeholders

%N		numeric value
%P		irrational number value
%S     string (numbers can be strings too)
%F     file name

Placeholders can be labelled. For example:

%<first name>S
%<age>N

func (*Commands) AddHelp

func (cmds *Commands) AddHelp(helpCommand string, helps map[string]string) error

AddHelp adds a "help" command to an already prepared Commands type. it uses the top-level nodes of the Commands instance as arguments for the specified helpCommand.

func (Commands) Help

func (cmds Commands) Help(keyword string) string

Help returns the help (and usage for the command).

func (Commands) HelpOverview

func (cmds Commands) HelpOverview() string

HelpOverview returns a columnised list of all help entries.

func (Commands) Len

func (cmds Commands) Len() int

Len implements Sort package interface.

func (Commands) Less

func (cmds Commands) Less(i int, j int) bool

Less implements Sort package interface.

func (Commands) String

func (cmds Commands) String() string

String returns the verbose representation of the command tree. Use this only for testing/validation purposes. HelpString() is more useful to the end user.

func (Commands) Swap

func (cmds Commands) Swap(i int, j int)

Swap implements Sort package interface.

func (Commands) Validate

func (cmds Commands) Validate(input string) error

Validate input string against command defintions.

func (Commands) ValidateTokens

func (cmds Commands) ValidateTokens(tokens *Tokens) error

ValidateTokens like Validate, but works on tokens rather than an input string.

type TabCompletion

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

TabCompletion should be initialised once with the instance of Commands it is to work with.

func NewTabCompletion

func NewTabCompletion(cmds *Commands) *TabCompletion

NewTabCompletion initialises a new TabCompletion instance. Completion works best if Commands has been sorted.

func (*TabCompletion) Complete

func (tc *TabCompletion) Complete(input string) string

Complete transforms the input such that the last word in the input is expanded to meet the closest match allowed by the template. Subsequent calls to Complete() without an intervening call to Reset() will cycle through the original available options.

func (*TabCompletion) Reset

func (tc *TabCompletion) Reset()

Reset is used to clear an outstanding completion session.

type Tokens

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

Tokens represents tokenised input. This can be used to walk through the input string (using get()) for eas(ier) parsing.

func TokeniseInput

func TokeniseInput(input string) *Tokens

TokeniseInput creates and returns a new Tokens instance.

func (*Tokens) End

func (tk *Tokens) End()

End the token traversal process. It can be restarted with the Reset() function.

func (*Tokens) Get

func (tk *Tokens) Get() (string, bool)

Get returns the next token in the list, and a success boolean - if the end of the token list has been reached, the function returns false instead of true.

func (Tokens) IsEnd

func (tk Tokens) IsEnd() bool

IsEnd returns true if we're at the end of the token list.

func (Tokens) Len

func (tk Tokens) Len() int

Len returns the number of tokens.

func (Tokens) Peek

func (tk Tokens) Peek() (string, bool)

Peek returns the next token in the list (without advancing the list), and a success boolean - if the end of the token list has been reached, the function returns false instead of true.

func (Tokens) Remainder

func (tk Tokens) Remainder() string

Remainder returns the remaining tokens as a string.

func (Tokens) Remaining

func (tk Tokens) Remaining() int

Remaining returns the count of reminaing tokens in the token list.

func (*Tokens) ReplaceEnd

func (tk *Tokens) ReplaceEnd(newEnd string)

ReplaceEnd changes the last entry of the token list.

func (*Tokens) Reset

func (tk *Tokens) Reset()

Reset begins the token traversal process from the beginning.

func (*Tokens) String

func (tk *Tokens) String() string

String representation of tokens.

func (*Tokens) Unget

func (tk *Tokens) Unget()

Unget walks backwards in the token list.

func (*Tokens) Update

func (tk *Tokens) Update(s string)

Update last token with a new value. Useful for normalising token entries.

Jump to

Keyboard shortcuts

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