cshell

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 10 Imported by: 0

README

cshell

A go package implementing a simple command line shell

Behavior notes

Input handling:

  • A command line may be terminated by CR, by LF, or by a CR LF pair, which is collapsed into one terminator. Earlier versions only recognized CR, so input coming from a pipe or an LF-only client never executed.
  • Control characters that carry no shell meaning (BEL, FF, ^A, ^U, ...) are dropped instead of being inserted into the command line and echoed to the terminal. They therefore no longer reach command handlers through args.
  • BS (^H) deletes the previous character, like DEL, since terminals use either one for backspace.
  • A control sequence is read to its end, so keys that carry a parameter (Delete, Home, a function key) no longer leave their digits on the command line. ESC followed by a character that this shell does not bind is treated as a meta sequence and both bytes are dropped; a line terminator inside a half finished sequence is honored rather than swallowed, so the line cannot get stuck.
  • A reader that returns nothing without an error is retried, and after maxEmptyReads of them Run reports it and stops, instead of spinning.

Commands:

  • A command name may be several words long (dev info), in which case it matches only a line whose leading words are exactly those words. The first word may be abbreviated (de info), the rest must be spelled out. A name given in full always beats an abbreviation, and a line that matches several commands without naming any of them in full is refused instead of guessed at. Single word names abbreviate as before (hist for history). Matching used to be a plain HasPrefix on the whole name, which put unrelated names in each other's way and made multi-word names unreachable.
  • Registering a command with a nil handler and running it reports an error instead of panicking, and a shell that was never given streams (SetIO) keeps quiet instead of panicking on its first write.

History:

  • New limits the history to defaultMaxHistory (1000) entries and drops the oldest once it is exceeded, so a long lived session cannot grow memory without bound. Set MaxHistory to 0 to keep everything.
  • A history entry is kept on a single line: line breaks handed to AddHistory become spaces, since an entry is listed on one line and written to a line oriented file.
  • The history command registers save <file> and load <file>, and the file name comes from shell input. Both subcommands are disabled unless a program opts in, otherwise any client holding a session gets an arbitrary file read (load) and file overwrite (save) primitive:
sh.AllowHistoryFiles = true                 // otherwise: "history file access is disabled"
sh.HistoryFileDir = "/var/lib/mysh/history" // optional; confines save/load to this directory

With HistoryFileDir set, a relative name is resolved against that directory and any name that resolves outside it, including through a symlink, is refused. Shell.SaveHistory and Shell.LoadHistory stay unrestricted, since they are called by the program rather than by shell input.

Caveats

  • A shell holds one session's state and is not synchronized. Give each session its own Shell and drive it from the goroutine that calls Run; do not call into a running shell from another goroutine.
  • Registering two commands under the same name is allowed but the first one wins, and there is no way to replace or remove a command once registered.
  • Output is written a character or two at a time. Where that matters, hand SetIO a buffered writer and flush it when the prompt is written, but note that the shell does not know when the program writes the writer directly, so interleaving needs care.

Documentation

Index

Constants

View Source
const (
	VT100_UP    = 65
	VT100_DOWN  = 66
	VT100_RIGHT = 67
	VT100_LEFT  = 68
	ASCII_TAB   = 0x09
	ASCII_CTRLC = 0x03
	ASCII_CTRLD = 0x04
	ASCII_BEL   = 0x07
	ASCII_BS    = 0x08
	ASCII_CR    = 0x0D
	ASCII_LF    = 0x0A
	ASCII_ESC   = 0x1B
	ASCII_DEL   = 0x7F

	FlagHide   = 1 << 0
	FlagNoargs = 1 << 1
	FlagAlias  = 1 << 2
)

Variables

View Source
var ErrHistoryFilesDisabled = errors.New("history file access is disabled, set Shell.AllowHistoryFiles to enable it")

ErrHistoryFilesDisabled is returned by the history save/load subcommands while Shell.AllowHistoryFiles is false.

View Source
var ErrNoSuchCommand = errors.New("no such command")

Functions

func ParseLine added in v1.0.2

func ParseLine(line string) (args []string, err error)

Types

type Command

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

type CommandFunc

type CommandFunc = func(args []string) error

type Shell

type Shell struct {
	Prompt string
	Echo   bool
	// AllowHistoryFiles enables the "save <file>" and "load <file>" subcommands
	// of the built-in history command.  It is disabled by default because the
	// file name comes from shell input, which otherwise gives anyone holding a
	// shell session an arbitrary file read (load) and file overwrite (save)
	// primitive against the process running the shell.
	AllowHistoryFiles bool
	// HistoryFileDir optionally restricts the files that the history save/load
	// subcommands may touch.  A relative name is resolved against it and a
	// resolved path that escapes the directory, including through a symlink, is
	// rejected.  Empty imposes no restriction beyond AllowHistoryFiles.
	HistoryFileDir string
	// MaxHistory bounds the number of command lines kept in the history, so that
	// a long lived session cannot grow it without limit; once it is exceeded the
	// oldest entries are dropped.  New defaults it to defaultMaxHistory, and 0
	// keeps every entry.
	MaxHistory int
	// contains filtered or unexported fields
}

func New

func New() (s *Shell)

New creates a new command prompt.

func (*Shell) AddHistory added in v1.4.0

func (s *Shell) AddHistory(line string)

AddHistory adds a line to the history

func (*Shell) ClearHistory added in v1.4.0

func (s *Shell) ClearHistory()

func (*Shell) Command

func (s *Shell) Command(name string, desc string, fx CommandFunc)

func (*Shell) CommandOneArg added in v1.3.0

func (s *Shell) CommandOneArg(name string, desc string, fx CommandFunc)

func (*Shell) DelHistory added in v1.4.0

func (s *Shell) DelHistory(n int)

DelHistory removes the last n lines from the history

func (*Shell) ExecuteLine added in v1.2.0

func (s *Shell) ExecuteLine(line string) (err error)

func (*Shell) GetHistory added in v1.4.0

func (s *Shell) GetHistory() (h []string)

GetHistory returns a copy of the history

func (*Shell) Help

func (s *Shell) Help(args []string) error

func (*Shell) HexDump

func (s *Shell) HexDump(buf []byte)

HexDump outputs a `hexdump -C` like dump of the buf argument

func (*Shell) History added in v1.3.0

func (s *Shell) History(args []string) error

func (*Shell) LoadHistory added in v1.4.0

func (s *Shell) LoadHistory(filename string) (err error)

func (*Shell) Print

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

Print sends output to the configured io.Writer Arguments are handled in the manner of fmt.Print.

func (*Shell) Printf

func (s *Shell) Printf(format string, v ...interface{})

Printf sends output to the configured io.Writer Arguments are handled in the manner of fmt.Printf.

func (*Shell) Println

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

Println sends output to the configured io.Writer Arguments are handled in the manner of fmt.Println.

func (*Shell) Run

func (s *Shell) Run()

Run reads and writes from the io streams generating the command prompt and executing commands.

func (*Shell) SaveHistory added in v1.4.0

func (s *Shell) SaveHistory(filename string) (err error)

func (*Shell) SearchHistory added in v1.4.0

func (s *Shell) SearchHistory(match string) (line string)

func (*Shell) SetEcho

func (s *Shell) SetEcho(echo bool)

SetEcho changes the echo state for the command prompt.

func (*Shell) SetFlags added in v1.3.0

func (s *Shell) SetFlags(name string, flags int) error

func (*Shell) SetIO

func (s *Shell) SetIO(r io.Reader, w io.Writer)

SetIO assigns input and output sources. They should conform to the io.Reader and io.Writer interface. The io.Reader should block until a characters are ready.

func (*Shell) SetPrompt

func (s *Shell) SetPrompt(prompt string)

SetPrompt changes the shell command prompt.

func (*Shell) Terminate added in v1.3.0

func (s *Shell) Terminate()

Jump to

Keyboard shortcuts

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