ContextStudioWizard/lib/utils.sh
Karamelmar 431e5493fc Fix set -e bug causing silent exit after valid input
- Replace all `[[ condition ]] && die` with `if/fi` — the && pattern
  exits silently when the condition is false under set -e
- Removed -e from set flags (kept -uo pipefail), all error paths are
  now explicit
- Declare `input` as local in ask/ask_yn/ask_choice to prevent leakage
- Use `read -r input || true` to handle EOF safely
- Fix ask_choice arithmetic to avoid (()) triggering exit on false

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 12:11:31 +01:00

76 lines
2.1 KiB
Bash

#!/usr/bin/env bash
# utils.sh — colors, prompts, helpers
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'
info() { echo -e "${CYAN}${BOLD}[info]${RESET} $*"; }
success() { echo -e "${GREEN}${BOLD}[ok]${RESET} $*"; }
warn() { echo -e "${YELLOW}${BOLD}[warn]${RESET} $*"; }
error() { echo -e "${RED}${BOLD}[error]${RESET} $*" >&2; }
die() { error "$*"; exit 1; }
header() { echo -e "\n${BOLD}${CYAN}━━━ $* ━━━${RESET}\n"; }
# ask VAR "prompt" "default"
ask() {
local var="$1" prompt="$2" default="$3"
local input
if [[ -n "$default" ]]; then
echo -ne "${BOLD}${prompt}${RESET} ${CYAN}[${default}]${RESET}: "
else
echo -ne "${BOLD}${prompt}${RESET}: "
fi
read -r input || true
if [[ -z "$input" && -n "$default" ]]; then
eval "$var=\"\$default\""
else
eval "$var=\"\$input\""
fi
}
# ask_yn VAR "prompt" "y|n"
ask_yn() {
local var="$1" prompt="$2" default="$3"
local input options
if [[ "$default" == "y" ]]; then options="Y/n"; else options="y/N"; fi
echo -ne "${BOLD}${prompt}${RESET} ${CYAN}[${options}]${RESET}: "
read -r input || true
input="${input:-$default}"
if [[ "$input" =~ ^[Yy]$ ]]; then
eval "$var=y"
else
eval "$var=n"
fi
}
# ask_choice VAR "prompt" option1 option2 ...
ask_choice() {
local var="$1" prompt="$2"; shift 2
local options=("$@")
local input idx
echo -e "${BOLD}${prompt}${RESET}"
for i in "${!options[@]}"; do
echo -e " ${CYAN}$((i+1))${RESET}) ${options[$i]}"
done
echo -ne "Choice ${CYAN}[1]${RESET}: "
read -r input || true
input="${input:-1}"
if [[ "$input" =~ ^[0-9]+$ ]] && (( input >= 1 && input <= ${#options[@]} )); then
idx=$(( input - 1 ))
else
idx=0
fi
eval "$var=\"\${options[$idx]}\""
}
require_cmd() {
command -v "$1" &>/dev/null || die "Required command not found: $1"
}
slugify() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-//;s/-$//'
}