rayvn/core
Core utilities, assertions and error handling.
Output & Error Functions
show()
Enhanced echo with text colors, styles, and standard echo options. Each FORMAT token applies to the immediately following TEXT arg only, then resets. Multiple FORMAT tokens before a TEXT arg accumulate for that one TEXT arg.
usage
show [-n] [-e|-E] [FORMAT|TEXT]...
-n | No trailing newline. |
-e | Enable backslash escape interpretation. |
-E | Suppress backslash escape interpretation. |
[FORMAT] (string) | A format token (see NOTES); applies to the next [TEXT] arg. |
[TEXT] (string) | A string to print with accumulated formats applied, then reset. |
notes
Available formats:
- Theme
primarysecondaryaccentsuccesserrorwarninginfomuted - Style
bolddimitalicunderlineblinkreversestrikethrough - Foreground
blackredgreenyellowbluemagentacyanwhite(andbright-*variants) - Background
bg-blackbg-redbg-greenbg-yellowbg-bluebg-magentabg-cyanbg-white(andbg-bright-*variants) - 256-color
IDX<0-255> - true-color
RGB<R:G:B> - Special
nl(insert newline),glue(suppress space before next arg)
While most modern terminals support 256-color or true-color (24 bit), stick to theme colors if compatibility is a concern — they automatically fall back to 16-color. Also be aware that some terminals do not support strikethrough.
example
show blue "blue text"
show bold red "bold red"
show -n yellow "no trailing newline"
show success "done"
show warning "check this"
show error "failed"
show italic underline green "italic underline green"
show bold blue "heading" "body text" # heading resets; body is plain
show cyan "colored" dim "dim, no color" # each arg gets its own format
show "Line 1" nl "Line 2" # newline between args
show bg-blue white "white on blue"
show IDX 42 "256-color #42" RGB 52:208:88 "truecolor"
show "(default:" blue "${configDir}" glue ")." # suppress space before closing paren
result="${ show bold green "ok"; }" # in command substitution
echo()
Shadows the bash builtin echo. Routes to the terminal device when stdout is a TTY, enabling tty capture in tests; see startTtyCapture(). Pass ‘-‘ as the first arg to write to stdout directly (bypasses TTY routing, e.g. when redirecting to another fd).
header()
Print a styled section header with an optional subtitle.
usage
header [-u] [colorIndex] header [subtitle...]
-u | Convert header to uppercase. |
colorIndex (int) | Color index: 0=bold, 1=primary, 2=accent, 3=secondary, 4=success, 5=warning, 6=error, 7=bold info. |
header (string) | Header text printed in index color. |
[subtitle] (string) | Subtitle text/formats printed via show. |
example
header "my header" # default bold header, no subtitle
header -u "${text}" "my subtitle" # uppercase bold header, plain subtitle
header 1 "my header" italic "my subtitle" # primary header, italic subtitle
commonOptions()
Prints common CLI options, optionally including a debug options section.
args
col (int) | Column width for option alignment (default: 21). |
includeDebug (bool) | Whether to print the debug options section (default: ‘true’). |
option()
Prints a formatted option line with the option name padded to a description column.
args
option (string) | The option name or flag to display. |
description (string) | The description text to print after padding. |
descriptionColumn (int) | Column position for the description (default: 21). |
warn()
Print a warning message to stderr with a ⚠️ prefix.
usage
warn message [FORMAT|TEXT]...
message (string) | Warning message text. |
[FORMAT] (string) | A show format token; applies to the next [TEXT] arg. |
[TEXT] (string) | Text to print with the preceding format applied. |
error()
Print an error message to stderr with a 🔺 prefix.
usage
error message [FORMAT|TEXT]...
message (string) | Error message text. |
[FORMAT] (string) | A show format token; applies to the next [TEXT] arg. |
[TEXT] (string) | Text to print with the preceding format applied. |
invalidArgs()
Fail with a stack trace. Shorthand for fail –trace on invalid arguments.
usage
invalidArgs message [FORMAT|TEXT]...
message (string) | Error message text. |
[FORMAT] (string) | A show format token; applies to the next [TEXT] arg. |
[TEXT] (string) | Text to print with the preceding format applied. |
fail()
Print an error and exit 1, optionally with a stack trace if in debug mode or explicitly with –trace.
usage
fail [--trace] message [FORMAT|TEXT]...
--trace | Force a stack trace regardless of debug mode. |
message (string) | Error message text. |
[FORMAT] (string) | A show format token; applies to the next [TEXT] arg. |
[TEXT] (string) | Text to print with the preceding format applied. |
bye()
Print an optional exit message, show stack if in debug mode, and exit 0.
usage
bye [message [FORMAT|TEXT]...]
[message] (string) | Exit message text. |
[FORMAT] (string) | A show format token; applies to the next [TEXT] arg. |
[TEXT] (string) | Text to print with the preceding format applied. |
stackTrace()
Print a formatted call stack, optionally preceded by a message.
usage
stackTrace [message [FORMAT|TEXT]...]
[message] (string) | Message text. |
[FORMAT] (string) | A show format token; applies to the next [TEXT] arg. |
[TEXT] (string) | Text to print with the preceding format applied. |
errorStream()
Print each line of a piped stream in error color to stderr.
example
someCommand 2> >( errorStream )
Argument & Variable Functions
parseOptionalArg()
Check if an argument matches an expected value, setting a result var via nameref.
args
argMatch (string) | Expected argument value to match against (e.g. -n). |
argValue (string) | Actual argument value to test. |
argResultRef (stringRef) | Name of var to set to argResultValue on match, or ‘’ if not. |
argResultValue (string) | Value to assign on match; defaults to ${argMatch}. |
returns
0 | matched |
1 | not matched |
booleanAsInteger()
Maps a boolean argument to 1 for true, 0 for false so that it can subsequently be tested using (( flag )).
args
arg (bool) | The boolean argument: ‘true’ or ‘false’ (case in-sensitive), 1 or 0. |
resultRef (stringRef) | Name of var to set result. |
example
local doX; booleanAsInteger "$1" doX # Set doX
local doY; booleanAsInteger "${1:-true}" doY # Set doY with default value.
varDefined()
Return 0 if a variable with the given name is defined, including empty or null-value vars.
assertVarDefined()
Fail if a variable with the given name is not defined.
eraseVars()
Overwrite one or more security sensitive variables with spaces then unset.
args
varName (stringRef) | Name of a variable to erase; may be repeated, silently ignored if unset. |
exportGlobalMaps()
Register one or more associative arrays (passed by name) for export to child processes. Bash cannot export associative arrays directly; this serializes them into an internal exported variable. When a child process sources rayvn.up, the map(s) will be restored. Needed when a script spawns a child process (e.g. via bash or exec) that sources rayvn.up and calls functions that depend on the map. Not needed for subshells (${ } and $( )), which inherit variables automatically. Call from a library _init function.
args
varName (stringRef) | Name of an associative array to register; may be repeated. |
example
# In 'myproject/mylib' _init_myproject_mylib(), build a lookup table, then register it so that
# child processes launched by the user's script (e.g. bash myOtherScript) see the populated map.
declare -gA myLookup=([foo]=1 [bar]=2)
exportGlobalMaps myLookup
Assertion Functions
assertIsInteractive()
Fail with an error if not running interactively.
assertFileExists()
Fails if the given path does not exist.
assertFile()
Fail if the given path does not exist or is not a regular file.
args
file (string) | Path that must exist and be a regular file. |
description (string) | Label used in the error message (default: “file”). |
assertDirectory()
Fail if the given path does not exist or is not a directory.
assertFileDoesNotExist()
Fail if the given path already exists.
assertPathWithinDirectory()
Fails if filePath is not located within dirPath, resolving symlinks before checking.
args
filePath (string) | Path to verify. |
dirPath (string) | Directory that must contain filePath. |
assertValidFileName()
Fail if name is not a valid cross-platform filename component.
args
name (string) | Filename component to validate (not a full path). |
notes
Rejects: empty string, . .. / control characters <>:”|?*
assertGitRepo()
Fail if the given directory (or PWD) is not within a git repository.
args
dir (string) | Directory to check (default: ${PWD}). |
assertCommand()
Run a command and fail if it exits non-zero or produces any stderr output.
usage
assertCommand [--transform FUNC] [--quiet] [--error MSG] command...
--transform FUNC (string) | Function name called as FUNC “stderr” to transform stderr before use in failure messages. |
--quiet | Suppress stderr content from the failure message. |
--error MSG (string) | Custom failure message (default: stderr output or generic exit code message). |
... (string) | The command and arguments to execute. |
example
session="${ assertCommand --error "Failed to unlock" bw unlock --raw; }"
# For pipelines, wrap in eval:
assertCommand --transform myStderrTransform --error "Failed" eval 'cmd1 | cmd2 > "${file}"'
trim()
Outputs a string with leading and trailing whitespace removed.
repeat()
Outputs a string repeated N times, without a trailing newline.
args
str (string) | String to repeat. |
count (int) | Number of repetitions. |
padString()
Outputs a string padded to a given width, measuring visible length by stripping ANSI codes.
args
string (string) | Target string. |
width (int) | Minimum visible character width. |
position (string) | Optional padding side: ‘after’/’left’ (default), ‘before’/’right’, or ‘center’. |
stripAnsi()
Outputs a string with any ANSI escape sequences removed.
containsAnsi()
Return 0 if a string contains ANSI escape sequences, 1 otherwise.
indexOf()
Find the index of a matching element in an array, storing the result in resultRef (-1 if not found).
args
match (string) | Match value; prefix with -p for prefix match, -s for suffix match, -r for regex. |
arrayRef (arrayRef) | Name of the indexed array to search. |
resultRef (stringRef) | Name of the variable to store the found index. |
returns
0 | match found |
1 | no match found |
memberOf()
Return 0 if item is a member of an array, 1 otherwise.
args
item (string) | Value to search for. |
arrayRef (arrayRef) | Name of the indexed array to search. |
maxArrayElementLength()
Outputs the length of the longest element in an array.
args
arrayRef (arrayRef) | Name of the indexed array to measure. |
copyMap()
Copy all key-value pairs from one associative array to another.
args
src | (mapRef) Name of the source map. |
dest | (mapRef) Name of the destination map (must already be declared with -A). |
Number & Random Value Functions
numericPlaces()
Outputs the number of decimal digits needed to represent integers up to maxValue.
args
maxValue (int) | Largest value to represent; must be a positive integer. |
startValue (int) | Index base: 0 (zero-indexed, default) or 1 (one-indexed). |
printNumber()
Outputs a number right-aligned within a fixed-width field.
args
number (int) | Number to output. |
places (int) | Minimum field width; defaults to 1. |
printList()
Prints a numbered list of items, with right-aligned numbers padded to a consistent width.
args
[--indent N] (int) | Leading spaces before each item; defaults to 4. |
items | (string…) Items to list; each becomes one numbered line. |
randomInteger()
Set a variable to a random integer, optionally capped at maxValue (inclusive).
args
intResult (stringRef) | Variable to receive the result. |
maxValue (int) | Optional inclusive upper bound; omits for full SRANDOM range. |
randomHexChar()
Set a random hex character (0–9, a–f) via nameref.
args
_hexResultRef (stringRef) | Name of the variable to receive the result. |
randomHexString()
Generate a random hex string of count characters, stored via nameref.
args
count (int) | Number of hex characters to generate. |
_resultRef (stringRef) | Name of the variable to receive the result. |
replaceRandomHex()
Replace every occurrence of a placeholder character in a string with random hex chars, in-place.
args
replaceChar (string) | The placeholder character to replace. |
replaceRef (stringRef) | Name of the variable to modify in-place. |
example
myStr="XXXX-XXXX"
replaceRandomHex "X" myStr # myStr becomes e.g. "3a7f-c209"
Time Functions
timeStamp()
Outputs the current timestamp as a sortable string: YYYY-MM-DD_HH.MM.SS_TZ
epochSeconds()
Outputs the current epoch time with microsecond precision via EPOCHREALTIME.
elapsedEpochSeconds()
Outputs elapsed seconds since a previously captured EPOCHREALTIME value (6 decimal places).
args
startTime (string) | Value previously captured from EPOCHREALTIME. |
File System Functions
withDefaultUmask()
Execute a command with umask 0022 (files readable by all, writable only by owner).
withUmask()
Execute a command with a temporary umask, restoring the original afterward.
args
newUmask (string) | Umask to set for the duration (e.g. 0022, 0077). |
command (string) | Command and arguments to execute. |
binaryPath()
Outputs the path to a binary, or fails with an optional custom error message if not found.
args
name (string) | Name of the binary to locate in PATH. |
errMsg (string) | Error message if not found; defaults to “’${name}’ not found”. |
tempDirPath()
Outputs the session temp directory path, optionally appended with a file name. Does not create the file or dir.
usage
tempDirPath [-r] [fileName]
-r | Replace ‘X’ chars in fileName with random hex chars, or generate an 8-char hex name if |
fileName (string) | Optional file name to append to the temp dir path. |
makeTempFile()
Creates a unique temp file in the session temp dir, outputting its path.
args
fileName (string) | Optional; see tempDirPath -r. |
makeTempFifo()
Creates a unique named pipe (FIFO) in the session temp dir, outputting its path.
args
fileName (string) | Optional; see tempDirPath -r. |
makeTempDir()
Create a unique temp directory in the session temp directory, outputting its path.
args
dirName (string) | Optional; see tempDirPath -r. |
makeSecureTempDir()
Create a unique temp directory backed by RAM when possible, storing the path in dirRef.
args
dirRef (stringRef) | Variable to receive the directory path. |
isRamBackedRef (stringRef) | Optional variable name; receives 1 if RAM-backed, 0 if disk-backed (default temp). |
sizeMb (int) | Optional RAM disk size in MB for hdiutil fallback (default: 64). |
notes
Strategy, in order of preference:
- Existing tmpfs/shm (set by rayvn-tmp or Linux /dev/shm): zero overhead.
- hdiutil RAM disk (macOS only, no sudo required): ~1–2s overhead to format and mount. An exit handler is registered automatically to detach the disk on exit.
- Regular mktemp: no overhead, but not RAM-backed; isRamBackedRef receives 0.
Callers that require RAM-backing (e.g. to ensure sensitive data never touches disk) should check isRamBackedRef and warn or abort when it is 0.
configDirPath()
Outputs the config directory path for the current or specified project, creating it if needed, optionally joined with fileName.
args
-p PROJECT (string) | Specify project name (default: ${currentProjectName}) |
fileName (string) | Optional name of a file to append to the config dir path. |
ensureDir()
Create directory if it does not already exist.
makeDir()
Create a directory (and any missing parents), outputting the final path.
args
dir (string) | Base directory path. |
subDir (string) | Optional subdirectory to append before creating. |
dirName()
Outputs the directory component of a path, equivalent to dirname.
baseName()
Outputs the final component of a path, equivalent to basename.
tildePath()
Outputs a path with the home directory prefix replaced by ‘~’.
readFile()
Read the entire contents of a file into a variable, without forking a subprocess. Trailing newlines are stripped, matching command substitution behavior.
usage
readFile [-p] file resultVar
-p | Preserve trailing newlines instead of stripping them. |
file (string) | Path to the file to read. |
resultVar (stringRef) | Name of variable to receive the file contents. |
setFileVar()
Set a nameref variable to the realpath of a file, failing if the path is not a regular file.
args
resultVar (stringRef) | Name of variable to receive the resolved file path. |
filePath (string) | Path to the file (must exist and be a regular file). |
description (string) | Label used in error messages. |
setDirVar()
Set a nameref variable to the realpath of a directory, failing if the path is not a directory.
args
resultVar (stringRef) | Name of variable to receive the resolved directory path. |
dirPath (string) | Path to the directory (must exist and be a directory). |
description (string) | Label used in error messages. |
Process & Environment Functions
pushIFS()
Push a new value onto the IFS stack and set IFS to that value. Use popIFS to restore the previous value.
args
newIFS (string) | The new IFS value. |
example
pushIFS $'\n'
for item in ${list}; do ...
popIFS
popIFS()
Pop a previously pushed IFS value, restoring IFS to its prior state.
example
pushIFS $'\n'
popIFS
addExitHandler()
Register a shell command to be executed at exit, in registration order.
projectVersion()
Outputs the version string for a rayvn project, reading its rayvn.pkg file.
args
projectName (string) | Name of the project (e.g. ‘rayvn’, ‘valt’). |
verbose (string) | If non-empty, appends release date or “(development)” to output. |
openUrl()
Open a URL in the default browser (macOS: open, Linux: xdg-open).
args
url (string) | The URL to open. |
executeClean()
Execute a command with rayvn internal variables unset, simulating a clean environment.
setDebug()
Enable debug mode.
usage
setDebug [OPTIONS]
--debug | Enable debug, write output to log file and show on exit. |
--debug-new | Enable debug, clear log file, write output to log file and show on exit. |
--debug-out | Enable debug, write output to the current terminal. |
--debug-tty TTY (string) | Enable debug, write output to the specified TTY (e.g., /dev/ttys001). |
--debug-tty . (string) | Enable debug, write output to the TTY path read from ~/.debug.tty. |