droboticflow/scripts/load-deploy-env.sh
2026-09-22 01:26:15 +08:00

98 lines
2.4 KiB
Bash

#!/usr/bin/env bash
if [[ -n "${DROBOTICFLOW_DEPLOY_ENV_LOADED:-}" ]]; then
return 0
fi
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEPLOY_ENV="${DEPLOY_ENV:-${1:-}}"
branch_matches_deploy_env() {
local branch="$1"
local env_name="$2"
case "$branch" in
"$env_name"|"$env_name"-*|"$env_name"/*|*/"$env_name"|*/"$env_name"-*|*/"$env_name"/*)
return 0
;;
*)
return 1
;;
esac
}
branch_requires_poc_env() {
local branch="$1"
branch_matches_deploy_env "$branch" "poc"
}
infer_deploy_env_from_branch() {
local branch
branch="$(git -C "$ROOT_DIR" branch --show-current 2>/dev/null || true)"
if [[ "$branch" == "dev" ]]; then
printf 'fanyu\n'
elif branch_requires_poc_env "$branch"; then
printf 'poc\n'
fi
}
validate_branch_deploy_env() {
local branch
branch="$(git -C "$ROOT_DIR" branch --show-current 2>/dev/null || true)"
if [[ "$branch" == "dev" && "$DEPLOY_ENV" != "fanyu" ]]; then
echo "ERROR: current branch 'dev' is reserved for the fanyu deployment environment; DEPLOY_ENV=$DEPLOY_ENV is not allowed. Use DEPLOY_ENV=fanyu or leave DEPLOY_ENV unset on dev." >&2
return 1
fi
if branch_requires_poc_env "$branch" && [[ "$DEPLOY_ENV" != "poc" ]]; then
echo "ERROR: current branch '$branch' is reserved for the poc deployment environment. Use DEPLOY_ENV=poc or leave DEPLOY_ENV unset on poc branches." >&2
return 1
fi
}
if [[ -z "$DEPLOY_ENV" ]]; then
DEPLOY_ENV="$(infer_deploy_env_from_branch)"
fi
if [[ -z "$DEPLOY_ENV" ]]; then
return 0
fi
validate_branch_deploy_env || return 1
PRESET_PATH="$ROOT_DIR/scripts/deploy-envs/$DEPLOY_ENV.env"
if [[ ! -f "$PRESET_PATH" ]]; then
echo "ERROR: unknown deployment environment '$DEPLOY_ENV' (expected $PRESET_PATH)" >&2
return 1
fi
LOCAL_CONFIG_ROOT="${XDG_CONFIG_HOME:-$HOME/.config}/droboticflow"
set -a
source "$PRESET_PATH"
for candidate in \
"$ROOT_DIR/.env.$DEPLOY_ENV.local" \
"$ROOT_DIR/.env.$DEPLOY_ENV.secrets" \
"$LOCAL_CONFIG_ROOT/deploy/$DEPLOY_ENV.env" \
"$LOCAL_CONFIG_ROOT/deploy/$DEPLOY_ENV.secrets.env"
do
if [[ -f "$candidate" ]]; then
source "$candidate"
fi
done
set +a
if [[ -z "${KUBECONFIG:-}" ]]; then
default_kubeconfig="$LOCAL_CONFIG_ROOT/kubeconfigs/$DEPLOY_ENV.config"
if [[ -f "$default_kubeconfig" ]]; then
export KUBECONFIG="$default_kubeconfig"
fi
fi
export DEPLOY_ENV
export DROBOTICFLOW_DEPLOY_ENV_LOADED="$DEPLOY_ENV"