process

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 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.

README

process logo

Run commands, stream output, and manage subprocesses in Go.

Go Reference Go Test Go version Version Published GitHub release count Unit coverage Tests (Linux CI)

Quick Start · Examples · Behavior · API

Installation

Requires Go 1.27 or newer. Install Process in your Go module:

go get github.com/goforj/process

Quick Start

Save this program as main.go in the same module, then run go run .:

package main

import (
	"fmt"
	"log"

	"github.com/goforj/process"
)

// main prints the installed Go version.
func main() {
	result, err := process.Command("go", "version").Run()
	if err != nil {
		log.Fatal(err)
	}

	// A command's exit status is separate from an execution error.
	if !result.OK() {
		log.Fatalf("go exited with status %d: %s", result.ExitCode, result.Stderr)
	}
	fmt.Print(result.Stdout)
}

Reuse settings across commands with a Runner. See execution and logging behavior for timeouts, exit handling, and application tests.

Runnable Examples

The testing example shows dependency injection and recorded commands. Browse the complete programs for JSON decoding, streaming output, background execution, and pipelines.

API Index

Group Functions
Construction Command
Runner NewRunner · Runner.Run
Testing processtest.Fake
Execution Run · OutputTrimmed · Start
Context WithContext · WithTimeout
OS Controls WithProcessTree
Environment Env · EnvOnly
Input StdinString
Streaming OnStdout · StdoutWriter
Output DisableBuffering
Decoding DecodeJSON · DecodeYAML · As · Into
Pipelining Pipe · PipelineResults
Process Done · Wait · PID · GracefulShutdown
Results OK · IsExitCode · EnsureSuccessful
Shadow Print ShadowPrint · WithMask

See the complete API documentation for every exported type and method.

Arguments

Arg

Arg appends arguments to the command.

cmd := process.Command("printf").Arg("hello")
out, err := cmd.Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

Construction

Command

Command constructs a new command without executing it.

cmd := process.Command("printf", "hello")
out, err := cmd.Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

Context

WithContext

WithContext binds the command to a context. A nil context is normalized to context.Background when execution begins.

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
res, err := process.Command("go", "env", "GOOS").WithContext(ctx).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

WithDeadline

WithDeadline binds the command to a deadline. Replacing a deadline retains the context previously supplied through WithContext as its parent.

res, err := process.Command("go", "env", "GOOS").WithDeadline(time.Now().Add(2 * time.Second)).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

WithTimeout

WithTimeout binds the command to a timeout. Replacing a timeout retains the context previously supplied through WithContext as its parent.

res, err := process.Command("go", "env", "GOOS").WithTimeout(2 * time.Second).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

Debugging

Args

Args returns the argv slice used for execution.

cmd := process.Command("go", "env", "GOOS")
fmt.Println(strings.Join(cmd.Args(), " "))
// Output:
// go env GOOS

ShellEscaped

ShellEscaped returns a shell-escaped string for logging only.

cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.ShellEscaped())
// Output:
// echo 'hello world' "it's"

String

String returns a human-readable representation of the command.

cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.String())
// Output:
// echo "hello world" it's

Decoding

As

As executes the command and decodes its selected output into T.

type Product struct {
	Name string `json:"name"`
}
product, err := process.Command("printf", `{"name":"Coffee"}`).DecodeJSON().As[Product]()
if err != nil {
	return err
}
fmt.Println(product.Name)
// Output:
// Coffee

Decode

Decode configures a custom decoder for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.

type payload struct {
	Name string
}
decoder := process.DecoderFunc(func(data []byte, dst any) error {
	out, ok := dst.(*payload)
	if !ok {
		return fmt.Errorf("expected *payload")
	}
	_, val, ok := strings.Cut(string(data), "=")
	if !ok {
		return fmt.Errorf("invalid payload")
	}
	out.Name = val
	return nil
})
var out payload
if err := process.Command("printf", "name=gopher").
	Decode(decoder).
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecodeJSON

DecodeJSON configures JSON decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecodeWith

DecodeWith executes the command and decodes stdout into dst.

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeWith(&out, process.DecoderFunc(json.Unmarshal)); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecodeYAML

DecodeYAML configures YAML decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source.

type payload struct {
	Name string `yaml:"name"`
}
var out payload
if err := process.Command("printf", "name: gopher").
	DecodeYAML().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

DecoderFunc.Decode

Decode implements Decoder.

decoder := process.DecoderFunc(json.Unmarshal)
var product struct {
	Name string `json:"name"`
}
if err := decoder.Decode([]byte(`{"name":"Coffee"}`), &product); err != nil {
	return err
}
fmt.Println(product.Name)
// Output:
// Coffee

FromCombined

FromCombined decodes from combined stdout+stderr.

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}'`).
	DecodeJSON().
	FromCombined().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

FromStderr

FromStderr decodes from stderr.

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}' 1>&2`).
	DecodeJSON().
	FromStderr().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

FromStdout

FromStdout decodes from stdout (default).

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	FromStdout().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

Into

Into executes the command and decodes into dst.

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

Trim

Trim trims whitespace before decoding.

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", "  {\"name\":\"gopher\"}  ").
	DecodeJSON().
	Trim().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

Environment

Env

Env adds environment variables to the command.

cmd := process.Command("go", "env", "GOOS").Env("MODE=prod")
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// Output:
// true

EnvAppend

EnvAppend merges variables into the inherited environment.

cmd := process.Command("go", "env", "GOOS").EnvAppend(map[string]string{"A": "1"})
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "A=1"))
// Output:
// true

EnvInherit

EnvInherit restores default environment inheritance.

cmd := process.Command("go", "env", "GOOS").EnvInherit()
fmt.Println(len(cmd.EnvList()) > 0)
// Output:
// true

EnvList

EnvList returns the environment list for execution.

cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1

EnvOnly

EnvOnly ignores the parent environment.

cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1

Errors

Error

Error returns the wrapped error message when available.

err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Error())
// Output:
// boom

ExitError.Error

Error reports the exit status without including potentially sensitive output.

err := process.ExitError{Result: process.Result{ExitCode: 7}}
fmt.Println(err.Error())
// Output:
// process: command exited with status 7

TimeoutError.Error

Error distinguishes inactivity from an elapsed total deadline.

err := process.TimeoutError{Idle: true}
fmt.Println(err.Error())
// Output:
// process: idle timeout exceeded

TimeoutError.Unwrap

Unwrap makes timeouts recognizable through errors.Is with context.DeadlineExceeded.

err := process.TimeoutError{}
fmt.Println(errors.Is(err.Unwrap(), context.DeadlineExceeded))
// Output:
// true

Unwrap

Unwrap exposes the underlying error.

err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Unwrap() != nil)
// Output:
// true

Execution

CombinedOutput

CombinedOutput executes the command and returns stdout and stderr in observed chunk order plus any execution error. Exact byte interleaving between the two operating-system streams is inherently scheduler-dependent.

output, err := process.Command("sh", "-c", "printf warning >&2").CombinedOutput()
if err != nil {
	return err
}
fmt.Println(output)
// Output:
// warning

OnExecCmd

OnExecCmd registers a callback to mutate the underlying exec.Cmd before process attaches its stdin, output capture, and pipeline wiring. Use it for fields such as SysProcAttr; process owns Stdin, Stdout, and Stderr during execution.

result, err := process.Command("go", "version").OnExecCmd(func(cmd *exec.Cmd) {
	cmd.WaitDelay = time.Second
}).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Output

Output executes the command and returns stdout and any error.

out, err := process.Command("printf", "hello").Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

OutputBytes

OutputBytes executes the command and returns stdout bytes and any error.

out, err := process.Command("printf", "hello").OutputBytes()
if err != nil {
	return err
}
fmt.Println(string(out))
// Output:
// hello

OutputTrimmed

OutputTrimmed executes the command and returns trimmed stdout and any error.

out, err := process.Command("printf", "hello\n").OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hello

Run

Run executes the command and returns the result and any execution error. A non-zero exit code is represented in Result and does not itself produce an error.

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

Start

Start executes the command asynchronously. Startup still completes synchronously, so a returned Process represents either a fully started pipeline or a completed error.

proc := process.Command("go", "env", "GOOS").Start()
res, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

Input

StdinBytes

StdinBytes sets stdin from a copy of bytes so later caller mutation cannot change the command input.

out, err := process.Command("cat").
	StdinBytes([]byte("hi")).
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

StdinFile

StdinFile sets stdin from a file.

file, err := os.CreateTemp("", "process-input-*")
if err != nil {
	return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteString("hello"); err != nil {
	return err
}
if _, err := file.Seek(0, 0); err != nil {
	return err
}
output, err := process.Command("cat").StdinFile(file).Output()
if err != nil {
	return err
}
fmt.Println(output)
// Output:
// hello

StdinReader

StdinReader sets stdin from an io.Reader.

out, err := process.Command("cat").
	StdinReader(strings.NewReader("hi")).
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

StdinString

StdinString sets stdin from a string.

out, err := process.Command("cat").
	StdinString("hi").
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

OS Controls

CreationFlags

CreationFlags is a no-op on non-Windows platforms; on Windows it sets process creation flags.

result, err := process.Command("go", "version").CreationFlags(process.CreateNewProcessGroup).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

HideWindow

HideWindow is a no-op on non-Windows platforms; on Windows it hides console windows.

result, err := process.Command("go", "version").HideWindow(true).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Pdeathsig

Pdeathsig signals the child when its creating OS thread exits on Linux. It is a no-op on other platforms.

out, err := process.Command("printf", "ok").Pdeathsig(syscall.SIGTERM).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

Setpgid

Setpgid places the child in a new process group for group signals.

out, err := process.Command("printf", "ok").Setpgid(true).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

Setsid

Setsid starts the child in a new session, detaching it from the terminal.

out, err := process.Command("printf", "ok").Setsid(true).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

WithProcessTree

WithProcessTree includes descendants when canceling or terminating a command. It owns a process group on Linux and macOS and a job object on Windows. Surviving members are terminated when the direct child exits. Unix children that create another group or session leave this scope. Unsupported platforms return an error before starting the command. The option applies to every stage in a pipeline and preserves the default behavior of other commands.

result, err := process.Command("go", "version").WithProcessTree().Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Output

DisableBuffering

DisableBuffering stops retaining this stage's stdout and stderr in results. Custom writers, callbacks, and pipeline connections still receive output. CombinedOutput also returns no captured bytes for this stage. Line callbacks retain an unfinished line until its newline or the end of the stream.

var output strings.Builder
result, err := process.Command("go", "env", "GOOS").
	StdoutWriter(&output).
	DisableBuffering().
	Run()
if err != nil {
	return err
}
fmt.Println("streamed:", output.Len() > 0, "captured bytes:", len(result.Stdout))
// Output:
// streamed: true captured bytes: 0

Pipelining

Pipe

Pipe appends a new command to the pipeline. Pipelines run on all platforms. Configuration called on the returned Cmd applies to the new stage; configure the current stage before Pipe when it needs different environment, context, or I/O.

out, err := process.Command("printf", "go").
	Pipe("tr", "a-z", "A-Z").
	OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// GO

PipeBestEffort

PipeBestEffort selects the last stage as the primary result while surfacing the first execution error. Every stage is started concurrently.

res, err := process.Command("false").
	Pipe("printf", "ok").
	PipeBestEffort().
	Run()
if err != nil {
	return err
}
fmt.Print(res.Stdout)
// Output:
// ok

PipeStrict

PipeStrict selects the first stage with an execution error or non-zero exit as the primary result. Every stage is still started concurrently.

res, err := process.Command("false").
	Pipe("printf", "ok").
	PipeStrict().
	Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode != 0)
// Output:
// true

PipelineResults

PipelineResults executes the command and returns per-stage results and the first execution error. Non-zero exit codes remain data in their corresponding Result.

results, err := process.Command("printf", "go").Pipe("tr", "a-z", "A-Z").PipelineResults()
if err != nil {
	return err
}
fmt.Println(results[0].Stdout, results[1].Stdout)
// Output:
// go GO

Process

Done

Done returns a channel that closes after all pipeline stages exit and their output is collected. Wait can then retrieve the immutable result without blocking.

proc := process.Command("go", "env", "GOOS").Start()
<-proc.Done()
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

GracefulShutdown

GracefulShutdown sends a signal and escalates to kill after the timeout.

proc := process.Command("sleep", "10").Start()
if err := proc.GracefulShutdown(os.Interrupt, time.Second); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

Interrupt

Interrupt sends an interrupt signal to the process.

proc := process.Command("sleep", "10").Start()
if err := proc.Interrupt(); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

KillAfter

KillAfter terminates the process after the given duration.

proc := process.Command("sleep", "10").Start()
proc.KillAfter(100 * time.Millisecond)
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

PID

PID returns the first pipeline stage's assigned process ID, or zero if no stage started. The ID remains available after completion and can be reused by the OS.

proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(proc.PID() > 0)
// Output:
// true

PIDs

PIDs returns an independent slice of assigned process IDs in pipeline order. IDs describe started stages, including stages that have already exited.

proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(len(proc.PIDs()))
// Output:
// 1

Running

Running reports whether a started pipeline is still collecting its result. It returns false for an unstarted handle and after Done closes.

proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(proc.Running())
// Output:
// false

Send

Send sends a signal to the process.

proc := process.Command("sleep", "10").Start()
if err := proc.Send(os.Interrupt); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

Terminate

Terminate kills the process immediately.

proc := process.Command("sleep", "10").Start()
if err := proc.Terminate(); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

Wait

Wait waits for the command to complete and returns the result and any error.

proc := process.Command("go", "version").Start()
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Results

EnsureSuccessful

EnsureSuccessful returns the execution error or an ExitError for a nonzero status. It returns nil for success and does not change the Result.

result, err := process.Command("go", "version").Run()
if err != nil {
	return err
}
fmt.Println(result.EnsureSuccessful() == nil)
// Output:
// true

IsExitCode

IsExitCode reports whether the exit code matches.

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.IsExitCode(0))
// Output:
// true

IsSignal

IsSignal reports whether the command terminated due to a signal.

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.IsSignal(os.Interrupt))
// Output:
// false

OK

OK reports whether the command exited cleanly without errors.

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.OK())
// Output:
// true

Runner

NewRunner

NewRunner returns reusable settings without starting a process.

runner := process.NewRunner().Timeout(5 * time.Second).CheckExit()
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.CheckExit

CheckExit returns a Runner that reports a nonzero child exit as an ExitError. The default keeps nonzero exits in Result.ExitCode without returning an error.

_, err := process.NewRunner().CheckExit().Run(context.Background(), "sh", "-c", "exit 7")
var exit *process.ExitError
if !errors.As(err, &exit) {
	return err
}
fmt.Println(exit.Result.ExitCode)
// Output:
// 7

Runner.Dir

Dir returns a Runner using path as each child's working directory.

result, err := process.NewRunner().Dir(os.TempDir()).Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.DisableBuffering

DisableBuffering returns a Runner that streams output without retaining it.

var output strings.Builder
result, err := process.NewRunner().Stdout(&output).DisableBuffering().
	Run(context.Background(), "printf", "ready")
if err != nil {
	return err
}
fmt.Println(output.String(), len(result.Stdout))
// Output:
// ready 0

Runner.Env

Env returns a Runner with one environment override. An empty value sets an empty variable; use UnsetEnv to remove a variable from the child environment.

result, err := process.NewRunner().Env("MODE", "production").Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.Contains(result.Stdout, "MODE=production"))
// Output:
// true

Runner.IdleTimeout

IdleTimeout returns a Runner that cancels after d without stdout or stderr activity. Any nonempty output chunk resets the limit, even without a newline. A nonpositive duration disables this limit.

_, err := process.NewRunner().IdleTimeout(time.Second).Run(context.Background(), "sleep", "10")
var timeout *process.TimeoutError
fmt.Println(errors.As(err, &timeout) && timeout.Idle)
// Output:
// true

Runner.Input

Input returns a Runner that supplies a fresh reader of input to each child.

result, err := process.NewRunner().Input("request").Run(context.Background(), "cat")
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// request

Runner.Run

Run executes a fresh command using these settings. Arguments are passed directly to the executable. A nil context is treated as context.Background.

runner := process.NewRunner().Env("GOTOOLCHAIN", "local")
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.Start

Start starts a fresh command and reports startup failures immediately. The returned handle supports the existing Process lifecycle methods. Its Wait result follows this Runner's timeout and CheckExit policies.

child, err := process.NewRunner().Start(context.Background(), "go", "version")
if err != nil {
	return err
}
result, err := child.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.Stderr

Stderr returns a Runner that streams stderr to w as well as capturing it. The caller owns w. A nil writer disables streaming.

var output strings.Builder
result, err := process.NewRunner().Stderr(&output).Run(context.Background(), "sh", "-c", "printf warning >&2")
if err != nil {
	return err
}
fmt.Println(output.String(), result.Stderr)
// Output:
// warning warning

Runner.Stdout

Stdout returns a Runner that streams stdout to w as well as capturing it. The caller owns w. A nil writer disables streaming.

var output strings.Builder
result, err := process.NewRunner().Stdout(&output).Run(context.Background(), "printf", "ready")
if err != nil {
	return err
}
fmt.Println(output.String(), result.Stdout)
// Output:
// ready ready

Runner.Timeout

Timeout returns a Runner with a total limit starting at each Run or Start call. A nonpositive duration disables this limit. The caller's context still applies.

result, err := process.NewRunner().Timeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.UnsetEnv

UnsetEnv returns a Runner that removes key from each child's environment.

result, err := process.NewRunner().Env("EXAMPLE_TOKEN", "test").UnsetEnv("EXAMPLE_TOKEN").
	Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.Contains(result.Stdout, "EXAMPLE_TOKEN="))
// Output:
// false

Runner.WaitDelay

WaitDelay returns a Runner that bounds output-pipe draining after the child exits or its context is canceled. A nonpositive duration leaves draining unlimited. This does not interrupt a caller-owned writer blocked in Write.

result, err := process.NewRunner().Timeout(5*time.Second).WaitDelay(time.Second).
	Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.WithProcessTree

WithProcessTree returns a Runner that includes descendants in cancellation and termination. The native ownership and platform limits match Cmd.WithProcessTree.

runner := process.NewRunner().WithProcessTree().Timeout(5 * time.Second)
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

Runner.WithoutInheritingEnv

WithoutInheritingEnv returns a Runner that starts with an empty environment. Explicit Env settings are retained. Executable lookup still uses the parent's PATH, as with os/exec; use an absolute program path to control lookup.

result, err := process.NewRunner().WithoutInheritingEnv().Env("MODE", "test").
	Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.TrimSpace(result.Stdout))
// Output:
// MODE=test

Shadow Print

ShadowOff

ShadowOff disables shadow printing for this command chain, preserving configuration.

result, err := process.Command("printf", "hello").ShadowPrint().ShadowOff().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

ShadowOn

ShadowOn enables shadow printing using the previously configured options.

cmd := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build"))
cmd.ShadowOff()
result, err := cmd.ShadowOn().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

ShadowPrint

ShadowPrint configures shadow printing for this command chain.

result, err := process.Command("printf", "hello").ShadowPrint().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

WithFormatter

WithFormatter sets a formatter for ShadowPrint output.

formatter := func(event process.ShadowEvent) string {
	return fmt.Sprintf("%s: %s", event.Phase, event.Command)
}
result, err := process.Command("printf", "hello").ShadowPrint(process.WithFormatter(formatter)).Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

WithMask

WithMask applies a masker to the shadow-printed command string.

mask := func(command string) string { return strings.ReplaceAll(command, "secret", "***") }
result, err := process.Command("printf", "secret").ShadowPrint(process.WithMask(mask)).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

WithPrefix

WithPrefix sets the shadow print prefix.

result, err := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build")).Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

Streaming

OnStderr

OnStderr registers a line callback for stderr. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline.

if _, err := process.Command("sh", "-c", "printf 'warning\\n' >&2").
	OnStderr(func(line string) { fmt.Println(line) }).Run(); err != nil {
	return err
}
// Output:
// warning

OnStdout

OnStdout registers a line callback for stdout. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline.

if _, err := process.Command("printf", "hi\n").
	OnStdout(func(line string) { fmt.Println(line) }).
	Run(); err != nil {
	return err
}
// Output:
// hi

StderrWriter

StderrWriter sets a raw writer for stderr.

When the writer is a terminal and no line callbacks or combined output are enabled, process passes stderr through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.

var output strings.Builder
if _, err := process.Command("sh", "-c", "printf warning >&2").StderrWriter(&output).Run(); err != nil {
	return err
}
fmt.Println(output.String())
// Output:
// warning

StdoutWriter

StdoutWriter sets a raw writer for stdout.

When the writer is a terminal and no line callbacks or combined output are enabled, process passes stdout through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.

var out strings.Builder
if _, err := process.Command("printf", "hello").
	StdoutWriter(&out).
	Run(); err != nil {
	return err
}
fmt.Print(out.String())
// Output:
// hello

WithPTY

WithPTY attaches stdout/stderr to a pseudo-terminal.

When enabled, stdout and stderr are merged into a single stream. OnStdout and OnStderr both receive the same lines, and Result.Stderr remains empty. Platforms without PTY support return an error when the command runs.

if _, err := process.Command("printf", "hi").
	WithPTY().
	OnStdout(func(line string) { fmt.Println(line) }).
	Run(); err != nil {
	return err
}
// Output:
// hi

Testing

processtest.Fake

Inject process.Executor into application code. Queue results on a separate fake for each test, then inspect its calls. Unexpected commands return an error and never start a real process.

status := func(ctx context.Context, commands process.Executor) (string, error) {
	result, err := commands.Run(ctx, "git", "status", "--short")
	if err != nil {
		return "", err
	}
	if err := result.EnsureSuccessful(); err != nil {
		return "", err
	}
	return strings.TrimSpace(result.Stdout), nil
}
var fake processtest.Fake
fake.Queue(process.Result{Stdout: " M README.md\n"})
output, err := status(context.Background(), &fake)
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(output)

call := fake.Calls()[0]
fmt.Println(call.Name, strings.Join(call.Args, " "))

_, err = fake.Run(context.Background(), "unexpected-command")
fmt.Println(errors.Is(err, processtest.ErrUnexpectedCommand))
// Output:
// M README.md
// git status --short
// true

WorkingDir

Dir

Dir sets the working directory.

dir, err := filepath.EvalSymlinks(os.TempDir())
if err != nil {
	return err
}
out, err := process.Command("pwd").Dir(dir).OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out == dir)
// Output:
// true

Development

make test          # Run library, generator, and example tests.
make vet           # Check all three Go modules.
make test-examples # Execute examples and check their output.
make test-race     # Check library tests for data races.
make generate   # Regenerate examples and the API reference from GoDoc.

The example suite executes every program and checks its output on Unix. Windows runs the portable Go-command examples and compiles the Unix-specific programs.

Edit the GoDoc examples or the tested fake example before regenerating. The docs and examples modules keep tooling out of the library's module download. Use make help for more commands.

For an existing application, see the migration guide.

Licensed under the MIT License.

Documentation

Overview

Package process provides explicit, fluent subprocess execution without shell parsing or interpolation.

A Runner holds immutable settings for repeated or concurrent executions. Runner.Run and Runner.Start take a context per invocation. CheckExit opts into returning ExitError for nonzero child exits. Applications can accept Executor to substitute a scoped fake from the processtest package.

A Cmd is a mutable configuration value and must not be changed or executed concurrently. Each execution creates fresh os/exec commands, captures stdout and stderr, and reports process status in Result. A non-zero child exit is represented by Result.ExitCode rather than an error; errors are reserved for failures to start, cancellation, and I/O failures.

Pipelines start every stage concurrently. Stage configuration methods apply to the stage on which they are called, while PipeStrict, PipeBestEffort, WithPTY, and shadow-print settings apply to the full chain.

Index

Constants

View Source
const (
	// CreateNewProcessGroup starts the process in a new process group.
	CreateNewProcessGroup = 0x00000200
	// CreateNewConsole creates a new console for the process.
	CreateNewConsole = 0x00000010
	// CreateNoWindow prevents console windows from being created.
	CreateNoWindow = 0x08000000
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cmd

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

Cmd represents a single command invocation or a pipeline stage. Cmd is mutable and must not be configured or executed concurrently.

func Command

func Command(name string, args ...string) *Cmd

Command constructs a new command without executing it. @group Construction

Example: command

cmd := process.Command("printf", "hello")
out, err := cmd.Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

func (*Cmd) Arg

func (c *Cmd) Arg(values ...any) *Cmd

Arg appends arguments to the command. @group Arguments

Example: add args

cmd := process.Command("printf").Arg("hello")
out, err := cmd.Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

func (*Cmd) Args

func (c *Cmd) Args() []string

Args returns the argv slice used for execution. @group Debugging

Example: args

cmd := process.Command("go", "env", "GOOS")
fmt.Println(strings.Join(cmd.Args(), " "))
// Output:
// go env GOOS

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() (string, error)

CombinedOutput executes the command and returns stdout and stderr in observed chunk order plus any execution error. Exact byte interleaving between the two operating-system streams is inherently scheduler-dependent. @group Execution

Example: combined output

output, err := process.Command("sh", "-c", "printf warning >&2").CombinedOutput()
if err != nil {
	return err
}
fmt.Println(output)
// Output:
// warning

func (*Cmd) CreationFlags

func (c *Cmd) CreationFlags(_ uint32) *Cmd

CreationFlags is a no-op on non-Windows platforms; on Windows it sets process creation flags. @group OS Controls

func (*Cmd) Decode

func (c *Cmd) Decode(decoder Decoder) *DecodeChain

Decode configures a custom decoder for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source. @group Decoding

Example: decode custom

type payload struct {
	Name string
}
decoder := process.DecoderFunc(func(data []byte, dst any) error {
	out, ok := dst.(*payload)
	if !ok {
		return fmt.Errorf("expected *payload")
	}
	_, val, ok := strings.Cut(string(data), "=")
	if !ok {
		return fmt.Errorf("invalid payload")
	}
	out.Name = val
	return nil
})
var out payload
if err := process.Command("printf", "name=gopher").
	Decode(decoder).
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*Cmd) DecodeJSON

func (c *Cmd) DecodeJSON() *DecodeChain

DecodeJSON configures JSON decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source. @group Decoding

Example: decode json

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*Cmd) DecodeWith

func (c *Cmd) DecodeWith(dst any, decoder Decoder) error

DecodeWith executes the command and decodes stdout into dst. @group Decoding

Example: decode with

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeWith(&out, process.DecoderFunc(json.Unmarshal)); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*Cmd) DecodeYAML

func (c *Cmd) DecodeYAML() *DecodeChain

DecodeYAML configures YAML decoding for this command. Decoding reads from stdout by default; use FromStdout, FromStderr, or FromCombined to select a source. @group Decoding

Example: decode yaml

type payload struct {
	Name string `yaml:"name"`
}
var out payload
if err := process.Command("printf", "name: gopher").
	DecodeYAML().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*Cmd) Dir

func (c *Cmd) Dir(path string) *Cmd

Dir sets the working directory. @group WorkingDir

Example: change dir

dir, err := filepath.EvalSymlinks(os.TempDir())
if err != nil {
	return err
}
out, err := process.Command("pwd").Dir(dir).OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out == dir)
// Output:
// true

func (*Cmd) DisableBuffering

func (c *Cmd) DisableBuffering() *Cmd

DisableBuffering stops retaining this stage's stdout and stderr in results. Custom writers, callbacks, and pipeline connections still receive output. CombinedOutput also returns no captured bytes for this stage. Line callbacks retain an unfinished line until its newline or the end of the stream. @group Output

Example: stream without capture

var output strings.Builder
result, err := process.Command("go", "env", "GOOS").
	StdoutWriter(&output).
	DisableBuffering().
	Run()
if err != nil {
	return err
}
fmt.Println("streamed:", output.Len() > 0, "captured bytes:", len(result.Stdout))
// Output:
// streamed: true captured bytes: 0

func (*Cmd) Env

func (c *Cmd) Env(values ...any) *Cmd

Env adds environment variables to the command. @group Environment

Example: set env

cmd := process.Command("go", "env", "GOOS").Env("MODE=prod")
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "MODE=prod"))
// Output:
// true

func (*Cmd) EnvAppend

func (c *Cmd) EnvAppend(values map[string]string) *Cmd

EnvAppend merges variables into the inherited environment. @group Environment

Example: append env

cmd := process.Command("go", "env", "GOOS").EnvAppend(map[string]string{"A": "1"})
fmt.Println(strings.Contains(strings.Join(cmd.EnvList(), ","), "A=1"))
// Output:
// true

func (*Cmd) EnvInherit

func (c *Cmd) EnvInherit() *Cmd

EnvInherit restores default environment inheritance. @group Environment

Example: inherit env

cmd := process.Command("go", "env", "GOOS").EnvInherit()
fmt.Println(len(cmd.EnvList()) > 0)
// Output:
// true

func (*Cmd) EnvList

func (c *Cmd) EnvList() []string

EnvList returns the environment list for execution. @group Environment

Example: env list

cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1

func (*Cmd) EnvOnly

func (c *Cmd) EnvOnly(values map[string]string) *Cmd

EnvOnly ignores the parent environment. @group Environment

Example: replace env

cmd := process.Command("go", "env", "GOOS").EnvOnly(map[string]string{"A": "1"})
fmt.Println(strings.Join(cmd.EnvList(), ","))
// Output:
// A=1

func (*Cmd) HideWindow

func (c *Cmd) HideWindow(_ bool) *Cmd

HideWindow is a no-op on non-Windows platforms; on Windows it hides console windows. @group OS Controls

func (*Cmd) OnExecCmd

func (c *Cmd) OnExecCmd(fn func(*exec.Cmd)) *Cmd

OnExecCmd registers a callback to mutate the underlying exec.Cmd before process attaches its stdin, output capture, and pipeline wiring. Use it for fields such as SysProcAttr; process owns Stdin, Stdout, and Stderr during execution. @group Execution

Example: exec cmd

result, err := process.Command("go", "version").OnExecCmd(func(cmd *exec.Cmd) {
	cmd.WaitDelay = time.Second
}).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (*Cmd) OnStderr

func (c *Cmd) OnStderr(fn func(string)) *Cmd

OnStderr registers a line callback for stderr. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline. @group Streaming

Example: stderr lines

if _, err := process.Command("sh", "-c", "printf 'warning\\n' >&2").
	OnStderr(func(line string) { fmt.Println(line) }).Run(); err != nil {
	return err
}
// Output:
// warning

func (*Cmd) OnStdout

func (c *Cmd) OnStdout(fn func(string)) *Cmd

OnStdout registers a line callback for stdout. The final unterminated line is delivered after the process exits. Output callbacks and writers are serialized across one pipeline. @group Streaming

Example: stdout lines

if _, err := process.Command("printf", "hi\n").
	OnStdout(func(line string) { fmt.Println(line) }).
	Run(); err != nil {
	return err
}
// Output:
// hi

func (*Cmd) Output

func (c *Cmd) Output() (string, error)

Output executes the command and returns stdout and any error. @group Execution

Example: output

out, err := process.Command("printf", "hello").Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// hello

func (*Cmd) OutputBytes

func (c *Cmd) OutputBytes() ([]byte, error)

OutputBytes executes the command and returns stdout bytes and any error. @group Execution

Example: output bytes

out, err := process.Command("printf", "hello").OutputBytes()
if err != nil {
	return err
}
fmt.Println(string(out))
// Output:
// hello

func (*Cmd) OutputTrimmed

func (c *Cmd) OutputTrimmed() (string, error)

OutputTrimmed executes the command and returns trimmed stdout and any error. @group Execution

Example: output trimmed

out, err := process.Command("printf", "hello\n").OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hello

func (*Cmd) Pdeathsig

func (c *Cmd) Pdeathsig(sig syscall.Signal) *Cmd

Pdeathsig signals the child when its creating OS thread exits on Linux. It is a no-op on other platforms. @group OS Controls

Example: pdeathsig

out, err := process.Command("printf", "ok").Pdeathsig(syscall.SIGTERM).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

func (*Cmd) Pipe

func (c *Cmd) Pipe(name string, args ...string) *Cmd

Pipe appends a new command to the pipeline. Pipelines run on all platforms. Configuration called on the returned Cmd applies to the new stage; configure the current stage before Pipe when it needs different environment, context, or I/O. @group Pipelining

Example: pipe

out, err := process.Command("printf", "go").
	Pipe("tr", "a-z", "A-Z").
	OutputTrimmed()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// GO

func (*Cmd) PipeBestEffort

func (c *Cmd) PipeBestEffort() *Cmd

PipeBestEffort selects the last stage as the primary result while surfacing the first execution error. Every stage is started concurrently. @group Pipelining

Example: best effort

res, err := process.Command("false").
	Pipe("printf", "ok").
	PipeBestEffort().
	Run()
if err != nil {
	return err
}
fmt.Print(res.Stdout)
// Output:
// ok

func (*Cmd) PipeStrict

func (c *Cmd) PipeStrict() *Cmd

PipeStrict selects the first stage with an execution error or non-zero exit as the primary result. Every stage is still started concurrently. @group Pipelining

Example: strict

res, err := process.Command("false").
	Pipe("printf", "ok").
	PipeStrict().
	Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode != 0)
// Output:
// true

func (*Cmd) PipelineResults

func (c *Cmd) PipelineResults() ([]Result, error)

PipelineResults executes the command and returns per-stage results and the first execution error. Non-zero exit codes remain data in their corresponding Result. @group Pipelining

Example: pipeline results

results, err := process.Command("printf", "go").Pipe("tr", "a-z", "A-Z").PipelineResults()
if err != nil {
	return err
}
fmt.Println(results[0].Stdout, results[1].Stdout)
// Output:
// go GO

func (*Cmd) Run

func (c *Cmd) Run() (Result, error)

Run executes the command and returns the result and any execution error. A non-zero exit code is represented in Result and does not itself produce an error. @group Execution

Example: run

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

func (*Cmd) Setpgid

func (c *Cmd) Setpgid(on bool) *Cmd

Setpgid places the child in a new process group for group signals. @group OS Controls

Example: setpgid

out, err := process.Command("printf", "ok").Setpgid(true).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

func (*Cmd) Setsid

func (c *Cmd) Setsid(on bool) *Cmd

Setsid starts the child in a new session, detaching it from the terminal. @group OS Controls

Example: setsid

out, err := process.Command("printf", "ok").Setsid(true).Output()
if err != nil {
	return err
}
fmt.Print(out)
// Output:
// ok

func (*Cmd) ShadowOff

func (c *Cmd) ShadowOff() *Cmd

ShadowOff disables shadow printing for this command chain, preserving configuration. @group Shadow Print

Example: shadow off

result, err := process.Command("printf", "hello").ShadowPrint().ShadowOff().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

func (*Cmd) ShadowOn

func (c *Cmd) ShadowOn() *Cmd

ShadowOn enables shadow printing using the previously configured options. @group Shadow Print

Example: shadow on

cmd := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build"))
cmd.ShadowOff()
result, err := cmd.ShadowOn().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

func (*Cmd) ShadowPrint

func (c *Cmd) ShadowPrint(opts ...ShadowOption) *Cmd

ShadowPrint configures shadow printing for this command chain. @group Shadow Print

Example: shadow print

result, err := process.Command("printf", "hello").ShadowPrint().Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

func (*Cmd) ShellEscaped

func (c *Cmd) ShellEscaped() string

ShellEscaped returns a shell-escaped string for logging only. @group Debugging

Example: shell escaped

cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.ShellEscaped())
// Output:
// echo 'hello world' "it's"

func (*Cmd) Start

func (c *Cmd) Start() *Process

Start executes the command asynchronously. Startup still completes synchronously, so a returned Process represents either a fully started pipeline or a completed error. @group Execution

Example: start

proc := process.Command("go", "env", "GOOS").Start()
res, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

func (*Cmd) StderrWriter

func (c *Cmd) StderrWriter(w io.Writer) *Cmd

StderrWriter sets a raw writer for stderr. @group Streaming

When the writer is a terminal and no line callbacks or combined output are enabled, process passes stderr through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.

Example: stderr writer

var output strings.Builder
if _, err := process.Command("sh", "-c", "printf warning >&2").StderrWriter(&output).Run(); err != nil {
	return err
}
fmt.Println(output.String())
// Output:
// warning

func (*Cmd) StdinBytes

func (c *Cmd) StdinBytes(input []byte) *Cmd

StdinBytes sets stdin from a copy of bytes so later caller mutation cannot change the command input. @group Input

Example: stdin bytes

out, err := process.Command("cat").
	StdinBytes([]byte("hi")).
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

func (*Cmd) StdinFile

func (c *Cmd) StdinFile(file *os.File) *Cmd

StdinFile sets stdin from a file. @group Input

Example: stdin file

file, err := os.CreateTemp("", "process-input-*")
if err != nil {
	return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err := file.WriteString("hello"); err != nil {
	return err
}
if _, err := file.Seek(0, 0); err != nil {
	return err
}
output, err := process.Command("cat").StdinFile(file).Output()
if err != nil {
	return err
}
fmt.Println(output)
// Output:
// hello

func (*Cmd) StdinReader

func (c *Cmd) StdinReader(reader io.Reader) *Cmd

StdinReader sets stdin from an io.Reader. @group Input

Example: stdin reader

out, err := process.Command("cat").
	StdinReader(strings.NewReader("hi")).
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

func (*Cmd) StdinString

func (c *Cmd) StdinString(input string) *Cmd

StdinString sets stdin from a string. @group Input

Example: stdin string

out, err := process.Command("cat").
	StdinString("hi").
	Output()
if err != nil {
	return err
}
fmt.Println(out)
// Output:
// hi

func (*Cmd) StdoutWriter

func (c *Cmd) StdoutWriter(w io.Writer) *Cmd

StdoutWriter sets a raw writer for stdout. @group Streaming

When the writer is a terminal and no line callbacks or combined output are enabled, process passes stdout through directly and does not buffer it for results. Writer failures are returned as ErrExec after already received bytes are captured.

Example: stdout writer

var out strings.Builder
if _, err := process.Command("printf", "hello").
	StdoutWriter(&out).
	Run(); err != nil {
	return err
}
fmt.Print(out.String())
// Output:
// hello

func (*Cmd) String

func (c *Cmd) String() string

String returns a human-readable representation of the command. @group Debugging

Example: string

cmd := process.Command("echo", "hello world", "it's")
fmt.Println(cmd.String())
// Output:
// echo "hello world" it's

func (*Cmd) WithContext

func (c *Cmd) WithContext(ctx context.Context) *Cmd

WithContext binds the command to a context. A nil context is normalized to context.Background when execution begins. @group Context

Example: with context

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
res, err := process.Command("go", "env", "GOOS").WithContext(ctx).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

func (*Cmd) WithDeadline

func (c *Cmd) WithDeadline(t time.Time) *Cmd

WithDeadline binds the command to a deadline. Replacing a deadline retains the context previously supplied through WithContext as its parent. @group Context

Example: with deadline

res, err := process.Command("go", "env", "GOOS").WithDeadline(time.Now().Add(2 * time.Second)).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

func (*Cmd) WithPTY

func (c *Cmd) WithPTY() *Cmd

WithPTY attaches stdout/stderr to a pseudo-terminal. @group Streaming

When enabled, stdout and stderr are merged into a single stream. OnStdout and OnStderr both receive the same lines, and Result.Stderr remains empty. Platforms without PTY support return an error when the command runs.

Example: with pty

if _, err := process.Command("printf", "hi").
	WithPTY().
	OnStdout(func(line string) { fmt.Println(line) }).
	Run(); err != nil {
	return err
}
// Output:
// hi

func (*Cmd) WithProcessTree added in v0.2.0

func (c *Cmd) WithProcessTree() *Cmd

WithProcessTree includes descendants when canceling or terminating a command. It owns a process group on Linux and macOS and a job object on Windows. Surviving members are terminated when the direct child exits. Unix children that create another group or session leave this scope. Unsupported platforms return an error before starting the command. The option applies to every stage in a pipeline and preserves the default behavior of other commands. @group OS Controls

Example: own descendant processes

result, err := process.Command("go", "version").WithProcessTree().Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (*Cmd) WithTimeout

func (c *Cmd) WithTimeout(d time.Duration) *Cmd

WithTimeout binds the command to a timeout. Replacing a timeout retains the context previously supplied through WithContext as its parent. @group Context

Example: with timeout

res, err := process.Command("go", "env", "GOOS").WithTimeout(2 * time.Second).Run()
if err != nil {
	return err
}
fmt.Println(res.ExitCode == 0)
// Output:
// true

type DecodeChain

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

DecodeChain configures typed decoding for a command.

func (*DecodeChain) As

func (d *DecodeChain) As[T any]() (T, error)

As executes the command and decodes its selected output into T. @group Decoding

Example: decode as a value

type Product struct {
	Name string `json:"name"`
}
product, err := process.Command("printf", `{"name":"Coffee"}`).DecodeJSON().As[Product]()
if err != nil {
	return err
}
fmt.Println(product.Name)
// Output:
// Coffee

func (*DecodeChain) FromCombined

func (d *DecodeChain) FromCombined() *DecodeChain

FromCombined decodes from combined stdout+stderr. @group Decoding

Example: decode combined

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}'`).
	DecodeJSON().
	FromCombined().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*DecodeChain) FromStderr

func (d *DecodeChain) FromStderr() *DecodeChain

FromStderr decodes from stderr. @group Decoding

Example: decode from stderr

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("sh", "-c", `printf '{"name":"gopher"}' 1>&2`).
	DecodeJSON().
	FromStderr().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*DecodeChain) FromStdout

func (d *DecodeChain) FromStdout() *DecodeChain

FromStdout decodes from stdout (default). @group Decoding

Example: decode from stdout

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	FromStdout().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*DecodeChain) Into

func (d *DecodeChain) Into(dst any) error

Into executes the command and decodes into dst. @group Decoding

Example: decode into

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", `{"name":"gopher"}`).
	DecodeJSON().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

func (*DecodeChain) Trim

func (d *DecodeChain) Trim() *DecodeChain

Trim trims whitespace before decoding. @group Decoding

Example: decode trim

type payload struct {
	Name string `json:"name"`
}
var out payload
if err := process.Command("printf", "  {\"name\":\"gopher\"}  ").
	DecodeJSON().
	Trim().
	Into(&out); err != nil {
	return err
}
fmt.Println(out.Name)
// Output:
// gopher

type Decoder

type Decoder interface {
	// Decode parses data into dst.
	Decode(data []byte, dst any) error
}

Decoder decodes serialized data into a destination value.

type DecoderFunc

type DecoderFunc func(data []byte, dst any) error

DecoderFunc adapts a function to a Decoder.

func (DecoderFunc) Decode

func (f DecoderFunc) Decode(data []byte, dst any) error

Decode implements Decoder. @group Decoding

Example: call a decoder

decoder := process.DecoderFunc(json.Unmarshal)
var product struct {
	Name string `json:"name"`
}
if err := decoder.Decode([]byte(`{"name":"Coffee"}`), &product); err != nil {
	return err
}
fmt.Println(product.Name)
// Output:
// Coffee

type ErrExec

type ErrExec struct {
	// Err contains the underlying start or I/O failure.
	Err error
	// ExitCode contains the child status when a process reached execution.
	ExitCode int
	// Signal contains the terminating signal on platforms that expose one.
	Signal os.Signal
	// Stderr contains captured diagnostic output available when the failure occurred.
	Stderr string
}

ErrExec reports a failure to start or an explicit execution failure.

func (ErrExec) Error

func (e ErrExec) Error() string

Error returns the wrapped error message when available. @group Errors

Example: error string

err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Error())
// Output:
// boom

func (ErrExec) Unwrap

func (e ErrExec) Unwrap() error

Unwrap exposes the underlying error. @group Errors

Example: unwrap

err := process.ErrExec{Err: fmt.Errorf("boom")}
fmt.Println(err.Unwrap() != nil)
// Output:
// true

type Executor added in v0.2.0

type Executor interface {
	// Run executes an explicit program and returns its collected result.
	Run(context.Context, string, ...string) (Result, error)
}

Executor runs a command with explicit arguments. Applications can accept this interface to use a Runner in production and a scoped fake in tests.

type ExitError added in v0.2.0

type ExitError struct {
	// Result contains the child outcome before checked-exit conversion.
	Result Result
}

ExitError reports a nonzero child status requested through CheckExit or EnsureSuccessful. Result retains captured output and the original exit status.

func (*ExitError) Error added in v0.2.0

func (e *ExitError) Error() string

Error reports the exit status without including potentially sensitive output. @group Errors

Example: describe an exit status

err := process.ExitError{Result: process.Result{ExitCode: 7}}
fmt.Println(err.Error())
// Output:
// process: command exited with status 7

type Process

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

Process represents an asynchronously running command. Its process-control and Wait methods may be called from separate goroutines.

func (*Process) Done

func (p *Process) Done() <-chan struct{}

Done returns a channel that closes after all pipeline stages exit and their output is collected. Wait can then retrieve the immutable result without blocking. @group Process

Example: wait for completion

proc := process.Command("go", "env", "GOOS").Start()
<-proc.Done()
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (*Process) GracefulShutdown

func (p *Process) GracefulShutdown(sig os.Signal, timeout time.Duration) error

GracefulShutdown sends a signal and escalates to kill after the timeout. @group Process

Example: graceful shutdown

proc := process.Command("sleep", "10").Start()
if err := proc.GracefulShutdown(os.Interrupt, time.Second); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

func (*Process) Interrupt

func (p *Process) Interrupt() error

Interrupt sends an interrupt signal to the process. @group Process

Example: interrupt

proc := process.Command("sleep", "10").Start()
if err := proc.Interrupt(); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

func (*Process) KillAfter

func (p *Process) KillAfter(d time.Duration)

KillAfter terminates the process after the given duration. @group Process

Example: kill after

proc := process.Command("sleep", "10").Start()
proc.KillAfter(100 * time.Millisecond)
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

func (*Process) PID

func (p *Process) PID() int

PID returns the first pipeline stage's assigned process ID, or zero if no stage started. The ID remains available after completion and can be reused by the OS. @group Process

Example: inspect a process ID

proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(proc.PID() > 0)
// Output:
// true

func (*Process) PIDs

func (p *Process) PIDs() []int

PIDs returns an independent slice of assigned process IDs in pipeline order. IDs describe started stages, including stages that have already exited. @group Process

Example: inspect pipeline IDs

proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(len(proc.PIDs()))
// Output:
// 1

func (*Process) Running

func (p *Process) Running() bool

Running reports whether a started pipeline is still collecting its result. It returns false for an unstarted handle and after Done closes. @group Process

Example: inspect completion

proc := process.Command("go", "env", "GOOS").Start()
if _, err := proc.Wait(); err != nil {
	return err
}
fmt.Println(proc.Running())
// Output:
// false

func (*Process) Send

func (p *Process) Send(sig os.Signal) error

Send sends a signal to the process. @group Process

Example: send signal

proc := process.Command("sleep", "10").Start()
if err := proc.Send(os.Interrupt); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

func (*Process) Terminate

func (p *Process) Terminate() error

Terminate kills the process immediately. @group Process

Example: terminate

proc := process.Command("sleep", "10").Start()
if err := proc.Terminate(); err != nil {
	return err
}
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.ExitCode != 0)
// Output:
// true

func (*Process) Wait

func (p *Process) Wait() (Result, error)

Wait waits for the command to complete and returns the result and any error. @group Process

Example: wait

proc := process.Command("go", "version").Start()
result, err := proc.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

type Result

type Result struct {
	// Stdout contains output captured from the selected command or pipeline stage.
	Stdout string
	// Stderr contains error output captured separately from stdout.
	Stderr string
	// ExitCode contains the process exit status, or -1 when no process state exists.
	ExitCode int
	// Err mirrors the execution error returned by Run, Wait, or their variants.
	Err error
	// Duration measures elapsed time from pipeline construction through process completion.
	Duration time.Duration
	// contains filtered or unexported fields
}

Result captures the outcome of a command execution.

func (Result) EnsureSuccessful added in v0.2.0

func (r Result) EnsureSuccessful() error

EnsureSuccessful returns the execution error or an ExitError for a nonzero status. It returns nil for success and does not change the Result. @group Results

Example: check a result

result, err := process.Command("go", "version").Run()
if err != nil {
	return err
}
fmt.Println(result.EnsureSuccessful() == nil)
// Output:
// true

func (Result) IsExitCode

func (r Result) IsExitCode(code int) bool

IsExitCode reports whether the exit code matches. @group Results

Example: exit code

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.IsExitCode(0))
// Output:
// true

func (Result) IsSignal

func (r Result) IsSignal(sig os.Signal) bool

IsSignal reports whether the command terminated due to a signal. @group Results

Example: signal

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.IsSignal(os.Interrupt))
// Output:
// false

func (Result) OK

func (r Result) OK() bool

OK reports whether the command exited cleanly without errors. @group Results

Example: ok

res, err := process.Command("go", "env", "GOOS").Run()
if err != nil {
	return err
}
fmt.Println(res.OK())
// Output:
// true

type Runner added in v0.2.0

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

Runner holds reusable command settings. Its zero value is ready to use. Configuration methods return independent copies, so a Runner can be shared across goroutines. Borrowed writers must support concurrent calls when the Runner executes multiple commands concurrently.

func NewRunner added in v0.2.0

func NewRunner() Runner

NewRunner returns reusable settings without starting a process. @group Runner

Example: reusable runner

runner := process.NewRunner().Timeout(5 * time.Second).CheckExit()
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) CheckExit added in v0.2.0

func (r Runner) CheckExit() Runner

CheckExit returns a Runner that reports a nonzero child exit as an ExitError. The default keeps nonzero exits in Result.ExitCode without returning an error. @group Runner

Example: checkexit with a runner

_, err := process.NewRunner().CheckExit().Run(context.Background(), "sh", "-c", "exit 7")
var exit *process.ExitError
if !errors.As(err, &exit) {
	return err
}
fmt.Println(exit.Result.ExitCode)
// Output:
// 7

func (Runner) Dir added in v0.2.0

func (r Runner) Dir(path string) Runner

Dir returns a Runner using path as each child's working directory. @group Runner

Example: dir with a runner

result, err := process.NewRunner().Dir(os.TempDir()).Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) DisableBuffering added in v0.2.0

func (r Runner) DisableBuffering() Runner

DisableBuffering returns a Runner that streams output without retaining it. @group Runner

Example: disablebuffering with a runner

var output strings.Builder
result, err := process.NewRunner().Stdout(&output).DisableBuffering().
	Run(context.Background(), "printf", "ready")
if err != nil {
	return err
}
fmt.Println(output.String(), len(result.Stdout))
// Output:
// ready 0

func (Runner) Env added in v0.2.0

func (r Runner) Env(key, value string) Runner

Env returns a Runner with one environment override. An empty value sets an empty variable; use UnsetEnv to remove a variable from the child environment. @group Runner

Example: env with a runner

result, err := process.NewRunner().Env("MODE", "production").Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.Contains(result.Stdout, "MODE=production"))
// Output:
// true

func (Runner) IdleTimeout added in v0.2.0

func (r Runner) IdleTimeout(d time.Duration) Runner

IdleTimeout returns a Runner that cancels after d without stdout or stderr activity. Any nonempty output chunk resets the limit, even without a newline. A nonpositive duration disables this limit. @group Runner

Example: idletimeout with a runner

_, err := process.NewRunner().IdleTimeout(time.Second).Run(context.Background(), "sleep", "10")
var timeout *process.TimeoutError
fmt.Println(errors.As(err, &timeout) && timeout.Idle)
// Output:
// true

func (Runner) Input added in v0.2.0

func (r Runner) Input(input string) Runner

Input returns a Runner that supplies a fresh reader of input to each child. @group Runner

Example: input with a runner

result, err := process.NewRunner().Input("request").Run(context.Background(), "cat")
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// request

func (Runner) Run added in v0.2.0

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

Run executes a fresh command using these settings. Arguments are passed directly to the executable. A nil context is treated as context.Background. @group Runner

Example: run with shared settings

runner := process.NewRunner().Env("GOTOOLCHAIN", "local")
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) Start added in v0.2.0

func (r Runner) Start(ctx context.Context, name string, args ...string) (*Process, error)

Start starts a fresh command and reports startup failures immediately. The returned handle supports the existing Process lifecycle methods. Its Wait result follows this Runner's timeout and CheckExit policies. @group Runner

Example: start with a runner

child, err := process.NewRunner().Start(context.Background(), "go", "version")
if err != nil {
	return err
}
result, err := child.Wait()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) Stderr added in v0.2.0

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

Stderr returns a Runner that streams stderr to w as well as capturing it. The caller owns w. A nil writer disables streaming. @group Runner

Example: stderr with a runner

var output strings.Builder
result, err := process.NewRunner().Stderr(&output).Run(context.Background(), "sh", "-c", "printf warning >&2")
if err != nil {
	return err
}
fmt.Println(output.String(), result.Stderr)
// Output:
// warning warning

func (Runner) Stdout added in v0.2.0

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

Stdout returns a Runner that streams stdout to w as well as capturing it. The caller owns w. A nil writer disables streaming. @group Runner

Example: stdout with a runner

var output strings.Builder
result, err := process.NewRunner().Stdout(&output).Run(context.Background(), "printf", "ready")
if err != nil {
	return err
}
fmt.Println(output.String(), result.Stdout)
// Output:
// ready ready

func (Runner) Timeout added in v0.2.0

func (r Runner) Timeout(d time.Duration) Runner

Timeout returns a Runner with a total limit starting at each Run or Start call. A nonpositive duration disables this limit. The caller's context still applies. @group Runner

Example: timeout with a runner

result, err := process.NewRunner().Timeout(5*time.Second).Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) UnsetEnv added in v0.2.0

func (r Runner) UnsetEnv(key string) Runner

UnsetEnv returns a Runner that removes key from each child's environment. @group Runner

Example: unsetenv with a runner

result, err := process.NewRunner().Env("EXAMPLE_TOKEN", "test").UnsetEnv("EXAMPLE_TOKEN").
	Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.Contains(result.Stdout, "EXAMPLE_TOKEN="))
// Output:
// false

func (Runner) WaitDelay added in v0.2.0

func (r Runner) WaitDelay(d time.Duration) Runner

WaitDelay returns a Runner that bounds output-pipe draining after the child exits or its context is canceled. A nonpositive duration leaves draining unlimited. This does not interrupt a caller-owned writer blocked in Write. @group Runner

Example: waitdelay with a runner

result, err := process.NewRunner().Timeout(5*time.Second).WaitDelay(time.Second).
	Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) WithProcessTree added in v0.2.0

func (r Runner) WithProcessTree() Runner

WithProcessTree returns a Runner that includes descendants in cancellation and termination. The native ownership and platform limits match Cmd.WithProcessTree. @group Runner

Example: reuse descendant ownership

runner := process.NewRunner().WithProcessTree().Timeout(5 * time.Second)
result, err := runner.Run(context.Background(), "go", "version")
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func (Runner) WithoutInheritingEnv added in v0.2.0

func (r Runner) WithoutInheritingEnv() Runner

WithoutInheritingEnv returns a Runner that starts with an empty environment. Explicit Env settings are retained. Executable lookup still uses the parent's PATH, as with os/exec; use an absolute program path to control lookup. @group Runner

Example: withoutinheritingenv with a runner

result, err := process.NewRunner().WithoutInheritingEnv().Env("MODE", "test").
	Run(context.Background(), "env")
if err != nil {
	return err
}
fmt.Println(strings.TrimSpace(result.Stdout))
// Output:
// MODE=test

type ShadowEvent

type ShadowEvent struct {
	// Command contains the display command after masking.
	Command string
	// RawCommand contains the unmasked display command and may include secrets.
	RawCommand string
	// Phase distinguishes output before execution from output after completion.
	Phase ShadowPhase
	// Duration contains elapsed execution time for ShadowAfter events.
	Duration time.Duration
	// Async reports whether execution was started through Start.
	Async bool
}

ShadowEvent captures details for ShadowPrint formatting.

type ShadowOption

type ShadowOption func(*shadowConfig)

ShadowOption configures ShadowPrint behavior.

func WithFormatter

func WithFormatter(fn func(ShadowEvent) string) ShadowOption

WithFormatter sets a formatter for ShadowPrint output. @group Shadow Print

Example: shadow formatter

formatter := func(event process.ShadowEvent) string {
	return fmt.Sprintf("%s: %s", event.Phase, event.Command)
}
result, err := process.Command("printf", "hello").ShadowPrint(process.WithFormatter(formatter)).Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

func WithMask

func WithMask(fn func(string) string) ShadowOption

WithMask applies a masker to the shadow-printed command string. @group Shadow Print

Example: shadow mask

mask := func(command string) string { return strings.ReplaceAll(command, "secret", "***") }
result, err := process.Command("printf", "secret").ShadowPrint(process.WithMask(mask)).Run()
if err != nil {
	return err
}
fmt.Println(result.OK())
// Output:
// true

func WithPrefix

func WithPrefix(prefix string) ShadowOption

WithPrefix sets the shadow print prefix. @group Shadow Print

Example: shadow prefix

result, err := process.Command("printf", "hello").ShadowPrint(process.WithPrefix("build")).Run()
if err != nil {
	return err
}
fmt.Println(result.Stdout)
// Output:
// hello

type ShadowPhase

type ShadowPhase string

ShadowPhase describes whether the shadow print is before or after execution.

const (
	// ShadowBefore labels the pre-execution shadow print.
	ShadowBefore ShadowPhase = "before"
	// ShadowAfter labels the post-execution shadow print.
	ShadowAfter ShadowPhase = "after"
)

type TimeoutError added in v0.2.0

type TimeoutError struct {
	// Result contains output and the execution error observed at cancellation.
	Result Result
	// Idle distinguishes inactivity from a total deadline.
	Idle bool
}

TimeoutError reports a command canceled by a total or idle deadline. Result retains partial output and the original execution error.

func (*TimeoutError) Error added in v0.2.0

func (e *TimeoutError) Error() string

Error distinguishes inactivity from an elapsed total deadline. @group Errors

Example: describe a timeout

err := process.TimeoutError{Idle: true}
fmt.Println(err.Error())
// Output:
// process: idle timeout exceeded

func (*TimeoutError) Unwrap added in v0.2.0

func (e *TimeoutError) Unwrap() error

Unwrap makes timeouts recognizable through errors.Is with context.DeadlineExceeded. @group Errors

Example: inspect a timeout cause

err := process.TimeoutError{}
fmt.Println(errors.Is(err.Unwrap(), context.DeadlineExceeded))
// Output:
// true

Directories

Path Synopsis
Package processtest provides isolated command fakes for applications that accept process.Executor.
Package processtest provides isolated command fakes for applications that accept process.Executor.

Jump to

Keyboard shortcuts

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