name: Prepare on: push: branches: - main workflow_dispatch: concurrency: group: prepare-${{ github.repository }} cancel-in-progress: false env: WORKSPACE_ROOT: "/data/workspace" jobs: prepare: runs-on: standard-ubuntu-22 steps: - name: 准备共享仓库和持久 Worktree run: | set -euo pipefail REPO_NAME="${{ github.event.repository.name }}" REPO_URL="${{ github.server_url }}/${{ github.repository }}.git" HEAD_SHA="${{ github.sha }}" REPOSITORY_DIR="${WORKSPACE_ROOT}/${REPO_NAME}/repository.git" WORKTREE_ROOT="${WORKSPACE_ROOT}/${REPO_NAME}/worktrees" case "$HEAD_SHA" in ''|*[!0-9a-fA-F]*) echo "无效的触发提交 SHA: $HEAD_SHA" >&2 exit 1 ;; esac echo "===== [$(date '+%F %T')] 开始准备共享仓库 =====" echo "共享仓库: $REPOSITORY_DIR" echo "Worktree 根目录: $WORKTREE_ROOT" echo "仓库地址: $REPO_URL" echo "触发提交: $HEAD_SHA" mkdir -p "$(dirname "$REPOSITORY_DIR")" "$WORKTREE_ROOT" if [ ! -d "$REPOSITORY_DIR" ]; then echo "首次使用,初始化 bare 仓库..." git init --bare "$REPOSITORY_DIR" elif [ "$(git --git-dir="$REPOSITORY_DIR" rev-parse --is-bare-repository)" != "true" ]; then echo "共享仓库目录不是 bare 仓库: $REPOSITORY_DIR" >&2 exit 1 fi if git --git-dir="$REPOSITORY_DIR" remote get-url origin >/dev/null 2>&1; then git --git-dir="$REPOSITORY_DIR" remote set-url origin "$REPO_URL" else git --git-dir="$REPOSITORY_DIR" remote add origin "$REPO_URL" fi echo "----- 从远端集中 fetch 一次 -----" git --git-dir="$REPOSITORY_DIR" fetch \ --prune --prune-tags --tags --force origin \ '+refs/heads/*:refs/remotes/origin/*' if ! git --git-dir="$REPOSITORY_DIR" cat-file -e "${HEAD_SHA}^{commit}"; then echo "共享仓库中不存在触发提交: $HEAD_SHA" >&2 exit 1 fi ensure_worktree() { role=$1 worktree_dir="${WORKTREE_ROOT}/${role}" if [ -e "$worktree_dir" ]; then if [ ! -f "$worktree_dir/.git" ]; then echo "Worktree 路径已存在但不是 linked worktree: $worktree_dir" >&2 return 1 fi common_dir=$(git -C "$worktree_dir" rev-parse --path-format=absolute --git-common-dir) if [ "$common_dir" != "$(realpath "$REPOSITORY_DIR")" ]; then echo "Worktree 不属于共享仓库: $worktree_dir" >&2 return 1 fi echo "复用持久 Worktree: $worktree_dir" return 0 fi echo "首次创建持久 Worktree: $worktree_dir" git --git-dir="$REPOSITORY_DIR" worktree add --detach "$worktree_dir" "$HEAD_SHA" } ensure_worktree "print1" ensure_worktree "print2" echo "----- 当前共享仓库状态 -----" git --git-dir="$REPOSITORY_DIR" log -1 --oneline "$HEAD_SHA" git --git-dir="$REPOSITORY_DIR" worktree list echo "===== Prepare 完成 =====" - name: 模拟准备耗时 run: | echo "[$(date '+%F %T')] Prepare 开始 sleep 10s ..." sleep 10 echo "[$(date '+%F %T')] Prepare 完成"