run

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 29 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 run executes a document's blocks in their envs.

Index

Constants

View Source
const (
	// ModeRunning is a run from the command line, such as mdsh doc.md or
	// mdsh -w doc.md. It is the default.
	ModeRunning = "running"
	// ModeInteractive is a run where someone picks blocks as they go:
	// mdsh -i and mdsh-gui.
	ModeInteractive = "interactive"
	// ModeReport is a run for a report, such as mdsh --pdf.
	ModeReport = "report"
)

The values of $MDSH_MODE, which tells blocks how they are being run.

View Source
const BackgroundWait = 5 * time.Second

BackgroundWait is how long a run waits, after its last block, for a background block with no timeout= to end before killing it.

View Source
const CastMIME = "application/x-asciicast"

CastMIME is the media type of an asciicast v2 file, for data: URIs.

View Source
const ExposeVar = "MDSH_EXPOSE"

ExposeVar lists, comma-separated, the caller's variables that {{$VAR}} may read. mdsh --expose adds to it.

View Source
const KillAfter = 5 * time.Second

KillAfter is Options.KillAfter for a run nobody can be asked about, such as mdsh on the command line.

View Source
const ResScheme = "res://"

ResScheme starts a path in the document's assets folder: res://notes.md is <doc>.assets/notes.md.

Variables

View Source
var ErrDependency = errors.New("a block it depends on failed")

ErrDependency is a block's error when a block its depends= names failed, so it didn't run.

View Source
var ErrFrontMatterFixed = fmt.Errorf("the front matter is fixed, so the shells start again with its settings: %w", ErrRestart)

ErrFrontMatterFixed is Sync's answer when the document's front matter didn't parse when the session started and now does: the shells were readied with the defaults, so they must start again with what it says. It is an ErrRestart.

View Source
var ErrNoConfirm = errors.New("block needs confirmation")

ErrNoConfirm is returned when a block needs confirming and the run has no way to ask.

View Source
var ErrNoTTY = errors.New("block needs a terminal (tty) and there is none")

ErrNoTTY is a tty block's error when the run has no terminal to give it.

View Source
var ErrRestart = errors.New("the first tty block needs mdsh to start again")

ErrRestart is Sync's answer when the document gained the first tty block after the session's shells started without terminals of their own.

View Source
var ErrSourcesNotApproved = errors.New("env.source files not approved")

ErrSourcesNotApproved is the error when a shell would start for a document whose env.source files nobody approved; see Options.ApproveSources.

Functions

func CallerVars added in v1.3.0

func CallerVars(d *doc.Document, environ []string) map[string]string

CallerVars is what {{$VAR}} reads from environ: mdsh's own MDSH_ variables, and the caller's variables that the person running mdsh named in $MDSH_EXPOSE, if d's front matter shares them with its blocks (env.share). Others read as unset. The list has to come from the person, not the document: a document someone sent could name $GITHUB_TOKEN in its own front matter as easily as in a placeholder.

func IsOwnVar added in v1.3.0

func IsOwnVar(name string) bool

IsOwnVar reports whether name is one of mdsh's own variables, such as MDSH_MODE, rather than one from the caller's environment.

func JoinArgs added in v1.3.0

func JoinArgs(args []string) string

JoinArgs is the reverse of SplitArgs: it quotes each argument that needs it.

func Lines

func Lines(data []byte, from, to int) ([]byte, error)

Lines returns lines from through to of data, numbered from 1 and inclusive. from 0 is the first line and to 0 the last.

func LookupAt

func LookupAt(lookup doc.Lookup, d *doc.Document, results []*Result, pos int) doc.Lookup

LookupAt wraps lookup for refs whose meaning depends on where they are used. {{$?}} is the exit status of the last block before pos that ran; {{$ran?}} is whether the last runnable block before pos ran. For a block's run= that is the block before it; for show= and the other display conditions, pos is past the block, so it is the block itself. With no such block they keep a stored value or read as unknown.

func NameBlocks added in v1.3.0

func NameBlocks(d *doc.Document, results []*Result, opts Options) ([]doc.Rename, error)

NameBlocks gives every runnable block in d that has no id one of its own, block-<uuidv7>, written into its fence, so it keeps it when blocks move. Call it before saving the document. Its saved output, copies, refs and image links follow the new id (see doc.Document.NameBlocks), and so do the image links in results. Files saved under the old id in <doc>.assets/ are renamed to match. Blocks keep their identity, so a session only needs a Sync.

func NamesAny added in v1.5.0

func NamesAny(code string, names []string) bool

NamesAny reports whether code names any of the variables in names, as a whole word: $NAME, ${NAME} and {{$NAME}} all do. With SecretVars, it says whether a block's output may hold a secret.

func NewLookup

func NewLookup(d *doc.Document, results []*Result, environ []string) doc.Lookup

NewLookup resolves refs for conditions and placeholders: {{$VAR}} from environ (unless environ is nil) as the front matter's env.share filters it for blocks (see CallerVars), {{$MDSH_VAR_name}} from the textbox or choice in d that binds it with var=, {{#block/env(VAR)}}, {{#block/?}} and {{#block/ran?}} from the block's result, and otherwise from a value a placeholder stored in the file. It reads results as they are when it is called, so it sees blocks that finish after it is made. {{$?}} and {{$ran?}} depend on where they are used; see LookupAt.

func OffReason added in v1.5.0

func OffReason(dep *doc.Block, why string) string

OffReason says why a dependency is switched off, for a question about it: why is as DependOff gets it. It reads after the block's name, as in "setup is marked skip".

func OutKind

func OutKind(b *doc.Block) string

OutKind returns the block's output kind: text, markdown, image, screenshot, or recording for a tty block.

func Outside added in v1.5.0

func Outside(d *doc.Document, opts Options) []string

Outside lists the files d's include blocks read and its out= files write that are outside the document's root, as the document writes them, in the order they come. Its result is what opts.AllowOutside would allow, so a front end can say so before it allows it: mdsh-gui asks once per document and asks again when the list changes. A block marked skip is listed too, since an edit can turn it on.

func Overstrike added in v1.3.0

func Overstrike(p []byte) []byte

Overstrike applies the backspaces in p: each one erases the rune before it on its line. Programs that format for a printer, such as man, mark bold as "c\bc" and underline as "_\bc"; this leaves the plain "c". Backspace spinners keep only what they showed last.

func PIDVar added in v1.2.0

func PIDVar(id string) string

PIDVar is the shell variable that holds the process ID of background block id, so later blocks can wait for it: MDSH_BG_ and the id, with anything but letters, digits and _ turned into _.

func Runnable

func Runnable(b *doc.Block) bool

Runnable reports whether mdsh knows how to run b.

func Shell

func Shell(d *doc.Document) string

Shell is the shell d's blocks run in: the front matter's shell, else zsh if any block is a zsh block, else "" for the default /bin/sh.

func ShellEnd added in v1.4.1

func ShellEnd(r *Result) string

ShellEnd says why a block's run ended its shell: "timeout" when its timeout= did, "stopped" when the run was stopped, or "exit" when the block ended it itself, as exit does. The next block in that env starts a new shell, without what earlier blocks set there.

func SourcePaths added in v1.5.0

func SourcePaths(d *doc.Document, opts Options) ([]string, error)

SourcePaths is the files the front matter's env.source names, as the shells would read them: a leading ~/ is the home folder, and other relative paths are relative to the document's folder (opts.File's, else opts.Dir). Each is made absolute and cleaned.

func SplitArgs added in v1.3.0

func SplitArgs(s string) ([]string, error)

SplitArgs splits s into arguments the way a shell splits words: at spaces, with '…' and "…" quoting and \ escaping the next character (outside single quotes). It expands nothing.

func Stale added in v1.4.0

func Stale(d *doc.Document, results []*Result) []bool

Stale reports, for each of d's blocks, whether its result in results is out of date: it ran, but a block its depends= names has run again since, had its run cleared, or is stale itself. A block that hasn't run isn't stale, nor is one whose dependency simply never ran.

func TopEnv added in v1.4.0

func TopEnv(d *doc.Document, opts Options) []string

TopEnv is the environment of d's top-level shell: opts.Environ as the front matter's env.share filters it. A local document gets env.Base and the names its env.share gives, or everything when the list has "..." (doc.Options.FullEnv). A remote document (opts.Remote) gets only the names it gives: no base set, and nothing when it names nothing.

func WithExpose added in v1.3.0

func WithExpose(environ []string, names []string) []string

WithExpose returns environ with names added to $MDSH_EXPOSE.

func WithMode added in v1.3.0

func WithMode(environ []string, mode string) []string

WithMode is environ with MDSH_MODE set to mode, so conditions such as show={{$MDSH_MODE}}!=report can read it.

Types

type Answer

type Answer int

Answer is a reply to Confirm.

const (
	Stop Answer = iota
	Go
	Skip
)

type Event

type Event struct {
	Kind     EventKind
	Block    *doc.Block
	Data     []byte
	Result   *Result
	Progress *Progress
}

Event reports progress. Data is set for Stdout and Stderr, Result for Done, and Progress for Status.

type EventKind

type EventKind int

EventKind says what an Event reports.

const (
	Started EventKind = iota
	Stdout
	Stderr
	Done
	// Status is a block reporting progress with mdsh ctl status. It
	// replaces the block's last status, and the block's Done ends it.
	// It comes from the control socket's goroutine, while the block
	// runs, so OnEvent must be safe to call from more than one.
	Status
)

type FrontMatterError added in v1.5.0

type FrontMatterError struct{ Err error }

FrontMatterError is what running a block returns while the document's front matter doesn't parse: mdsh runs nothing with settings it can't read.

func (*FrontMatterError) Error added in v1.5.0

func (e *FrontMatterError) Error() string

func (*FrontMatterError) Unwrap added in v1.5.0

func (e *FrontMatterError) Unwrap() error

type Options

type Options struct {
	// File is the document's path, used for MDSH_FILE and image paths.
	// Empty when the document came from stdin.
	File string
	// Dir is the working directory for every env. Defaults to File's
	// directory, or the current directory.
	Dir string
	// LinkDir is where image links are relative to. Defaults to Dir; set
	// it when the rendered markdown is saved somewhere else.
	LinkDir string
	// Args are the positional parameters, $1 and on.
	Args []string
	// Environ is the caller's environment. Defaults to os.Environ().
	Environ []string
	// AllowOutside lets includes and out= files reach outside the
	// document's root (see package docroot), as mdsh --allow-outside
	// does. Leave it off unless the document is trusted.
	AllowOutside bool
	// AllowedOutside are files, as the document writes them in an
	// include's file= or an out=, that may reach outside the document's
	// root though AllowOutside is off: the list run.Outside gave when
	// the user allowed it, so a file added since stays inside.
	AllowedOutside []string
	// Remote marks a document loaded from a URL (http, https, ftp,
	// sftp). Its shells get only the caller's variables its env.share
	// and share= name, without env.Base (PATH, HOME, USER, ...), and
	// none at all when it names none. See TopEnv.
	Remote bool
	// Shell overrides the front matter's shell.
	Shell string
	// Source runs in every shell as it starts, after the files the
	// front matter's env.source names, such as aliases and functions
	// read from the files given to --source.
	Source string
	// StopOnError stops at the first failing block, whatever the front
	// matter says.
	StopOnError bool
	// Only runs the named block and the earlier blocks in its env chain.
	Only string
	// OnEvent, if set, is called as blocks start, write and finish.
	OnEvent func(Event)
	// ApproveSources is asked, right before the first shell starts,
	// whether to read in the files the front matter's env.source names:
	// paths are the files that would be read, each made absolute. Go
	// sources them into every shell; Skip starts the shells without
	// them; Stop starts no shell, and what needed one fails with
	// ErrSourcesNotApproved, which stops a run. If ApproveSources is
	// nil, a document with env.source stops that way, since nobody can
	// say yes. A shell that only answers a question, as the History
	// pane's prompt does, asks too. Source, the caller's own, is not
	// asked about. See package trust for remembering the answer.
	ApproveSources func(paths []string) Answer
	// Step asks Confirm before every block that would run, not just
	// those with the confirm attribute.
	Step bool
	// Confirm is asked before each block that has the confirm attribute,
	// or every block in step mode, right before it runs, after the
	// blocks its depends= names. Its answer runs the block, skips it
	// (keeping any output saved in the file) or stops the run there.
	// If Confirm is nil, the run stops at the first such block with
	// ErrNoConfirm, since nobody can answer.
	Confirm func(*doc.Block) Answer
	// Depend is asked before running dep, a block that b's depends=
	// names and that hasn't run in this session (or failed when it
	// did). The whole chain is worked out first; then each dep is
	// asked about from the top of the chain down, right before it would
	// run, once the blocks it needs have run. Go runs dep then, Skip
	// goes on without it, and Stop runs neither it, the rest of the
	// chain nor b. b's own Confirm comes after. Answering Go also
	// answers dep's own confirm. If Depend is nil, the run stops there
	// with ErrNoConfirm, as for Confirm.
	// A dep with nothing to run, only blank lines and # comments, and
	// no confirm attribute, runs without asking.
	Depend func(dep, b *doc.Block) Answer
	// DependOff is asked instead of Depend about a dependency that is
	// switched off where it stands: marked skip, or with a run=
	// condition that is false (why is "skip", "run=" or "run=once").
	// Go runs it anyway; Skip treats it as done without running it, so
	// b still runs; Stop is as for Depend. It is asked even when Depend
	// always answers Go, as mdsh --yes does, since skip reads as "this
	// won't run". If DependOff is nil, such a dependency is skipped,
	// and the audit log says why.
	DependOff func(dep, b *doc.Block, why string) Answer
	// TTY is the terminal that blocks marked tty run on. If it is nil,
	// such blocks fail with ErrNoTTY.
	TTY *os.File
	// Terminal, if TTY is nil, is a terminal the caller draws itself,
	// such as a pane in a window, for blocks marked tty to run on.
	Terminal *env.Terminal
	// TakeTTY, if set, is called before a tty block uses TTY, so a front
	// end that draws on the terminal can step aside. The block runs once
	// it returns, and calls the function it returned when done with TTY.
	TakeTTY func(*doc.Block) (giveBack func())
	// Mode is $MDSH_MODE: ModeRunning, ModeInteractive or ModeReport.
	// Defaults to ModeRunning.
	Mode string
	// Audit, if set, gets the run's events: blocks starting, ending
	// and skipped, envs starting, and calls to the control socket. The
	// caller writes run.start and run.end.
	Audit *audit.Log
	// PTY starts every shell with a terminal of its own, as a document
	// with a tty block does, so Session.RunTyped can run any block on
	// Terminal.
	PTY bool
	// KillAfter, if set, kills a block's shell when the block is still
	// running that long after the run was stopped or the block timed
	// out. Stopping a block interrupts it, as ctrl+c would, and keeps
	// its shell and what earlier blocks set there; one that won't stop
	// runs on until Session.Kill, or until KillAfter. Zero is for a
	// caller that asks the user before Session.Kill. See
	// env.Config.KillAfter.
	KillAfter time.Duration
}

Options control a run.

type Progress added in v1.3.0

type Progress struct {
	Text     string
	Step, Of int
}

Progress is what a block reported with mdsh ctl status. Step and Of are 0 when it gave no count.

type Result

type Result struct {
	Block   *doc.Block
	Ran     bool // false if skipped or not reached
	Skipped bool // skip, run= false, unknown language, not selected by Only, or skipped at the prompt
	Stdout  []byte
	Stderr  []byte
	Status  int
	// Exited is true when the block ended its shell, as exit does, or its
	// shell was killed.
	Exited bool
	// Running is true while a background block is still going. Its
	// output and status come in once it ends.
	Running bool
	Err     error
	// Image is the markdown image target when the block has out=image:
	// a path relative to the document, or a data: URI.
	Image string
	// Vars holds the variables placeholders ask for, as the block left
	// them. Unset variables are empty.
	Vars map[string]string
	// Declined is true when the block asked for confirmation and the run
	// stopped there instead.
	Declined bool
	// Seq orders the session's runs: each block run gets the next one,
	// counting from 1. It is 0 for a block that hasn't run.
	Seq uint64
	// Deps holds, for each block the block's depends= names, that
	// block's Seq when this one started, so Stale can tell when one has
	// run again since, or had its run cleared.
	Deps map[string]uint64
	// Duration is how long the block ran, from its Started event to its
	// Done, for a block that ran in a Session. A background block's runs
	// until Reap sees it end.
	Duration time.Duration
	// TimedOut is true when the block's timeout= ended it, which stops
	// the run.
	TimedOut bool
}

Result is what one block did.

func Includes

func Includes(d *doc.Document, opts Options) []*Result

Includes reads the files d's include blocks name. It returns one result per block, like Run, with only the include blocks filled in: Stdout holds the selected lines. A relative path is relative to opts.Dir, or opts.File's directory; res://name is name in the document's assets folder, <doc>.assets. The file must be a regular file of at most docroot.MaxRead bytes inside the document's root, unless opts.AllowOutside or opts.AllowedOutside names it.

func Run

func Run(ctx context.Context, d *doc.Document, opts Options) ([]*Result, error)

Run executes d's blocks in order and returns one result per block. It stops early when a block ends its shell, or when a block fails and on_error is stop. Blocks after the stop are returned with Ran false.

func (*Result) ExitStatus

func (r *Result) ExitStatus() int

ExitStatus is the block's exit status, or 1 when mdsh failed to run it (r.Err) and there is no status.

func (*Result) Failed

func (r *Result) Failed() bool

Failed reports whether the block ran and did not succeed.

type Session added in v1.1.0

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

Session runs a document's blocks, keeping each env's shell alive from one run to the next. Run uses one to run the whole document; an interactive front end uses one to run blocks as they are picked.

A Session runs one thing at a time: don't call RunFrom or RunBlock while another call is running.

func NewSession added in v1.1.0

func NewSession(d *doc.Document, opts Options) (*Session, error)

NewSession reads d's include blocks and readies its envs. No shell is started until a block runs in it. Close the session when done.

func (*Session) Ask added in v1.3.0

func (s *Session) Ask(ctx context.Context, script string) (string, error)

Ask runs script in the shell of the document's top-level env, where blocks with no env= run, and returns what it printed. It sees what blocks left there, such as the directory and variables, and should change none of it, so put it in a subshell. Call it while nothing runs; ending ctx ends the shell.

func (*Session) AskSized added in v1.4.0

func (s *Session) AskSized(ctx context.Context, script string, cols, rows int) (string, error)

AskSized is Ask with the shell's terminal, if it has one, sized cols by rows first. Zero leaves it as it is.

func (*Session) Close added in v1.1.0

func (s *Session) Close()

Close ends the session's shells, and any background block still running, which it reports as killed, and removes the control socket.

func (*Session) Kill added in v1.4.1

func (s *Session) Kill() bool

Kill ends the shell a block is running in, at once, as when a block that was stopped won't stop. What blocks set there is gone; the next block in that env starts a new shell. It reports whether a block was running. It is safe to call while a block runs.

func (*Session) PTY added in v1.3.0

func (s *Session) PTY() bool

PTY reports whether the session's shells have terminals of their own, which RunTyped needs.

func (*Session) ReadIncludes added in v1.3.0

func (s *Session) ReadIncludes()

ReadIncludes reads every include block's file again, as after a run whose blocks may have written them. Call it while nothing runs.

func (*Session) Reap added in v1.2.0

func (s *Session) Reap()

Reap finishes the results of background blocks that have ended, and reports each with a Done event. Run calls it before each block and at the end; a front end running blocks one at a time can call it to catch up while nothing runs.

func (*Session) Results added in v1.1.0

func (s *Session) Results() []*Result

Results returns one result per block, in order. A block run again gets a new result, so hold on to the slice only while nothing runs.

func (*Session) RunBlock added in v1.1.0

func (s *Session) RunBlock(ctx context.Context, i int) (*Result, error)

RunBlock runs block i alone and returns its new result. It runs the block even if it is marked skip, its run= condition is false or Only leaves it out, since running it is what was asked for. First the blocks its depends= needs are asked about and run, from the top of the chain down, as Options.Depend says; a Stop there keeps the old result, and a failed dependency returns ErrDependency. Then a confirm block is confirmed, right before it runs; if the answer is not Go, the old result stays and RunBlock returns it. An include block reads its file again. It returns an error if the block can't run at all.

func (*Session) RunFrom added in v1.1.0

func (s *Session) RunFrom(ctx context.Context, from int) error

RunFrom runs the blocks from index from to the end, the way Run does: it honors skip, run= (once included), Only, confirm, depends= and step mode, and stops when a block ends its shell or fails with on_error stop. Blocks it runs again get new results.

func (*Session) RunRange added in v1.3.0

func (s *Session) RunRange(ctx context.Context, from, to int) error

RunRange runs blocks from up to but not including to, as RunFrom runs them: confirm, run=, skip, depends= and on_error all apply, and a block's dependencies run first even when they are outside the range. mdsh-gui uses it to run a section.

func (*Session) RunTyped added in v1.3.0

func (s *Session) RunTyped(ctx context.Context, i int) (r *Result, fullScreen bool, err error)

RunTyped runs block i on Terminal, as if it had been typed there: what is typed in the terminal goes to it, and it shows what it writes. A block that switched to the terminal's alternate screen, as vim or top do, gets its session as a recording, the way a tty block does, and RunTyped reports it as full screen. Any other block gets the text it showed as its stdout. It runs with the shell's job control on, where the shell has it, so ctrl+z stops it, ending the run with status 128 plus SIGTSTP, and fg in a later RunTyped brings it back. The session needs Options.PTY, or a tty block, and Options.Terminal.

func (*Session) SecretVars added in v1.4.0

func (s *Session) SecretVars() []string

SecretVars are the full names, MDSH_VAR_ and the name, of the variables mdsh ctl set --secret has made this session, sorted. A view hides the copy buttons of a block whose code names one.

func (*Session) SetArgs added in v1.4.1

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

SetArgs sets the positional parameters, $1 and on, in every shell the session has started, and for those it starts later, keeping what blocks set in them. Call it while nothing runs.

func (*Session) SetChoices added in v1.4.1

func (s *Session) SetChoices(only string, step, stopOnError bool) error

SetChoices changes what runs and how, as --only, --step and --stop-on-error do, keeping the shells and what blocks set in them. Call it while nothing runs.

func (*Session) SetFile added in v1.3.0

func (s *Session) SetFile(file string)

SetFile renames the document the session runs: blocks run from now on see file as MDSH_FILE and save their assets in <file>.assets, linked from file's folder. The shells and their working directory stay as they are.

func (*Session) SetResult added in v1.4.0

func (s *Session) SetResult(i int, r *Result)

SetResult puts r in as block i's result, as when a notebook clears a block's run or an undo puts it back, so depends= and Stale see it. The shell keeps what the run did. Call it while nothing runs.

func (*Session) Sync added in v1.1.0

func (s *Session) Sync() error

Sync catches the session up with changes to the document since it started: blocks appended, as by doc.AppendBlock, blocks edited in place, as by doc.Document.SetBlock, and a new source, as by doc.Document.SetSource. A block that kept its identity keeps its result, wherever it moved; a new block starts with none, except that a new include block is read. Front matter fixed since the session started returns ErrFrontMatterFixed. Call it while nothing runs.

func (*Session) Wait added in v1.2.0

func (s *Session) Wait(ctx context.Context) error

Wait waits for the background blocks still running, each until its timeout= or, without one, for BackgroundWait, and kills those that don't end in time. If ctx ends first, it kills them all.

Jump to

Keyboard shortcuts

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