exec

Imports

Imports #

"errors"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"bytes"
"context"
"errors"
"internal/godebug"
"internal/syscall/execenv"
"io"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"io/fs"
"io/fs"
"syscall"
"io/fs"
"syscall"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"errors"
"internal/syscall/unix"
"io/fs"
"os"
"path/filepath"
"strings"
"syscall"

Constants & Variables

ErrDot var #

ErrDot indicates that a path lookup resolved to an executable in the current directory due to ‘.’ being in the path, either implicitly or explicitly. See the package documentation for details. Note that functions in this package do not return ErrDot directly. Code should use errors.Is(err, ErrDot), not err == ErrDot, to test whether a returned error err is due to this condition.

var ErrDot = *ast.CallExpr

ErrNotFound var #

ErrNotFound is the error resulting if a path search failed to find an executable file.

var ErrNotFound = *ast.CallExpr

ErrNotFound var #

ErrNotFound is the error resulting if a path search failed to find an executable file.

var ErrNotFound = *ast.CallExpr

ErrNotFound var #

ErrNotFound is the error resulting if a path search failed to find an executable file.

var ErrNotFound = *ast.CallExpr

ErrNotFound var #

ErrNotFound is the error resulting if a path search failed to find an executable file.

var ErrNotFound = *ast.CallExpr

ErrWaitDelay var #

ErrWaitDelay is returned by [Cmd.Wait] if the process exits with a successful status code but its output pipes are not closed before the command's WaitDelay expires.

var ErrWaitDelay = *ast.CallExpr

execerrdot var #

var execerrdot = *ast.CallExpr

execwait var #

var execwait = *ast.CallExpr

Structs

Cmd struct #

Cmd represents an external command being prepared or run. A Cmd cannot be reused after calling its [Cmd.Run], [Cmd.Output] or [Cmd.CombinedOutput] methods.

type Cmd struct {
Path string
Args []string
Env []string
Dir string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
ExtraFiles []*os.File
SysProcAttr *syscall.SysProcAttr
Process *os.Process
ProcessState *os.ProcessState
ctx context.Context
Err error
Cancel func() error
WaitDelay time.Duration
childIOFiles []io.Closer
parentIOPipes []io.Closer
goroutine []func() error
goroutineErr <-chan error
ctxResult <-chan ctxResult
createdByStack []byte
lookPathErr error
cachedLookExtensions struct{...}
}

Error struct #

Error is returned by [LookPath] when it fails to classify a file as an executable.

type Error struct {
Name string
Err error
}

ExitError struct #

An ExitError reports an unsuccessful exit by a command.

type ExitError struct {
*os.ProcessState
Stderr []byte
}

ctxResult struct #

A ctxResult reports the result of watching the Context associated with a running command (and sending corresponding signals if needed).

type ctxResult struct {
err error
timer *time.Timer
}

prefixSuffixSaver struct #

prefixSuffixSaver is an io.Writer which retains the first N bytes and the last N bytes written to it. The Bytes() methods reconstructs it with a pretty error message.

type prefixSuffixSaver struct {
N int
prefix []byte
suffix []byte
suffixOff int
skipped int64
}

wrappedError struct #

wrappedError wraps an error without relying on fmt.Errorf.

type wrappedError struct {
prefix string
err error
}

Functions

Bytes method #

func (w *prefixSuffixSaver) Bytes() []byte

CombinedOutput method #

CombinedOutput runs the command and returns its combined standard output and standard error.

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

Command function #

Command returns the [Cmd] struct to execute the named program with the given arguments. It sets only the Path and Args in the returned structure. If name contains no path separators, Command uses [LookPath] to resolve name to a complete path if possible. Otherwise it uses name directly as Path. The returned Cmd's Args field is constructed from the command name followed by the elements of arg, so arg should not include the command name itself. For example, Command("echo", "hello"). Args[0] is always name, not the possibly resolved Path. On Windows, processes receive the whole command line as a single string and do their own parsing. Command combines and quotes Args into a command line string with an algorithm compatible with applications using CommandLineToArgvW (which is the most common way). Notable exceptions are msiexec.exe and cmd.exe (and thus, all batch files), which have a different unquoting algorithm. In these or other similar cases, you can do the quoting yourself and provide the full command line in SysProcAttr.CmdLine, leaving Args empty.

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

CommandContext function #

CommandContext is like [Command] but includes a context. The provided context is used to interrupt the process (by calling cmd.Cancel or [os.Process.Kill]) if the context becomes done before the command completes on its own. CommandContext sets the command's Cancel function to invoke the Kill method on its Process, and leaves its WaitDelay unset. The caller may change the cancellation behavior by modifying those fields before starting the command.

func CommandContext(ctx context.Context, name string, arg ...string) *Cmd

Environ method #

Environ returns a copy of the environment in which the command would be run as it is currently configured.

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

Error method #

func (e *ExitError) Error() string

Error method #

func (e *Error) Error() string

Error method #

func (w wrappedError) Error() string

LookPath function #

LookPath searches for an executable named file in the directories named by the PATH environment variable. LookPath also uses PATHEXT environment variable to match a suitable candidate. If file contains a slash, it is tried directly and the PATH is not consulted. Otherwise, on success, the result is an absolute path. In older versions of Go, LookPath could return a path relative to the current directory. As of Go 1.19, LookPath will instead return that path along with an error satisfying [errors.Is](err, [ErrDot]). See the package documentation for more details.

func LookPath(file string) (string, error)

LookPath function #

LookPath searches for an executable named file in the directories named by the path environment variable. If file begins with "/", "#", "./", or "../", it is tried directly and the path is not consulted. On success, the result is an absolute path. In older versions of Go, LookPath could return a path relative to the current directory. As of Go 1.19, LookPath will instead return that path along with an error satisfying [errors.Is](err, [ErrDot]). See the package documentation for more details.

func LookPath(file string) (string, error)

LookPath function #

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. The result may be an absolute path or a path relative to the current directory.

func LookPath(file string) (string, error)

LookPath function #

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. Otherwise, on success, the result is an absolute path. In older versions of Go, LookPath could return a path relative to the current directory. As of Go 1.19, LookPath will instead return that path along with an error satisfying [errors.Is](err, [ErrDot]). See the package documentation for more details.

func LookPath(file string) (string, error)

Output method #

Output runs the command and returns its standard output. Any returned error will usually be of type [*ExitError]. If c.Stderr was nil and the returned error is of type [*ExitError], Output populates the Stderr field of the returned error.

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

Run method #

Run starts the specified command and waits for it to complete. The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status. If the command starts but does not complete successfully, the error is of type [*ExitError]. Other error types may be returned for other situations. If the calling goroutine has locked the operating system thread with [runtime.LockOSThread] and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

func (c *Cmd) Run() error

Start method #

Start starts the specified command but does not wait for it to complete. If Start returns successfully, the c.Process field will be set. After a successful call to Start the [Cmd.Wait] method must be called in order to release associated system resources.

func (c *Cmd) Start() error

StderrPipe method #

StderrPipe returns a pipe that will be connected to the command's standard error when the command starts. [Cmd.Wait] will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to use [Cmd.Run] when using StderrPipe. See the StdoutPipe example for idiomatic usage.

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

StdinPipe method #

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts. The pipe will be closed automatically after [Cmd.Wait] sees the command exit. A caller need only call Close to force the pipe to close sooner. For example, if the command being run will not exit until standard input is closed, the caller must close the pipe.

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdoutPipe method #

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts. [Cmd.Wait] will close the pipe after seeing the command exit, so most callers need not close the pipe themselves. It is thus incorrect to call Wait before all reads from the pipe have completed. For the same reason, it is incorrect to call [Cmd.Run] when using StdoutPipe. See the example for idiomatic usage.

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

String method #

String returns a human-readable description of c. It is intended only for debugging. In particular, it is not suitable for use as input to a shell. The output of String may vary across Go releases.

func (c *Cmd) String() string

Unwrap method #

func (e *Error) Unwrap() error

Unwrap method #

func (w wrappedError) Unwrap() error

Wait method #

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete. The command must have been started by [Cmd.Start]. The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status. If the command fails to run or doesn't complete successfully, the error is of type [*ExitError]. Other error types may be returned for I/O problems. If any of c.Stdin, c.Stdout or c.Stderr are not an [*os.File], Wait also waits for the respective I/O loop copying to or from the process to complete. Wait releases any resources associated with the [Cmd].

func (c *Cmd) Wait() error

Write method #

func (w *prefixSuffixSaver) Write(p []byte) (n int, err error)

addCriticalEnv function #

addCriticalEnv adds any critical environment variables that are required (or at least almost always required) on the operating system. Currently this is only used for Windows.

func addCriticalEnv(env []string) []string

argv method #

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

awaitGoroutines method #

awaitGoroutines waits for the results of the goroutines copying data to or from the command's I/O pipes. If c.WaitDelay elapses before the goroutines complete, awaitGoroutines forcibly closes their pipes and returns ErrWaitDelay. If timer is non-nil, it must send to timer.C at the end of c.WaitDelay.

func (c *Cmd) awaitGoroutines(timer *time.Timer) error

childStderr method #

func (c *Cmd) childStderr(childStdout *os.File) (*os.File, error)

childStdin method #

func (c *Cmd) childStdin() (*os.File, error)

childStdout method #

func (c *Cmd) childStdout() (*os.File, error)

chkStat function #

func chkStat(file string) error

closeDescriptors function #

func closeDescriptors(closers []io.Closer)

dedupEnv function #

dedupEnv returns a copy of env with any duplicates removed, in favor of later values. Items not of the normal environment "key=value" form are preserved unchanged. Except on Plan 9, items containing NUL characters are removed, and an error is returned along with the remaining values.

func dedupEnv(env []string) ([]string, error)

dedupEnvCase function #

dedupEnvCase is dedupEnv with a case option for testing. If caseInsensitive is true, the case of keys is ignored. If nulOK is false, items containing NUL characters are allowed.

func dedupEnvCase(caseInsensitive bool, nulOK bool, env []string) ([]string, error)

environ method #

environ returns a best-effort copy of the environment in which the command would be run as it is currently configured. If an error occurs in computing the environment, it is returned alongside the best-effort copy.

func (c *Cmd) environ() ([]string, error)

fill method #

fill appends up to len(p) bytes of p to *dst, such that *dst does not grow larger than w.N. It returns the un-appended suffix of p.

func (w *prefixSuffixSaver) fill(dst *[]byte, p []byte) (pRemain []byte)

findExecutable function #

func findExecutable(file string) error

findExecutable function #

func findExecutable(file string, exts []string) (string, error)

findExecutable function #

func findExecutable(file string) error

hasExt function #

func hasExt(file string) bool

interfaceEqual function #

interfaceEqual protects against panics from doing equality tests on two interfaces with non-comparable underlying types.

func interfaceEqual(a any, b any) bool

lookExtensions function #

lookExtensions finds windows executable by its dir and path. It uses LookPath to try appropriate extensions. lookExtensions does not search PATH, instead it converts `prog` into `.\prog`. If the path already has an extension found in PATHEXT, lookExtensions returns it directly without searching for additional extensions. For example, "C:\foo\example.com" would be returned as-is even if the program is actually "C:\foo\example.com.exe".

func lookExtensions(path string, dir string) (string, error)

lookExtensions function #

lookExtensions is a no-op on non-Windows platforms, since they do not restrict executables to specific extensions.

func lookExtensions(path string, dir string) (string, error)

lookExtensions function #

lookExtensions is a no-op on non-Windows platforms, since they do not restrict executables to specific extensions.

func lookExtensions(path string, dir string) (string, error)

lookExtensions function #

lookExtensions is a no-op on non-Windows platforms, since they do not restrict executables to specific extensions.

func lookExtensions(path string, dir string) (string, error)

lookPath function #

lookPath implements LookPath for the given PATHEXT list.

func lookPath(file string, exts []string) (string, error)

pathExt function #

func pathExt() []string

skipStdinCopyError function #

skipStdinCopyError optionally specifies a function which reports whether the provided stdin copy error should be ignored.

func skipStdinCopyError(err error) bool

skipStdinCopyError function #

skipStdinCopyError optionally specifies a function which reports whether the provided stdin copy error should be ignored.

func skipStdinCopyError(err error) bool

skipStdinCopyError function #

skipStdinCopyError optionally specifies a function which reports whether the provided stdin copy error should be ignored.

func skipStdinCopyError(err error) bool

watchCtx method #

watchCtx watches c.ctx until it is able to send a result to resultc. If c.ctx is done before a result can be sent, watchCtx calls c.Cancel, and/or kills cmd.Process it after c.WaitDelay has elapsed. watchCtx manipulates c.goroutineErr, so its result must be received before c.awaitGoroutines is called.

func (c *Cmd) watchCtx(resultc chan<- ctxResult)

writerDescriptor method #

writerDescriptor returns an os.File to which the child process can write to send data to w. If w is nil, writerDescriptor returns a File that writes to os.DevNull.

func (c *Cmd) writerDescriptor(w io.Writer) (*os.File, error)

Generated with Arrow