Documentation
¶
Overview ¶
Package env runs code in long-lived shell processes and stacks them into named environments.
Index ¶
- Constants
- Variables
- func CanInteractive(path string) bool
- func Environ(vars map[string]string) []string
- func Filter(vars map[string]string, share []string) map[string]string
- func FilterStrict(vars map[string]string, share []string) map[string]string
- func IsBase(name string) bool
- func Vars(environ []string) map[string]string
- type Config
- type Env
- type Event
- type Job
- type Proc
- type Shell
- func (s *Shell) Background(ctx context.Context, script, pidVar string) (*Job, error)
- func (s *Shell) BackgroundTerminal(ctx context.Context, script, pidVar string, t Terminal, rec io.Writer) (*Job, error)
- func (s *Shell) Busy() bool
- func (s *Shell) Close() error
- func (s *Shell) Done() <-chan struct{}
- func (s *Shell) ExitStatus() int
- func (s *Shell) Exited() bool
- func (s *Shell) Exported(ctx context.Context) (map[string]string, error)
- func (s *Shell) Foreground() int
- func (s *Shell) Interactive() bool
- func (s *Shell) Jobs() []ShellJob
- func (s *Shell) Kill()
- func (s *Shell) PID() int
- func (s *Shell) Run(ctx context.Context, script string, stdout, stderr io.Writer) (status int, exited bool, err error)
- func (s *Shell) RunKillAfter(ctx context.Context, script string, stdout, stderr io.Writer, ...) (status int, exited bool, err error)
- func (s *Shell) RunLine(ctx context.Context, line string, out io.Writer) (status int, exited bool, err error)
- func (s *Shell) RunScripted(ctx context.Context, script string, cols, rows int, out io.Writer, ...) (status int, exited bool, err error)
- func (s *Shell) RunTTY(ctx context.Context, script string, tty *os.File, rec io.Writer) (status int, exited bool, err error)
- func (s *Shell) RunTerminal(ctx context.Context, script string, t Terminal, rec io.Writer) (status int, exited bool, err error)
- func (s *Shell) SetSize(cols, rows int)
- func (s *Shell) State() (State, bool)
- func (s *Shell) Type(keys []byte) error
- func (s *Shell) View(w io.Writer)
- func (s *Shell) Want(names []string) error
- func (s *Shell) Watch(fn func(Event))
- type ShellJob
- type ShellProcs
- type Stack
- func (s *Stack) Close()
- func (s *Stack) Get(ctx context.Context, name string, share []string) (*Env, error)
- func (s *Stack) Interactive(name string) bool
- func (s *Stack) KillBusy() bool
- func (s *Stack) KillProcess(pid int) bool
- func (s *Stack) Processes() []ShellProcs
- func (s *Stack) Scripted(name string) bool
- func (s *Stack) SetArgs(ctx context.Context, args []string) error
- func (s *Stack) SetInteractive(name string) bool
- func (s *Stack) Side(st State) *Stack
- func (s *Stack) TopInteractive() bool
- type State
- type Terminal
Constants ¶
const BasePrefix = "LC_"
BasePrefix marks the locale variables that are base along with Base.
const TopLevel = ""
TopLevel is the name of the env blocks run in when they set no env=.
Variables ¶
var Base = []string{
"PATH", "HOME", "USER", "LOGNAME", "SHELL",
"TERM", "COLORTERM",
"LANG", "LANGUAGE", "TZ", "TMPDIR",
"__CF_USER_TEXT_ENCODING",
}
Base lists the variables every share list passes, unless it drops them by name (-PATH), so a block whose env is filtered can still find programs, its home folder and the temp folder, and print text in the user's language. None of them holds a secret: they say who the user is, where their files are and how to talk to the terminal, all of which a block can learn another way (id, ~, getpwuid). Names starting with BasePrefix (LC_ALL, LC_CTYPE, ...) are base too.
Left out on purpose: anything that grants access rather than describing the user, such as SSH_AUTH_SOCK, DBUS_SESSION_BUS_ADDRESS, XDG_RUNTIME_DIR, DISPLAY and tokens. Those stay behind share.
var ErrBusy = errors.New("the shell is running a command")
ErrBusy is returned by RunLine when the shell is running a command, so it isn't at a prompt to type at.
var ErrExited = errors.New("shell exited")
ErrExited is returned by Run when the block ended the shell, for example by calling exit. The shell can't run anything else.
var ErrKilled = errors.New("killed")
ErrKilled is a job's error when Kill ended it, or its shell ended first.
var ErrLineTyped = errors.New("a line is being typed at the prompt")
ErrLineTyped is returned by RunLine when keys were typed at the prompt since it was drawn, so a line may be half typed.
var ErrNoPTY = errors.New("shell has no terminal of its own")
ErrNoPTY is returned by RunTTY on a shell started without Config.TTY.
var ErrNotForeground = errors.New("mdsh is not in the terminal's foreground")
ErrNotForeground is returned by RunTTY when mdsh isn't in the terminal's foreground, for example when it runs in the background.
var ErrNotInteractive = errors.New("shell isn't interactive")
ErrNotInteractive is returned by the methods that need a shell started with Config.Interactive.
var ErrNotStopped = fmt.Errorf("%w, which didn't stop as ctrl+z stops it", ErrBusy)
ErrNotStopped is returned by RunLine when the command typed at the terminal that holds the shell didn't stop for ctrl+z. It is an ErrBusy.
var ErrTapeEnded = errors.New("still running 10s after its input ended")
ErrTapeEnded is returned by RunScripted when the block is still running a while after drive has typed everything, most likely waiting for input that will never come.
Functions ¶
func CanInteractive ¶ added in v1.8.0
CanInteractive reports whether the shell at path can run with Config.Interactive: a POSIX shell, on Unix.
func Filter ¶
Filter keeps the variables named in share, and the Base set. Nil share keeps all of them. "..." (or "*") in share keeps all, and a name prefixed with "-" is dropped even if "..." or the plain name also appears, so [..., -USER] keeps everything but USER. A base variable is dropped the same way: [-PATH] keeps the base set but PATH.
func FilterStrict ¶ added in v1.4.0
FilterStrict is Filter without the Base set: share keeps exactly the names it lists. Documents loaded from a URL (http, https, ftp, sftp) use it, so a script fetched from the internet sees none of the caller's environment it didn't name, PATH and HOME included.
Types ¶
type Config ¶
type Config struct {
Path string // shell binary; defaults to /bin/sh
Env []string // KEY=value, the shell's whole environment
Dir string // working directory
Args []string // positional parameters, $1 and on
// TTY gives the shell a pseudo-terminal of its own as its
// controlling terminal, so RunTTY can run blocks on it.
TTY bool
// KillAfter, if set, kills the shell when a script is still
// running that long after its run was stopped or timed out and the
// script was interrupted (see Run). Zero leaves it running until
// Kill, for a caller that asks the user first.
KillAfter time.Duration
// Interactive runs the shell as an interactive shell (-i) on a
// pseudo-terminal of its own, which it reads commands from, so job
// control works as in a terminal: ctrl+z, fg, bg and jobs. mdsh
// hooks into its prompt (OSC 133 marks and a state fifo) to learn
// where each command starts and ends, its status, and the shell's
// jobs and variables. Blocks run by a line typed at the prompt, and
// their output and errors share the terminal. The shell reads the
// user's rc files. Unix only; Path must be a POSIX shell.
Interactive bool
// Login, with Interactive, starts the shell as a login shell, so it
// reads the profile files too.
Login bool
// Init runs in the shell once it starts, before any block, such as
// aliases and functions to define. Its exit status is ignored, but
// an Init that ends the shell is an error.
Init string
}
Config starts a shell.
type Env ¶
type Env struct {
Name string // full name, such as "build/test"; "" for the top level
Parent *Env
Shell *Shell
}
Env is a named shell stacked on its parent.
type Event ¶ added in v1.8.0
type Event struct {
// Kind is "start" when a command starts, with Command; "end" when
// it ends, with Status; "state" when the shell sent its state, at
// each prompt; "line" when a line typed at the terminal ran no
// command, as a comment doesn't in bash and zsh, with Command;
// "status" with Records; "copy" with Copied.
Kind string
Command string
Status int
State *State
// Typed, on start and end, says RunLine typed the command; it is
// false for one typed at the terminal through Type.
Typed bool
// Resumed, on start, says the command is mdsh bringing back the
// job RunLine stopped to run its line, as fg: not one to record.
Resumed bool
// Output, on the end of a command not typed by RunLine, is what it
// wrote to the terminal, from its start to its end, escapes and
// all.
Output []byte
// Records, on "status", are the shell's terminal's records: what
// the programs on it reported about themselves with OSC 7501, each
// time they change. A command's end drops its working and blocked
// records, as a terminal does at the next prompt.
Records []termstatus.Report
// Copied, on "copy", is the text a program on the shell's terminal
// put on the clipboard with OSC 52.
Copied string
}
Event is something an interactive shell did, for Shell.Watch.
type Job ¶ added in v1.2.0
type Job struct {
// PID is the background job's process ID, as $! gave it.
PID int
// contains filtered or unexported fields
}
Job is a script running in the background of its shell, started by Background. Its output goes to files, so it never mixes with the output of what the shell runs next.
func (*Job) Done ¶ added in v1.2.0
Done reports whether the job has ended, and its exit status. A job that was killed, or whose shell ended, has status -1 and ErrKilled.
func (*Job) Ended ¶ added in v1.8.0
func (j *Job) Ended() <-chan struct{}
Ended is closed once a job BackgroundTerminal started has ended and all it wrote to its terminal has been shown. It is nil for other jobs.
type Proc ¶ added in v1.7.0
type Proc struct {
PID int `json:"pid"`
// Command is the command line, as ps shows it.
Command string `json:"command"`
// Secs is how long the process has run, in seconds.
Secs int `json:"secs"`
// Block names the background block the process is, if it is one,
// and Status says what the program on its terminal reports it is
// doing, when one does (see termstatus.Summary).
Block string `json:"block,omitempty"`
Status string `json:"status,omitempty"`
Children []*Proc `json:"children,omitempty"`
}
Proc is a process that a shell started, directly or through others, and the processes it started in turn.
type Shell ¶
type Shell struct {
// contains filtered or unexported fields
}
Shell is one long-lived shell process. Blocks run in it one at a time, so variables, functions and the working directory carry over.
func StartContext ¶ added in v1.8.0
StartContext launches a shell, as Start does, unless ctx ends first: a shell whose start hangs, such as one whose rc file waits for input or that hides mdsh's markers, is killed as soon as ctx ends, since nothing has run in it to lose.
func (*Shell) Background ¶ added in v1.2.0
Background starts script as a background job of the shell, the way `script &` would: in a subshell, so it sees the shell's variables, functions and working directory but what it sets stays its own. Its stdin is /dev/null and its stdout and stderr are kept apart from the shell's. pidVar, if not empty, is a shell variable set to the job's process ID, so later scripts can wait for it.
A script with a syntax error doesn't start: the job is already done, with status 2 and the error as its stderr.
func (*Shell) BackgroundTerminal ¶ added in v1.8.0
func (s *Shell) BackgroundTerminal(ctx context.Context, script, pidVar string, t Terminal, rec io.Writer) (*Job, error)
BackgroundTerminal starts script as a background job, as Background does, but on a pseudo-terminal of its own rather than with no terminal at all: what is typed on t goes to the script, and what the script shows goes to t.Out and to rec, until the job ends. The terminal takes t's size, and follows it.
The job can't be a subshell of the shell, since a program such as vim or ssh needs its terminal to be its session's controlling terminal, and a subshell is in the shell's session. So it runs in a new shell of the same kind, in a session of its own, that first takes on the shell's state: its exported variables through the environment, and its other variables, functions, aliases, options, positional parameters and working directory as stateScript lists them. In a shell other than bash and zsh, functions don't carry over. The job isn't the shell's child, so the shell can't wait for it; pidVar still holds its process ID, for kill.
A script with a syntax error doesn't start: the job is already done, with status 2 and the error as its stderr.
func (*Shell) Done ¶ added in v1.8.0
func (s *Shell) Done() <-chan struct{}
Done is closed when the shell has ended.
func (*Shell) ExitStatus ¶ added in v1.4.1
ExitStatus is the shell's exit status once it has ended, or 0.
func (*Shell) Exited ¶ added in v1.1.0
Exited reports whether the shell has ended, by a block calling exit or by being killed.
func (*Shell) Foreground ¶ added in v1.8.0
Foreground is the process group in the foreground of an interactive shell's terminal, when a command holds it, or 0 at the prompt.
func (*Shell) Interactive ¶ added in v1.8.0
Interactive reports whether the shell was started with Config.Interactive.
func (*Shell) Jobs ¶ added in v1.8.0
Jobs lists an interactive shell's jobs that haven't ended: from its job table where the shell reports it, or else from the process groups on its terminal other than its own, which have no numbers.
func (*Shell) Kill ¶ added in v1.4.1
func (s *Shell) Kill()
Kill ends the shell, and whatever it is running, at once. A Run waiting on an interrupted script returns.
func (*Shell) Run ¶
func (s *Shell) Run(ctx context.Context, script string, stdout, stderr io.Writer) (status int, exited bool, err error)
Run runs script in the shell and returns its exit status. The script's stdin is /dev/null. If the script ends the shell, Run returns ErrExited and the shell's exit status. If ctx ends first, the script is interrupted, as ctrl+c would, and Run returns status 130 and ctx's error with the shell still alive, and what earlier scripts set in it (see interrupt). Should the script not stop, Run waits until it does, or until Kill, or Config.KillAfter, ends the shell.
func (*Shell) RunKillAfter ¶ added in v1.8.0
func (s *Shell) RunKillAfter(ctx context.Context, script string, stdout, stderr io.Writer, killAfter time.Duration) (status int, exited bool, err error)
RunKillAfter is Run with killAfter in place of Config.KillAfter: if the script is still running that long after ctx ended and it was interrupted, the shell is killed. It is for a script nobody is asked about, such as one that reads the shell's prompt, when the shell was started for blocks whose user is asked first.
func (*Shell) RunLine ¶ added in v1.8.0
func (s *Shell) RunLine(ctx context.Context, line string, out io.Writer) (status int, exited bool, err error)
RunLine types line at an interactive shell's prompt, as if typed and followed by Enter, and waits for the command to end. Its output, as the terminal showed it, escapes and all, goes to out, and its exit status is returned; -1 if the shell didn't say. It fails with ErrBusy if a command is running, and ErrLineTyped if someone has typed at the prompt, rather than add to their line. If ctx ends first, the command is interrupted as ctrl+c would and RunLine returns 130 and ctx's error.
func (*Shell) RunScripted ¶
func (s *Shell) RunScripted(ctx context.Context, script string, cols, rows int, out io.Writer, drive func(ctx context.Context, keys io.Writer) error) (status int, exited bool, err error)
RunScripted runs script on the shell's own pseudo-terminal, sized cols by rows, with no person at it: drive types the input, writing to keys, while the script runs, and everything the script shows goes to out. If drive fails, or the script is still running 10s after drive is done, the script is interrupted, or if it won't stop the shell is killed, and the error returned.
func (*Shell) RunTTY ¶
func (s *Shell) RunTTY(ctx context.Context, script string, tty *os.File, rec io.Writer) (status int, exited bool, err error)
RunTTY runs script like Run, but on the shell's own pseudo-terminal, with mdsh in the middle: what is typed on tty goes to the script, and what the script writes to its terminal goes to tty and to rec. Since the pseudo-terminal is the controlling terminal of the shell's session, programs that need a terminal, such as docker run -it, work, ctrl+c reaches the running command and window size changes are passed on. An interrupted command ends; the rest of the script goes on. tty must be mdsh's controlling terminal, with mdsh in its foreground group.
func (*Shell) RunTerminal ¶ added in v1.2.0
func (s *Shell) RunTerminal(ctx context.Context, script string, t Terminal, rec io.Writer) (status int, exited bool, err error)
RunTerminal runs script like RunTTY, but on t, a terminal mdsh draws itself rather than one it runs on: what is typed on t goes to the script, and what the script writes to its terminal goes to t.Out and to rec. The shell's pseudo-terminal takes t's size, and follows it.
func (*Shell) SetSize ¶ added in v1.4.0
SetSize sizes the shell's pseudo-terminal, if it has one, so what asks the terminal its size between blocks, such as a prompt drawn to fit the width, sees the size it is shown at.
func (*Shell) State ¶ added in v1.8.0
State is what an interactive shell reported at its last prompt.
func (*Shell) View ¶ added in v1.8.0
View sets where an interactive shell's terminal stream goes, as a terminal would show it, from now on; nil drops it.
type ShellJob ¶ added in v1.8.0
type ShellJob struct {
// N is the job number, as in %1. Zero for a job found through ps,
// which has no number.
N int
// PGID is the job's process group: the PID jobs -l shows for it.
PGID int
// State is "running", "stopped" or "done", or what the shell said
// if it is none of those.
State string
// Command is the job's command line.
Command string
}
ShellJob is one entry of an interactive shell's job table.
type ShellProcs ¶ added in v1.7.0
type ShellProcs struct {
// Env is the env's name, "" for the top level.
Env string `json:"env"`
PID int `json:"pid"`
Secs int `json:"secs"`
Children []*Proc `json:"children,omitempty"`
}
ShellProcs is an env's shell and the processes under it.
type Stack ¶
type Stack struct {
// OnStart, if set, is called as each env's shell starts, with the
// share it was made with (nil for the top level, whose Config.Env
// is already filtered) and the names of the variables it was given.
OnStart func(e *Env, share, names []string)
// OnExited, if set, is called when Get finds that e's shell has
// ended, as a block calling exit or a kill does, with its exit
// status, before it starts a new one in its place.
OnExited func(e *Env, status int)
// Strict makes share lists pass only what they name, without the
// Base set. It is for documents loaded from a URL, which must not get
// even PATH or HOME unless they ask (see FilterStrict).
Strict bool
// Prepare, if set, is called before the stack starts its first
// shell, with the Config every shell starts with, to change, such as
// to set Init once someone has said it may run. If it fails, no
// shell starts, Get returns its error, and the next Get calls it
// again.
Prepare func(cfg *Config) error
// contains filtered or unexported fields
}
Stack creates envs on first use and keeps them for reuse.
func (*Stack) Get ¶
Get returns the env called name, creating it and any missing parents. share is used only when the env is created: it lists the parent's exported variables the new env receives. Nil means all of them. An env whose shell has exited is created again, with a fresh shell.
func (*Stack) Interactive ¶ added in v1.8.0
Interactive reports whether env name runs, or will run, interactively.
func (*Stack) KillBusy ¶ added in v1.4.1
KillBusy kills the shells running a script (see Shell.Kill), those still starting too, and reports whether there were any. Unlike the stack's other methods, it may be called while a script runs.
func (*Stack) KillProcess ¶ added in v1.7.0
KillProcess kills process pid and what it started, if it runs under one of the stack's shells, and reports whether it did. The shells themselves are not killed this way: Restart Shells ends those.
func (*Stack) Processes ¶ added in v1.7.0
func (s *Stack) Processes() []ShellProcs
Processes lists the stack's shells, those still starting too, each with the processes under it: what blocks are running, background blocks, and anything a block or the History pane left running, such as cmd &. It is empty where ps can't be read.
func (*Stack) Scripted ¶ added in v1.8.0
Scripted reports whether a scripted shell runs for env name now, one SetInteractive would end.
func (*Stack) SetArgs ¶ added in v1.4.1
SetArgs sets the positional parameters in every shell started, and in those started from now on. Call it while no script runs.
func (*Stack) SetInteractive ¶ added in v1.8.0
SetInteractive has the sub-env name run interactively, on a terminal of its own, from its next start, when the top level does (Config.Interactive). A shell can't become interactive as it runs, so a scripted shell already running for name is ended, and what blocks set there is lost: the caller asks first (see Scripted). It reports whether it ended one. The top level, "", is left as it is.
func (*Stack) Side ¶ added in v1.8.0
Side is a stack of its own whose top-level shell starts from st, the state the interactive top-level shell of s reported: its exported variables and its directory, though not its functions or aliases, which it doesn't report. Its shells are scripted and apart from s's; the caller closes it.
func (*Stack) TopInteractive ¶ added in v1.8.0
TopInteractive reports whether the top-level env's shell runs, or will run, interactively.
type State ¶ added in v1.8.0
type State struct {
Status int
PWD string
OldPWD string
PID int
// Jobs is the shell's job table, as jobs -l lists it. A shell that
// can't list its jobs at the prompt, such as dash, whose prompt
// hook runs in a subshell, leaves it nil and Shell.Jobs asks ps.
Jobs []ShellJob
// JobsKnown says the shell listed its jobs, even if none.
JobsKnown bool
// Exported is the shell's exported environment.
Exported map[string]string
// Vars are the variables named in the want file, exported or not.
// A variable that isn't set is left out.
Vars map[string]string
}
State is what an interactive shell reports about itself at each prompt, through the state fifo: the last command's status, where it is, its jobs and its variables.
type Terminal ¶ added in v1.2.0
type Terminal struct {
// Keys carries what is typed, as the bytes a terminal would send.
Keys <-chan []byte
// Out shows what the script writes to its terminal.
Out io.Writer
// Size is the terminal's size in cells. Nil, or a zero size, means
// 80 by 24.
Size func() (cols, rows int)
// Resized, if not nil, says when Size changes.
Resized <-chan struct{}
// Status, if set, is told what the programs on the terminal report
// about themselves with OSC 7501 (package termstatus): called with
// the terminal's records each time they change, and with nil once
// the script has ended and the terminal is let go. It may be
// called from another goroutine.
Status func([]termstatus.Report)
// Clipboard, if set, is called with the text a program on the
// terminal puts on the clipboard with OSC 52, for a terminal that
// would otherwise drop it. It may be called from another goroutine.
Clipboard func(text string)
// JobControl runs the script with the shell's job control on, as
// in an interactive shell: ctrl+z stops a command and the shell
// carries on, and jobs, fg and bg work. Off, or in a shell that
// can't do job control without being interactive, such as bash and
// zsh, ctrl+z is ignored: a command that stops itself, such as nvim,
// is continued at once.
JobControl bool
}
Terminal is a terminal mdsh draws itself, such as a pane in a window, for RunTerminal. It has no file of its own: keys arrive on a channel and what the script shows goes to a writer.