Documentation
¶
Overview ¶
Package shell provides the Cogent Shell (cosh), which combines the best parts of Go and bash to provide an integrated shell experience that allows you to easily run terminal commands while using Go for complicated logic.
Index ¶
- func AddQuotes(str string) string
- func EscapeQuotes(str string) string
- func ExecWordIsCommand(f string) bool
- func ExecWords(ln string) ([]string, error)
- type ReadlineCompleter
- type Shell
- func (sh *Shell) ActiveSSH() *sshclient.Client
- func (sh *Shell) AddCommand(name string, cmd func(args ...string))
- func (sh *Shell) AddError(err error) error
- func (sh *Shell) AddLine(ln string)
- func (sh *Shell) AddPath(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) CancelExecution()
- func (sh *Shell) Cd(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) Close()
- func (sh *Shell) CloseSSH()
- func (sh *Shell) CmdArgs(errOk bool, sargs []string, i int) []string
- func (sh *Shell) CoSSH(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) Code() string
- func (sh *Shell) CompleteEdit(data any, text string, cursorPos int, completion complete.Completion, ...) (ed complete.Edit)
- func (sh *Shell) CompleteMatch(data any, text string, posLine, posChar int) (md complete.Matches)
- func (sh *Shell) DeleteJob(cmdIO *exec.CmdIO) bool
- func (sh *Shell) EndContext()
- func (sh *Shell) Exec(errOk, start, output bool, cmd any, args ...any) string
- func (sh *Shell) ExecArgs(cmdIO *exec.CmdIO, errOk bool, cmd any, args ...any) (*sshclient.Client, string, []string)
- func (sh *Shell) Exit(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) Fg(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) HandleArgErr(errok bool, err error) error
- func (sh *Shell) Host() string
- func (sh *Shell) HostAndDir() string
- func (sh *Shell) InstallBuiltins()
- func (sh *Shell) JobIDExpand(args []string) int
- func (sh *Shell) JobsCmd(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) Kill(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) OutToFile(cl *sshclient.Client, cmdIO *exec.CmdIO, errOk bool, sargs []string, i int) []string
- func (sh *Shell) OutToPipe(cl *sshclient.Client, cmdIO *exec.CmdIO, errOk bool, sargs []string, i int) []string
- func (sh *Shell) Output(cmd any, args ...any) string
- func (sh *Shell) OutputErrOK(cmd any, args ...any) string
- func (sh *Shell) ResetLines()
- func (sh *Shell) Run(cmd any, args ...any)
- func (sh *Shell) RunBuiltinOrCommand(cmdIO *exec.CmdIO, cmd string, args ...string) bool
- func (sh *Shell) RunErrOK(cmd any, args ...any)
- func (sh *Shell) SSHByHost(host string) (*sshclient.Client, error)
- func (sh *Shell) Scp(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) Set(cmdIO *exec.CmdIO, args ...string) error
- func (sh *Shell) Start(cmd any, args ...any)
- func (sh *Shell) StartContext() context.Context
- func (sh *Shell) Tokens(ln string) Tokens
- func (sh *Shell) TotalDepth() int
- func (sh *Shell) TranspileCode(code string)
- func (sh *Shell) TranspileConfig() error
- func (sh *Shell) TranspileExec(ewords []string, output bool) Tokens
- func (sh *Shell) TranspileExecString(str string, output bool) Tokens
- func (sh *Shell) TranspileFile(in string, out string) error
- func (sh *Shell) TranspileGo(toks Tokens) Tokens
- func (sh *Shell) TranspileLine(ln string) string
- func (sh *Shell) TranspileLineTokens(ln string) Tokens
- type Token
- func (tk *Token) IsBacktickString() bool
- func (tk *Token) IsBracket() bool
- func (tk *Token) IsGo() bool
- func (tk *Token) IsOp() bool
- func (tk *Token) IsPathDelim() bool
- func (tk *Token) IsPathExtraDelim() bool
- func (tk *Token) IsValidExecIdent() bool
- func (tk *Token) IsWord() bool
- func (tk *Token) String() string
- type Tokens
- func (tk *Tokens) Add(tok token.Token, str ...string) *Token
- func (tk *Tokens) AddTokens(toks Tokens) *Tokens
- func (tk Tokens) BracketDepths() (paren, brace, brack int)
- func (tk Tokens) Code() string
- func (tk Tokens) Contains(toks ...token.Token) bool
- func (tk *Tokens) DeleteLastComma()
- func (tk *Tokens) Insert(i int, tok token.Token, str ...string) *Token
- func (tk Tokens) Last() *Token
- func (tk Tokens) Path(idx0 bool) (string, int)
- func (tk Tokens) ReplaceIdentAt(at int, str string, n int) Tokens
- func (tk Tokens) RightMatching() int
- func (tk Tokens) String() string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddQuotes ¶ added in v0.1.4
AddQuotes surrounds given string with quotes, also escaping any contained quotes
func EscapeQuotes ¶ added in v0.1.4
EscapeQuotes replaces any " with \"
func ExecWordIsCommand ¶ added in v0.1.4
ExecWordIsCommand returns true if given exec word is a command-like string (excluding any paths)
Types ¶
type ReadlineCompleter ¶ added in v0.1.4
type ReadlineCompleter struct {
Shell *Shell
}
ReadlineCompleter implements github.com/ergochat/readline.AutoCompleter.
type Shell ¶
type Shell struct { // Config is the [exec.Config] used to run commands. Config exec.Config // StdIOWrappers are IO wrappers sent to the interpreter, so we can // control the IO streams used within the interpreter. // Call SetWrappers on this with another StdIO object to update settings. StdIOWrappers exec.StdIO // ssh connection, configuration SSH *sshclient.Config // collection of ssh clients SSHClients map[string]*sshclient.Client // SSHActive is the name of the active SSH client SSHActive string // depth of parens at the end of the current line. if 0, was complete. ParenDepth int // depth of braces at the end of the current line. if 0, was complete. BraceDepth int // depth of brackets at the end of the current line. if 0, was complete. BrackDepth int // stack of transpiled lines, that are accumulated in TranspileCode Lines []string // stack of runtime errors Errors []error // Builtins are all the builtin shell commands Builtins map[string]func(cmdIO *exec.CmdIO, args ...string) error // commands that have been defined, which can be run in Exec mode. Commands map[string]func(args ...string) // Jobs is a stack of commands running in the background // (via Start instead of Run) Jobs stack.Stack[*exec.CmdIO] // Cancel, while the interpreter is running, can be called // to stop the code interpreting. // It is connected to the Ctx context, by StartContext() // Both can be nil. Cancel func() // Ctx is the context used for cancelling current shell running // a single chunk of code, typically from the interpreter. // We are not able to pass the context around so it is set here, // in the StartContext function. Clear when done with ClearContext. Ctx context.Context // contains filtered or unexported fields }
Shell represents one running shell context.
func (*Shell) AddCommand ¶ added in v0.1.4
AddCommand adds given command to list of available commands
func (*Shell) AddError ¶
AddError adds the given error to the error stack if it is non-nil, and calls the Cancel function if set, to stop execution. This is the main way that shell errors are handled. It also prints the error.
func (*Shell) CancelExecution ¶ added in v0.1.4
func (sh *Shell) CancelExecution()
CancelExecution calls the Cancel() function if set.
func (*Shell) Close ¶ added in v0.1.4
func (sh *Shell) Close()
Close closes any resources associated with the shell, including terminating any commands that are not running "nohup" in the background.
func (*Shell) CloseSSH ¶ added in v0.1.4
func (sh *Shell) CloseSSH()
CloseSSH closes all open ssh client connections
func (*Shell) CoSSH ¶ added in v0.1.4
CoSSH manages SSH connections, which are referenced by the @name identifier. It handles the following cases:
- @name -- switches to using given host for all subsequent commands
- host [name] -- connects to a server specified in first arg and switches to using it, with optional name instead of default sequential number.
- close -- closes all open connections, or the specified one
func (*Shell) CompleteEdit ¶ added in v0.1.4
func (sh *Shell) CompleteEdit(data any, text string, cursorPos int, completion complete.Completion, seed string) (ed complete.Edit)
CompleteEdit is the complete.EditFunc for the shell.
func (*Shell) CompleteMatch ¶ added in v0.1.4
CompleteMatch is the complete.MatchFunc for the shell.
func (*Shell) DeleteJob ¶ added in v0.1.4
DeleteJob deletes the given job and returns true if successful
func (*Shell) EndContext ¶ added in v0.1.4
func (sh *Shell) EndContext()
EndContext ends a processing context, clearing the Ctx and Cancel fields.
func (*Shell) Exec ¶
Exec handles command execution for all cases, parameterized by the args. It executes the given command string, waiting for the command to finish, handling the given arguments appropriately. If there is any error, it adds it to the shell, and triggers CancelExecution.
- errOk = don't call AddError so execution will not stop on error
- start = calls Start on the command, which then runs asynchronously, with a goroutine forked to Wait for it and close its IO
- output = return the output of the command as a string (otherwise return is "")
func (*Shell) ExecArgs ¶ added in v0.1.4
func (sh *Shell) ExecArgs(cmdIO *exec.CmdIO, errOk bool, cmd any, args ...any) (*sshclient.Client, string, []string)
ExecArgs processes the args to given exec command, handling all of the input / output redirection and file globbing, homedir expansion, etc.
func (*Shell) HandleArgErr ¶ added in v0.1.4
func (*Shell) Host ¶ added in v0.1.4
Host returns the name we're running commands on, which is empty if localhost (default).
func (*Shell) HostAndDir ¶ added in v0.1.4
HostAndDir returns the name we're running commands on, which is empty if localhost (default), and the current directory on that host.
func (*Shell) InstallBuiltins ¶
func (sh *Shell) InstallBuiltins()
InstallBuiltins adds the builtin shell commands to [Shell.Builtins].
func (*Shell) JobIDExpand ¶ added in v0.1.4
JobIDExpand expands %n job id values in args with the full PID returns number of PIDs expanded
func (*Shell) Kill ¶ added in v0.1.4
Kill kills a job by job number or PID. Just expands the job id expressions %n into PIDs and calls system kill.
func (*Shell) OutToFile ¶ added in v0.1.4
func (sh *Shell) OutToFile(cl *sshclient.Client, cmdIO *exec.CmdIO, errOk bool, sargs []string, i int) []string
OutToFile processes the > arg that sends output to a file
func (*Shell) OutToPipe ¶ added in v0.1.4
func (sh *Shell) OutToPipe(cl *sshclient.Client, cmdIO *exec.CmdIO, errOk bool, sargs []string, i int) []string
OutToPipe processes the | arg that sends output to a pipe
func (*Shell) Output ¶
Output executes the given command string, handling the given arguments appropriately. If there is any error, it adds it to the shell. It returns the stdout as a string and forwards stderr to exec.Config.Stderr appropriately.
func (*Shell) OutputErrOK ¶ added in v0.1.4
OutputErrOK executes the given command string, handling the given arguments appropriately. If there is any error, it adds it to the shell. It returns the stdout as a string and forwards stderr to exec.Config.Stderr appropriately.
func (*Shell) ResetLines ¶
func (sh *Shell) ResetLines()
ResetLines resets the stack of transpiled lines
func (*Shell) Run ¶ added in v0.1.4
Run executes the given command string, waiting for the command to finish, handling the given arguments appropriately. If there is any error, it adds it to the shell, and triggers CancelExecution. It forwards output to exec.Config.Stdout and exec.Config.Stderr appropriately.
func (*Shell) RunBuiltinOrCommand ¶ added in v0.1.4
RunBuiltinOrCommand runs a builtin or a command
func (*Shell) RunErrOK ¶ added in v0.1.4
RunErrOK executes the given command string, waiting for the command to finish, handling the given arguments appropriately. It does not stop execution if there is an error. If there is any error, it adds it to the shell. It forwards output to exec.Config.Stdout and exec.Config.Stderr appropriately.
func (*Shell) SSHByHost ¶ added in v0.1.4
SSHByHost returns the SSH client for given host name, with err if not found
func (*Shell) Scp ¶ added in v0.1.4
Scp performs file copy over SSH connection, with the remote filename prefixed with the @name: and the local filename un-prefixed. The order is from -> to, as in standard cp. The remote filename is automatically relative to the current working directory on the remote host.
func (*Shell) Start ¶ added in v0.1.4
Start starts the given command string for running in the background, handling the given arguments appropriately. If there is any error, it adds it to the shell. It forwards output to exec.Config.Stdout and exec.Config.Stderr appropriately.
func (*Shell) StartContext ¶ added in v0.1.4
StartContext starts a processing context, setting the Ctx and Cancel Fields. Call EndContext when current operation finishes.
func (*Shell) TotalDepth ¶
TotalDepth returns the sum of any unresolved paren, brace, or bracket depths.
func (*Shell) TranspileCode ¶
TranspileCode processes each line of given code, adding the results to the LineStack
func (*Shell) TranspileConfig ¶ added in v0.1.4
TranspileConfig transpiles the .cosh startup config file in the user's home directory if it exists.
func (*Shell) TranspileExec ¶
TranspileExec returns transpiled tokens assuming Exec code, with the given bools indicating the type of run to execute.
func (*Shell) TranspileExecString ¶
TranspileExecString returns transpiled tokens assuming Exec code, from a backtick-encoded string, with the given bool indicating whether [Output] is needed.
func (*Shell) TranspileFile ¶
TranspileFile transpiles the given input cosh file to the given output Go file, adding package main and func main declarations.
func (*Shell) TranspileGo ¶
TranspileGo returns transpiled tokens assuming Go code. Unpacks any backtick encapsulated shell commands.
func (*Shell) TranspileLine ¶
TranspileLine is the main function for parsing a single line of shell input, returning a new transpiled line of code that converts Exec code into corresponding Go function calls.
func (*Shell) TranspileLineTokens ¶
TranspileLineTokens returns the tokens for the full line
type Token ¶
type Token struct { // Go token classification Tok token.Token // Literal string Str string // position in the original string. // this is only set for the original parse, // not for transpiled additions. Pos token.Pos }
Token provides full data for one token
func (*Token) IsBacktickString ¶
IsBacktickString returns true if the given STRING uses backticks
func (*Token) IsBracket ¶
IsBracket returns true if the given token is a bracket delimiter: paren, brace, bracket
func (*Token) IsPathDelim ¶ added in v0.1.4
func (*Token) IsPathExtraDelim ¶ added in v0.1.4
func (*Token) IsValidExecIdent ¶ added in v0.1.4
IsValidExecIdent returns true if the given token is a valid component of an Exec mode identifier
type Tokens ¶
type Tokens []*Token
Tokens is a slice of Token
func (Tokens) BracketDepths ¶
BracketDepths returns the depths for the three bracket delimiters [paren, bracket, brace], based on unmatched right versions.
func (Tokens) Code ¶
Code returns concatenated Str values of the tokens, to generate a surface-valid code string.
func (Tokens) Contains ¶ added in v0.1.4
Contains returns true if the token string contains any of the given token(s)
func (*Tokens) DeleteLastComma ¶
func (tk *Tokens) DeleteLastComma()
DeleteLastComma removes any final Comma. easier to generate and delete at the end
func (Tokens) Path ¶ added in v0.1.4
Path extracts a standard path or URL expression from the current list of tokens (starting at index 0), returning the path string and the number of tokens included in the path. Restricts processing to contiguous elements with no spaces! If it is not a path, returns nil string, 0
func (Tokens) ReplaceIdentAt ¶ added in v0.1.4
ReplaceIdentAt replaces an identifier spanning n tokens starting at given index, with a single identifier with given string. This is used in Exec mode for dealing with identifiers and paths that are separately-parsed by Go.
func (Tokens) RightMatching ¶
RightMatching returns the position (or -1 if not found) for the right matching [paren, bracket, brace] given the left one that is at the 0 position of the current set of tokens.