ishell

package module
v0.0.0-...-a7612be Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2016 License: MIT Imports: 13 Imported by: 0

README

ishell

ishell is an interactive shell library for creating interactive cli applications.

Documentation

Usage

import "strings"
import "github.com/abiosoft/ishell"

func main(){
    // create new shell.
    // by default, new shell includes 'exit', 'help' and 'clear' commands.
    shell := ishell.New()

	// display welcome info.
	shell.Println("Sample Interactive Shell")

	// register a function for "greet" command.
    shell.Register("greet", func(args ...string) (string, error) {
        name := "Stranger"
        if len(args) > 0 {
            name = strings.Join(args, " ")
        }
		return "Hello "+name, nil
	})

	// start shell
	shell.Start()
}

Execution

Sample Interactive Shell
>>> help
Commands:
exit help greet
>>> greet Someone Somewhere
Hello Someone Somewhere
>>> exit
$
Reading input.
// simulate an authentication
shell.Register("login", func(args ...string) (string, error) {
	// disable the '>>>' for cleaner same line input.
	shell.ShowPrompt(false)
	defer shell.ShowPrompt(true) // yes, revert after login.

    // get username
	shell.Print("Username: ")
	username := shell.ReadLine()

    // get password.
	shell.Print("Password: ")
	password := shell.ReadPassword()

	... // do something with username and password

    return "Authentication Successful.", nil
})

Execution

>>> login
Username: someusername
Password:
Authentication Successful.
Multiline input.

Builtin support for multiple lines.

>>> This is \
... multi line

>>> Cool that << EOF
... everything here goes
... as a single argument. 
... EOF

User defined

shell.Register("multi", func(args ...string) (string, error) {
	shell.Println("Input some lines:")
	// read until a semicolon ';' is found
	// use shell.ReadMultiLinesFunc for more control.
	lines := shell.ReadMultiLines(";")
	shell.Println("You wrote:")
	return lines, nil
})

Execution

>>> multi
Input some lines:
>>> this is user defined 
... multiline input;
You wrote:
this is user defined
multiline input;
Keyboard interrupt.

Builtin interrupt handler.

>>> ^C
Input Ctrl-C once more to exit
>>> ^C
Interrupted
exit status 1

Custom

shell.RegisterInterrupt(func(args ...string) (string, error) { ... })
Durable history.
// Read and write history to $HOME/.ishell_history
shell.SetHomeHistoryPath(".ishell_history")

Check example code for more.

Supported Platforms

  • Linux
  • OSX
  • Windows

Note

ishell is in active development and can still change significantly.

Roadmap (in no particular order)

  • Support multiline inputs.
  • Command history.
  • Tab completion.
  • Handle ^C interrupts.
  • Subcommands and help texts.
  • Coloured outputs.
  • Testing, testing, testing.

Contribution

  1. Create an issue to discuss it.
  2. Send in Pull Request.

License

MIT

Credits

Library Use
github.com/flynn/go-shlex splitting input into command and args.
gopkg.in/readline.v1 history, tab completion and reading passwords.

Documentation

Overview

Package ishell implements an interactive shell.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExitErr

func ExitErr(err string) error

ExitErr creates a Exit level error. Program terminates if encountered.

func PanicErr

func PanicErr(err string) error

PanicErr creates a Panic level error. Program panics if encountered.

func StopErr

func StopErr(err string) error

StopErr creates a Stop level error. Shell stops if encountered.

func WarnErr

func WarnErr(err string) error

WarnErr creates a Warn level error

Types

type CmdFunc

type CmdFunc func(args ...string) (output string, err error)

CmdFunc represents a command function that is called after an input to the shell. The shell input is split into command and arguments like cli args and the arguments are passed to this function. The shell will print output if output != "".

type Shell

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

Shell is an interactive cli shell.

func New

func New() *Shell

New creates a new shell with default settings. Uses standard output and default prompt ">> ".

func (*Shell) Active

func (s *Shell) Active() bool

Active tells if the shell is active. i.e. Start is previously called.

func (*Shell) ClearScreen

func (s *Shell) ClearScreen() error

ClearScreen clears the screen. Same behaviour as running 'clear' in unix terminal or 'cls' in windows cmd.

func (*Shell) Commands

func (s *Shell) Commands() []string

Commands returns a sorted list of all registered commands.

func (*Shell) IgnoreCase

func (s *Shell) IgnoreCase(ignore bool)

IgnoreCase specifies whether commands should not be case sensitive. Defaults to false i.e. commands are case sensitive. If true, commands must be registered in lower cases. e.g. shell.Register("cmd", ...)

func (*Shell) Print

func (s *Shell) Print(val ...interface{})

Print prints to output.

func (*Shell) PrintCommands

func (s *Shell) PrintCommands()

PrintCommands prints a space separated list of registered commands to the shell.

func (*Shell) Println

func (s *Shell) Println(val ...interface{})

Println prints to output and ends with newline character.

func (*Shell) ReadLine

func (s *Shell) ReadLine() string

ReadLine reads a line from standard input.

func (*Shell) ReadMultiLines

func (s *Shell) ReadMultiLines(terminator string) string

ReadMultiLines reads multiple lines from standard input. It stops reading when terminator is encountered at the end of the line. It returns the lines read including terminator. For more control, use ReadMultiLinesFunc.

func (*Shell) ReadMultiLinesFunc

func (s *Shell) ReadMultiLinesFunc(f func(string) bool) string

ReadMultiLinesFunc reads multiple lines from standard input. It passes each read line to f and stops reading when f returns false.

func (*Shell) ReadPassword

func (s *Shell) ReadPassword() string

ReadPassword reads password from standard input without echoing the characters. Note that this only works as expected when the standard input is a terminal.

func (*Shell) Register

func (s *Shell) Register(command string, function CmdFunc)

Register registers a function for command. It overwrites existing function, if any.

func (*Shell) RegisterGeneric

func (s *Shell) RegisterGeneric(function CmdFunc)

RegisterGeneric registers a generic function for all inputs. It is called if the shell input could not be handled by any of the registered functions. Unlike Register, the entire line is passed as first argument to CmdFunc.

func (*Shell) RegisterInterrupt

func (s *Shell) RegisterInterrupt(function CmdFunc)

RegisterInterrupt registers a function to handle keyboard interrupt.

func (*Shell) SetHistoryPath

func (s *Shell) SetHistoryPath(path string) error

SetHistoryPath sets where readlines history file location. Use an empty string to disable history file. It is empty by default.

func (*Shell) SetHomeHistoryPath

func (s *Shell) SetHomeHistoryPath(path string)

SetHomeHistoryPath is a convenience method that sets the history path with a $HOME prepended path.

func (*Shell) SetMultiPrompt

func (s *Shell) SetMultiPrompt(prompt string)

SetMultiPrompt sets the prompt string used for multiple lines. The string to be displayed before the cursor; starting from the second line of input.

func (*Shell) SetOut

func (s *Shell) SetOut(writer io.Writer)

SetOut sets the writer to write outputs to.

func (*Shell) SetPrompt

func (s *Shell) SetPrompt(prompt string)

SetPrompt sets the prompt string. The string to be displayed before the cursor.

func (*Shell) ShowPrompt

func (s *Shell) ShowPrompt(show bool)

ShowPrompt sets whether prompt should show when requesting input for ReadLine and ReadPassword. Defaults to true.

func (*Shell) Start

func (s *Shell) Start()

Start starts the shell. It reads inputs from standard input and calls registered functions accordingly. This function blocks until the shell is stopped.

func (*Shell) Stop

func (s *Shell) Stop()

Stop stops the shell. This will stop the shell from auto reading inputs and calling registered functions. A stopped shell is only inactive but totally functional. Its functions can still be called.

func (*Shell) Unregister

func (s *Shell) Unregister(command string)

Unregister unregisters a function for a command

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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