Skip to content

Instantly share code, notes, and snippets.

@jpcofr
Created April 14, 2026 05:28
Show Gist options
  • Select an option

  • Save jpcofr/9f008e872a984da7d7bc2a23c1dec2b3 to your computer and use it in GitHub Desktop.

Select an option

Save jpcofr/9f008e872a984da7d7bc2a23c1dec2b3 to your computer and use it in GitHub Desktop.
Bash UI library

Script UI Library

Professional bash UI/UX library providing consistent look and feel across all bash scripts.

Overview

The UI library (scripts/lib/ui.sh) provides a comprehensive set of functions for creating consistent, professional-looking terminal output with:

  • Consistent color scheme across all scripts
  • Box drawing for headers and footers
  • Interactive prompts with standardized behavior
  • Status indicators (checkmarks, crosses, bullets)
  • Formatted output (key-value pairs, sections, tables)
  • Error handling with helpful suggestions

Quick Start

#!/bin/bash
# Load the UI library
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/ui.sh"

# Use UI functions
ui_box_header "My Script Title" 40
ui_nl

ui_step "Performing operation..."
# ... do work ...
ui_check "Operation completed"

ui_nl
ui_box_footer_success "✅ All done!" 40

Color Scheme

Color Variable Usage
Red UI_RED Errors, failures
Green UI_GREEN Success, completions
Yellow UI_YELLOW Warnings, prompts
Blue UI_BLUE Information, headers
Cyan UI_CYAN Highlights, steps
Gray UI_GRAY Separators, muted text

All colors automatically reset to UI_NC (no color) after use.

Function Reference

Box Drawing

ui_box_header "Title" [width]

Creates a boxed header with centered title.

ui_box_header "My Script Title" 40
# Output:
# ╔════════════════════════════════════════╗
# ║     My Script Title                    ║
# ╚════════════════════════════════════════╝

ui_box_footer_success "Message" [width]

Creates a green success footer box.

ui_box_footer_success "✅ Build Complete!" 40

ui_box_footer_error "Message" [width]

Creates a red error footer box.

ui_box_footer_error "❌ Build Failed" 40

Messages

ui_error "Message"

Prints error message in red (to stderr).

ui_error "File not found"

ui_warn "Message"

Prints warning message in yellow (to stderr).

ui_warn "Configuration file missing, using defaults"

ui_info "Message"

Prints informational message in blue.

ui_info "Processing files..."

ui_success "Message"

Prints success message in green.

ui_success "✓ All tests passed"

ui_highlight "Message"

Prints highlighted message in cyan.

ui_highlight "Method: AddressSanitizer (ASan)"

Progress Indicators

ui_step "Description"

Indicates a step in progress (▶️ icon).

ui_step "Compiling source files..."

ui_bullet "Item"

Prints a bullet point item.

ui_bullet "main.cpp"
ui_bullet "utils.cpp"

ui_check "Item"

Prints an item with checkmark (✓).

ui_check "Build completed successfully"

ui_cross "Item"

Prints an item with cross mark (✗).

ui_cross "Optional feature disabled"

Thematic Icons

ui_clean "Cleaning build directory..."  # 🧹
ui_inspect "Verifying output..."        # 🔍
ui_config "Loading configuration..."    # ⚙️
ui_launch "Starting application..."     # 🚀
ui_video "Generating video..."          # 🎬

Interactive Functions

ui_confirm "Question" [default_yes]

Asks yes/no question, returns 0 for yes, 1 for no.

if ui_confirm "Continue with build?" true; then
    echo "Building..."
else
    echo "Cancelled"
fi

# With default No:
if ui_confirm "Delete files?" false; then
    rm -rf temp/
fi

ui_input "Prompt" [default]

Gets input from user with optional default value.

name=$(ui_input "Enter name: " "default_name")
port=$(ui_input "Enter port: ")

ui_progress "Message"

Displays animated spinner (background process).

ui_progress "Building..." &
SPINNER_PID=$!
# ... do long-running work ...
kill $SPINNER_PID 2>/dev/null

Validation Functions

ui_require_command "cmd" "install_hint"

Checks if command exists, shows installation hint if not.

if ! ui_require_command "cmake" "brew install cmake"; then
    exit 1
fi

ui_require_file "path" "hint"

Checks if file exists.

if ! ui_require_file "config.toml" "Run: cp config.example.toml config.toml"; then
    exit 1
fi

ui_require_dir "path" "hint"

Checks if directory exists.

if ! ui_require_dir "build" "Run: mkdir build && cd build && cmake .."; then
    exit 1
fi

Section Functions

ui_section "Title"

Prints a major section header.

ui_section "Build Configuration"
# Output:
# ═══════════════════════════════════════
#   Build Configuration
# ═══════════════════════════════════════

ui_subsection "Title"

Prints a subsection header.

ui_subsection "Environment Variables"
# Output:
# ▶ Environment Variables

Table Functions

ui_keyval "Key" "Value" [indent]

Prints a key-value pair with alignment.

ui_keyval "Build Type" "Debug"
ui_keyval "Compiler" "clang++"
# Output:
#   Build Type:               Debug
#   Compiler:                 clang++

ui_keyval_color "Key" "Value" [color] [indent]

Prints a colored key-value pair.

ui_keyval_color "Status" "Running" "$UI_GREEN"

Error Handling

ui_die "Message" [exit_code]

Prints error and exits with code (default: 1).

ui_die "Critical error occurred" 1

ui_error_suggest "Error" "Suggestion"

Prints error with helpful suggestion.

ui_error_suggest "Build failed" "Try running: ./scripts/build.sh -c"

Utility Functions

ui_separator [character]

Prints a horizontal separator line.

ui_separator      # Default: ----
ui_separator "="  # Custom: ====

ui_nl [count]

Prints empty line(s).

ui_nl      # One blank line
ui_nl 3    # Three blank lines

ui_center "Text" [width]

Centers text within specified width.

ui_center "My Script Title" 80

Help Formatting

ui_help_section "Title"

Formats help section headers.

ui_help_section "Options"

ui_help_option "flag" "description"

Formats help option entries.

ui_help_option "-r, --release" "Build in release mode"
ui_help_option "-v, --verbose" "Verbose output"

ui_help_example "command" "description"

Formats help examples.

ui_help_example "./build.sh -r" "Release build"
ui_help_example "./build.sh -c -r" "Clean release build"

Complete Example Script

#!/bin/bash
set -e

# Load UI library
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/ui.sh"

# Show header
ui_box_header "🎯 My Build Script" 40
ui_nl

# Validate requirements
if ! ui_require_command "cmake" "brew install cmake"; then
    exit 1
fi

# Interactive prompt
if ! ui_confirm "Start build?" true; then
    ui_warn "Build cancelled"
    exit 0
fi

# Show configuration
ui_section "Build Configuration"
ui_keyval "Build Type" "Debug"
ui_keyval "Generator" "Ninja"
ui_keyval "Jobs" "8"
ui_nl

# Perform build steps
ui_step "Configuring CMake..."
cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug ..

ui_step "Building binaries..."
ninja -j8
ui_check "Build completed"

ui_nl

# Show results
ui_box_footer_success "✅ Build Successful!" 40
ui_nl

ui_subsection "Output"
ui_keyval "Binary" "./build/bin/myapp"
ui_nl

ui_info "Run: ./build/bin/myapp"

Design Principles

  1. Consistency: All scripts use the same color scheme and formatting
  2. Readability: Clear visual hierarchy with boxes, sections, and bullets
  3. User-friendly: Interactive prompts with sensible defaults
  4. Professional: Clean output suitable for both interactive and CI/CD use
  5. Maintainable: Centralized UI logic makes updates easy

Migration Guide

Before (Old Style)

echo -e "${GREEN}Starting build...${NC}"
echo ""
if [ ! -f "$FILE" ]; then
    echo -e "${RED}Error: File not found${NC}"
    exit 1
fi
echo -e "  ${BLUE}${NC} Building..."
echo -e "${GREEN}✓ Done${NC}"

After (New Style)

ui_success "Starting build..."
ui_nl
if ! ui_require_file "$FILE" "Create file first"; then
    exit 1
fi
ui_bullet "Building..."
ui_check "Done"

All Refactored Scripts

The following scripts now use the UI library:

  • build.sh - Main build script
  • quick-test.sh - Quick functionality test
  • test-video.sh - Video generation test
  • test-leaks.sh - Memory leak testing
  • run-hooks.sh - Pre-commit hooks runner

Benefits

For Developers

  • Faster script writing - reusable components
  • Consistent UX - users know what to expect
  • Less boilerplate - no more color code duplication
  • Better error handling - standardized patterns

For Users

  • Professional appearance - polished terminal output
  • Clear visual hierarchy - easy to scan output
  • Helpful prompts - standardized yes/no questions
  • Better error messages - contextual help included

Future Enhancements

Potential additions to the library:

  • Progress bars for long operations
  • Multi-column table formatting
  • More sophisticated menu systems
  • Logging to file alongside terminal output
  • Theme support (dark/light modes)
  • Emoji support toggle for environments that don't support them

Contributing

When adding new UI functions:

  1. Follow the naming convention: ui_<category>_<action>
  2. Add documentation in this README
  3. Export the function at the end of ui.sh
  4. Keep color usage consistent with existing patterns
  5. Test on both macOS and Linux if possible

See Also

UI Library Quick Reference Card

Loading the Library

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/ui.sh"

Most Common Functions

Headers & Footers

ui_box_header "Title" 40           # Boxed header
ui_box_footer_success "✅ Done" 40 # Success box
ui_box_footer_error "❌ Failed" 40 # Error box

Messages

ui_error "Something failed"        # Red error (stderr)
ui_warn "Careful!"                 # Yellow warning (stderr)
ui_info "FYI: information"         # Blue info
ui_success "It worked!"            # Green success
ui_highlight "Important detail"    # Cyan highlight

Progress Indicators

ui_step "Doing something..."       # ▶️ Step indicator
ui_bullet "Item"                   # • Bullet point
ui_check "Completed"               # ✓ Checkmark
ui_cross "Skipped"                 # ✗ Cross mark

Thematic Icons

ui_clean "Cleaning..."             # 🧹
ui_inspect "Checking..."           # 🔍
ui_config "Configuring..."         # ⚙️
ui_launch "Starting..."            # 🚀
ui_video "Recording..."            # 🎬

Interactive

# Yes/no prompt (returns 0=yes, 1=no)
if ui_confirm "Continue?" true; then
    # User said yes (true = default yes)
fi

# Get input
name=$(ui_input "Your name: " "default")

Validation

ui_require_command "cmake" "brew install cmake" || exit 1
ui_require_file "config.toml" "Create it first" || exit 1
ui_require_dir "build/" "Run cmake first" || exit 1

Sections

ui_section "Major Section"         # ═══ header ═══
ui_subsection "Subsection"         # ▶ header

Key-Value Pairs

ui_keyval "Build Type" "Debug"     # Aligned table
ui_keyval_color "Status" "OK" "$UI_GREEN"

Error Handling

ui_die "Fatal error" 1             # Print & exit
ui_error_suggest "Failed" "Try: make clean"

Utilities

ui_nl                              # Blank line
ui_nl 3                            # 3 blank lines
ui_separator                       # --------
ui_separator "="                   # ========

Help Formatting

ui_help_section "Options"
ui_help_option "-v, --verbose" "Verbose output"
ui_help_example "./script -v" "With verbose"

Color Constants

UI_RED      # Errors
UI_GREEN    # Success
UI_YELLOW   # Warnings
UI_BLUE     # Info
UI_CYAN     # Highlights
UI_GRAY     # Muted
UI_NC       # No color (reset)

Typical Script Structure

#!/bin/bash
set -e

# 1. Load library
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/ui.sh"

# 2. Show header
ui_box_header "My Script Title" 40
ui_nl

# 3. Validate requirements
ui_require_command "cmake" "brew install cmake" || exit 1

# 4. Interactive prompt
if ! ui_confirm "Start?" true; then
    ui_warn "Cancelled"
    exit 0
fi

# 5. Show config
ui_section "Configuration"
ui_keyval "Option" "Value"
ui_nl

# 6. Do work with progress
ui_step "Processing..."
# ... work ...
ui_check "Done"

# 7. Show results
ui_nl
ui_box_footer_success "✅ Complete!" 40
ui_nl

ui_subsection "Output"
ui_keyval "Result" "/path/to/output"

Common Patterns

Check then proceed

if ! ui_require_file "$FILE" "Create it first"; then
    exit 1
fi

Show status

ui_step "Building..."
if make; then
    ui_check "Build successful"
else
    ui_cross "Build failed"
    exit 1
fi

List items

ui_info "Files processed:"
for file in *.txt; do
    ui_bullet "$file"
done

Configuration display

ui_section "Settings"
ui_keyval "Mode" "$MODE"
ui_keyval "Output" "$OUTPUT_DIR"
ui_keyval "Verbose" "$VERBOSE"
ui_nl

Multiple options help

ui_help_section "Options"
ui_help_option "-h, --help" "Show help"
ui_help_option "-v, --verbose" "Verbose mode"
ui_nl

ui_help_section "Examples"
ui_help_example "./script -v" "Verbose"
ui_help_example "./script --help" "Help"

Tips

  1. Always use ui_nl instead of echo ""
  2. Exit codes: 0 = success, 1 = error
  3. Errors to stderr: ui_error and ui_warn go to stderr
  4. Consistent widths: Use 40 for narrow, 80 for wide boxes
  5. Color sparingly: Too many colors = visual noise
  6. Test interactively: Make sure prompts work as expected

See Full Docs

scripts/lib/README.md - Complete API reference with examples

#!/bin/bash
# UI Library
# Common UI/UX functions for consistent user interaction across all scripts
#
# Usage: source "$(dirname "$0")/lib/ui.sh"
# ============================================================================
# COLOR SUPPORT DETECTION
# ============================================================================
# Detect if terminal supports colors
# Checks: output is to terminal, tput exists, and terminal supports 8+ colors
if [[ -t 1 ]] && command -v tput &> /dev/null && [[ $(tput colors 2>/dev/null) -ge 8 ]]; then
UI_COLOR_ENABLED=true
else
UI_COLOR_ENABLED=false
fi
# ============================================================================
# COLOR DEFINITIONS
# ============================================================================
# ANSI color codes for consistent terminal output (disabled if not supported)
if [ "$UI_COLOR_ENABLED" = true ]; then
readonly UI_RED='\033[0;31m'
readonly UI_GREEN='\033[0;32m'
readonly UI_YELLOW='\033[1;33m'
readonly UI_BLUE='\033[0;34m'
readonly UI_CYAN='\033[0;36m'
# shellcheck disable=SC2034 # provided for library consumers
readonly UI_MAGENTA='\033[0;35m'
# shellcheck disable=SC2034 # provided for library consumers
readonly UI_WHITE='\033[1;37m'
readonly UI_GRAY='\033[0;90m'
readonly UI_NC='\033[0m' # No Color
else
# No color support - use empty strings for clean output
readonly UI_RED=''
readonly UI_GREEN=''
readonly UI_YELLOW=''
readonly UI_BLUE=''
readonly UI_CYAN=''
# shellcheck disable=SC2034 # provided for library consumers
readonly UI_MAGENTA=''
# shellcheck disable=SC2034 # provided for library consumers
readonly UI_WHITE=''
readonly UI_GRAY=''
readonly UI_NC=''
fi
# ============================================================================
# BOX DRAWING CHARACTERS
# ============================================================================
readonly UI_BOX_TL='╔' # Top Left
readonly UI_BOX_TR='╗' # Top Right
readonly UI_BOX_BL='╚' # Bottom Left
readonly UI_BOX_BR='╝' # Bottom Right
readonly UI_BOX_H='═' # Horizontal
readonly UI_BOX_V='║' # Vertical
# ============================================================================
# FORMATTING FUNCTIONS
# ============================================================================
# Print a horizontal line of specified length
# Usage: ui_line [length] [character]
ui_line() {
local length="${1:-40}"
local char="${2:-${UI_BOX_H}}"
printf "%${length}s" | tr ' ' "$char"
}
# Print a box header with title
# Usage: ui_box_header "Title" [width]
ui_box_header() {
local title="$1"
local width="${2:-40}"
local padding=$(( (width - ${#title} - 4) / 2 ))
echo -e "${UI_BLUE}${UI_BOX_TL}$(ui_line "$width")${UI_BOX_TR}${UI_NC}"
printf '%s' "${UI_BLUE}${UI_BOX_V}${UI_NC}"
printf "%${padding}s" ""
printf "${UI_BLUE} %s ${UI_NC}" "$title"
printf "%${padding}s" ""
printf '%s\n' "${UI_BLUE}${UI_BOX_V}${UI_NC}"
echo -e "${UI_BLUE}${UI_BOX_BL}$(ui_line "$width")${UI_BOX_BR}${UI_NC}"
}
# Print a box footer (success)
# Usage: ui_box_footer_success "Message" [width]
ui_box_footer_success() {
local message="$1"
local width="${2:-40}"
local padding=$(( (width - ${#message} - 4) / 2 ))
echo -e "${UI_GREEN}${UI_BOX_TL}$(ui_line "$width")${UI_BOX_TR}${UI_NC}"
printf '%s' "${UI_GREEN}${UI_BOX_V}${UI_NC}"
printf "%${padding}s" ""
printf "${UI_GREEN} %s ${UI_NC}" "$message"
printf "%${padding}s" ""
printf '%s\n' "${UI_GREEN}${UI_BOX_V}${UI_NC}"
echo -e "${UI_GREEN}${UI_BOX_BL}$(ui_line "$width")${UI_BOX_BR}${UI_NC}"
}
# Print a box footer (error)
# Usage: ui_box_footer_error "Message" [width]
ui_box_footer_error() {
local message="$1"
local width="${2:-40}"
local padding=$(( (width - ${#message} - 4) / 2 ))
echo -e "${UI_RED}${UI_BOX_TL}$(ui_line "$width")${UI_BOX_TR}${UI_NC}"
printf '%s' "${UI_RED}${UI_BOX_V}${UI_NC}"
printf "%${padding}s" ""
printf "${UI_RED} %s ${UI_NC}" "$message"
printf "%${padding}s" ""
printf '%s\n' "${UI_RED}${UI_BOX_V}${UI_NC}"
echo -e "${UI_RED}${UI_BOX_BL}$(ui_line "$width")${UI_BOX_BR}${UI_NC}"
}
# ============================================================================
# MESSAGE FUNCTIONS
# ============================================================================
# Print an error message
# Usage: ui_error "Message"
ui_error() {
echo -e "${UI_RED}Error: $1${UI_NC}" >&2
}
# Print a warning message
# Usage: ui_warn "Message"
ui_warn() {
echo -e "${UI_YELLOW}Warning: $1${UI_NC}" >&2
}
# Print an info message
# Usage: ui_info "Message"
ui_info() {
echo -e "${UI_BLUE}$1${UI_NC}"
}
# Print a success message
# Usage: ui_success "Message"
ui_success() {
echo -e "${UI_GREEN}$1${UI_NC}"
}
# Print a highlighted message
# Usage: ui_highlight "Message"
ui_highlight() {
echo -e "${UI_CYAN}$1${UI_NC}"
}
# Print a step indicator
# Usage: ui_step "Step description"
ui_step() {
echo -e "${UI_CYAN}▶️ $1${UI_NC}"
}
# Print a bullet point
# Usage: ui_bullet "Item"
ui_bullet() {
echo -e " ${UI_BLUE}•${UI_NC} $1"
}
# Print a checkmark item
# Usage: ui_check "Item"
ui_check() {
echo -e " ${UI_GREEN}✓${UI_NC} $1"
}
# Print a cross item
# Usage: ui_cross "Item"
ui_cross() {
echo -e " ${UI_RED}✗${UI_NC} $1"
}
# Print a cleaning/maintenance indicator
# Usage: ui_clean "Description"
ui_clean() {
echo -e "${UI_CYAN}🧹 $1${UI_NC}"
}
# Print an inspection indicator
# Usage: ui_inspect "Description"
ui_inspect() {
echo -e "${UI_CYAN}🔍 $1${UI_NC}"
}
# Print a gear/configuration indicator
# Usage: ui_config "Description"
ui_config() {
echo -e "${UI_BLUE}⚙️ $1${UI_NC}"
}
# Print a rocket/launch indicator
# Usage: ui_launch "Description"
ui_launch() {
echo -e "${UI_BLUE}🚀 $1${UI_NC}"
}
# Print a video/media indicator
# Usage: ui_video "Description"
ui_video() {
echo -e "${UI_BLUE}🎬 $1${UI_NC}"
}
# ============================================================================
# INTERACTIVE FUNCTIONS
# ============================================================================
# Ask a yes/no question (returns 0 for yes, 1 for no)
# Usage: if ui_confirm "Proceed?"; then ...
# Options: ui_confirm "Question" [default_yes]
ui_confirm() {
local question="$1"
local default_yes="${2:-false}"
local prompt
if [ "$default_yes" = true ]; then
prompt="(Y/n)"
else
prompt="(y/N)"
fi
while true; do
read -p "$(echo -e "${UI_YELLOW}")${question} ${prompt} $(echo -e "${UI_NC}")" -n 1 -r
echo
if [[ -z "$REPLY" ]]; then
# Empty response - use default
[ "$default_yes" = true ] && return 0 || return 1
elif [[ $REPLY =~ ^[Yy]$ ]]; then
return 0
elif [[ $REPLY =~ ^[Nn]$ ]]; then
return 1
else
ui_warn "Please answer 'y' or 'n'"
fi
done
}
# Ask for input with a prompt
# Usage: result=$(ui_input "Enter value: " [default])
ui_input() {
local prompt="$1"
local default="$2"
local result
if [ -n "$default" ]; then
read -r -p "$(echo -e "${UI_CYAN}")${prompt}[${default}]: $(echo -e "${UI_NC}")" result
echo "${result:-$default}"
else
read -r -p "$(echo -e "${UI_CYAN}")${prompt}$(echo -e "${UI_NC}")" result
echo "$result"
fi
}
# Display a progress indicator
# Usage: ui_progress "Processing..." &
# PID=$!
# # ... do work ...
# kill $PID 2>/dev/null
ui_progress() {
local message="$1"
local spin='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
local i=0
while true; do
i=$(( (i+1) % ${#spin} ))
printf "\r${UI_CYAN}${spin:$i:1} %s${UI_NC}" "$message"
sleep 0.1
done
}
# ============================================================================
# VALIDATION FUNCTIONS
# ============================================================================
# Check if a command exists
# Usage: ui_require_command "cmake" "Install with: brew install cmake"
ui_require_command() {
local cmd="$1"
local install_hint="$2"
if ! command -v "$cmd" &> /dev/null; then
ui_error "$cmd is not installed"
if [ -n "$install_hint" ]; then
echo ""
echo "$install_hint"
fi
return 1
fi
return 0
}
# Check if a file exists
# Usage: ui_require_file "config.toml" "Run setup first"
ui_require_file() {
local file="$1"
local hint="$2"
if [ ! -f "$file" ]; then
ui_error "Required file not found: $file"
if [ -n "$hint" ]; then
echo ""
echo "$hint"
fi
return 1
fi
return 0
}
# Check if a directory exists
# Usage: ui_require_dir "build" "Run cmake first"
ui_require_dir() {
local dir="$1"
local hint="$2"
if [ ! -d "$dir" ]; then
ui_error "Required directory not found: $dir"
if [ -n "$hint" ]; then
echo ""
echo "$hint"
fi
return 1
fi
return 0
}
# ============================================================================
# SECTION FUNCTIONS
# ============================================================================
# Print a section header
# Usage: ui_section "Configuration"
ui_section() {
echo ""
echo -e "${UI_BLUE}═══════════════════════════════════════${UI_NC}"
echo -e "${UI_BLUE} $1${UI_NC}"
echo -e "${UI_BLUE}═══════════════════════════════════════${UI_NC}"
echo ""
}
# Print a subsection header
# Usage: ui_subsection "Build Settings"
ui_subsection() {
echo ""
echo -e "${UI_GREEN}▶ $1${UI_NC}"
echo ""
}
# ============================================================================
# TABLE FUNCTIONS
# ============================================================================
# Print a key-value pair
# Usage: ui_keyval "Key" "Value" [indent]
ui_keyval() {
local key="$1"
local value="$2"
local indent="${3:- }"
printf "${indent}%-25s %s\n" "$key:" "$value"
}
# Print a colored key-value pair
# Usage: ui_keyval_color "Key" "Value" [color] [indent]
ui_keyval_color() {
local key="$1"
local value="$2"
local color="${3:-${UI_NC}}"
local indent="${4:- }"
printf "${indent}%-25s ${color}%s${UI_NC}\n" "$key:" "$value"
}
# ============================================================================
# ERROR HANDLING
# ============================================================================
# Exit with error message and code
# Usage: ui_die "Fatal error occurred" [exit_code]
ui_die() {
local message="$1"
local code="${2:-1}"
echo ""
ui_box_footer_error "$message"
echo ""
exit "$code"
}
# Print error with suggestion
# Usage: ui_error_suggest "Build failed" "Try running: make clean"
ui_error_suggest() {
local error="$1"
local suggestion="$2"
ui_error "$error"
echo ""
echo -e "${UI_YELLOW}Suggestion:${UI_NC}"
echo " $suggestion"
echo ""
}
# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================
# Print a separator line
# Usage: ui_separator [character]
ui_separator() {
local char="${1:--}"
echo -e "${UI_GRAY}$(printf '%*s' 80 '' | tr ' ' "$char")${UI_NC}"
}
# Print an empty line
# Usage: ui_nl [count]
ui_nl() {
local count="${1:-1}"
for ((i=0; i<count; i++)); do
echo ""
done
}
# Print centered text
# Usage: ui_center "Text" [width]
ui_center() {
local text="$1"
local width="${2:-80}"
local padding=$(( (width - ${#text}) / 2 ))
printf "%${padding}s%s\n" "" "$text"
}
# ============================================================================
# HELP FORMATTING
# ============================================================================
# Print help section header
# Usage: ui_help_section "Options"
ui_help_section() {
echo -e "${UI_BLUE}$1:${UI_NC}"
}
# Print help option
# Usage: ui_help_option "-h, --help" "Show help message"
ui_help_option() {
local option="$1"
local description="$2"
printf " %-30s %s\n" "$option" "$description"
}
# Print help example
# Usage: ui_help_example "script.sh -r" "Release build"
ui_help_example() {
local command="$1"
local description="$2"
if [ -n "$description" ]; then
printf " %-40s ${UI_GRAY}# %s${UI_NC}\n" "$command" "$description"
else
echo " $command"
fi
}
# ============================================================================
# EXPORT FUNCTIONS
# ============================================================================
# Export all UI functions for use in other scripts
export -f ui_line ui_box_header ui_box_footer_success ui_box_footer_error
export -f ui_error ui_warn ui_info ui_success ui_highlight
export -f ui_step ui_bullet ui_check ui_cross
export -f ui_clean ui_inspect ui_config ui_launch ui_video
export -f ui_confirm ui_input ui_progress
export -f ui_require_command ui_require_file ui_require_dir
export -f ui_section ui_subsection
export -f ui_keyval ui_keyval_color
export -f ui_die ui_error_suggest
export -f ui_separator ui_nl ui_center
export -f ui_help_section ui_help_option ui_help_example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment