#!/usr/bin/env bash set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" BASE_REF="${BASE_REF:-}" SKIP_FETCH=0 usage() { cat <<'EOF' Usage: bash scripts/check-branch-baseline.sh [--skip-fetch] Checks that the current branch is not behind origin/main. Environment: BASE_REF Base ref to compare against. Defaults to origin/main when available. EOF } while [[ $# -gt 0 ]]; do case "$1" in --skip-fetch) SKIP_FETCH=1 ;; -h|--help) usage exit 0 ;; *) echo "Unknown argument: $1" >&2 usage >&2 exit 1 ;; esac shift done git -C "${ROOT}" rev-parse --is-inside-work-tree >/dev/null if [[ "${SKIP_FETCH}" -ne 1 ]] && git -C "${ROOT}" remote get-url origin >/dev/null 2>&1; then git -C "${ROOT}" fetch origin --prune fi if [[ -z "${BASE_REF}" ]]; then for candidate in origin/main origin/master main master; do if git -C "${ROOT}" rev-parse --verify --quiet "${candidate}" >/dev/null; then BASE_REF="${candidate}" break fi done fi branch="$(git -C "${ROOT}" branch --show-current)" if [[ -z "${branch}" ]]; then echo "Baseline check failed: detached HEAD is not allowed for development or release." >&2 exit 1 fi if ! git -C "${ROOT}" rev-parse --verify --quiet "${BASE_REF}" >/dev/null; then echo "Baseline check failed: base ref not found: ${BASE_REF}" >&2 exit 1 fi read -r ahead behind < <(git -C "${ROOT}" rev-list --left-right --count "HEAD...${BASE_REF}") if [[ "${behind}" -ne 0 ]]; then echo "Baseline check failed: ${branch} is behind ${BASE_REF} by ${behind} commit(s)." >&2 echo "Run: git fetch origin --prune && git rebase ${BASE_REF}" >&2 exit 1 fi echo "Baseline check passed: ${branch} is current with ${BASE_REF} (ahead ${ahead})."