Skip to main content

Utils Module

This module provides shared, dependency-light utility functions and timing/display helpers used across the bearflare.sh pipeline.

Module Overview

  • Purpose: Provide shared, dependency-light utility functions and timing/display helpers used across the bearflare.sh pipeline.
  • Primary modules:
    • src/lib/utils/core.sh: Core utilities (command checks, string helpers, Bash 3.2-compatible "maps", fatal error handler).
    • src/lib/utils/timing.sh: Timing helpers and terminal section/timing display helpers.

Dependencies

  • Standalone by design (pure shell functions).
  • Optional: log() (expected from src/lib/logging/; utilities gracefully skip logging when log() is absent).

Core Utilities (src/lib/utils/core.sh)

  • have_cmd(command_name): Check whether a command exists on PATH
  • map_key_sanitize(key): Convert an arbitrary key to a safe variable-name fragment for Bash 3.2 "maps"
  • map_set(map_name, key, value): Set a value in a Bash 3.2-compatible "map"
  • map_get(map_name, key, [default]): Read a value from a Bash 3.2-compatible "map"
  • strip_ansi(string): Remove ANSI escape codes from a string
  • format_number(number): Format integers with thousands separators for readability
  • truncate_string(string, [max_len]): Truncate long strings for terminal/log display
  • die(message...): Fatal error handler: prints message(s) to stderr and exits non-zero

Timing Utilities (src/lib/utils/timing.sh)

  • now_ns(): Get a nanosecond-resolution timestamp, with a macOS-compatible fallback
  • print_timing(operation_name, elapsed_ms): Display a concise "completed in Xms" line in terminal output
  • print_section(title): Print a visually distinct section header, and optionally log the same boundary

Bash 3.2 Compatibility

macOS ships with Bash 3.2 by default, which does not support associative arrays (declare -A). This codebase uses map_* functions to implement map-like storage by dynamically naming variables:

  • Storage key: ${MAPNAME}__${SANITIZED_KEY}
  • Setting: printf -v "$var" '%s' "$value"
  • Getting: indirect expansion via ${!var} with an existence check using ${!var+x}

Integration Guidelines

Sourcing Order

  1. Source src/lib/utils/core.sh
  2. Source src/lib/utils/timing.sh
  3. Source logging module (if present) that defines log()