gosh

package module
v0.0.0-...-2f473e1 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2015 License: Apache-2.0 Imports: 8 Imported by: 0

README

gosh version 0.0.1

Gosh is a simple package designed to make creating command line shells in go a little bit easier. The concept is simple: have a command prompt with auto-completion and history that can execute commands written in go. The commands can be hierarchical, similar to the CLI in common network operating systems. The commands can also be more like traditional OS commands, with no hierarchy.

Examples

A simple example of a single command shell:

package main

import (
  "fmt"
  "github.com/abates/gosh"
)

type cmd string

func (c cmd) Exec() error {
  fmt.Printf("Executing %s\n", string(c))
  return nil
}

var commands = gosh.CommandMap{
  "cmd": cmd("My Command!"),
}

func main() {
  shell := gosh.NewShell(commands)
  shell.Exec()
}

Any arguments that follow the command on the prompt are passed into the Exec method by way of the os.Args string slice. The shell will initialize with a default line editor that implements history, auto-completion and the prompt string.

The default shell can be supplied with a customized prompter:

func main() {
  shell := gosh.NewShell(commands)
  shell.SetPrompter(func() string {
    return "Custom Prompt> "
  })
  shell.Exec()
}

Commands can optionally specify auto-completion candidates for their arguments:

type cmd string

func (c cmd) Exec() error {
  fmt.Printf("Executing %s\n", string(c))
  return nil
}

func (c cmd) Completions(field string) []string {
  return []string{"arg1", "arg2", "arg3"}
}

Command hierarchies can be created with the CommandTree struct:

var commands = gosh.CommandMap{
  "show": gosh.NewTreeCommand(gosh.CommandMap{
    "interface":  InterfaceCommand{},
    "interfaces": InterfacesCommand{},
    "time":       TimeCommand{},
  }),
}

Documentation

https://godoc.org/github.com/abates/gosh

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDefaultPrompter indicates that the Prompt is not a DefaultPrompt so the
	// prompter function cannot be overridden
	ErrDefaultPrompter = errors.New("can only set the prompter on the DefaultPrompt")

	// ErrDuplicateCommand indicates a command with the same name already exists
	// in the CommandMap
	ErrDuplicateCommand = errors.New("command already exists")

	// ErrNilCallback indicates that a callback function was set to nil
	ErrNilCallback = errors.New("cannot assign nil callback functions")

	// ErrNilLineEditor indicates that the Prompt's line editor was set to nil
	ErrNilLineEditor = errors.New("cannot assign a nil line editor")

	// ErrNilPrompt indicates that the Shell's Prompt was set to nil
	ErrNilPrompt = errors.New("cannot assign a nil prompt")

	// ErrNilPrompter indicates that the Prompt's prompter was set to nil
	ErrNilPrompter = errors.New("cannot assign a nil prompter")

	// ErrNilWriter indicates the shell's writer was set to nil
	ErrNilWriter = errors.New("cannot assign a nil writer")

	// ErrNoMatchingCommand indicates a matching command could not be found in the CommandMap
	ErrNoMatchingCommand = errors.New("no matching command")
)

Functions

This section is empty.

Types

type Closeable

type Closeable interface {
	Close() error
}

Closeable objects implement a Close method.

If the prompt detects that the line editor implements Closeable then it will call Close upon completing the prompt cycle

type Command

type Command interface {
	Exec() error
}

Command indicates that an object can be executed

Exec should perform any computation necessary to execute the command that provides the interface. Prior to calling the Exec method, the shell will assign the arguments to os.Args. If the command is expecting any arguments, then they will be availabe as os.Args. The argument list includes the command path as os.Args[0]

type CommandMap

type CommandMap map[string]Command

CommandMap is exactly what it sounds like.

CommandMap is a map of Commands that are keyed by the command name that should be typed at the prompt. If the prompt should execute a command when ls\n is typed, then the command name is ls and the Command is the concrete implementation that provides Exec. When ls\n is typed at the prompt, the backing Command will be looked up in the CommandMap and its Exec method called

func (CommandMap) Add

func (commands CommandMap) Add(commandName string, command Command) error

Add a comand to the map

func (CommandMap) Exec

func (commands CommandMap) Exec(fields []string) error

Exec finds and execute a command corresponding to the argument list

func (CommandMap) Find

func (commands CommandMap) Find(arguments []string) (Command, []string, error)

Find traverses the command map using the arguments slice and return the Command whose path exactly matches the argument list. If no Command can be found with an exact matching path then ErrNoMatchingCommand is returned.

type Completable

type Completable interface {
	Completions(field string) []string
}

Completable is the interface for making a Command auto-completable

Completions returns a slice of strings representing the list of completion candidates. The method is called with the field immediately following the command. For instance. If the command being completed is "ls /has/cheesburger" Then the Completion method for ls will be provided the string /has/cheeseburger

type DefaultLineEditor

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

DefaultLineEditor is a concrete implementation of LineEditor that uses github.com/peterh/liner as the line editor

func NewDefaultLineEditor

func NewDefaultLineEditor(commands CommandMap) *DefaultLineEditor

NewDefaultLineEditor returns a fully initialized line editor that includes autocompletion and history

func (*DefaultLineEditor) Close

func (d *DefaultLineEditor) Close() error

Close returns the terminal to the original state. This includes taking the terminal out of raw mode and turning echo back on

func (*DefaultLineEditor) Prompt

func (d *DefaultLineEditor) Prompt(prompt string) (string, error)

Prompt will prompt the user with the prompt string, collect the response and return it. If the upstream liner.Prompt function succeeds, then the response is added to the history. The collected string and any associated error is returned

type DefaultPrompt

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

DefaultPrompt is a concrete implementation of Prompt

DefaultPrompt includes a basi "> " prompt and the DefaultLineEditor which provides tab completion and command history

func NewDefaultPrompt

func NewDefaultPrompt(commands CommandMap) *DefaultPrompt

NewDefaultPrompt returns a fully initialized DefaultPrompt.

When NextResponse is called on the DefaultPrompt the prompt will be "> ". The DefaultLineEditor is used so tab completions and history is available

func (*DefaultPrompt) Close

func (p *DefaultPrompt) Close() error

Close closes the line editor (if it is closeable)

func (*DefaultPrompt) NextResponse

func (p *DefaultPrompt) NextResponse() (string, error)

NextResponse prompts the user and returns the uer's input

func (*DefaultPrompt) SetLineEditor

func (p *DefaultPrompt) SetLineEditor(lineEditor LineEditor) error

SetLineEditor allows overriding the default line editor

The DefaultPrompt uses github.com/peterh/liner as the default line editor. This can be overridden with a different LineEditor implementation. If SetLineEditor is called with a nil LineEditor then the ErrNilLineEditor error is returned

func (*DefaultPrompt) SetPrompter

func (p *DefaultPrompt) SetPrompter(prompter func() string) error

SetPrompter will allow overriding the default prompter.

If the prompter argument is nil then the prompter is not overridden and the ErrNilCallback is returned. Otherwise the prompter is set to whatever function is provided

type LineEditor

type LineEditor interface {
	Prompt(string) (string, error)
}

LineEditor wraps the basic Prompt method

type Prompt

type Prompt interface {
	NextResponse() (string, error)
}

Prompt receivers implement a NextResponse method

NextResponse should return any response provided by the user as well as any error encountered during the prompting

type Prompter

type Prompter func() string

Prompter returns the prompt string used in NextResponse

Prompter is a function that is called to generate the prompt string that will preced user input. For instance, if a Prompter returns the string "> " then all input lines will begin with that string and user input starts just after the space following the ">"

type Shell

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

Shell is the foundation for Gosh

A Shell provides a way to prompt users for command input and then execute those commands. It includes line editing, history and command completion.

func NewShell

func NewShell(commands CommandMap) *Shell

NewShell returns a fully initialized Shell for the given CommandMap

func (*Shell) Exec

func (shell *Shell) Exec()

Exec starts the Shell prompt/execute loop.

Exec returns upon io.EOF in the input stream

func (*Shell) SetErrorWriter

func (shell *Shell) SetErrorWriter(writer io.Writer) error

SetErrorWriter overrides the error stream

Shell defaults to use os.Stderr for error messages. This can be overridden with a non-nil io.Writer. A nil writer generates the ErrNilWriter error

func (*Shell) SetPrompt

func (shell *Shell) SetPrompt(prompt Prompt) error

SetPrompt overrides the Shell' Prompt implementation

Shell is intialized with a DefaultPrompt to prompt the user and gather responses. This includes command completion and history. However, the Prompt can be overridden by a different implementation. If a nil Prompt is given, then ErrNilPrompt is returned

func (*Shell) SetPrompter

func (shell *Shell) SetPrompter(prompter Prompter) error

SetPrompter overrides the prompter when the DefaultPrompt is being used

A nil prompt will generate the ErrNilPrompter error and trying to override the prompter when the DefaultPrompt is not being used generates ErrDefaultPrompter

type TreeCommand

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

TreeCommand is a concrete implementation of Command

TreeCommand provides the ability to create a hierarchy of commands. This type of command hierarchy is very common in command line interfaces for network appliances such as router and firewalls (think JunOS or Cisco IOS)

func NewTreeCommand

func NewTreeCommand(commands CommandMap) TreeCommand

NewTreeCommand creates a TreeCommand for the given CommandMap

func (TreeCommand) Add

func (t TreeCommand) Add(name string, command Command) error

Add another sub-command to this TreeCommand

func (TreeCommand) Exec

func (t TreeCommand) Exec() error

Exec does nothing since a TreeCommand only contains sub-commands

func (TreeCommand) SubCommands

func (t TreeCommand) SubCommands() CommandMap

SubCommands returns the CommandMap of sub commands that belong to this TreeCommand

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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