Documentation
¶
Overview ¶
Package taskrunner executes an IDE's build / run / test commands as child processes: a dependency graph of Tasks run in topological order (independent tasks in parallel), every output line streamed as an Event, per-task and whole-run cancellation that kills the entire process group, and a History of what finished, how long it took and how it ended.
It exists to replace the hardcoded, uncancellable `go build ./...`, `go test -v ./...` and `go vet ./...` invocations in cmd/silkide: those spawn a bare exec.Command per keystroke, with no queue, no way to stop a runaway build and no record of what ran before.
Design notes:
Nothing here touches the GUI. The Runner only emits Events; a panel decides how to render them. That keeps the package headless — no GLFW, no Cairo, no font metrics — so it is fully testable.
Every task ends with exactly ONE EventExit, including tasks that never spawned a process (cancelled while queued, or skipped because a dependency did not succeed). EventStart is emitted only for a task whose process actually started, so a consumer can rely on "start … exit" or a bare "exit".
Events go out on a buffered channel and are never dropped: a consumer MUST drain Events for the whole duration of Run, otherwise a full buffer blocks the task that is producing output. Close ends the stream when the Runner is done with.
Cancellation kills the process GROUP, not just the direct child, so the compilers and test binaries the go tool forks die with it (see process.go).
A Task never goes through a shell: Cmd and Args are passed to os/exec as-is, so nothing in a task definition can be expanded, globbed or injected.
Index ¶
Constants ¶
const ( // EventStart reports that a task's process started. Line carries the // rendered command line (Task.CommandLine). EventStart = "start" // EventStdout is one line the task wrote to stdout, newline stripped. EventStdout = "stdout" // EventStderr is one line the task wrote to stderr, newline stripped. EventStderr = "stderr" // EventExit reports that a task reached a final state. Code is the // process exit status, or -1 when there is none (killed by a signal, // never started, cancelled while queued, skipped). Line carries the // reason when the task did not succeed, and is empty otherwise. EventExit = "exit" )
Event kinds. Kind is a plain string so a UI can switch on it and log it without a conversion table.
Variables ¶
var ( ErrEmptyID = errors.New("taskrunner: task id must not be empty") ErrEmptyCmd = errors.New("taskrunner: task command must not be empty") ErrRunning = errors.New("taskrunner: a run is already in flight") ErrClosed = errors.New("taskrunner: runner is closed") ErrNoTasks = errors.New("taskrunner: no tasks submitted") )
Sentinel errors returned by Submit, Run and Close. Graph problems are reported by TopoSort as *CycleError, *DuplicateIDError or *MissingDepError.
Functions ¶
func TopoSort ¶
TopoSort returns every node ID in dependency order: an ID appears only after all of the IDs it depends on. It doubles as the graph validator and returns, without a partial result:
- ErrEmptyID for a node with no ID,
- *DuplicateIDError for a repeated ID,
- *MissingDepError for a dependency outside the graph,
- *CycleError when the remaining edges cannot be ordered.
The order is deterministic and depends only on the input: Kahn's algorithm pops from a ready queue kept sorted by input position, so nodes that become runnable at the same time are emitted in submission order. The same nodes always yield the same slice, which is what makes a build log reproducible. Repeated edges ("a" listing "b" twice) are collapsed rather than rejected.
The result is a total order; the Runner uses it as the scan order of its scheduler (and therefore as the tie-break between tasks that are ready at the same moment), not as a serialization of the run.
Types ¶
type CycleError ¶
type CycleError struct{ Cycle []string }
CycleError reports that the submitted graph is not a DAG. Cycle is the offending path with its entry point repeated at both ends, e.g. ["build", "test", "build"], so the message reads as a loop.
func (*CycleError) Error ¶
func (e *CycleError) Error() string
type DuplicateIDError ¶
type DuplicateIDError struct{ ID string }
DuplicateIDError reports two nodes sharing an ID. IDs address tasks in Cancel and in every Event, so they have to be unique.
func (*DuplicateIDError) Error ¶
func (e *DuplicateIDError) Error() string
type Event ¶
Event is one thing that happened to a task, streamed live on the channel returned by Events. At is the wall-clock time it happened.
type MissingDepError ¶
type MissingDepError struct{ ID, Dep string }
MissingDepError reports a dependency on an ID that is not part of the graph. Running the task anyway would silently ignore an unmet dependency, so it is an error instead.
func (*MissingDepError) Error ¶
func (e *MissingDepError) Error() string
type Node ¶
Node is one vertex of the dependency graph: an ID plus the IDs that must finish before it may start. It is the graph-level projection of a Task (Task.ID / Task.DependsOn), which keeps this file free of any exec concern.
type Record ¶
type Record struct {
TaskID string
Name string
Status Status
Code int
Started time.Time
Finished time.Time
Duration time.Duration
Err error
}
Record is the post-mortem of one finished task: how it ended, with what exit code, and how long it took. Err carries the detail behind a non-successful Status (the Wait error for StatusFailed, context.Canceled for StatusCancelled, the blocking dependency for StatusSkipped) and is nil for StatusSucceeded. Code is -1 when there was no exit status.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner queues tasks, runs the resulting dependency graph and reports what happened. A Runner is safe for concurrent use: Submit, Cancel, CancelAll and History may be called from any goroutine (typically the UI thread) while Run executes on another.
func (*Runner) Cancel ¶
Cancel stops one task of the in-flight run: a running task has its process group killed, a queued task is dropped before it starts (both end up as StatusCancelled, which in turn skips whatever depends on them). It reports whether there was such a task left to cancel.
func (*Runner) CancelAll ¶
func (r *Runner) CancelAll()
CancelAll stops the whole in-flight run: every running process group is killed and every queued task is recorded as cancelled. It is a no-op when the Runner is idle. Run returns once the kills have been reaped.
func (*Runner) Close ¶
Close ends the event stream so a `for range Events()` consumer terminates. It is idempotent, and reports ErrRunning if a run is still in flight (closing the channel under a producer would panic) — cancel and let Run return first.
func (*Runner) Events ¶
Events is the live stream of the Runner. The consumer must keep reading it while Run executes; the channel is closed by Close.
func (*Runner) History ¶
History returns a copy of the finished-task records, oldest first, in the order the tasks reached their terminal state. It accumulates across runs of the same Runner and is safe to read while a run is in flight.
func (*Runner) Run ¶
Run executes every submitted task, honouring DependsOn: a task starts once all of its dependencies have succeeded, and tasks with no dependency on each other run concurrently. Run blocks until every task has reached a terminal state and all of its events have been handed to the stream.
The returned error only describes why the run could not be performed as specified — ErrClosed, ErrRunning, ErrNoTasks, or a graph error from TopoSort (*CycleError, *DuplicateIDError, *MissingDepError). The outcome of the tasks themselves is not an error of Run: read it from the EventExit stream or from History.
Cancelling ctx has the same effect as CancelAll: running processes are killed and queued tasks are recorded as cancelled.
type Status ¶
type Status string
Status is the lifecycle state of a task within one run.
const ( StatusPending Status = "pending" StatusRunning Status = "running" StatusSucceeded Status = "succeeded" StatusFailed Status = "failed" StatusCancelled Status = "cancelled" StatusSkipped Status = "skipped" )
Task states. Pending and Running are transient; the remaining four are terminal and are what shows up in History.
type Task ¶
type Task struct {
ID string
Name string
Cmd string
Args []string
Dir string
Env map[string]string
DependsOn []string
}
Task is one command to run. ID is the handle used by Cancel and carried by every Event, and must be unique within a Runner; Name is the human-readable label a UI shows ("Build", "Run tests"). Cmd/Args are passed straight to os/exec — no shell, no expansion. Dir is the working directory (empty means the parent's). Env holds overrides layered on top of the parent environment, not a replacement for it. DependsOn lists task IDs that must SUCCEED first; if one of them fails, is cancelled or is itself skipped, this task is skipped.
func (Task) CommandLine ¶
CommandLine renders the task as a one-line header for a log pane, e.g. `go build ./...`. Empty arguments and arguments containing whitespace or quotes are quoted so the line stays unambiguous. Display only — nothing is ever handed to a shell.