Documentation
¶
Index ¶
- Variables
- func IsBrokenPipe(err error) bool
- func Names() []string
- func NoFlags(fn HandlerFunc) func(*FlagSet) HandlerFunc
- func NormalizeBareNumberArg(args []string, valueFlags []string) []string
- func UnsupportedSummary() []string
- type CallContext
- type Command
- type CommandMeta
- type FeatureMeta
- type FileID
- type Flag
- type FlagSet
- type HandlerFunc
- type ProcProvider
- func (p *ProcProvider) GetByPIDs(ctx context.Context, pids []int) ([]procinfo.ProcInfo, error)
- func (p *ProcProvider) GetSession(ctx context.Context) ([]procinfo.ProcInfo, error)
- func (p *ProcProvider) ListAll(ctx context.Context) ([]procinfo.ProcInfo, error)
- func (p *ProcProvider) ProcPath() string
- func (p *ProcProvider) ReadKernelFile(name string) (string, error)
- type Result
Constants ¶
This section is empty.
Variables ¶
var ErrVarStorageExceeded = errors.New("variable storage limit exceeded")
ErrVarStorageExceeded is returned by CallContext.SetVar when the assignment would push the runner's total variable storage past its cap. This is a script-aborting condition: AST-level assignments treat it the same way (see interp/vars.go), so state-mutating builtins should propagate it via Result.Exiting=true rather than continuing with status 1, matching bash's resource-cap DoS guard.
Functions ¶
func IsBrokenPipe ¶ added in v0.0.11
IsBrokenPipe reports whether err is a broken-pipe (EPIPE) error, which occurs when writing to a pipe whose read end has been closed. In bash this triggers SIGPIPE which silently terminates the writer; builtins should use this to suppress error messages on pipe closure.
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.
func NormalizeBareNumberArg ¶ added in v0.0.10
NormalizeBareNumberArg rewrites legacy -N shorthand (e.g. -5) to -n N so that pflag can parse it. Only a bare -<digits> token in the first argument position is rewritten; -<digits> appearing later in the argument list is left unchanged (matching GNU head/tail behavior where the obsolete form is only accepted as the first option). Processing stops at "--".
When the first argument is a value-taking flag (-n, -c, --lines, --bytes), the second argument is its value and must not be rewritten — even if it looks like -<digits> (e.g. "head -n -9223372036854775809").
valueFlags lists the flags that consume the next argument as a value (e.g. []string{"-n", "-c", "--lines", "--bytes"}).
func UnsupportedSummary ¶ added in v0.0.15
func UnsupportedSummary() []string
UnsupportedSummary returns a concise list of intentionally unsupported rshell functionality for display in the top-level help output.
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)
// ReadlinkFile returns the destination of a symbolic link within the
// shell's path restrictions.
ReadlinkFile func(ctx context.Context, path string) (string, 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
// HostPrefix returns the configured host-mount prefix used by
// container-style sandboxes to translate host-absolute paths
// (e.g. /var/log/pods/...) into the prefixed paths the sandbox can
// open (e.g. /mnt/host/var/log/pods/...). Returns "" when no prefix
// is configured. Builtins that resolve absolute symlink targets
// (e.g. pwd -P) use this to keep their output consistent with what
// the sandbox itself accepts.
HostPrefix func() string
// CanonicalizeRootPrefix translates a configured AllowedPaths root
// prefix in absPath to that root's canonical (symlink-resolved)
// form. Used by `pwd -P` so that when the sandbox root is itself a
// symlink (e.g. /tmp/link -> /tmp/real), the printed path reflects
// the resolution that os.Root has already followed implicitly. If
// absPath is outside every root or the matching root is not a
// symlink, the input is returned unchanged.
CanonicalizeRootPrefix func(absPath string) string
// ChangeDir mutates the shell's working directory. The supplied path
// must be absolute. Implementations validate that the target exists,
// is a directory, and lies inside AllowedPaths; on any failure the
// previous working directory is preserved and an error is returned.
// On success, $OLDPWD is set to the previous directory and $PWD is
// set to absDir. Used exclusively by the cd builtin.
ChangeDir func(absDir string) error
// LookupEnvVar reads an environment variable from the shell's
// overlay environment. Returns (value, true) if the variable is
// set, ("", false) otherwise. The cd builtin uses this to resolve
// $HOME (no-arg form) and $OLDPWD (the `cd -` form) without
// requiring a full WriteEnviron handle on every CallContext.
LookupEnvVar func(name string) (string, bool)
// 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)
// RunCommandWithStdin is like RunCommand but lets the caller supply a
// stdin reader for the child. Used by xargs to give children empty
// stdin (matching POSIX behavior of redirecting child stdin from
// /dev/null) while still reading items from the parent's stdin itself.
// If nil, callers should fall back to RunCommand.
RunCommandWithStdin func(ctx context.Context, dir string, name string, args []string, stdin io.Reader) (uint8, error)
// SetVar assigns a value to a shell variable in the calling shell's
// scope. Returns an error if the value exceeds the per-variable size
// limit or if the total variable-storage cap would be exceeded.
// Used by builtins that mutate parent-shell state, such as read.
SetVar func(name, value string) error
// GetVar returns the value of a shell variable. The bool reports
// whether the variable was set; an unset variable returns ("", false).
// Used by builtins that need to consult shell state, such as read
// reading IFS for field-splitting.
GetVar func(name string) (value string, ok bool)
// 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) 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
// NormalizeArgs, if non-nil, rewrites raw argument slices before pflag
// parsing. This allows commands to support legacy flag syntax that pflag
// cannot handle natively (e.g. head/tail -5 → -n 5).
NormalizeArgs func(args []string) []string
}
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
HasFlags bool // true when MakeFlags registers at least one flag
}
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 FeatureMeta ¶ added in v0.0.15
type FeatureMeta struct {
Name string
Description string
Supported []string
Unsupported []string
Notes []string
}
FeatureMeta holds metadata for an rshell language/runtime feature exposed by the help builtin. The list is maintained in Go code so `help` output stays deterministic and can be validated against builtin command names.
func Feature ¶ added in v0.0.15
func Feature(name string) (FeatureMeta, bool)
Feature returns the metadata for a named rshell feature. The returned FeatureMeta's Supported/Unsupported/Notes slices are independent copies — callers may freely mutate them without affecting the registry.
func Features ¶ added in v0.0.15
func Features() []FeatureMeta
Features returns rshell features in display order. The returned slice and each FeatureMeta's Supported/Unsupported/Notes slices are independent copies — callers may freely mutate them without affecting the registry.
type FileID ¶
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 ¶
Flag is a type alias for pflag.Flag, exposed so command files can use FlagSet.Visit without importing pflag directly.
type 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) GetSession ¶ added in v0.0.6
GetSession returns processes in the current process session.
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 cd implements the cd builtin command.
|
Package cd implements the cd 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 df implements the df builtin command.
|
Package df implements the df builtin command. |
|
Package du implements the du builtin command.
|
Package du implements the du 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
|
|
|
diskstats
Package diskstats reads mounted-filesystem usage information from the kernel and presents it as a normalised cross-platform Mount struct.
|
Package diskstats reads mounted-filesystem usage information from the kernel and presents it as a normalised cross-platform Mount struct. |
|
flagparser
Package flagparser bridges between pflag and the GNU-getopt wording that rshell builtins are expected to match.
|
Package flagparser bridges between pflag and the GNU-getopt wording that rshell builtins are expected to match. |
|
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. |
|
winpoll
Package winpoll provides a non-consuming readability probe for Windows file handles.
|
Package winpoll provides a non-consuming readability probe for Windows file handles. |
|
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 pwd implements the pwd builtin command.
|
Package pwd implements the pwd builtin command. |
|
Package read implements the read builtin command.
|
Package read implements the read 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. |
|
Package xargs implements the xargs builtin command.
|
Package xargs implements the xargs builtin command. |