Files
dukang/deploy/deploy.sh
T

126 lines
2.8 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# 本地执行:SSH 到服务器拉代码并发布
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ENV_FILE="$SCRIPT_DIR/deploy.env"
DEPLOY_HOST=""
DEPLOY_USER="root"
DEPLOY_PORT="22"
DEPLOY_SSH_KEY=""
APP_ROOT="/opt/dukang-haoke"
GIT_REMOTE="origin"
GIT_BRANCH="dev"
CHECK_ONLY=false
RELEASE_ARGS=()
usage() {
cat <<'EOF'
用法: deploy/deploy.sh [选项] [-- 远程 release 参数]
环境配置: deploy/deploy.env(可复制 deploy.env.example
选项:
--host HOST 服务器地址(覆盖 deploy.env
--user USER SSH 用户,默认 root
--port PORT SSH 端口,默认 22
--key PATH SSH 私钥路径
--branch BRANCH 发布分支,默认 dev
--check 仅 SSH 连接并查看 PM2 / 端口状态
-h, --help 显示帮助
示例:
./deploy/deploy.sh
./deploy/deploy.sh --branch main
./deploy/deploy.sh -- --skip-db
./deploy/deploy.sh -- --seed --accept-data-loss
EOF
}
load_env() {
if [[ -f "$ENV_FILE" ]]; then
# shellcheck disable=SC1090
source "$ENV_FILE"
fi
}
while [[ $# -gt 0 ]]; do
case "$1" in
--host) DEPLOY_HOST="$2"; shift 2 ;;
--user) DEPLOY_USER="$2"; shift 2 ;;
--port) DEPLOY_PORT="$2"; shift 2 ;;
--key) DEPLOY_SSH_KEY="$2"; shift 2 ;;
--branch) GIT_BRANCH="$2"; shift 2 ;;
--check) CHECK_ONLY=true; shift ;;
-h|--help) usage; exit 0 ;;
--)
shift
RELEASE_ARGS=("$@")
break
;;
*) RELEASE_ARGS+=("$1"); shift ;;
esac
done
load_env
if [[ -z "$DEPLOY_HOST" ]]; then
echo "错误: 未配置 DEPLOY_HOST。请创建 deploy/deploy.env 或使用 --host" >&2
exit 1
fi
SSH_OPTS=(-o "StrictHostKeyChecking=accept-new" -p "$DEPLOY_PORT")
if [[ -n "$DEPLOY_SSH_KEY" ]]; then
SSH_OPTS+=(-i "$DEPLOY_SSH_KEY")
fi
TARGET="${DEPLOY_USER}@${DEPLOY_HOST}"
run_remote() {
ssh "${SSH_OPTS[@]}" "$TARGET" "$@"
}
if [[ "$CHECK_ONLY" == true ]]; then
echo "==> 检查 $TARGET"
run_remote "pm2 list; ss -tlnp | grep -E '809[0-3]' || true"
exit 0
fi
REMOTE_RELEASE_ARGS=""
if [[ ${#RELEASE_ARGS[@]} -gt 0 ]]; then
REMOTE_RELEASE_ARGS="${RELEASE_ARGS[*]}"
fi
echo "==> 发布到 $TARGET ($GIT_BRANCH)"
run_remote bash -s <<EOF
set -euo pipefail
APP_ROOT="$APP_ROOT"
GIT_REMOTE="$GIT_REMOTE"
GIT_BRANCH="$GIT_BRANCH"
RELEASE_ARGS="$REMOTE_RELEASE_ARGS"
export DEPLOY_TRIGGER=manual
export APP_ROOT
cd "\$APP_ROOT"
if [[ ! -d .git ]]; then
echo "错误: \$APP_ROOT 不是 git 仓库" >&2
exit 1
fi
if [[ -n "\$RELEASE_ARGS" ]]; then
echo "==> 拉取代码"
git fetch "\$GIT_REMOTE"
git checkout "\$GIT_BRANCH"
git pull --ff-only "\$GIT_REMOTE" "\$GIT_BRANCH"
bash deploy/remote-release.sh \$RELEASE_ARGS
else
echo "==> 拉取代码并发布(auto-release"
bash deploy/auto-release.sh
fi
EOF
echo "==> 本地发布命令已完成"