58 lines
1.2 KiB
Bash
Executable File
58 lines
1.2 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Environment loader and profile support
|
|
# Provides: load_env [--profile <name>] [--file <path>] and helpers
|
|
|
|
set -euo pipefail
|
|
|
|
DEFAULT_ENV_FILE="${DEFAULT_ENV_FILE:-.env}"
|
|
|
|
load_env() {
|
|
local profile=""; local file="$DEFAULT_ENV_FILE"; local opt
|
|
while [[ $# -gt 0 ]]; do
|
|
opt="$1"
|
|
case "$opt" in
|
|
--profile)
|
|
profile="$2"; shift 2;;
|
|
--file)
|
|
file="$2"; shift 2;;
|
|
*)
|
|
break;;
|
|
esac
|
|
done
|
|
if [ -f "$file" ]; then
|
|
local had_nounset=0
|
|
if [[ $- == *u* ]]; then
|
|
had_nounset=1
|
|
set +u
|
|
fi
|
|
# shellcheck disable=SC2046
|
|
set -a; . "$file"; set +a
|
|
(( had_nounset )) && set -u
|
|
fi
|
|
if [ -n "$profile" ]; then
|
|
local pf="${file}.${profile}"
|
|
if [ -f "$pf" ]; then
|
|
local had_nounset_profile=0
|
|
if [[ $- == *u* ]]; then
|
|
had_nounset_profile=1
|
|
set +u
|
|
fi
|
|
# shellcheck disable=SC2046
|
|
set -a; . "$pf"; set +a
|
|
(( had_nounset_profile )) && set -u
|
|
fi
|
|
fi
|
|
}
|
|
|
|
require_env() {
|
|
local name="$1"
|
|
if [ -z "${!name:-}" ]; then
|
|
echo "Missing required env: $name" >&2
|
|
return 1
|
|
fi
|
|
}
|
|
|
|
current_profile() {
|
|
echo "${ENV_PROFILE:-}"
|
|
}
|