commandline

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2024 License: 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)
}

Tab Completion

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

Extensions

Extensions are a way of giving a command additional arguments that are not in the original template. This is good for handling specialist arguments that are rarely used but none-the-less would benefit from tab-completion.

To give a command an extension the %x directive is used. The placeholder must have a label for it to be effective. In the example below the label is "listing". Note that labels are case insensitive.

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

Once the template has been parsed, an extension handler must be added with the AddExtension() function. In addition to the label argument, which must be the same as the label given in the template, the AddExtension() function also requires an implementation of the interface.

The Commands() function of the Extension interface will return another instance of the Commands type. This instance will be used when the %x directive is encounted during validation or tab completion.

Index

Constants

View Source
const HelpCommand = "HELP"

The command that should be used to invoke the HELP system

Variables

This section is empty.

Functions

func AddHelp added in v0.35.0

func AddHelp(cmds *Commands) error

AddHelp() adds the HELP command to the list of commands if it hasn't been added already (or was part of the template given to the ParseCommandTemplate() function)

It is up to the user of the commandline package to do something with the HELP command

func HelpSummary added in v0.35.0

func HelpSummary(cmds *Commands) string

HelpSummary returns a string showing the top-level HELP topics in five columns

Types

type Commands

type Commands struct {
	// 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
%X  extension

Placeholders can be labelled. For example:

%<first name>S
%<age>N

Returned commands are sorted alphabetically

func (*Commands) AddExtension added in v0.35.0

func (cmds *Commands) AddExtension(group string, extension Extension)

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. Only really useful for the validation process.

func (Commands) Swap

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

Swap implements Sort package interface.

func (Commands) Usage added in v0.35.0

func (cmds Commands) Usage(command string) string

Usage returns the usage string for a command

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 Extension added in v0.35.0

type Extension interface {
	CommandExtension(extension string) *Commands
}

A commandline Extension provides an instance of Commands such that it can be used to extend the number of parameters available to a command, mainly for tab-completion purposes

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

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 TabCompletionReset() will cycle through the original available options.

func (*TabCompletion) Match added in v0.35.0

func (tc *TabCompletion) Match(n *node, tokens *Tokens)

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