Documentation
¶
Overview ¶
Package "do" provides helper functions for automating common build, file system, and command-line operations in task scripts.
This package is designed exclusively for task scripts run via 'go run'. It can't work properly when imported in compiled binaries, and therefore panics to avoid unintended behaviour.
Index ¶
- Variables
- func AppendFile(path, content string) string
- func AppendFileWithContext(ctx context.Context, path, content string) (string, error)
- func Archive(source, target string) string
- func ArchiveWithContext(ctx context.Context, source, target string) (string, error)
- func Assert(condition bool, msg string)
- func Assertf(condition bool, format string, args ...any)
- func BaseName(path string) string
- func Copy(src, dst string) string
- func CopyWithContext(ctx context.Context, src, dst string) (string, error)
- func CreateDir(path string) string
- func CreateDirWithContext(ctx context.Context, path string) (string, error)
- func CreateSymlink(target, linkPath string) string
- func CreateSymlinkWithContext(ctx context.Context, target, linkPath string) (string, error)
- func CurrentDir() string
- func Delete(path string) string
- func DeleteWithContext(ctx context.Context, path string) (string, error)
- func Dir(path string) string
- func DirWithContext(ctx context.Context, path string) (string, error)
- func DoAsync(funcs ...func() (any, error)) ([]asyncResult, error)
- func Download(url, dest string) string
- func DownloadWithContext(ctx context.Context, url, dest string) (string, error)
- func Env() envManager
- func Exists(path string) bool
- func ExistsWithContext(ctx context.Context, path string) (bool, error)
- func Extension(path string) string
- func Fail(msg string)
- func Failf(format string, args ...any)
- func FileName(path string) string
- func FileNameWithContext(ctx context.Context, path string) (string, error)
- func Find(root, pattern string) []string
- func FindWithContext(ctx context.Context, root, pattern string) ([]string, error)
- func Get(url string) string
- func GetWithContext(ctx context.Context, url string) (string, error)
- func GoToDir(elem ...string)
- func GoToTaskDir(elem ...string)
- func Info(msg string)
- func Infof(format string, args ...any)
- func IsCommand(name string) bool
- func IsCommandWithContext(ctx context.Context, name string) (bool, error)
- func IsDir(path string) bool
- func IsDirWithContext(ctx context.Context, path string) (bool, error)
- func IsExecutable(path string) bool
- func IsExecutableWithContext(ctx context.Context, path string) (bool, error)
- func IsFile(path string) bool
- func IsFileWithContext(ctx context.Context, path string) (bool, error)
- func IsSymlink(path string) bool
- func IsSymlinkWithContext(ctx context.Context, path string) (bool, error)
- func ListDir(path string) []string
- func ListDirWithContext(ctx context.Context, path string) ([]string, error)
- func Log(msg string)
- func Logf(format string, args ...any)
- func Move(src, dst string) string
- func MoveWithContext(ctx context.Context, src, dst string) (string, error)
- func Must[T any](val T, err error) T
- func Mute()
- func NewContext() taskContext
- func NewContextFrom(ctx context.Context) taskContext
- func NewContextWithIO(output *Output, input *Input) taskContext
- func NewMapEnvManager() envManager
- func NewMapEnvManagerFrom(em envManager) envManager
- func NewMapEnvManagerFromMap(data map[string]string) envManager
- func Post(url, contentType, body string) string
- func PostWithContext(ctx context.Context, url, contentType, body string) (string, error)
- func Printf(format string, args ...any)
- func Println(msg string)
- func ProvideHelp(msg string)
- func Read() string
- func ReadFile(path string) string
- func ReadFileWithContext(ctx context.Context, path string) (string, error)
- func ReadLine() string
- func Readf(format string, a ...any)
- func ResolvePath(path string) string
- func ResolvePathWithContext(ctx context.Context, path string) (string, error)
- func ResolveSymlink(path string) string
- func ResolveSymlinkWithContext(ctx context.Context, path string) (string, error)
- func Run(command string, args ...string)
- func RunTask(name string, args ...string)
- func StartingDir() string
- func Subcommand(defaultCmd string, valid ...string) *subcommand
- func SubcommandWithContext(ctx context.Context, defaultCmd string, valid ...string) (*subcommand, error)
- func Success(msg string)
- func Successf(format string, args ...any)
- func TaskDir() string
- func TaskName() string
- func TaskNameWithContext(ctx context.Context) (string, error)
- func Touch(path string) string
- func TouchWithContext(ctx context.Context, path string) (string, error)
- func Unarchive(source, destination string) string
- func UnarchiveWithContext(ctx context.Context, source, destination string) (string, error)
- func Unmute()
- func Which(name string) string
- func WhichAny(names ...string) string
- func WhichAnyWithContext(ctx context.Context, names ...string) (string, error)
- func WhichWithContext(ctx context.Context, name string) (string, error)
- func WriteFile(path, content string) string
- func WriteFileWithContext(ctx context.Context, path, content string) (string, error)
- type Input
- type Output
- func (o *Output) ErrWriter() io.Writer
- func (o *Output) Fail(msg string)
- func (o *Output) Failf(format string, args ...any)
- func (o *Output) Info(msg string)
- func (o *Output) Infof(format string, args ...any)
- func (o *Output) IsMuted() bool
- func (o *Output) Log(msg string)
- func (o *Output) Logf(format string, args ...any)
- func (o *Output) Mute()
- func (o *Output) Printf(format string, args ...any)
- func (o *Output) Println(msg string)
- func (o *Output) Success(msg string)
- func (o *Output) Successf(format string, args ...any)
- func (o *Output) Unmute()
- func (o *Output) Writer() io.Writer
- type Response
- type SubcommandResult
- func Exec(command string, args ...string) SubcommandResult
- func ExecTask(name string, args ...string) SubcommandResult
- func ExecTaskWithContext(ctx context.Context, name string, args ...string) (SubcommandResult, error)
- func ExecWithContext(ctx context.Context, command string, args ...string) (SubcommandResult, error)
- func RunTaskWithContext(ctx context.Context, name string, args ...string) (SubcommandResult, error)
- func RunWithContext(ctx context.Context, command string, args ...string) (SubcommandResult, error)
Constants ¶
This section is empty.
Variables ¶
var ErrBrokenSymlink = errors.New("symlink target does not exist")
ErrBrokenSymlink indicates that a symbolic link exists but its target does not. This error is returned by ExistsWithContext when checking a path that is a symlink pointing to a non-existent or inaccessible target.
var ErrNonZeroExit = errors.New("command exited with non-zero exit code")
ErrNonZeroExit is returned when a command exits with a non-zero exit code. The exit code can be retrieved from the first return value of Exec/ExecWithContext.
Functions ¶
func AppendFile ¶
AppendFile appends content to a file, creating it if necessary, exiting on error. Relative paths are resolved from the current working directory. Returns the path of the appended file.
func AppendFileWithContext ¶
AppendFileWithContext appends to a file with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- Permission is denied (wrapped os.ErrPermission)
- The path is a directory
- Insufficient disk space
- I/O errors occur
func Archive ¶
Archive creates a zip archive from a source file or directory, exiting on error. Relative paths are resolved from the current working directory. The archive will contain the top-level folder or file from the source path. Symlinks are preserved as symlinks in the archive. Returns the path of the created archive.
func ArchiveWithContext ¶
ArchiveWithContext creates a zip archive with context support for cancellation. The context can override the working directory via context.WithDir(). Cancellation is checked between files during the walk. Symlinks are preserved in the archive by storing the link target as the entry data.
Returns an error if:
- The context is cancelled (context.Err())
- The source does not exist (wrapped os.ErrNotExist)
- Permission is denied for source or target (wrapped os.ErrPermission)
- Insufficient disk space
- Cannot create or write to target file
- I/O errors occur
func BaseName ¶
BaseName returns the last element of a path. Trailing slashes are removed before extracting the last element. If the path is empty, BaseName returns ".". If the path consists entirely of slashes, BaseName returns "/".
func Copy ¶
Copy recursively copies a file, directory, or symlink, exiting on error. Relative paths are resolved from the current working directory. Symlinks are preserved as symlinks (not followed), maintaining the original link target. Returns the destination path.
func CopyWithContext ¶
CopyWithContext recursively copies with context support for cancellation. The context can override the working directory via context.WithDir(). For directory copies, cancellation is checked between files.
Returns an error if:
- The context is cancelled (context.Err())
- The source does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
- Insufficient disk space
- I/O errors occur
func CreateDir ¶
CreateDir creates a directory at the given path, including any necessary parents, exiting on error. Relative paths are resolved from the current working directory. Returns the path of the created directory.
func CreateDirWithContext ¶
CreateDirWithContext creates a directory with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- Permission is denied (wrapped os.ErrPermission)
- The path exists as a file
- Insufficient disk space
func CreateSymlink ¶
CreateSymlink creates a symbolic link at linkPath pointing to target, exiting on error. Both relative paths are resolved from the current working directory. The target path is stored as-is in the symlink (relative or absolute). The target does not need to exist (dangling symlinks are allowed). Fails if linkPath already exists. Returns the path of the created symlink.
func CreateSymlinkWithContext ¶
CreateSymlinkWithContext creates a symbolic link with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The link path already exists (wrapped os.ErrExist)
- Permission is denied (wrapped os.ErrPermission)
- The filesystem does not support symlinks (platform-specific)
- On Windows: administrator privileges or developer mode may be required
func CurrentDir ¶
func CurrentDir() string
CurrentDir returns the current working directory. Panics if the current directory cannot be determined.
func Delete ¶
Delete recursively deletes a file or directory, exiting on error. Relative paths are resolved from the current working directory. Returns the path of the deleted item.
func DeleteWithContext ¶
DeleteWithContext deletes a file or directory with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- Permission is denied (wrapped os.ErrPermission)
Note: If the path does not exist, DeleteWithContext returns successfully (no-op).
func Dir ¶
Dir returns the directory path, exiting on error. If path is a directory, returns the path as-is. If path is a file, returns the parent directory. Relative paths are resolved from the current working directory.
func DirWithContext ¶
DirWithContext returns the directory path with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
func DoAsync ¶
DoAsync runs multiple functions concurrently and collects all results. Each function returns a value and an error. Results are collected in order, so results[i] corresponds to funcs[i].
Returns:
- []asyncResult: One result per function, in order. Check .Error() to see if failed.
- error: Non-nil if any function failed (for Must compatibility). Contains all errors joined.
The error return allows DoAsync to work with Must:
results := Must(DoAsync(...))
Individual results can be accessed by index:
if results[3].Error() != nil {
// Function 3 failed
}
value := results[5].String() // Get string from function 5, or Fail
func Download ¶
Download downloads a file from a URL to a destination path, exiting on error. Relative paths are resolved from the current working directory. Returns the destination path.
func DownloadWithContext ¶
DownloadWithContext downloads a file from a URL with context support for cancellation. Relative paths are resolved from the current working directory. Verifies the downloaded size matches Content-Length when available. Returns the destination path.
Returns an error if:
- The context is cancelled or times out (context.Err())
- The HTTP request fails (network errors, DNS resolution, invalid URL)
- The server returns a non-2xx status code
- Content-Length mismatch detected
- Permission is denied to write destination file (wrapped os.ErrPermission)
- Insufficient disk space
- I/O errors occur
func Env ¶
func Env() envManager
Env provides access to the environment variables for the current process through the default environment manager.
func Exists ¶
Exists checks if a file or directory exists at the given path. Relative paths are resolved from the current working directory. Returns false if the path does not exist, if it's a broken symlink, or if it cannot be accessed due to permissions. Note: This differs from os.Stat by detecting broken symlinks explicitly.
func ExistsWithContext ¶
ExistsWithContext checks if a file or directory exists with context support. The context can override the working directory via context.WithDir(). Returns (true, nil) if the path exists and is accessible. Returns (false, error) if: - The path does not exist (error will be os.ErrNotExist) - The path is a broken symlink (error will wrap ErrBrokenSymlink) - The path cannot be accessed (error will indicate permission or other issue) - The context is cancelled (error will be the context error)
func Extension ¶
Extension returns the file extension without the leading dot. Returns "" if the path has no extension. Hidden files starting with a dot (like ".bashrc") are treated as having no extension. Examples: "/foo/bar.go" → "go", "/foo/bar" → "", ".bashrc" → ""
func Fail ¶
func Fail(msg string)
Fail prints an error message with an X prefix and exits with code 1.
func FileName ¶
FileName returns the filename without extension, exiting on error. Returns an error if the path is a directory. Relative paths are resolved from the current working directory. Example: "/foo/bar/fizz.go" → "fizz"
func FileNameWithContext ¶
FileNameWithContext returns the filename without extension with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- The path is a directory (not a file)
- Permission is denied (wrapped os.ErrPermission)
func Find ¶
Find finds all files and directories matching a pattern within a root directory, exiting on error. Relative paths are resolved from the current working directory. Recurses into subdirectories. Symlinks are followed during traversal.
func FindWithContext ¶
FindWithContext finds matching files with context support for cancellation. The context can override the working directory via context.WithDir(). Cancellation is checked between directory entries. Symlinks are followed during traversal.
Returns an error if:
- The context is cancelled (context.Err())
- The pattern is invalid (malformed glob pattern)
- The root directory does not exist (wrapped os.ErrNotExist)
- Permission is denied for any directory (wrapped os.ErrPermission)
- A directory cannot be traversed (other walk errors)
func Get ¶
Get performs an HTTP GET request and returns the response body as a string, exiting on error. Returns an error for non-2xx status codes.
func GetWithContext ¶
GetWithContext performs an HTTP GET request with context support.
Returns an error if:
- The context is cancelled or times out (context.Err())
- The HTTP request fails (network errors, DNS resolution, invalid URL)
- The server returns a non-2xx status code
- The response body cannot be read
func GoToDir ¶
func GoToDir(elem ...string)
GoToDir changes the current working directory to the path formed by joining the provided path elements. This affects all subsequent operations that use relative paths until another GoToDir call is made.
Note: This function is not safe for concurrent use. For concurrent operations, use *WithContext functions with context.WithDir() instead.
func GoToTaskDir ¶
func GoToTaskDir(elem ...string)
GoToTaskDir changes the current working directory to the task file's directory, optionally joined with additional path elements. Call this at the start of your task file to ensure relative paths resolve from the task file's location rather than where 'go run' was invoked.
Note: This function is not safe for concurrent use. For concurrent operations, use *WithContext functions with context.WithDir() instead.
Example:
func main() {
do.GoToTaskDir() // go to task file's directory
do.GoToTaskDir("..") // go to parent of task file's directory
do.GoToTaskDir("foo/bar") // go to foo/bar relative to task file's directory
}
func IsCommand ¶
IsCommand checks if a command is available in PATH. Returns false (suppressing any errors) if the command is not found.
func IsCommandWithContext ¶
IsCommandWithContext checks if a command is available with context support. Returns (false, nil) if the command is not found (expected negative case). Returns (false, error) if the context is cancelled or PATH lookup fails.
func IsDir ¶
IsDir checks if a path is a directory. If the path is a symlink, it checks the symlink's target. Returns false (suppressing any errors) if the path does not exist or cannot be accessed. Relative paths are resolved from the current working directory.
func IsDirWithContext ¶
IsDirWithContext checks if a path is a directory with context support. If the path is a symlink, it checks the symlink's target. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
func IsExecutable ¶
IsExecutable checks if a file can be executed on the current platform. On Unix systems (Linux, macOS, BSD), checks if any execute permission bit is set. On Windows, checks if the file extension matches PATHEXT environment variable (defaults to .COM, .EXE, .BAT, .CMD, .VBS, .JS, .WS, .MSC, .PS1 if not set). Returns false for directories, symlinks, and non-existent files. Relative paths are resolved from the current working directory.
func IsExecutableWithContext ¶
IsExecutableWithContext checks if a file is executable with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
func IsFile ¶
IsFile checks if a path is a regular file. If the path is a symlink, it checks the symlink's target. Returns false (suppressing any errors) if the path does not exist or cannot be accessed. Relative paths are resolved from the current working directory.
func IsFileWithContext ¶
IsFileWithContext checks if a path is a regular file with context support. If the path is a symlink, it checks the symlink's target. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
func IsSymlink ¶
IsSymlink checks if a path is a symbolic link. Returns false (suppressing any errors) if the path does not exist or cannot be accessed. Relative paths are resolved from the current working directory.
func IsSymlinkWithContext ¶
IsSymlinkWithContext checks if a path is a symbolic link with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
func ListDir ¶
ListDir returns all entries (files and directories) in a directory, exiting on error. Relative paths are resolved from the current working directory. Unlike Find, it does not recurse into subdirectories.
func ListDirWithContext ¶
ListDirWithContext lists directory contents with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The directory does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
- The path is not a directory
func Move ¶
Move renames (moves) a file or directory, exiting on error. Relative paths are resolved from the current working directory. Returns the destination path.
func MoveWithContext ¶
MoveWithContext moves a file or directory with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The source does not exist (wrapped os.ErrNotExist)
- The destination already exists (wrapped os.ErrExist)
- Permission is denied (wrapped os.ErrPermission)
- Source and destination are on different filesystems (requires copy+delete)
func Mute ¶
func Mute()
Mute suppresses all output from package-level functions (Log, Info, Success, etc.). Does not modify environment variables. Child processes inherit muted mode when Run*, Exec*, RunTask, or ExecTask detect the output is muted and automatically set DO_MUTED_MODE=1 for the subprocess.
Call Unmute() to restore normal output.
Note: Mute() is not safe for concurrent use. Only call from the main goroutine of your task script.
func NewContext ¶
func NewContext() taskContext
NewContext creates a new context with context.Background(). The context has output and input set to package-level output and input by default.
func NewContextFrom ¶
NewContextFrom wraps an existing context.Context into a context. The context has output and input set to package-level output and input by default. Any additional configuration (output, input, dir, env, etc.) should be added via the With* methods after wrapping.
func NewContextWithIO ¶
NewContextWithIO creates a new context with Output and Input configured. Pass nil for output or input to use package-level defaults. This is a shortcut for:
ctx := NewContext()
if output != nil { ctx = ctx.WithOutput(output) }
if input != nil { ctx = ctx.WithInput(input) }
func NewMapEnvManager ¶
func NewMapEnvManager() envManager
NewMapEnvManager returns an envManager implementation for interacting with environment variables as a sandboxed in-memory map.
func NewMapEnvManagerFrom ¶
func NewMapEnvManagerFrom(em envManager) envManager
NewMapEnvManagerFrom returns an envManager implementation for interacting with environment variables as a sandboxed in-memory map from another envManager instance.
func NewMapEnvManagerFromMap ¶
NewMapEnvManagerFromMap returns an envManager implementation for interacting with environment variables as a sandboxed in-memory map from another map.
func Post ¶
Post performs an HTTP POST request with the given content type and body, exiting on error. Returns the response body as a string, or an error for non-2xx status codes.
func PostWithContext ¶
PostWithContext performs an HTTP POST request with context support.
Returns an error if:
- The context is cancelled or times out (context.Err())
- The HTTP request fails (network errors, DNS resolution, invalid URL)
- The server returns a non-2xx status code
- The response body cannot be read
func Println ¶
func Println(msg string)
Println is an alias for Log, provided for Go developers familiar with fmt.Println.
func ProvideHelp ¶
func ProvideHelp(msg string)
ProvideHelp checks if "help" was passed as the first argument. If so, it prints the provided message and exits with status 0. This is typically called at the start of a task file to provide usage info.
func Read ¶
func Read() string
Read reads a single whitespace-delimited value from stdin. Returns the value as a string (reads up to whitespace, newline, or EOF). Exits with code 1 on error (but not on EOF).
func ReadFile ¶
ReadFile reads and returns the contents of a file as a string, exiting on error. Relative paths are resolved from the current working directory.
func ReadFileWithContext ¶
ReadFileWithContext reads a file with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The file does not exist (wrapped os.ErrNotExist)
- Permission is denied (wrapped os.ErrPermission)
- The path is a directory
- I/O errors occur
func ReadLine ¶
func ReadLine() string
ReadLine reads a line from stdin (up to newline). Exits with code 1 on error.
func Readf ¶
Readf reads formatted input from stdin according to a format string. Exits with code 1 on error.
func ResolvePath ¶
ResolvePath resolves a path against the current working directory and returns the absolute path. It is intended to be used after GoToTask() to resolve paths from a consistent location (e.g. project root). Absolute paths are returned as-is. Exits on error.
func ResolvePathWithContext ¶
ResolvePathWithContext resolves a path and returns it as an absolute path. It resolves relative paths against the directory set by context.WithDir(), or the current working directory if no directory is set in the context. Absolute paths are returned as-is.
func ResolveSymlink ¶
ResolveSymlink follows symbolic links recursively to find the ultimate target, exiting on error. Relative paths are resolved from the current working directory. Returns the absolute path to the final target. Works on symlinks, regular files, and directories (returns cleaned absolute path for non-symlinks). Fails if the path does not exist or if circular symlinks are detected.
func ResolveSymlinkWithContext ¶
ResolveSymlinkWithContext resolves symlinks with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- The path does not exist (wrapped os.ErrNotExist)
- A circular symlink is detected
- Permission is denied (wrapped os.ErrPermission)
- Too many levels of symlinks (platform-specific limit, typically 40)
func RunTask ¶
RunTask runs another task file by name, exiting on error. The task file is resolved relative to the calling task's directory. Output is streamed to stdout/stderr.
func StartingDir ¶
func StartingDir() string
StartingDir returns the original working directory captured at package initialisation. This value remains constant regardless of any subsequent GoTo calls.
func Subcommand ¶
Subcommand is a convenience wrapper around SubcommandWithContext that exits on error. It creates a new parser for defining flags and a subcommand.
func SubcommandWithContext ¶
func SubcommandWithContext(ctx context.Context, defaultCmd string, valid ...string) (*subcommand, error)
SubcommandWithContext creates a new parser for defining flags and a subcommand, returning an error if the parsed subcommand is invalid.
func TaskDir ¶
func TaskDir() string
TaskDir returns the directory containing the task file. Panics if the task file location cannot be determined. This works reliably regardless of wrapper functions between the caller and main.
func TaskName ¶
func TaskName() string
TaskName returns the file name of the task file, exiting on error. This works reliably regardless of wrapper functions between the caller and main.
func TaskNameWithContext ¶
TaskNameWithContext returns the file name of the task file. This works reliably regardless of wrapper functions between the caller and main.
func Touch ¶
Touch creates an empty file or updates its modification time if it exists, exiting on error. Relative paths are resolved from the current working directory. Returns the path of the touched file.
func TouchWithContext ¶
TouchWithContext touches a file with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- Permission is denied (wrapped os.ErrPermission)
- The path is a directory
- Insufficient disk space
func Unarchive ¶
Unarchive extracts a zip archive to a destination folder, exiting on error. Relative paths are resolved from the current working directory. Includes protection against the "zip slip" vulnerability. Symlinks are recreated as symlinks at the destination. Returns the destination path.
func UnarchiveWithContext ¶
UnarchiveWithContext extracts a zip archive with context support for cancellation. The context can override the working directory via context.WithDir(). Cancellation is checked between zip entries. Symlinks stored in the archive are recreated as symlinks.
Returns an error if:
- The context is cancelled (context.Err())
- The archive file does not exist (wrapped os.ErrNotExist)
- The archive file is corrupt or invalid
- Zip slip attack detected (path traversal attempt)
- Permission is denied (wrapped os.ErrPermission)
- Insufficient disk space
- Cannot create destination directories or files
func Unmute ¶
func Unmute()
Unmute restores normal output from package-level functions after Mute() has been called. Does not modify environment variables.
Note: Unmute() is not safe for concurrent use. Only call from the main goroutine of your task script.
func Which ¶
Which finds the full path to a command in PATH, exiting on error. Returns the absolute path to the executable. Fails if the command is not found.
func WhichAny ¶
WhichAny returns the path to the first available command from the list. Returns empty string if none are found, allowing graceful fallback handling. Useful for checking alternative tools: WhichAny("python3", "python"). When called with no arguments, returns empty string.
func WhichAnyWithContext ¶
WhichAnyWithContext finds the first available command with context support. Returns the path to the first found command and nil error. Returns ("", error) if none are found, where error is the last lookup error encountered. Returns ("", error) if the context is cancelled. Checks for cancellation between each command lookup.
func WhichWithContext ¶
WhichWithContext finds a command path with context support.
Returns an error if:
- The context is cancelled (context.Err())
- The command is not found in PATH (exec.ErrNotFound)
func WriteFile ¶
WriteFile writes content to a file, creating it if necessary, exiting on error. Relative paths are resolved from the current working directory. Returns the path of the written file.
func WriteFileWithContext ¶
WriteFileWithContext writes to a file with context support. The context can override the working directory via context.WithDir().
Returns an error if:
- The context is cancelled (context.Err())
- Permission is denied (wrapped os.ErrPermission)
- The path is a directory
- Insufficient disk space
- I/O errors occur
Types ¶
type Input ¶
type Input struct {
// contains filtered or unexported fields
}
Input handles input operations with a configured input source. Create inputs with NewInput(in) or use the package-level functions which delegate to the default input. Note: Input is not safe for concurrent use by multiple goroutines due to the internal scanner state.
func NewEmptyInput ¶
func NewEmptyInput() *Input
NewEmptyInput creates an empty input source. This is a a convenience method equivalent to:
input := NewInput(bytes.NewReader(nil))
func NewInput ¶
NewInput creates a new Input with the specified input source. If in is nil, defaults to os.Stdin.
func NewInputFromFile ¶
NewFileInput creates an input source from a file. The file is read fully into a memory buffer.
func (*Input) Read ¶
Read reads a single whitespace-delimited value from input. Returns the value as a string (reads up to whitespace, newline, or EOF). Uses fmt.Fscan internally. Exits with code 1 on error (but not on EOF).
func (*Input) ReadLine ¶
ReadLine reads a full line from input (up to newline). Uses bufio.Scanner internally to read the complete line including spaces. Exits with code 1 on error.
type Output ¶
type Output struct {
// contains filtered or unexported fields
}
Output handles output operations with immutable output destinations. Create outputs with NewOutput(out, err) or use the package-level functions which delegate to the default output. Output is thread-safe because its fields are immutable after construction.
func NewMutedOutput ¶
func NewMutedOutput() *Output
NewMutedOutput creates a new Output that discards all output. The output is created in muted mode with both writers set to io.Discard. This is a convenience constructor equivalent to:
output := NewOutput(io.Discard, io.Discard) output.Mute()
func NewOutput ¶
NewOutput creates a new Output with the specified output destinations. Both writers must be non-nil.
func (*Output) ErrWriter ¶
ErrWriter returns the error writer for this output. Returns io.Discard when in muted mode, otherwise returns the configured writer.
func (*Output) Failf ¶
Failf prints a formatted error message with an X prefix and exits with code 1.
func (*Output) Mute ¶
func (o *Output) Mute()
Mute enables muted mode for this Output instance. When muted, Writer() and ErrWriter() return io.Discard. Does not modify environment variables.
type Response ¶
type Response struct {
StatusCode int
// contains filtered or unexported fields
}
Response holds the result of an HTTP request.
func Request ¶
Request performs an HTTP request with custom method, headers, and body, exiting on error. Unlike Get and Post, this function returns the Response for any status code, allowing the caller to handle non-2xx responses.
func RequestWithContext ¶
func RequestWithContext(ctx context.Context, method, url string, body string, headers map[string]string) (Response, error)
RequestWithContext performs an HTTP request with context support for cancellation. Unlike GetWithContext and PostWithContext, this function returns the Response for any status code, allowing the caller to handle non-2xx responses.
Returns an error if:
- The context is cancelled or times out (context.Err())
- The HTTP request fails (network errors, DNS resolution, invalid URL)
- The request cannot be created (malformed URL, invalid method)
- The response body cannot be read (partial response may be returned)
type SubcommandResult ¶
SubcommandResult holds the output from command execution.
func Exec ¶
func Exec(command string, args ...string) SubcommandResult
Exec executes a command, captures stdout and stderr, and exits on error. Both outputs are trimmed of trailing whitespace.
func ExecTask ¶
func ExecTask(name string, args ...string) SubcommandResult
ExecTask runs another task file by name with the given arguments, exiting on error. The task file is resolved relative to the calling task file's directory. Returns the captured output.
func ExecTaskWithContext ¶
func ExecTaskWithContext(ctx context.Context, name string, args ...string) (SubcommandResult, error)
ExecTaskWithContext runs another task file with context support. The task file is resolved relative to the calling task file's directory. Returns the captured output and any error.
Returns an error if:
- The context is cancelled (context.Err())
- The task file path cannot be determined (errCallerUnknown)
- The task file does not exist or cannot be compiled
- The command exits with a non-zero exit code (ErrNonZeroExit)
func ExecWithContext ¶
ExecWithContext executes a command with context support and captures stdout and stderr. Both outputs are trimmed of trailing whitespace.
Returns an error if:
- The context is cancelled (context.Err())
- The command is not found in PATH (exec.ErrNotFound)
- The command cannot be executed (permission or other system errors)
- The command exits with a non-zero exit code (ErrNonZeroExit)
func RunTaskWithContext ¶
RunTaskWithContext runs another task file with context support. The task file is resolved relative to the calling task's directory. Output is streamed to stdout/stderr. Returns the command result and any error.
Returns an error if:
- The context is cancelled (context.Err())
- The task file path cannot be determined (errCallerUnknown)
- The task file does not exist or cannot be compiled
- The command exits with a non-zero exit code (ErrNonZeroExit)
func RunWithContext ¶
RunWithContext executes a command with context support, returning an error on failure. Output is streamed to stdout/stderr.
Returns an error if:
- The context is cancelled (context.Err())
- The command is not found in PATH (exec.ErrNotFound)
- The command cannot be executed (permission or other system errors)
- The command exits with a non-zero exit code (ErrNonZeroExit)