shell

package
v3.87.1 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2024 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package shell provides a cross-platform virtual shell abstraction for executing commands.

It is intended for internal use by buildkite-agent only.

Index

Constants

This section is empty.

Variables

View Source
var DiscardLogger = &WriterLogger{
	Writer: io.Discard,
}

DiscardLogger discards all log messages

View Source
var ErrShellNotStarted = errors.New("shell not started")

ErrShellNotStarted is returned when the shell has not started a process.

View Source
var StderrLogger = &WriterLogger{
	Writer: os.Stderr,
	Ansi:   true,
}

StderrLogger is a Logger that writes to Stderr

Functions

func BatchEscape

func BatchEscape(str string) string

BatchEscape escapes a string for use with an `ECHO` statement in a Windows Batch file. http://www.robvanderwoude.com/escapechars.php

func ExitCode

func ExitCode(err error) int

ExitCode extracts an exit code from an error where the platform supports it, otherwise returns 0 for no error and 1 for an error

func IsExitError

func IsExitError(err error) bool

IsExitError reports whether err is an ExitError or exec.ExitError.

func IsExitSignaled

func IsExitSignaled(err error) bool

IsExitSignaled returns true if the error is an ExitError that was caused by receiving a signal.

func LookPath

func LookPath(file string, path string, fileExtensions string) (string, error)

LookPath searches for an executable binary named file in the directories within the path variable, which is a colon delimited path. If file contains a slash, it is tried directly

Types

type Command

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

Command represents a command that can be run in a shell.

func (Command) Run

func (c Command) Run(ctx context.Context, opts ...RunCommandOpt) error

Run runs the command and waits for it to complete.

func (Command) RunAndCaptureStdout

func (c Command) RunAndCaptureStdout(ctx context.Context, opts ...RunCommandOpt) (string, error)

RunAndCaptureStdout is Run, but automatically sets options: * ShowPrompt(false) (overridable) * CaptureStdout() (not overridable) and returns the captured output.

type ExitError

type ExitError struct {
	Code int
	Err  error
}

ExitError is an error that carries a shell exit code

func (*ExitError) Error

func (ee *ExitError) Error() string

func (*ExitError) Unwrap

func (ee *ExitError) Unwrap() error

type Logger

type Logger interface {
	io.Writer

	// Printf prints a line of output
	Printf(format string, v ...any)

	// Headerf prints a Buildkite formatted header
	Headerf(format string, v ...any)

	// Commentf prints a comment line, e.g `# my comment goes here`
	Commentf(format string, v ...any)

	// Errorf shows a Buildkite formatted error expands the previous group
	Errorf(format string, v ...any)

	// Warningf shows a buildkite bootstrap warning
	Warningf(format string, v ...any)

	// OptionalWarningf shows a warning, but only if it hasn't been explicitly disabled by the user
	OptionalWarningf(id, format string, v ...any)

	// Promptf prints a shell prompt
	Promptf(format string, v ...any)
}

Logger represents a logger that outputs to a buildkite shell.

type LoggerStreamer

type LoggerStreamer struct {
	Logger Logger
	Prefix string
	// contains filtered or unexported fields
}

func NewLoggerStreamer

func NewLoggerStreamer(logger Logger) *LoggerStreamer

func (*LoggerStreamer) Close

func (l *LoggerStreamer) Close() error

func (*LoggerStreamer) Output

func (l *LoggerStreamer) Output() error

func (*LoggerStreamer) Write

func (l *LoggerStreamer) Write(p []byte) (n int, err error)

type NewShellOpt

type NewShellOpt = func(*Shell)

func WithCommandLog

func WithCommandLog(log *[][]string) NewShellOpt

func WithDebug

func WithDebug(d bool) NewShellOpt

func WithDryRun

func WithDryRun(d bool) NewShellOpt

func WithEnv

func WithEnv(e *env.Environment) NewShellOpt

func WithInterruptSignal

func WithInterruptSignal(sig process.Signal) NewShellOpt

func WithLogger

func WithLogger(l Logger) NewShellOpt

func WithPTY

func WithPTY(pty bool) NewShellOpt

func WithSignalGracePeriod

func WithSignalGracePeriod(d time.Duration) NewShellOpt

func WithStdout

func WithStdout(w io.Writer) NewShellOpt

func WithTraceContextCodec

func WithTraceContextCodec(c tracetools.Codec) NewShellOpt

func WithWD

func WithWD(wd string) NewShellOpt

type RunCommandOpt

type RunCommandOpt = func(*runConfig)

RunCommandOpt is the type of functional options that can be passed to Command.Run.

func CaptureStdout

func CaptureStdout(s *string) RunCommandOpt

CaptureStdout captures the entire stdout stream to a string instead of the shell's stdout. By default, it is not captured. The string pointer is updated with the stdout of the process after it has exited.

func ShowPrompt

func ShowPrompt(show bool) RunCommandOpt

ShowPrompt causes the command and arguments being run to be printed in the shell's stdout. By default this is enabled (prompt is shown).

func ShowStderr

func ShowStderr(show bool) RunCommandOpt

ShowStderr can be used to hide stderr from the shell's stdout. By default, it is enabled (the process stderr is directed to the shell's stdout).

func WithExtraEnv

func WithExtraEnv(e *env.Environment) RunCommandOpt

WithExtraEnv can be used to set additional env vars for this run.

func WithStringSearch

func WithStringSearch(m map[string]bool) RunCommandOpt

WithStringSearch causes both the stdout and stderr streams of the process to be searched for strings. (This does not require capturing either stream in full.) After the process is finished, the map can be inspected to see which ones were observed.

type Shell

type Shell struct {
	Logger

	// The running environment for the shell.
	Env *env.Environment
	// contains filtered or unexported fields
}

Shell represents a virtual shell, handles logging, executing commands and provides hooks for capturing output and exit conditions.

Provides a lowest-common denominator abstraction over macOS, Linux and Windows

func New

func New(opts ...NewShellOpt) (*Shell, error)

New returns a new Shell. The default stdout is os.Stdout, the default logger writes to os.Stderr, the initial working directory is the result of calling os.Getwd, the default environment variable set is read from os.Environ, and the default trace context encoding is Gob.

func NewTestShell

func NewTestShell(t *testing.T, opts ...NewShellOpt) *Shell

NewTestShell creates a shell with suitable defaults for tests. Note that it still really for real executes commands, unless WithDryRun(true) is passed. By default is set up with minimal env vars, and throws away stdout (unless DEBUG_SHELL is set or WithStdout is passed).

func (*Shell) AbsolutePath

func (s *Shell) AbsolutePath(executable string) (string, error)

AbsolutePath returns the absolute path to an executable based on the PATH and PATHEXT of the Shell

func (*Shell) Chdir

func (s *Shell) Chdir(path string) error

Chdir changes the working directory of the shell

func (*Shell) CloneWithStdin

func (s *Shell) CloneWithStdin(r io.Reader) *Shell

CloneWithStdin returns a copy of the Shell with the provided io.Reader set as the Stdin for the next command. The copy should be discarded after one command. For example:

sh.CloneWithStdin(strings.NewReader("hello world")).Run("cat")

func (*Shell) Command

func (s *Shell) Command(command string, args ...string) Command

Command returns a command that can be run in the shell.

func (*Shell) Getwd

func (s *Shell) Getwd() string

Getwd returns the current working directory of the shell

func (*Shell) Interrupt

func (s *Shell) Interrupt()

Interrupt interrupts the running process, if there is one.

func (*Shell) LockFile

func (s *Shell) LockFile(ctx context.Context, path string) (Unlocker, error)

LockFile creates a cross-process file-based lock. To set a timeout on attempts to acquire the lock, pass a context with a timeout.

func (*Shell) Script

func (s *Shell) Script(path string) (Command, error)

Script returns a command that runs a script in the shell. The path is either executed directly, or some kind of intepreter is executed in order to interpret it (loosely: powershell.exe for .ps1 files, bash(.exe) for shell scripts without shebang lines).

func (*Shell) Terminate

func (s *Shell) Terminate()

Terminate terminates the running process, if there is one.

func (*Shell) WaitStatus

func (s *Shell) WaitStatus() (process.WaitStatus, error)

Returns the WaitStatus of the shell's process.

The shell must have started at least one process.

type TestingLogger

type TestingLogger struct {
	*testing.T
}

func (TestingLogger) Commentf

func (tl TestingLogger) Commentf(format string, v ...any)

func (TestingLogger) Errorf

func (tl TestingLogger) Errorf(format string, v ...any)

func (TestingLogger) Headerf

func (tl TestingLogger) Headerf(format string, v ...any)

func (TestingLogger) OptionalWarningf

func (tl TestingLogger) OptionalWarningf(_id, format string, v ...any)

func (TestingLogger) Printf

func (tl TestingLogger) Printf(format string, v ...any)

func (TestingLogger) Promptf

func (tl TestingLogger) Promptf(format string, v ...any)

func (TestingLogger) Warningf

func (tl TestingLogger) Warningf(format string, v ...any)

func (TestingLogger) Write

func (tl TestingLogger) Write(b []byte) (int, error)

type Unlocker

type Unlocker interface {
	Unlock() error
}

Unlocker implementations are things that can be unlocked, such as a cross-process lock. This interface exists for implementation-hiding.

type WriterLogger

type WriterLogger struct {
	Writer             io.Writer
	Ansi               bool
	DisabledWarningIDs []string
}

WriterLogger provides a logger that writes to an io.Writer

func NewWriterLogger

func NewWriterLogger(writer io.Writer, ansi bool, disabledWarningIDs []string) *WriterLogger

func (*WriterLogger) Commentf

func (wl *WriterLogger) Commentf(format string, v ...any)

func (*WriterLogger) Errorf

func (wl *WriterLogger) Errorf(format string, v ...any)

func (*WriterLogger) Headerf

func (wl *WriterLogger) Headerf(format string, v ...any)

func (*WriterLogger) OptionalWarningf

func (wl *WriterLogger) OptionalWarningf(id, format string, v ...any)

func (*WriterLogger) Printf

func (wl *WriterLogger) Printf(format string, v ...any)

func (*WriterLogger) Promptf

func (wl *WriterLogger) Promptf(format string, v ...any)

func (*WriterLogger) Warningf

func (wl *WriterLogger) Warningf(format string, v ...any)

func (*WriterLogger) Write

func (wl *WriterLogger) Write(b []byte) (int, error)

Jump to

Keyboard shortcuts

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