#!/usr/bin/env bash set -euo pipefail BASE_BRANCH="${1:-main}" if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then echo "Not a git repository" exit 1 fi CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) if [ "$CURRENT_BRANCH" = "HEAD" ]; then echo "Detached HEAD is not supported by this script" exit 1 fi if [ "$CURRENT_BRANCH" = "$BASE_BRANCH" ]; then echo "Refusing to run on base branch: $BASE_BRANCH" echo "Please switch to a feature/fix branch first." exit 1 fi if [ -n "$(git status --porcelain)" ]; then STASH_NAME="$(date +%F)-${CURRENT_BRANCH}-safe-sync" echo "Working tree is dirty, stashing as: ${STASH_NAME}" git stash push -u -m "$STASH_NAME" >/dev/null STASHED=1 else STASHED=0 fi echo "Fetching latest refs..." git fetch origin --prune echo "Rebasing ${CURRENT_BRANCH} onto origin/${BASE_BRANCH}..." git rebase "origin/${BASE_BRANCH}" if [ "$STASHED" -eq 1 ]; then echo "Restoring stashed changes..." git stash pop || { echo "stash pop has conflicts; resolve manually, then continue." exit 2 } fi echo "Safe sync done."