ComposeSync/config-parser.sh

120 lines
No EOL
3.5 KiB
Bash

#!/bin/bash
# ComposeSync Configuration Parser
# Supports both .env and TOML formats
set -euo pipefail
# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Configuration file paths
CONFIG_DIR="$SCRIPT_DIR"
ENV_FILE="$CONFIG_DIR/.env"
TOML_FILE="$CONFIG_DIR/config.toml"
# Function to parse TOML configuration
parse_toml() {
local toml_file="$1"
if [ ! -f "$toml_file" ]; then
return 1
fi
log "Loading TOML configuration from $toml_file"
# Initialize arrays
declare -g -A STACK_NAMES=()
local current_section=""
local stack_count=0
# Read TOML file and convert to environment variables
while IFS= read -r line; do
# Skip comments and empty lines
[[ "$line" =~ ^[[:space:]]*# ]] && continue
[[ -z "${line// }" ]] && continue
# Parse section headers [section]
if [[ "$line" =~ ^[[:space:]]*\[([^\]]+)\][[:space:]]*$ ]]; then
current_section="${BASH_REMATCH[1]}"
continue
fi
# Parse key-value pairs
if [[ "$line" =~ ^[[:space:]]*([^=]+)[[:space:]]*=[[:space:]]*(.+)$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
# Remove quotes from value
value=$(echo "$value" | sed 's/^"\(.*\)"$/\1/' | sed "s/^'\(.*\)'$/\1/")
# Remove inline comments (everything after #)
value=$(echo "$value" | sed 's/[[:space:]]*#.*$//')
# Trim whitespace
key=$(echo "$key" | xargs)
value=$(echo "$value" | xargs)
# Convert to environment variable format
if [ -n "$current_section" ]; then
if [[ "$current_section" == "global" ]]; then
# Global settings
export "${key^^}"="$value"
else
# Stack configurations
stack_count=$((stack_count + 1))
STACK_NAMES[$stack_count]="$current_section"
export "STACK_${stack_count}_${key^^}"="$value"
fi
fi
fi
done < "$toml_file"
# Set STACKS count
export STACKS=$stack_count
return 0
}
# Function to load configuration
load_config() {
# Try TOML first, then fall back to .env
if [ -f "$TOML_FILE" ]; then
if parse_toml "$TOML_FILE"; then
log "Successfully loaded TOML configuration"
return 0
else
log "Failed to parse TOML file, falling back to .env"
fi
fi
# Try multiple .env locations
local env_locations=(
"$ENV_FILE" # Default location
"$(dirname "${BASH_SOURCE[0]}")/.env" # Same directory as script
".env" # Current directory
)
for env_file in "${env_locations[@]}"; do
if [ -f "$env_file" ]; then
log "Loading .env configuration from $env_file"
# Use set -a to automatically export variables
set -a
source "$env_file"
set +a
return 0
fi
done
log "ERROR: No configuration file found at $TOML_FILE or any .env locations"
return 1
}
# Function to log messages (if not already defined)
if ! declare -F log >/dev/null; then
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
fi
# Export the function so it can be used by other scripts
export -f load_config
export -f parse_toml