process

package
v1.17.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type OnOutputFunc

type OnOutputFunc func(typ OutputType, line []byte)

OnOutputFunc is a callback function invoked when the process produces output. The typ(OutputType) parameter indicates whether the data came from stdout or stderr, and line contains the raw output bytes (typically a line of text).

type OnPipeOutputFunc added in v1.17.0

type OnPipeOutputFunc func(typ OutputType, line []byte, key string)

OnPipeOutputFunc is a callback function invoked when any command in the pipeline produces output. typ(OutputType) indicates whether the data came from stdout or stderr, line contains the raw output bytes, and key identifies which command in the pipeline produced the output.

type OnPoolOutputFunc added in v1.17.0

type OnPoolOutputFunc func(typ OutputType, line []byte, key string)

OnPoolOutputFunc is a callback function invoked when any process in the pool produces output. The typ(OutputType) parameter indicates whether the data came from stdout or stderr, line contains the raw output bytes, and key identifies which process in the pool produced the output.

type OutputType

type OutputType int

OutputType represents the type of output stream produced by a running process.

const (
	// OutputTypeStdout indicates output written to the standard output stream.
	OutputTypeStdout OutputType = iota

	// OutputTypeStderr indicates output written to the standard error stream.
	OutputTypeStderr
)

type Pipe added in v1.17.0

type Pipe interface {
	// Command creates a new command to be added to the pipeline.
	// The command's stdout will be connected to the stdin of the next command in the pipeline.
	// If only name is provided, and the name contains special characters (like spaces, &, |),
	// the name will be added a `/bin/sh -c` or `cmd /c` wrapper to ensure correct execution.
	// This feature provides a convenient way to run complex shell commands that don't need to add the wrapper manually.
	Command(name string, arg ...string) PipeCommand
}

Pipe defines an interface for adding commands to a pipeline.

type PipeCommand added in v1.17.0

type PipeCommand interface {
	// As assigns a unique string key to the command.
	// This key is used to identify the command in the output handler.
	As(key string) PipeCommand

	// WithSpinner enables a loading spinner in the terminal while the process is running.
	WithSpinner(message ...string) PipeCommand
}

PipeCommand defines an interface for configuring a command within a pipeline.

type Pipeline added in v1.17.0

type Pipeline interface {
	// DisableBuffering prevents capture of stdout/stderr into memory buffers.
	// When disabled, Result.Output and Result.ErrorOutput will be empty strings.
	DisableBuffering() Pipeline

	// Env adds or overrides environment variables for all steps.
	Env(vars map[string]string) Pipeline

	// Input sets the stdin source for the first step in the pipeline.
	Input(in io.Reader) Pipeline

	// Path sets the working directory for all steps.
	Path(path string) Pipeline

	// Pipe adds commands to the pipeline using the provided configurer function.
	// This method allows for fluent chaining of pipeline configuration methods.
	Pipe(configurer func(Pipe)) Pipeline

	// Quietly discards live stdout/stderr instead of mirroring to os.Stdout/err.
	Quietly() Pipeline

	// OnOutput registers a handler that receives line-delimited output produced
	// by each step while the pipeline runs.
	OnOutput(handler OnPipeOutputFunc) Pipeline

	// Run executes, waits for completion, and returns the final Result.
	Run() Result

	// Start starts execution asynchronously, returning a RunningPipe.
	Start() (RunningPipe, error)

	// Timeout sets a maximum duration for the entire pipeline execution.
	Timeout(timeout time.Duration) Pipeline

	// WithContext binds pipeline execution to the provided context.
	WithContext(ctx context.Context) Pipeline

	// WithSpinner enables a loading spinner in the terminal while the pipeline is running.
	WithSpinner(message ...string) Pipeline
}

Pipeline defines a builder-style API for constructing and running a sequence of commands connected via OS pipes. Implementations are mutable and should not be used concurrently. Each configuration method returns the same Pipeline instance to allow fluent chaining. The Run/Start methods spawn the processes according to the provided builder.

type Pool added in v1.17.0

type Pool interface {
	// If only name is provided, and the name contains special characters (like spaces, &, |),
	// the name will be added a `/bin/sh -c` or `cmd /c` wrapper to ensure correct execution.
	// This feature provides a convenient way to run complex shell commands that don't need to add the wrapper manually.
	Command(name string, arg ...string) PoolCommand
}

type PoolBuilder added in v1.17.0

type PoolBuilder interface {
	// Concurrency sets the maximum number of processes that can run simultaneously.
	// If n is zero or less, a default value (e.g., the number of tasks) will be used.
	Concurrency(n int) PoolBuilder

	// OnOutput sets a callback that is invoked for each line of output.
	// WARNING: This callback may be called concurrently from multiple goroutines.
	// Callers must ensure thread-safety when accessing shared state.
	OnOutput(handler OnPoolOutputFunc) PoolBuilder

	// Pool adds commands to the process pool using the provided configurer function.
	// This method allows for fluent chaining of pool configuration methods.
	Pool(configurer func(Pool)) PoolBuilder

	// Run starts the pool, waits for all processes to complete, and returns a
	// map of the results, keyed by the process keys.
	Run() (map[string]Result, error)

	// Start launches the pool asynchronously and returns a handle to the running
	// pool, allowing for interaction with the live processes.
	Start() (RunningPool, error)

	// Timeout sets a total time limit for the entire pool operation. If the
	// timeout is exceeded, all running processes will be terminated.
	Timeout(timeout time.Duration) PoolBuilder

	// WithContext binds the pool's lifecycle to the provided context. If the context
	// is canceled, all running processes will be terminated.
	WithContext(ctx context.Context) PoolBuilder

	// WithSpinner enables a loading spinner in the terminal while the pool is running.
	WithSpinner(message ...string) PoolBuilder
}

PoolBuilder defines the interface for configuring and launching a pool of concurrent processes.

type PoolCommand added in v1.17.0

type PoolCommand interface {
	// As assigns a unique string key to the process. This key is used
	// to identify the process in the final results map and in the output handler.
	As(key string) PoolCommand

	// DisableBuffering prevents this process's output from being buffered in memory.
	// This is a critical optimization for commands with large output volumes.
	// Note: The result for this process will have an empty output.
	DisableBuffering() PoolCommand

	// Env sets environment variables for this specific process.
	Env(vars map[string]string) PoolCommand

	// Input sets the stdin source for this specific process.
	Input(in io.Reader) PoolCommand

	// Path sets the working directory for this specific process.
	Path(path string) PoolCommand

	// Quietly suppresses all process output from this specific process,
	// preventing it from being captured or sent to the output handler.
	Quietly() PoolCommand

	// Timeout sets a maximum execution duration for this specific process,
	// overriding the pool's timeout if set.
	Timeout(timeout time.Duration) PoolCommand

	// WithContext binds the lifecycle of this specific process to the provided
	// context, overriding the pool's context if set.
	WithContext(ctx context.Context) PoolCommand
}

PoolCommand provides a builder interface for a single command within a pool. It must satisfy the Schedulable interface to be used by scheduling strategies.

type Process

type Process interface {
	// DisableBuffering prevents the process's stdout and stderr from being buffered
	// in memory. This is a critical optimization for commands that produce a large
	// volume of output, especially when that output is already being handled by
	// an OnOutput streaming callback.
	//
	// CONSEQUENCE: As output is not captured, the following methods on the
	// Running and Result handles will always return an empty string:
	//   - Running.Output()
	//   - Running.ErrorOutput()
	//   - Result.Output()
	//   - Result.ErrorOutput()
	DisableBuffering() Process

	// Env adds or overrides environment variables for the process.
	// Modifies the current process configuration.
	Env(vars map[string]string) Process

	// Input sets the stdin source for the process.
	// By default, processes run without stdin input.
	Input(in io.Reader) Process

	// Path sets the working directory where the process will be executed.
	Path(path string) Process

	// Pipe creates a pipeline of commands where the output of each command is connected to the input of the next command.
	// The configurer function is used to define the sequence of commands in the pipeline.
	//
	// Note: Process configurations (timeout, context, etc.) are NOT inherited by the pipeline.
	// You must configure these settings directly on the returned Pipeline instance.
	Pipe(configurer func(Pipe)) Pipeline

	// Pool creates a pool of concurrent processes that can be executed and managed together.
	// The configurer function is used to define the commands to be executed in the pool.
	//
	// Note: Process configurations (timeout, context, etc.) are NOT inherited by the pool.
	// You must configure these settings directly on the returned PoolBuilder instance.
	Pool(configurer func(Pool)) PoolBuilder

	// Quietly suppresses all process output, discarding both stdout and stderr.
	Quietly() Process

	// OnOutput registers a handler to receive stdout and stderr output
	// while the process runs. Multiple handlers may be chained depending
	// on the implementation.
	OnOutput(handler OnOutputFunc) Process

	// Run starts the process, waits for it to complete, and returns the result.
	// If only name is provided, and the name contains special characters (like spaces, &, |),
	// the name will be added a `/bin/sh -c` or `cmd /c` wrapper to ensure correct execution.
	// This feature provides a convenient way to run complex shell commands that don't need to add the wrapper manually.
	Run(name string, arg ...string) Result

	// Start begins running the process asynchronously and returns a Running
	// handle to monitor and control its execution. The caller must later
	// wait or terminate the process explicitly.
	Start(name string, arg ...string) (Running, error)

	// Timeout sets a maximum execution duration for the process.
	// If the timeout is exceeded, the process will be terminated.
	// A zero duration disables the timeout.
	Timeout(timeout time.Duration) Process

	// TTY runs the command in an interactive TTY mode.
	//
	// This is the method you need when you're running a command that asks for
	// input, requires a password, or shows a TUI menu (like `artisan make:controller`).
	// It essentially "borrows" your terminal and gives it to the subprocess.
	//
	// Be aware of two major side effects:
	//  1. Output is NOT captured. It goes straight to your terminal. The
	//     Result object won't contain any output from the command.
	//  2. The `.Input()` method is ignored. Your live keyboard becomes the
	//     command's standard input.
	TTY() Process

	// WithContext binds the process lifecycle to the provided context.
	// If the context is canceled or reaches its deadline, the process
	// will be terminated. When combined with Timeout, the earlier of
	// the two deadlines takes effect.
	WithContext(ctx context.Context) Process

	// WithSpinner enables a loading spinner in the terminal while the process is running.
	WithSpinner(message ...string) Process
}

Process defines an interface for configuring and running external processes.

Implementations are mutable and should not be reused concurrently. Each method modifies the same underlying process configuration.

type Result

type Result interface {
	// Command returns the full command string used to start the process,
	// including program name and arguments.
	Command() string

	// Error returns any error encountered during process execution (Go-related error).
	Error() error

	// ErrorOutput returns the full contents written to stderr by the process.
	ErrorOutput() string

	// ExitCode returns the process exit code. A zero value typically
	// indicates success, while non-zero indicates failure.
	ExitCode() int

	// Failed reports whether the process exited with a non-zero exit code.
	Failed() bool

	// Output returns the full contents written to stdout by the process.
	Output() string

	// SeeInErrorOutput reports whether the given substring is present
	// in the process stderr output.
	SeeInErrorOutput(needle string) bool

	// SeeInOutput reports whether the given substring is present
	// in the process stdout output.
	SeeInOutput(needle string) bool

	// Successful reports whether the process exited with a zero exit code.
	Successful() bool
}

Result represents the outcome of a finished process execution. It provides access to exit status, captured output, and helper methods for inspecting process behavior.

type Running

type Running interface {
	// Done returns a read-only channel that is closed once the process has exited.
	//
	// This provides an efficient, non-polling mechanism to wait for process completion,
	// typically in a select statement.
	//
	// After receiving a signal from this channel, the caller is still required to
	// call Wait() to retrieve the process's final Result and to release all
	// underlying system resources. Failure to do so will result in a resource leak.
	Done() <-chan struct{}

	// ErrorOutput returns the complete stderr captured from the process so far.
	//
	// WARNING: This method buffers the entire output in memory. For processes that
	// may generate a large volume of output, use the Process.OnOutput() callback during
	// configuration to stream the data instead.
	ErrorOutput() string

	// Output returns the complete stdout captured from the process so far.
	//
	// WARNING: This method buffers the entire output in memory. For processes that
	// may generate a large volume of output, use the Process.OnOutput() callback during
	// configuration to stream the data instead.
	Output() string

	// PID returns the operating system process ID.
	PID() int

	// Running reports whether the process still exists according to the OS.
	// NOTE: This may return true for a "zombie" process (one that has terminated
	// but has not been reaped). Wait() must be called to reap the process.
	Running() bool

	// Signal sends the given signal to the process.
	Signal(sig os.Signal) error

	// Stop attempts to gracefully stop the process by sending the provided signal
	// (defaulting to SIGTERM). If the process does not exit within the given
	// timeout, it is forcibly killed (SIGKILL).
	Stop(timeout time.Duration, sig ...os.Signal) error

	// Wait blocks until the process exits and returns its final Result.
	// This call is required to reap the process and release all system resources.
	Wait() Result
}

Running represents a handle to a single, active process. Its primary role is to manage the lifecycle and inspect the state of the process.

type RunningPipe added in v1.17.0

type RunningPipe interface {
	// PIDs returns a mapping of step keys to their process IDs. Keys are the
	// identifiers assigned to each step (via PipeCommand.As or default numeric index).
	PIDs() map[string]int
	// Running reports whether any process in the pipeline is still running.
	Running() bool
	// Done returns a channel that is closed when the pipeline finishes
	// (successfully or with failure). It is safe to use in select statements.
	Done() <-chan struct{}
	// Wait blocks until the pipeline completes and returns the aggregated
	// result of the last step.
	Wait() Result
	// Stop attempts to gracefully stop all processes. On Unix this typically
	// sends SIGTERM then SIGKILL after the timeout. On Windows, processes are
	// terminated immediately. Returns the first error encountered, if any.
	Stop(timeout time.Duration, sig ...os.Signal) error
	// Signal sends the provided signal to all running processes where supported
	// by the platform. On Windows, some signals may be a no-op.
	Signal(sig os.Signal) error
}

RunningPipe represents a running pipeline of OS commands connected together via pipes. It exposes methods to observe state (PIDs, Running, Done), wait for completion (Wait), and control execution (Stop, Signal). Implementations should be safe for read-only use from multiple goroutines.

type RunningPool added in v1.17.0

type RunningPool interface {
	// Done returns a channel that is closed when all pool processes have finished
	// and their results have been collected. This allows non-blocking checks or
	// select-based waits across multiple pools.
	Done() <-chan struct{}

	// PIDs returns a map of process IDs keyed by the command keys supplied during
	// pool configuration. If a process failed to start, its PID will be 0.
	PIDs() map[string]int

	// Running reports whether the pool is still executing. It uses a non-blocking
	// select on the Done channel to avoid races or blocking calls.
	Running() bool

	// Signal sends an OS signal to each running process in the pool. The first
	// error encountered is returned, though all processes are still signaled.
	// Processes that are nil or have already terminated are skipped silently.
	Signal(sig os.Signal) error

	// Stop attempts to gracefully terminate each process in the pool using the
	// specified timeout and optional signal(s). The first error encountered is
	// returned, but all processes receive the stop request. If a process does
	// not exit within the timeout, it may be forcefully killed depending on the
	// platform implementation.
	Stop(timeout time.Duration, sig ...os.Signal) error

	// Wait blocks until the Done channel is closed and returns the final results
	// map, keyed by the command keys provided during pool configuration.
	Wait() map[string]Result
}

RunningPool is a handle to a collection of concurrently running processes spawned by PoolBuilder. It provides process introspection (PIDs, Running status), coordinated lifecycle controls (Signal, Stop), and a completion mechanism (Done, Wait).

Jump to

Keyboard shortcuts

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