process

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 22 Imported by: ? modules, 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 process executes external programs such as git, ffmpeg, or build scripts, and supports faking them in tests.

Call Run directly, or chain configuration helpers such as Dir and Timeout before running a command. Commands execute through the Runner belonging to the application carried in ctx, so HTTP handlers pass r while jobs, listeners, and console commands pass their ctx:

res, err := process.Run(r, "git", "log", "-1", "--format=%h")
res, err := process.Dir("scripts").Timeout(2*time.Minute).Run(ctx, "bash", "import.sh")

Arguments are passed directly to the executable without invoking a shell, so untrusted input cannot alter command execution. Use Runner.Shell when you explicitly need shell features such as pipes or globs. By default, processes start in the application's base path, inherit its environment, and terminate after 60 seconds or when ctx is canceled.

A Runner is immutable: every option method returns a new runner so you can reuse a configured runner as a shared template across goroutines. In tests, install a Fake through processtest to intercept commands without spawning real processes.

On Unix systems, each process leads its own process group. Signals, Running.Stop, timeouts, and context cancellation apply to the entire group, stopping any child processes it spawned. Background processes left running after the command exits normally continue running without blocking return.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFaked = errors.New("process: no fake answers the process")

ErrNotFaked is returned when a Fake cannot answer a command, either because stray processes are blocked and no pattern matched or because a configured response sequence has been exhausted.

Functions

This section is empty.

Types

type Command

type Command struct {
	// Program is the executable name or path, such as "git". It is empty for
	// shell commands.
	Program string
	// Args holds the arguments passed after Program, exactly as supplied.
	Args []string
	// Script is the shell command string passed to [Runner.Shell] or
	// [Runner.StartShell], and is empty for direct program invocations.
	Script string
	// Dir is the working directory resolved against the application's base
	// path.
	Dir string
	// Timeout is the maximum total run duration, or 0 for no limit.
	Timeout time.Duration
	// IdleTimeout is the maximum duration without output, or 0 for no limit.
	IdleTimeout time.Duration
	// Env holds environment variables explicitly set with [Runner.Env],
	// excluding inherited variables.
	Env map[string]string
	// UnsetEnv lists inherited environment variables removed with
	// [Runner.UnsetEnv].
	UnsetEnv []string
	// InheritEnv reports whether the process inherits the application's
	// environment.
	InheritEnv bool
	// Input is the text written to the process's standard input.
	Input string
}

Command describes a process invocation and its resolved options for use by Fake implementations and test assertions.

func (*Command) String

func (c *Command) String() string

String formats the command line as a shell-quoted program and arguments (for example, "ls -la 'my files'"), or returns Script verbatim for shell commands. Fake matchers and test assertions compare against this string.

type ExitError

type ExitError struct {
	Result *Result
}

ExitError is returned by Result.EnsureSuccessful or a runner configured with Runner.EnsureSuccessful when a process fails or is terminated by a signal. Its message includes the command, exit status, and the tail of its output.

func (*ExitError) Error

func (e *ExitError) Error() string

Error formats the exit failure along with the tail of the process output.

func (*ExitError) TraceSummary

func (e *ExitError) TraceSummary() (string, string)

TraceSummary describes the exit by its status, without the process's output.

type Fake

type Fake interface {
	// Run returns the [Result] or error (such as [*StartError] or
	// [*TimeoutError]) that executing cmd should produce.
	Run(cmd *Command) (*Result, error)
}

Fake intercepts process execution in tests, recording commands and returning canned results instead of spawning operating-system processes. Install one through Runner.Fake or processtest.New.

type Options

type Options struct {
	// BasePath is the default working directory for processes and the root
	// against which relative [Runner.Dir] paths are resolved. An empty value
	// uses the current working directory.
	BasePath string
	// Logger receives a debug log entry when each process finishes. When nil,
	// [slog.Default] is used.
	Logger *slog.Logger
}

Options configures a standalone Runner created with New, such as the runner created by laravel.New for an application.

type Result

type Result struct {
	// Command is the formatted command line returned by [Command.String].
	Command string
	// ExitCode is the process exit code, or -1 if the process was killed by a
	// signal or timed out.
	ExitCode int
	// Output contains captured standard output. It is empty when [Runner.Quietly]
	// is enabled.
	Output string
	// ErrorOutput contains captured standard error. It is empty when
	// [Runner.Quietly] is enabled.
	ErrorOutput string
}

Result holds the exit status and captured output of a completed process.

func Run

func Run(ctx context.Context, program string, args ...string) (*Result, error)

Run executes program with args using the application's Runner from ctx, following Runner.Run:

res, err := process.Run(r, "git", "log", "-1", "--format=%h")

Run panics if ctx does not carry an application scope.

func Shell

func Shell(ctx context.Context, script string) (*Result, error)

Shell executes script through the system shell using the application's Runner from ctx, following Runner.Shell. Shell panics if ctx does not carry an application scope.

func (*Result) EnsureSuccessful

func (r *Result) EnsureSuccessful() error

EnsureSuccessful returns an *ExitError if the process failed, or nil if it exited with status code 0.

func (*Result) Failed

func (r *Result) Failed() bool

Failed reports whether the process exited with a non-zero status code or was killed by a signal.

func (*Result) Successful

func (r *Result) Successful() bool

Successful reports whether the process exited with status code 0.

type Runner

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

Runner configures and executes external processes. Package-level helpers such as Dir and Run create a runner bound to the application in ctx and apply their options on top of the application's base runner.

Every configuration method returns a new Runner without modifying the receiver, so a configured Runner is safe to share across goroutines and reuse as a template:

importer := process.Dir("scripts").Env("IMPORT_PATH", "storage/imports")

users, err := importer.Run(ctx, "bash", "import.sh", "users")
posts, err := importer.Run(ctx, "bash", "import.sh", "posts")

func Dir

func Dir(dir string) *Runner

Dir returns an application-scoped Runner configured with Runner.Dir.

func EnsureSuccessful

func EnsureSuccessful() *Runner

EnsureSuccessful returns an application-scoped Runner configured with Runner.EnsureSuccessful.

func Env

func Env(name, value string) *Runner

Env returns an application-scoped Runner configured with Runner.Env.

func IdleTimeout

func IdleTimeout(timeout time.Duration) *Runner

IdleTimeout returns an application-scoped Runner configured with Runner.IdleTimeout.

func Input

func Input(input string) *Runner

Input returns an application-scoped Runner configured with Runner.Input.

func New

func New(options Options) *Runner

New creates a standalone Runner with a 60-second default timeout using the provided Options.

func Quietly

func Quietly() *Runner

Quietly returns an application-scoped Runner configured with Runner.Quietly.

func Stderr

func Stderr(w io.Writer) *Runner

Stderr returns an application-scoped Runner configured with Runner.Stderr.

func Stdout

func Stdout(w io.Writer) *Runner

Stdout returns an application-scoped Runner configured with Runner.Stdout.

func Timeout

func Timeout(timeout time.Duration) *Runner

Timeout returns an application-scoped Runner configured with Runner.Timeout.

func UnsetEnv

func UnsetEnv(name string) *Runner

UnsetEnv returns an application-scoped Runner configured with Runner.UnsetEnv.

func WithoutInheritingEnv

func WithoutInheritingEnv() *Runner

WithoutInheritingEnv returns an application-scoped Runner configured with Runner.WithoutInheritingEnv.

func (*Runner) Dir

func (r *Runner) Dir(dir string) *Runner

Dir returns a Runner whose processes start in dir. Relative paths are resolved against the application's base path.

func (*Runner) EnsureSuccessful

func (r *Runner) EnsureSuccessful() *Runner

EnsureSuccessful returns a Runner that fails with an *ExitError whenever a process exits with a non-zero status code or is terminated by a signal. This applies to Runner.Run, Runner.Shell, and Running.Wait, but not to Running.Stop.

func (*Runner) Env

func (r *Runner) Env(name, value string) *Runner

Env returns a Runner that sets environment variable name to value for its processes, overriding any inherited value.

func (*Runner) Fake

func (r *Runner) Fake(f Fake) bool

Fake installs f to intercept processes executed by r and any runners derived from r. If a fake is already installed, Fake leaves it unchanged and returns false.

func (*Runner) IdleTimeout

func (r *Runner) IdleTimeout(timeout time.Duration) *Runner

IdleTimeout returns a Runner that kills a process if it produces no output on standard output or standard error for timeout. Exceeding the limit fails the run with a *TimeoutError whose Idle field is true. Pass 0 (the default) to disable the idle timeout.

func (*Runner) Input

func (r *Runner) Input(input string) *Runner

Input returns a Runner that writes input to each process's standard input and then closes the stream. By default, standard input is empty.

func (*Runner) Quietly

func (r *Runner) Quietly() *Runner

Quietly returns a Runner that discards buffered output from the returned Result so high-volume processes do not accumulate output in memory. Streaming writers set with Runner.Stdout and Runner.Stderr, as well as Running.Chunks and Running.WaitUntil, still receive the output.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, program string, args ...string) (*Result, error)

Run executes program with args and waits for it to finish. Arguments are passed directly to the executable without shell interpretation. A non-zero exit code returns a *Result and a nil error unless Runner.EnsureSuccessful is enabled.

Run returns a *StartError if the executable cannot be started, a *TimeoutError if a timeout elapses, or the context error if ctx is canceled first (killing the process in the last two cases). If r was created via a package-level helper, Run panics when ctx does not carry an application scope.

func (*Runner) Shell

func (r *Runner) Shell(ctx context.Context, script string) (*Result, error)

Shell executes script through the system shell (sh -c on Unix, cmd /S /C on Windows) and waits for it to finish, following the same error and timeout rules as Runner.Run. Use Shell for pipes, redirects, and globs, and never interpolate untrusted user input into script; pass user input as separate arguments to Runner.Run instead.

func (*Runner) Start

func (r *Runner) Start(ctx context.Context, program string, args ...string) (*Running, error)

Start launches program with args and returns a *Running handle immediately without waiting for the process to exit. The process is killed if ctx is canceled. Start returns a *StartError if the executable cannot be launched, and panics if r was created via a package-level helper and ctx does not carry an application scope.

func (*Runner) StartShell

func (r *Runner) StartShell(ctx context.Context, script string) (*Running, error)

StartShell launches script through the system shell like Runner.Shell and returns a *Running handle immediately like Runner.Start.

func (*Runner) Stderr

func (r *Runner) Stderr(w io.Writer) *Runner

Stderr returns a Runner that tees each process's standard error to w as it arrives, following the same rules as Runner.Stdout.

func (*Runner) Stdout

func (r *Runner) Stdout(w io.Writer) *Runner

Stdout returns a Runner that tees each process's standard output to w as it arrives. Writes to w and the Runner.Stderr writer are serialized. If w returns an error, the process continues to completion and the run returns that write error afterward.

func (*Runner) Timeout

func (r *Runner) Timeout(timeout time.Duration) *Runner

Timeout returns a Runner that kills a process if it runs longer than timeout, replacing the 60-second default. Exceeding the limit fails the run with a *TimeoutError. Pass 0 to disable the timeout.

func (*Runner) UnsetEnv

func (r *Runner) UnsetEnv(name string) *Runner

UnsetEnv returns a Runner that removes name from the environment inherited by its processes.

func (*Runner) WithoutInheritingEnv

func (r *Runner) WithoutInheritingEnv() *Runner

WithoutInheritingEnv returns a Runner whose processes receive only the variables explicitly added with Runner.Env, regardless of where in the option chain this method is called. Include PATH if the command spawns other executables.

type Running

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

Running represents an in-flight process started with Runner.Start or Runner.StartShell. Its standard output and standard error are drained continuously so the process never blocks on a full pipe.

Call Running.Wait to await completion or Running.Stop to terminate the process gracefully. If the context passed to Start or StartShell is canceled, the process is killed automatically.

func Start

func Start(ctx context.Context, program string, args ...string) (*Running, error)

Start launches program with args using the application's Runner from ctx, following Runner.Start. Start panics if ctx does not carry an application scope.

func StartShell

func StartShell(ctx context.Context, script string) (*Running, error)

StartShell launches script through the system shell using the application's Runner from ctx, following Runner.StartShell. StartShell panics if ctx does not carry an application scope.

func (*Running) Chunks

func (r *Running) Chunks(ctx context.Context) iter.Seq[string]

Chunks returns an iterator over output chunks from standard output and standard error as they arrive, ending when the process closes its output or ctx is canceled.

Chunks yields unread chunks in arrival order, resuming where any previous Chunks loop or Running.WaitUntil call left off. Each chunk contains whatever bytes the process wrote in a single read, which may be part of a line or multiple lines. Unread chunks remain buffered in memory until the Running handle is discarded.

func (*Running) Done

func (r *Running) Done() <-chan struct{}

Done returns a channel that closes once the process exits and all of its output has been read.

func (*Running) PID

func (r *Running) PID() int

PID returns the operating-system process ID, or 0 for a faked process.

func (*Running) Signal

func (r *Running) Signal(sig os.Signal) error

Signal delivers sig to the running process and, on Unix, to its entire process group. Faked processes ignore signals and return nil. Signal returns an error if the process has already finished or on Windows.

func (*Running) Stop

func (r *Running) Stop(grace time.Duration) (*Result, error)

Stop terminates the process gracefully and returns its *Result. On Unix, Stop sends SIGTERM to the process group and escalates to SIGKILL if it is still running after grace elapses. On Windows, Stop kills the process immediately.

If the process exits on its own before being killed, Stop returns its normal result. Stop does not enforce Runner.EnsureSuccessful; a killed process returns a result with ExitCode set to -1.

func (*Running) Wait

func (r *Running) Wait() (*Result, error)

Wait blocks until the process finishes and returns its *Result, applying the same error rules as Runner.Run.

func (*Running) WaitUntil

func (r *Running) WaitUntil(ctx context.Context, match func(chunk string) bool) bool

WaitUntil consumes output chunks from Running.Chunks until match returns true, such as waiting for a dev server to log that it is ready. It returns false if the process closes its output or ctx is canceled before a match is found. Because match inspects one chunk at a time, text split across chunk boundaries does not match.

type StartError

type StartError struct {
	// Command is the formatted command line returned by [Command.String].
	Command string
	// Dir is the working directory in which the process attempted to start.
	Dir string
	// Err is the underlying error from starting the process.
	Err error
}

StartError is returned when a process cannot be started, such as when the executable is missing. It wraps the underlying os/exec error, so errors.Is(err, exec.ErrNotFound) detects a missing binary.

func (*StartError) Error

func (e *StartError) Error() string

Error formats the startup failure with the command, working directory, and underlying error.

func (*StartError) Unwrap

func (e *StartError) Unwrap() error

Unwrap returns the underlying error that prevented the process from starting.

type TimeoutError

type TimeoutError struct {
	// Result holds any output captured before the process was killed. Its
	// ExitCode is -1.
	Result *Result
	// Timeout is the duration limit that elapsed.
	Timeout time.Duration
	// Idle reports whether the process exceeded [Runner.IdleTimeout] rather
	// than [Runner.Timeout].
	Idle bool
}

TimeoutError is returned when a process exceeds its Runner.Timeout or Runner.IdleTimeout and is killed. Its message includes the command, duration limit, and the tail of its output.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error formats the timeout failure along with the tail of the process output.

Jump to

Keyboard shortcuts

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