Skip to content

Library Reference

Gordon T Watts edited this page Jan 26, 2026 · 1 revision

Library Reference

Complete overview of MAINFRAME's 77 libraries and 2,000+ functions.


Table of Contents


Core Libraries

These libraries form the foundation of MAINFRAME.

common.sh (Loader)

The main entry point that loads all other libraries.

source "$MAINFRAME_ROOT/lib/common.sh"

Key Functions:

  • mainframe version - Show version info
  • mainframe help - Show help
  • mainframe doctor - Check installation

Data Processing

json.sh (34 functions)

JSON creation and manipulation without jq.

Function Description Example
json_object Create JSON object json_object "name=John" "age:number=30"
json_array Create JSON array json_array "a" "b" "c"
json_get Get value from JSON json_get "$json" "name"
json_merge Merge two objects json_merge "$a" "$b"
json_pretty Pretty print JSON json_pretty "$json"
json_has Check if key exists json_has "$json" "name"
json_keys Get all keys json_keys "$json"
json_values Get all values json_values "$json"

csv.sh (34 functions)

RFC 4180 compliant CSV parsing.

Function Description Example
csv_row Create CSV row csv_row "name" "age" "city"
csv_parse_line Parse CSV line csv_parse_line "$line"
csv_get Get field by index csv_get "$line" 0
csv_to_json Convert to JSON csv_to_json < data.csv
csv_headers Get header row csv_headers < data.csv
csv_count Count rows csv_count < data.csv

pure-string.sh (34 functions)

String manipulation in pure bash.

Function Description Example
trim_string Trim whitespace trim_string " hello "
to_lower Lowercase to_lower "HELLO"
to_upper Uppercase to_upper "hello"
replace_all Replace all occurrences replace_all "a-b-c" "-" "_"
split_string Split into array split_string "a,b,c" ","
string_contains Check substring string_contains "hello" "ell"
starts_with Check prefix starts_with "hello" "hel"
ends_with Check suffix ends_with "hello" "lo"
substring Extract substring substring "hello" 1 3
pad_left Left pad pad_left "42" 5 "0"
pad_right Right pad pad_right "hi" 5 " "

pure-array.sh (33 functions)

Array operations in pure bash.

Function Description Example
array_unique Remove duplicates array_unique "${arr[@]}"
array_join Join with delimiter array_join "${arr[@]}" ", "
array_contains Check membership array_contains "${arr[@]}" "x"
array_sort Sort array array_sort "${arr[@]}"
array_reverse Reverse array array_reverse "${arr[@]}"
array_filter Filter with function array_filter fn "${arr[@]}"
array_map Map with function array_map fn "${arr[@]}"
array_reduce Reduce with function array_reduce fn init "${arr[@]}"
array_index Find index array_index "${arr[@]}" "x"
array_slice Get slice array_slice 1 3 "${arr[@]}"

template.sh (30 functions)

Mustache-style template rendering.

Function Description Example
template::render Render template template::render "$tpl" name=John
template::file Render file template::file "tpl.txt" name=John
template::escape Escape HTML template::escape "<script>"

System Operations

pure-file.sh (37 functions)

File operations without cat/head/tail.

Function Description Example
file_exists Check existence file_exists "/path/to/file"
file_size Get size in bytes file_size "/path/to/file"
file_lines Count lines file_lines "/path/to/file"
read_file Read contents read_file "/path/to/file"
write_file Write contents write_file "/path" "content"
head_lines First N lines head_lines "/path" 10
tail_lines Last N lines tail_lines "/path" 10

proc.sh (40 functions)

Process management.

Function Description Example
proc_exists Check if running proc_exists $pid
proc_find_by_port Find by port proc_find_by_port 8080
proc_find_by_name Find by name proc_find_by_name "nginx"
lockfile_acquire Acquire lock lockfile_acquire "/tmp/lock"
lockfile_release Release lock lockfile_release "/tmp/lock"
with_timeout Run with timeout with_timeout 5 long_command
with_lock Run under lock with_lock "/tmp/lock" cmd

env.sh (36 functions)

Environment variable management.

Function Description Example
env_set Set and export env_set "VAR" "value"
env_get Get with default env_get "VAR" "default"
env_require Require variable env_require "API_KEY"
env_load_dotenv Load .env file env_load_dotenv ".env"
env_path_prepend Add to PATH env_path_prepend "/opt/bin"
env_detect_shell Detect shell env_detect_shell

path.sh (30 functions)

Cross-platform path manipulation.

Function Description Example
path_normalize Normalize path path_normalize "/a//b/../c"
path_join Join paths path_join "/a" "b" "c"
path_is_safe Check traversal path_is_safe "/base" "$path"
path_absolute Get absolute path path_absolute "relative/path"
path_relative Get relative path path_relative "/a/b" "/a"
path_dir Get directory path_dir "/a/b/file.txt"
path_base Get basename path_base "/a/b/file.txt"
path_ext Get extension path_ext "/a/b/file.txt"

docker.sh (57 functions)

Docker and Compose helpers.

Function Description Example
docker_running Check daemon docker_running
docker_container_running Check container docker_container_running "nginx"
docker_exec Exec in container docker_exec "nginx" "cat /etc/nginx/nginx.conf"
docker_logs Get logs docker_logs "nginx" 100
compose_up Start services compose_up
compose_exec Exec in service compose_exec "web" "npm test"

Network and Crypto

http.sh (35 functions)

HTTP client in pure bash (uses /dev/tcp or openssl for HTTPS).

Function Description Example
http_get GET request http_get "http://api.example.com"
http_post POST request http_post "$url" "$body"
http_download Download file http_download "$url" "/local/path"
url_parse Parse URL url_parse "https://example.com/path"
query_string Build query string query_string "a=1" "b=2"

crypto.sh (17 functions)

Hashing and encoding.

Function Description Example
sha256 SHA-256 hash sha256 "data"
md5 MD5 hash md5 "data"
base64_encode Base64 encode base64_encode "hello"
base64_decode Base64 decode base64_decode "aGVsbG8="
random_token Secure random random_token 32

git.sh (52 functions)

Git workflow helpers.

Function Description Example
git_branch Current branch git_branch
git_is_dirty Check for changes git_is_dirty
git_commit_hash Short commit hash git_commit_hash
git_changed_files List changed files git_changed_files
git_summary JSON summary git_summary

datetime.sh (45 functions)

Date and time operations.

Function Description Example
now Unix timestamp now
now_iso ISO format now_iso
date_add Add duration date_add $(now) "2d"
date_subtract Subtract duration date_subtract $(now) "1w"
format_relative "2 hours ago" format_relative $ts
format_duration "1h 30m" format_duration 5400
is_weekend Check weekend is_weekend $(now)

Safety Layer

validation.sh (34 functions)

Input validation and sanitization.

Function Description Example
validate_int Validate integer validate_int "$n" 0 100
validate_email Validate email validate_email "$email"
validate_url Validate URL validate_url "$url"
validate_path_safe Prevent traversal validate_path_safe "$p" "/base"
sanitize_shell_arg Escape for shell sanitize_shell_arg "$input"
sanitize_filename Safe filename sanitize_filename "$name"
sanitize_html Escape HTML sanitize_html "$text"

guard.sh (21 functions)

Defensive guards.

Function Description Example
guard_not_empty Require non-empty guard_not_empty "$var" "var"
guard_file_exists Require file guard_file_exists "$path"
guard_disk_space Require disk space guard_disk_space "/var" 1024
guard_memory Require memory guard_memory 512
guard_lock Acquire lock guard_lock "/tmp/lock"

error.sh (25 functions)

Error handling and stack traces.

Function Description Example
try Try block try { risky_operation; }
catch Catch block catch { handle_error; }
throw Throw error throw "E_INVALID" "message"
stack_trace Print stack stack_trace
die Exit with error die 1 "Fatal error"

AI Agent Optimized

output.sh (25+ functions)

Universal Structured Output Protocol (USOP).

Function Description Example
output_success Success JSON output_success "done"
output_error Error JSON output_error "E_NOT_FOUND" "msg" "hint"
output_int Integer output output_int 42
output_bool Boolean output output_bool true
output_json_object JSON object output output_json_object '{"id":1}'
output_list List output output_list "a" "b" "c"

agent_safety.sh (28 functions)

Safe command execution for AI agents.

Function Description Example
agent_safe_exec Safe dispatch agent_safe_exec "ls" "-la"
agent_validate_command Validate command agent_validate_command "git"
agent_ensure_dir Idempotent mkdir agent_ensure_dir "/path"
agent_ensure_file Idempotent write agent_ensure_file "/path" "content"
agent_audit_log Audit logging agent_audit_log "action" "target"

agent_comm.sh (35 functions)

Multi-agent communication.

Function Description Example
agent_register Register agent agent_register "worker-1"
agent_send Send message agent_send "worker-2" "task" "$data"
agent_receive Receive messages agent_receive "worker-1" 10
agent_claim_task Claim task agent_claim_task "$task_id"

idempotent.sh (15+ functions)

Retry-safe operations.

Function Description Example
ensure_dir Create if missing ensure_dir "/path"
ensure_file Write if different ensure_file "/path" "content"
ensure_line Add if absent ensure_line "/file" "line"
ensure_symlink Link if needed ensure_symlink "/link" "/target"
ensure_command Install if missing ensure_command "jq" "jq"

atomic.sh (15+ functions)

Atomic file operations.

Function Description Example
atomic_write Atomic write atomic_write "/path" "content"
atomic_replace Atomic replace atomic_replace "/path" "new"
file_checkpoint Create checkpoint file_checkpoint "/path"
file_rollback Restore checkpoint file_rollback "/path"

observe.sh (20+ functions)

Structured observability.

Function Description Example
trace_start Start trace trace_start "operation"
trace_step Add step trace_step "step 1"
trace_end End trace trace_end
observe_command Observe command observe_command ls -la

Language Analysis

typescript.sh (22 functions)

TypeScript project analysis (no tsc required).

Function Description Example
ts_file_imports Extract imports ts_file_imports "src/index.ts"
ts_import_graph Dependency graph ts_import_graph "$dir"
ts_circular_deps Find circular deps ts_circular_deps "$dir"
ts_breaking_changes Detect breaking changes ts_breaking_changes "v1" "v2"

python.sh (17 functions)

Python project analysis (no Python required).

Function Description Example
py_file_imports Extract imports py_file_imports "app/main.py"
py_import_graph Dependency graph py_import_graph "$dir"
py_detect_manager Detect pip/poetry/etc py_detect_manager "$dir"
py_summary Project summary py_summary "$dir"

UI and CLI

ansi.sh (90 functions)

Terminal colors and styling.

Function Description Example
ansi_red Red text ansi_red "error"
ansi_green Green text ansi_green "success"
ansi_bold Bold text ansi_bold "important"
ansi_reset Reset formatting ansi_reset

tui.sh (30 functions)

Terminal UI components.

Function Description Example
progress_bar Show progress progress_bar 50 100
spinner Show spinner spinner "Loading..."
prompt User prompt prompt "Continue?" "y/n"
select_menu Selection menu select_menu "a" "b" "c"

cli.sh (35 functions)

Declarative CLI framework.

Function Description Example
cli_parse Parse arguments cli_parse "$@"
cli_option Define option cli_option "-v" "--verbose"
cli_command Define command cli_command "build" build_fn
cli_help Generate help cli_help

log.sh (30 functions)

Structured JSON logging.

Function Description Example
log_debug Debug level log_debug "details"
log_info Info level log_info "message"
log_warn Warning level log_warn "warning"
log_error Error level log_error "error"
log_json JSON log entry log_json "event" "data"

DevOps and CI/CD

ci.sh (35 functions)

CI/CD portability.

Function Description Example
ci_detect Detect CI system ci_detect
ci_is_pr Check if PR ci_is_pr
ci_branch Get branch name ci_branch
ci_commit Get commit hash ci_commit
ci_set_output Set CI output ci_set_output "key" "value"

health.sh (35 functions)

Health check framework.

Function Description Example
health_check Run health check health_check
health_add Add check health_add "db" check_db
health_server HTTP health server health_server 8080

Loading Libraries

Load All (Default)

source "$MAINFRAME_ROOT/lib/common.sh"

Load Specific Libraries

export MAINFRAME_ROOT="$HOME/.mainframe"

# Load only what you need
source "$MAINFRAME_ROOT/lib/pure-string.sh"
source "$MAINFRAME_ROOT/lib/json.sh"
source "$MAINFRAME_ROOT/lib/validation.sh"

Lazy Loading

# common.sh supports lazy loading
export MAINFRAME_LAZY=1
source "$MAINFRAME_ROOT/lib/common.sh"

# Libraries load on first function call

Complete Reference

For all 2,000+ function signatures with full documentation:

CHEATSHEET.md


MAINFRAME · The AI-Native Bash Runtime

Home · Quick Start · CHEATSHEET.md

Clone this wiki locally