infra/git-bridge/bin/sync-main-forward.sh

69 lines
2.0 KiB
Bash
Executable File

#!/bin/sh
set -eu
. /app/config/repositories.conf
state_repo=/state/infra.git
lock_dir=/state/forward-sync.lock
mkdir -p /state
mkdir -p "$HOME"
if ! mkdir "$lock_dir" 2>/dev/null; then
echo "forward sync is already running" >&2
exit 75
fi
trap 'rmdir "$lock_dir" 2>/dev/null || true' EXIT INT TERM
export GIT_TERMINAL_PROMPT=0
export GIT_ASKPASS=/app/bin/git-askpass.sh
if [ ! -d "$state_repo" ]; then
git init --bare "$state_repo" >/dev/null
fi
if git -C "$state_repo" remote get-url gitea >/dev/null 2>&1; then
[ "$(git -C "$state_repo" remote get-url gitea)" = "$GITEA_REMOTE" ] || {
echo "gitea remote mismatch" >&2
exit 2
}
else
git -C "$state_repo" remote add gitea "$GITEA_REMOTE"
fi
if git -C "$state_repo" remote get-url github >/dev/null 2>&1; then
[ "$(git -C "$state_repo" remote get-url github)" = "$GITHUB_REMOTE" ] || {
echo "github remote mismatch" >&2
exit 2
}
else
git -C "$state_repo" remote add github "$GITHUB_REMOTE"
fi
git -C "$state_repo" fetch --no-tags gitea \
"+refs/heads/$MAIN_BRANCH:refs/remotes/gitea/$MAIN_BRANCH"
gitea_sha=$(git -C "$state_repo" rev-parse "refs/remotes/gitea/$MAIN_BRANCH")
if git -C "$state_repo" ls-remote --exit-code --heads github \
"refs/heads/$MAIN_BRANCH" >/dev/null 2>&1; then
git -C "$state_repo" fetch --no-tags github \
"+refs/heads/$MAIN_BRANCH:refs/remotes/github/$MAIN_BRANCH"
github_sha=$(git -C "$state_repo" rev-parse "refs/remotes/github/$MAIN_BRANCH")
if ! git -C "$state_repo" merge-base --is-ancestor "$github_sha" "$gitea_sha"; then
echo "sync refused: GitHub Main is not an ancestor of Gitea Main" >&2
exit 42
fi
fi
git -C "$state_repo" push github \
"refs/remotes/gitea/$MAIN_BRANCH:refs/heads/$MAIN_BRANCH"
verified_sha=$(git -C "$state_repo" ls-remote github \
"refs/heads/$MAIN_BRANCH" | awk 'NR == 1 { print $1 }')
[ "$verified_sha" = "$gitea_sha" ] || {
echo "sync verification failed" >&2
exit 1
}
echo "forward sync completed"
echo "branch=$MAIN_BRANCH"
echo "commit=$gitea_sha"
echo "force_push=false"