builtins

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Names

func Names() []string

Names returns a sorted list of all registered builtin command names.

func NoFlags

func NoFlags(fn HandlerFunc) func(*FlagSet) HandlerFunc

NoFlags wraps a HandlerFunc in the MakeFlags format for commands that declare no flags.

Types

type CallContext

type CallContext struct {
	Stdout io.Writer
	Stderr io.Writer
	Stdin  io.Reader

	// InLoop is true when the builtin runs inside a for loop.
	InLoop bool

	// LastExitCode is the exit code from the previous command.
	LastExitCode uint8

	// OpenFile opens a file within the shell's path restrictions.
	OpenFile func(ctx context.Context, path string, flags int, mode os.FileMode) (io.ReadWriteCloser, error)

	// ReadDir reads a directory within the shell's path restrictions.
	// Entries are returned sorted by name. Used by builtins like ls
	// that need deterministic sorted output.
	ReadDir func(ctx context.Context, path string) ([]fs.DirEntry, error)

	// OpenDir opens a directory within the shell's path restrictions for
	// incremental reading via ReadDir(n). Caller must close the handle.
	OpenDir func(ctx context.Context, path string) (fs.ReadDirFile, error)

	// IsDirEmpty checks whether a directory is empty by reading at most
	// one entry. More efficient than reading all entries.
	IsDirEmpty func(ctx context.Context, path string) (bool, error)

	// ReadDirLimited reads directory entries, skipping the first offset entries
	// and returning up to maxRead entries sorted by name within the read window.
	// Returns (entries, truncated, error). When truncated is true, the directory
	// contained more entries beyond the returned set.
	ReadDirLimited func(ctx context.Context, path string, offset, maxRead int) ([]fs.DirEntry, bool, error)

	// StatFile returns file info within the shell's path restrictions (follows symlinks).
	StatFile func(ctx context.Context, path string) (fs.FileInfo, error)

	// LstatFile returns file info within the shell's path restrictions (does not follow symlinks).
	LstatFile func(ctx context.Context, path string) (fs.FileInfo, error)

	// AccessFile checks whether the file at path is accessible with the given mode
	// within the shell's path restrictions. Mode: 0x04=read, 0x02=write, 0x01=execute.
	AccessFile func(ctx context.Context, path string, mode uint32) error

	// PortableErr normalizes an OS error to a POSIX-style message.
	PortableErr func(err error) string

	// Now is the time captured at the start of each Run() call. Builtins
	// should use this instead of calling time.Now() directly, so the time
	// source is consistent across all commands in a single run.
	//
	// Note: this means all builtins within one Run() share the same reference
	// time, whereas bash evaluates each command against its own invocation
	// time. This is an intentional trade-off for consistency within a script
	// run.
	//
	// Run() always sets this before dispatching any builtin; Reset() clears
	// it, so it is always re-set by the next Run() call. The zero value
	// (time.Time{}) is reserved as the unset sentinel; callers constructing
	// CallContext directly (e.g. in tests) must set this to a non-zero value
	// before invoking builtins that use time predicates (find -mmin/-mtime,
	// ls -l).
	Now time.Time

	// FileIdentity extracts canonical file identity from FileInfo.
	// On Unix: dev+inode from Stat_t. On Windows: volume serial + file index
	// via GetFileInformationByHandle. The path parameter is needed on Windows
	// where FileInfo.Sys() lacks identity fields; Unix ignores it.
	FileIdentity func(path string, info fs.FileInfo) (FileID, bool)

	// CommandAllowed reports whether a command name is permitted under the
	// current shell policy. Used by the help builtin to list only executable
	// commands.
	CommandAllowed func(name string) bool

	// WorkDir returns the shell's current working directory (absolute path).
	// Used by builtins that need to compute absolute paths for sub-operations.
	WorkDir func() string

	// RunCommand executes a builtin command within the shell's sandbox.
	// dir overrides the working directory for path resolution.
	// Returns the command's exit code.
	RunCommand func(ctx context.Context, dir string, name string, args []string) (uint8, error)
	// Proc provides access to the proc filesystem for the ps builtin.
	// The path is fixed at construction time and cannot be overridden by callers.
	Proc *ProcProvider
}

CallContext provides the capabilities available to builtin commands. It is created by the Runner for each builtin invocation.

func (*CallContext) Errf

func (c *CallContext) Errf(format string, a ...any)

Errf writes a formatted string to stderr.

func (*CallContext) Out

func (c *CallContext) Out(s string)

Out writes a string to stdout.

func (*CallContext) Outf

func (c *CallContext) Outf(format string, a ...any)

Outf writes a formatted string to stdout.

type Command

type Command struct {
	Name        string
	Description string
	Help        string
	MakeFlags   func(*FlagSet) HandlerFunc
}

Command pairs a builtin name with its flag-declaring factory. MakeFlags registers any flags on the provided FlagSet and returns the bound handler. Commands that accept no flags may ignore fs via NoFlags.

func (Command) Register

func (c Command) Register()

Register adds the Command to the builtin registry. For each invocation the framework creates a fresh *FlagSet, passes it to MakeFlags so the command can register its flags, parses the raw args, writes any error to stderr (exit 1), and then calls the bound handler with positional args only.

If MakeFlags registers no flags (e.g. via NoFlags), the framework skips parsing entirely and passes all raw args to the handler unchanged. This lets commands like echo treat flag-shaped literals (e.g. -n) correctly.

type CommandMeta

type CommandMeta struct {
	Name        string
	Description string
	Help        string
}

CommandMeta holds metadata about a registered builtin command.

func Meta

func Meta(name string) (CommandMeta, bool)

Meta returns the metadata for a registered builtin command.

type FileID

type FileID struct {
	Dev uint64
	Ino uint64
}

FileID is a comparable file identity for cycle detection. On Unix: device + inode. On Windows: volume serial + file index. Used as map key for visited-set tracking.

type Flag

type Flag = pflag.Flag

Flag is a type alias for pflag.Flag, exposed so command files can use FlagSet.Visit without importing pflag directly.

type FlagSet

type FlagSet = pflag.FlagSet

FlagSet is a type alias for pflag.FlagSet. Command files receive a *FlagSet from the framework without needing to import pflag directly (the builtins package is always allowed by the import allowlist).

type HandlerFunc

type HandlerFunc func(ctx context.Context, callCtx *CallContext, args []string) Result

HandlerFunc is the bound handler called by the framework after flags are parsed. args contains only the positional (non-flag) arguments.

func Lookup

func Lookup(name string) (HandlerFunc, bool)

Lookup returns the handler for a builtin command.

type ProcProvider added in v0.0.6

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

ProcProvider gives builtins controlled access to the proc filesystem. The path is fixed at construction time and cannot be overridden by callers.

func NewProcProvider added in v0.0.6

func NewProcProvider(path string) *ProcProvider

NewProcProvider returns a ProcProvider for the given proc filesystem path. If path is empty, DefaultProcPath ("/proc") is used.

func (*ProcProvider) GetByPIDs added in v0.0.6

func (p *ProcProvider) GetByPIDs(ctx context.Context, pids []int) ([]procinfo.ProcInfo, error)

GetByPIDs returns process info for the given PIDs.

func (*ProcProvider) GetSession added in v0.0.6

func (p *ProcProvider) GetSession(ctx context.Context) ([]procinfo.ProcInfo, error)

GetSession returns processes in the current process session.

func (*ProcProvider) ListAll added in v0.0.6

func (p *ProcProvider) ListAll(ctx context.Context) ([]procinfo.ProcInfo, error)

ListAll returns all running processes.

func (*ProcProvider) ProcPath added in v0.0.8

func (p *ProcProvider) ProcPath() string

ProcPath returns the configured proc filesystem path (e.g. "/proc" or "/host/proc").

func (*ProcProvider) ReadKernelFile added in v0.0.8

func (p *ProcProvider) ReadKernelFile(name string) (string, error)

ReadKernelFile reads a single-line value from a /proc/sys/kernel/ pseudo-file. name is the filename relative to sys/kernel/ (e.g. "ostype", "hostname"). The returned value is trimmed of trailing whitespace.

type Result

type Result struct {
	// Code is the exit status code.
	Code uint8

	// Exiting signals that the shell should exit (set by the "exit" builtin).
	Exiting bool

	// BreakN > 0 means break out of N enclosing loops.
	BreakN int

	// ContinueN > 0 means continue from N enclosing loops.
	ContinueN int
}

Result captures the outcome of executing a builtin command.

Directories

Path Synopsis
Package breakcmd implements the break builtin command.
Package breakcmd implements the break builtin command.
Package cat implements the cat builtin command.
Package cat implements the cat builtin command.
Package continuecmd implements the continue builtin command.
Package continuecmd implements the continue builtin command.
Package cut implements the cut builtin command.
Package cut implements the cut builtin command.
Package echo implements the echo builtin command.
Package echo implements the echo builtin command.
Package exit implements the exit builtin command.
Package exit implements the exit builtin command.
Package falsecmd implements the false builtin command.
Package falsecmd implements the false builtin command.
Package find implements the find builtin command.
Package find implements the find builtin command.
Package grep implements the grep builtin command.
Package grep implements the grep builtin command.
Package head implements the head builtin command.
Package head implements the head builtin command.
Package help implements the help builtin command.
Package help implements the help builtin command.
internal
procinfo
Package procinfo provides OS-specific process information for the ps builtin.
Package procinfo provides OS-specific process information for the ps builtin.
procnetroute
Package procnetroute reads the Linux IPv4 routing table from /proc/net/route.
Package procnetroute reads the Linux IPv4 routing table from /proc/net/route.
procnetsocket
Package procnetsocket reads Linux socket state from /proc/net/.
Package procnetsocket reads Linux socket state from /proc/net/.
procpath
Package procpath provides the single canonical default path to the Linux proc filesystem.
Package procpath provides the single canonical default path to the Linux proc filesystem.
procsyskernel
Package procsyskernel reads Linux kernel information from /proc/sys/kernel/.
Package procsyskernel reads Linux kernel information from /proc/sys/kernel/.
winnet
Package winnet provides socket enumeration for Windows via iphlpapi.dll.
Package winnet provides socket enumeration for Windows via iphlpapi.dll.
Package ip implements the ip builtin command.
Package ip implements the ip builtin command.
Package ls implements the ls builtin command.
Package ls implements the ls builtin command.
Package ping implements the ping builtin command.
Package ping implements the ping builtin command.
Package printf implements the printf builtin command.
Package printf implements the printf builtin command.
Package ps implements the ps builtin command.
Package ps implements the ps builtin command.
Package sed implements the sed builtin command.
Package sed implements the sed builtin command.
Package sort implements the sort builtin command.
Package sort implements the sort builtin command.
Package ss implements the ss builtin command.
Package ss implements the ss builtin command.
Package strings_cmd implements the strings builtin command.
Package strings_cmd implements the strings builtin command.
Package tail implements the tail builtin command.
Package tail implements the tail builtin command.
Package testcmd implements the POSIX test and [ builtin commands.
Package testcmd implements the POSIX test and [ builtin commands.
Package testutil provides shared test helpers for builtin command tests.
Package testutil provides shared test helpers for builtin command tests.
Package tr implements the tr builtin command.
Package tr implements the tr builtin command.
Package truecmd implements the true builtin command.
Package truecmd implements the true builtin command.
Package uname implements the uname builtin command.
Package uname implements the uname builtin command.
Package uniq implements the uniq builtin command.
Package uniq implements the uniq builtin command.
Package wc implements the wc builtin command.
Package wc implements the wc builtin command.

Jump to

Keyboard shortcuts

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