cmd

package
v2.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package cmd defines types and functions for running commands.

Index

Constants

View Source
const DefaultRedactMask = "[REDACTED]"

DefaultRedactMask is the string that will be used to replace redacted text in the logs.

Variables

View Source
var (
	// ErrInvalidCommand is returned when a command is somehow invalid.
	ErrInvalidCommand = errors.New("invalid command")

	// ErrWroteStderr is returned when a windows command writes to stderr, unless AllowWinStderr is set.
	ErrWroteStderr = errors.New("command wrote output to stderr")
)
View Source
var DisableRedact = false

DisableRedact will disable all redaction of sensitive data.

Functions

This section is empty.

Types

type ContextRunner

type ContextRunner interface {
	fmt.Stringer
	WindowsChecker
	ExecContext(ctx context.Context, command string, opts ...ExecOption) error
	ExecOutputContext(ctx context.Context, command string, opts ...ExecOption) (string, error)
	ExecReaderContext(ctx context.Context, command string, opts ...ExecOption) io.Reader
	Start(ctx context.Context, command string, opts ...ExecOption) (protocol.Waiter, error)
}

ContextRunner is a command runner that can run commands with a context.

type DecorateFunc

type DecorateFunc func(string) string

DecorateFunc is a function that takes a string and returns a decorated string.

type ErrorExecutor

type ErrorExecutor struct {
	Err error
}

ErrorExecutor is an executor that always returns the given error. It implements the Runner interface.

This is used to make some of the accessors easier to use without having to check for the second return value. Instead of a, err := c.Foo(), you can use c.Foo().DoSomething() and it will return the error from Foo() when DoSomething() is called.

func NewErrorExecutor

func NewErrorExecutor(err error) *ErrorExecutor

NewErrorExecutor returns a new ErrorExecutor with the given error.

func (*ErrorExecutor) Exec

func (r *ErrorExecutor) Exec(_ string, _ ...ExecOption) error

Exec returns the given error.

func (*ErrorExecutor) ExecContext

func (r *ErrorExecutor) ExecContext(_ context.Context, _ string, _ ...ExecOption) error

ExecContext returns the given error.

func (*ErrorExecutor) ExecOutput

func (r *ErrorExecutor) ExecOutput(_ string, _ ...ExecOption) (string, error)

ExecOutput returns the given error and an empty string.

func (*ErrorExecutor) ExecOutputContext

func (r *ErrorExecutor) ExecOutputContext(_ context.Context, _ string, _ ...ExecOption) (string, error)

ExecOutputContext returns the given error and an empty string.

func (*ErrorExecutor) ExecReader

func (r *ErrorExecutor) ExecReader(command string, opts ...ExecOption) io.Reader

ExecReader returns a pipereader where the writer end is closed with the given error.

func (*ErrorExecutor) ExecReaderContext

func (r *ErrorExecutor) ExecReaderContext(_ context.Context, _ string, _ ...ExecOption) io.Reader

ExecReaderContext returns a pipereader where the writer end is closed with the given error.

func (*ErrorExecutor) ExecScanner

func (r *ErrorExecutor) ExecScanner(command string, opts ...ExecOption) *bufio.Scanner

ExecScanner returns a scanner that reads from a pipereader where the writer end is closed with the given error.

func (*ErrorExecutor) ExecScannerContext

func (r *ErrorExecutor) ExecScannerContext(ctx context.Context, command string, opts ...ExecOption) *bufio.Scanner

ExecScannerContext returns a scanner that reads from a pipereader where the writer end is closed with the given error.

func (*ErrorExecutor) Explain

func (r *ErrorExecutor) Explain(command string, opts ...ExecOption) Explanation

Explain returns an Explanation with per-call decorators applied. ErrorExecutor has no global decorators and no connection, so OS-specific wrapping is not applied.

func (*ErrorExecutor) Format

func (r *ErrorExecutor) Format(cmd string) string

Format returns the command string as is.

func (*ErrorExecutor) IsWindows

func (r *ErrorExecutor) IsWindows() bool

IsWindows returns false.

func (*ErrorExecutor) Proc

func (r *ErrorExecutor) Proc(cmd string) *Proc

Proc returns a Proc bound to this executor for the given command.

func (*ErrorExecutor) Start

Start returns the given error.

func (*ErrorExecutor) StartBackground

func (r *ErrorExecutor) StartBackground(_ string, _ ...ExecOption) (protocol.Waiter, error)

StartBackground returns the given error.

func (*ErrorExecutor) StartProcess

func (r *ErrorExecutor) StartProcess(_ context.Context, _ string, _ io.Reader, _ io.Writer, _ io.Writer) (protocol.Waiter, error)

StartProcess returns the given error.

func (*ErrorExecutor) String

func (r *ErrorExecutor) String() string

String returns "error-executor".

type ExecOption

type ExecOption func(*ExecOptions)

ExecOption is a functional option for the exec package.

func AllowWinStderr

func AllowWinStderr() ExecOption

AllowWinStderr exec option allows command to output to stderr without failing.

func Decorate

func Decorate(decorator DecorateFunc) ExecOption

Decorate exec option for applying a custom decorator to the command string.

func HideCommand

func HideCommand() ExecOption

HideCommand exec option for hiding the command-string and stdin contents from the logs.

func HideOutput

func HideOutput() ExecOption

HideOutput exec option for hiding the command output from logs.

func LogError

func LogError(v bool) ExecOption

LogError exec option for enabling or disabling live error logging during exec.

func LogInput

func LogInput(v bool) ExecOption

LogInput exec option for enabling or disabling live input logging during exec.

func Logger

func Logger(l log.Logger) ExecOption

Logger exec option for setting a custom logger.

func PS

func PS() ExecOption

PS exec option for using powershell to execute the command on windows.

func PSCompressed

func PSCompressed() ExecOption

PSCompressed is like PS but for long command scriptlets. The script will be gzipped and base64 encoded and includes a small decompression script at the beginning of the command. This can allow running longer scripts than the 8191 characters that powershell.exe allows.

func Redact

func Redact(match string) ExecOption

Redact exec option for defining a redact regexp pattern that will be replaced with [REDACTED] in the logs.

func Sensitive

func Sensitive() ExecOption

Sensitive exec option for disabling all logging of the command.

func Stderr

func Stderr(w io.Writer) ExecOption

Stderr exec option for sending command stderr to an io.Writer.

func Stdin

func Stdin(r io.Reader) ExecOption

Stdin exec option for sending data to the command through stdin.

func StdinString

func StdinString(s string) ExecOption

StdinString exec option for sending string data to the command through stdin.

func Stdout

func Stdout(w io.Writer) ExecOption

Stdout exec option for sending command stdout to an io.Writer.

func StreamOutput

func StreamOutput() ExecOption

StreamOutput exec option for sending the command output to info log.

func Trace

func Trace(t Tracer) ExecOption

Trace exec option for attaching a Tracer to a single command execution. If the Tracer also implements OutputTracer, per-line stdout and stderr hooks are enabled automatically.

func TrimOutput

func TrimOutput(v bool) ExecOption

TrimOutput exec option for controlling if the output of the command will be trimmed of whitespace.

type ExecOptions

type ExecOptions struct {
	log.LoggerInjectable
	// contains filtered or unexported fields
}

ExecOptions is a collection of exec options.

func Build

func Build(opts ...ExecOption) *ExecOptions

Build returns an instance of Options.

func (*ExecOptions) AllowWinStderr

func (o *ExecOptions) AllowWinStderr() bool

AllowWinStderr returns the allowWinStderr option.

func (*ExecOptions) Apply

func (o *ExecOptions) Apply(opts ...ExecOption)

Apply the supplied options to the Options.

func (*ExecOptions) ErrString

func (o *ExecOptions) ErrString() string

ErrString returns the contents of stderr after exec.

func (*ExecOptions) Format

func (o *ExecOptions) Format(cmd string) string

Format returns the command string with all per-call decorators applied.

func (*ExecOptions) FormatOutput

func (o *ExecOptions) FormatOutput(s string) string

FormatOutput is for trimming whitespace from the command output if TrimOutput is enabled.

func (*ExecOptions) LogCommand

func (o *ExecOptions) LogCommand() bool

LogCommand returns true if the command should be logged, false if not.

func (*ExecOptions) OutputClosers

func (o *ExecOptions) OutputClosers() []io.Closer

OutputClosers returns a copy of the WriteClosers created by this ExecOptions that must be closed after the process finishes to release their resources.

func (*ExecOptions) Redact

func (o *ExecOptions) Redact(s string) string

Redact returns a redacted version of the given string.

func (*ExecOptions) RedactReader

func (o *ExecOptions) RedactReader(r io.Reader) io.Reader

RedactReader returns a reader that will redact sensitive content from the input.

func (*ExecOptions) RedactString

func (o *ExecOptions) RedactString(s string) string

RedactString filters out sensitive content from strings.

func (*ExecOptions) RedactWriter

func (o *ExecOptions) RedactWriter(w io.Writer) io.Writer

RedactWriter returns a writer that will redact sensitive content from the output.

func (*ExecOptions) Redacter

func (o *ExecOptions) Redacter() redact.Redacter

Redacter returns a redact.Rredacter prepared with the redact mask and string matchers set via the options.

func (*ExecOptions) Stderr

func (o *ExecOptions) Stderr() io.Writer

Stderr returns the Stderr writer. If error logging is enabled, it will be a MultiWriter that writes to the log.

func (*ExecOptions) Stdin

func (o *ExecOptions) Stdin() io.Reader

Stdin returns the Stdin reader. If input logging is enabled, it will be a TeeReader that writes to the log.

func (*ExecOptions) Stdout

func (o *ExecOptions) Stdout() io.Writer

Stdout returns the Stdout writer. If output logging is enabled, it will be a MultiWriter that writes to the log.

type Executor

type Executor struct {
	log.LoggerInjectable
	// contains filtered or unexported fields
}

Executor is an Runner that runs commands on a host.

func NewExecutor

func NewExecutor(conn protocol.ProcessStarter, decorators ...DecorateFunc) *Executor

NewExecutor returns a new Executor.

func (*Executor) Exec

func (r *Executor) Exec(command string, opts ...ExecOption) error

Exec executes the command and returns an error if unsuccessful.

func (*Executor) ExecContext

func (r *Executor) ExecContext(ctx context.Context, command string, opts ...ExecOption) error

ExecContext executes the command and returns an error if unsuccessful.

func (*Executor) ExecOutput

func (r *Executor) ExecOutput(command string, opts ...ExecOption) (string, error)

ExecOutput executes the command and returns the stdout output or an error.

func (*Executor) ExecOutputContext

func (r *Executor) ExecOutputContext(ctx context.Context, command string, opts ...ExecOption) (string, error)

ExecOutputContext executes the command and returns the stdout output or an error.

func (*Executor) ExecReader

func (r *Executor) ExecReader(command string, opts ...ExecOption) io.Reader

ExecReader executes the command and returns a reader for the stdout output. Reads from the Reader will return any error that occurred during the command's execution.

func (*Executor) ExecReaderContext

func (r *Executor) ExecReaderContext(ctx context.Context, command string, opts ...ExecOption) io.Reader

ExecReaderContext executes the command and returns a reader for the stdout output. Reads from the reader will return any error that occurred during the command's execution.

func (*Executor) ExecScanner

func (r *Executor) ExecScanner(command string, opts ...ExecOption) *bufio.Scanner

ExecScanner executes the command and returns a bufio.Scanner for the stdout output. Reads from the scanner will return any error that occurred during the command's execution.

func (*Executor) ExecScannerContext

func (r *Executor) ExecScannerContext(ctx context.Context, command string, opts ...ExecOption) *bufio.Scanner

ExecScannerContext executes the command and returns a bufio.Scanner for the stdout output. Reads from the scanner will return any error that occurred during the command's execution.

func (*Executor) Explain

func (r *Executor) Explain(command string, opts ...ExecOption) Explanation

Explain returns the formatted command without running it. Use this to inspect the effect of decorators, sudo wrapping, PowerShell encoding, and redaction without executing anything. Explain never probes the host to determine OS-specific wrapping; wrapping is included only when the OS has already been determined (see OSWrappingKnown in the returned Explanation).

func (*Executor) Format

func (r *Executor) Format(cmd string) string

Format returns the command string decorated with the runner's global decorators.

func (*Executor) IsWindows

func (r *Executor) IsWindows() bool

IsWindows returns true if the host is running Windows.

func (*Executor) Proc

func (r *Executor) Proc(cmd string) *Proc

Proc returns a Proc bound to this runner for the given command. Set Stdin, Stdout, Stderr on the returned Proc before calling Start or Run.

func (*Executor) SetTracer

func (r *Executor) SetTracer(t Tracer)

SetTracer attaches a runner-wide Tracer. It fires for every command unless overridden per-call via the Trace option. SetTracer must not be called concurrently with Start, Exec, or any other command-execution method.

func (*Executor) Start

func (r *Executor) Start(ctx context.Context, command string, opts ...ExecOption) (protocol.Waiter, error)

Start starts the command and returns a Waiter.

func (*Executor) StartBackground

func (r *Executor) StartBackground(command string, opts ...ExecOption) (protocol.Waiter, error)

StartBackground starts the command and returns a Waiter.

func (*Executor) StartProcess

func (r *Executor) StartProcess(ctx context.Context, command string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (protocol.Waiter, error)

StartProcess calls the connection's StartProcess method. This is done to satisfy the connection interface and thus allow chaining of runners.

func (*Executor) String

func (r *Executor) String() string

String returns the client's string representation.

type Explanation

type Explanation struct {
	// Formatted is the command string after all global and per-call
	// decorators, sudo wrapping, and any OS-specific prefixes that can be
	// determined without probing the connection (e.g. "cmd.exe /C"). When
	// OSWrappingKnown is false, OS-specific prefixes are omitted.
	Formatted string
	// Decoded is the human-readable form of Formatted. PowerShell
	// EncodedCommand payloads are decoded so you can read the actual script.
	Decoded string
	// Logged is the command as it appears in debug log lines: Decoded with
	// any strings registered via [Redact] replaced by the redact mask. It is
	// empty when command logging is disabled.
	Logged string
	// CommandLogged reports whether Logged would be emitted by command logging.
	CommandLogged bool
	// OSWrappingKnown reports whether Formatted could include OS-specific
	// command wrapping without probing the connection.
	OSWrappingKnown bool
}

Explanation holds the formatted representations of a command as it would appear at each stage of the execution pipeline.

type Formatter

type Formatter interface {
	Format(cmd string) string
}

Formatter is an interface that can format commands by applying decorators.

type OutputTracer

type OutputTracer interface {
	Tracer
	// StdoutLine fires for each line written to stdout. The line does not
	// include a trailing newline character.
	StdoutLine(host, line string)
	// StderrLine fires for each line written to stderr. The line does not
	// include a trailing newline character.
	StderrLine(host, line string)
}

OutputTracer extends Tracer with per-line stdout and stderr hooks. Implement this alongside Tracer to receive output as individual lines. Each line is delivered without the trailing newline. A partial final line (not terminated by a newline) is flushed when the process exits.

Concurrency: StdoutLine and StderrLine may be called concurrently with each other and with [Tracer.ProcessFinished]. Implementations must be safe for concurrent use.

type Proc

type Proc struct {
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

Proc is a command bound to a runner. Set Stdin, Stdout, and Stderr as needed, then call Start or Run. Modeled after os/exec.Cmd.

func (*Proc) Run

func (p *Proc) Run(ctx context.Context, opts ...ExecOption) error

Run starts the command and waits for it to complete.

func (*Proc) Start

func (p *Proc) Start(ctx context.Context, opts ...ExecOption) (protocol.Waiter, error)

Start starts the command and returns a Waiter.

type Runner

type Runner interface {
	Formatter
	WindowsChecker
	SimpleRunner
	ContextRunner
	Proc(cmd string) *Proc
	// Explain returns an [Explanation] describing how the command would be processed,
	// without actually running it. The Explanation includes the fully decorated
	// command string (Formatted), the decoded/human-readable form (Decoded), the
	// redacted version that would appear in logs (Logged), and whether the OS
	// wrapping decision was known (OSWrappingKnown). Use this to inspect the effect of
	// decorators, sudo wrapping, PowerShell encoding, and redaction.
	Explain(cmd string, opts ...ExecOption) Explanation
	// ProcessStarter is included to allow runners to accept another runner as their connection for chaining.
	protocol.ProcessStarter
}

Runner is a full featured command runner for clients.

type SimpleRunner

type SimpleRunner interface {
	fmt.Stringer
	WindowsChecker
	Exec(command string, opts ...ExecOption) error
	ExecOutput(command string, opts ...ExecOption) (string, error)
	ExecReader(command string, opts ...ExecOption) io.Reader
	ExecScanner(command string, opts ...ExecOption) *bufio.Scanner
	StartBackground(command string, opts ...ExecOption) (protocol.Waiter, error)
}

SimpleRunner is a command runner that can run commands without a context.

type Tracer

type Tracer interface {
	// CommandFormatted fires just before a process is started, with the final
	// command string after all decorators and OS-specific wrapping.
	CommandFormatted(host, formatted string)
	// ProcessStarted fires after the underlying process starts successfully.
	ProcessStarted(host, formatted string)
	// ProcessFinished fires after the process exits.
	// duration is the wall-clock time since ProcessStarted. err is nil on success.
	ProcessFinished(host, formatted string, duration time.Duration, err error)
}

Tracer observes command lifecycle events on an Executor. Register a Tracer via Trace (per-call) or Executor.SetTracer (runner-wide).

type WindowsChecker

type WindowsChecker interface {
	IsWindows() bool
}

WindowsChecker is implemented by types that can check if the underlying host OS is Windows.

Jump to

Keyboard shortcuts

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