env

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 24 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package env runs code in long-lived shell processes and stacks them into named environments.

Index

Constants

View Source
const BasePrefix = "LC_"

BasePrefix marks the locale variables that are base along with Base.

View Source
const TopLevel = ""

TopLevel is the name of the env blocks run in when they set no env=.

Variables

View Source
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.

View Source
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.

View Source
var ErrKilled = errors.New("killed")

ErrKilled is a job's error when Kill ended it, or its shell ended first.

View Source
var ErrNoPTY = errors.New("shell has no terminal of its own")

ErrNoPTY is returned by RunTTY on a shell started without Config.TTY.

View Source
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.

View Source
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 Environ

func Environ(vars map[string]string) []string

Environ turns vars into sorted KEY=value pairs.

func Filter

func Filter(vars map[string]string, share []string) map[string]string

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

func FilterStrict(vars map[string]string, share []string) map[string]string

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.

func IsBase added in v1.4.0

func IsBase(name string) bool

IsBase reports whether name is in the base set.

func Vars

func Vars(environ []string) map[string]string

Vars turns KEY=value pairs into a map.

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
	// 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 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

func (j *Job) Done() (status int, done bool, err error)

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) Kill added in v1.2.0

func (j *Job) Kill()

Kill ends the job and every process it started, unless it is done.

func (*Job) Output added in v1.2.0

func (j *Job) Output() (stdout, stderr []byte)

Output returns what the job has written so far.

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 Start

func Start(cfg Config) (*Shell, error)

Start launches a shell.

func (*Shell) Background added in v1.2.0

func (s *Shell) Background(ctx context.Context, script, pidVar string) (*Job, error)

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) Busy added in v1.4.1

func (s *Shell) Busy() bool

Busy reports whether a script is running in the shell.

func (*Shell) Close

func (s *Shell) Close() error

Close ends the shell and removes its temp files.

func (*Shell) ExitStatus added in v1.4.1

func (s *Shell) ExitStatus() int

ExitStatus is the shell's exit status once it has ended, or 0.

func (*Shell) Exited added in v1.1.0

func (s *Shell) Exited() bool

Exited reports whether the shell has ended, by a block calling exit or by being killed.

func (*Shell) Exported

func (s *Shell) Exported(ctx context.Context) (map[string]string, error)

Exported returns the shell's exported variables.

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) 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

func (s *Shell) SetSize(cols, rows int)

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.

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 NewStack

func NewStack(cfg Config) *Stack

NewStack returns a stack whose top-level env starts with cfg.

func (*Stack) Close

func (s *Stack) Close()

Close ends every shell in the stack.

func (*Stack) Get

func (s *Stack) Get(ctx context.Context, name string, share []string) (*Env, error)

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) KillBusy added in v1.4.1

func (s *Stack) KillBusy() bool

KillBusy kills the shells running a script (see Shell.Kill) and reports whether there were any. Unlike the stack's other methods, it may be called while a script runs.

func (*Stack) SetArgs added in v1.4.1

func (s *Stack) SetArgs(ctx context.Context, args []string) error

SetArgs sets the positional parameters in every shell started, and in those started from now on. Call it while no script runs.

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{}
	// 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.
	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.

func (Terminal) Dims added in v1.2.0

func (t Terminal) Dims() (cols, rows int)

Dims is t's size, or 80 by 24 if it has none.

Jump to

Keyboard shortcuts

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