run

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 28 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 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 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.

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

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 (exit, or a timeout).
	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.
	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.

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