Documentation
¶
Overview ¶
Package run executes a document's blocks in their envs.
Index ¶
- Constants
- Variables
- func CallerVars(d *doc.Document, environ []string) map[string]string
- func IsOwnVar(name string) bool
- func JoinArgs(args []string) string
- func Lines(data []byte, from, to int) ([]byte, error)
- func LookupAt(lookup doc.Lookup, d *doc.Document, results []*Result, pos int) doc.Lookup
- func NameBlocks(d *doc.Document, results []*Result, opts Options) ([]doc.Rename, error)
- func NewLookup(d *doc.Document, results []*Result, environ []string) doc.Lookup
- func OutKind(b *doc.Block) string
- func Overstrike(p []byte) []byte
- func PIDVar(id string) string
- func Runnable(b *doc.Block) bool
- func Shell(d *doc.Document) string
- func SplitArgs(s string) ([]string, error)
- func WithExpose(environ []string, names []string) []string
- func WithMode(environ []string, mode string) []string
- type Answer
- type Event
- type EventKind
- type Options
- type Progress
- type Result
- type Session
- func (s *Session) Ask(ctx context.Context, script string) (string, error)
- func (s *Session) Close()
- func (s *Session) PTY() bool
- func (s *Session) ReadIncludes()
- func (s *Session) Reap()
- func (s *Session) Results() []*Result
- func (s *Session) RunBlock(ctx context.Context, i int) (*Result, error)
- func (s *Session) RunFrom(ctx context.Context, from int) error
- func (s *Session) RunRange(ctx context.Context, from, to int) error
- func (s *Session) RunTyped(ctx context.Context, i int) (r *Result, fullScreen bool, err error)
- func (s *Session) SetFile(file string)
- func (s *Session) Sync() error
- func (s *Session) Wait(ctx context.Context) error
Constants ¶
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.
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.
const ExposeVar = "MDSH_EXPOSE"
ExposeVar lists, comma-separated, the caller's variables that {{$VAR}} may read. mdsh --expose adds to it.
const ResScheme = "res://"
ResScheme starts a path in the document's assets folder: res://notes.md is <doc>.assets/notes.md.
Variables ¶
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.
var ErrNoConfirm = errors.New("block needs confirmation")
ErrNoConfirm is returned when a block needs confirming and the run has no way to ask.
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.
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
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
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
JoinArgs is the reverse of SplitArgs: it quotes each argument that needs it.
func Lines ¶
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 ¶
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
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 ¶
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 ¶
OutKind returns the block's output kind: text, markdown, image, screenshot, or recording for a tty block.
func Overstrike ¶ added in v1.3.0
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
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 Shell ¶
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
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 WithExpose ¶ added in v1.3.0
WithExpose returns environ with names added to $MDSH_EXPOSE.
Types ¶
type Event ¶
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
// 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. 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). Go runs dep first, Skip goes on without it, and Stop runs
// neither. Answering Go also answers dep's own confirm. If Depend
// is nil, the run stops there with ErrNoConfirm, as for Confirm.
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
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
}
Result is what one block did.
func Includes ¶
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 ¶
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 ¶
ExitStatus is the block's exit status, or 1 when mdsh failed to run it (r.Err) and there is no status.
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
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
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) 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
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
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
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. A confirm block is still confirmed first; if the answer is not Go, the old result stays and RunBlock returns it. Then the blocks its depends= names are asked about and run, as Options.Depend says; a Stop there keeps the old result too, and a failed dependency returns ErrDependency. 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
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
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
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) SetFile ¶ added in v1.3.0
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) Sync ¶ added in v1.1.0
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.