Skip to content

Instantly share code, notes, and snippets.

@sdeleuze
Last active April 2, 2025 15:54
Show Gist options
  • Save sdeleuze/00e0b8fccc0310ef45fb75cbf960ff72 to your computer and use it in GitHub Desktop.
Save sdeleuze/00e0b8fccc0310ef45fb75cbf960ff72 to your computer and use it in GitHub Desktop.
Git hooks preventing merging of main in Spring baseline branches. Use `git rebase` instead of previous usages of `git merge` with fast forward.
#!/usr/bin/env bash
# -------------------------------------------------------------------------#
# Avoid merging main into baseline branches #
# -------------------------------------------------------------------------#
#
# Put this file in your local repo, in the .git/hooks folder and make sure
# it is executable.
#
# The name of the file *must* be "pre-merge-commit" for Git to pick it up.
#
# Make sure to configure 'git config --add merge.ff false' or
# 'git config --global merge.ff false' otherwise this hook won't work for
# fast-forward merges.
if [[ $GIT_REFLOG_ACTION =~ ^merge[:space:].* ]]; then
echo "Invalid GIT_REFLOG_ACTION value: '${GIT_REFLOG_ACTION}' should start by 'merge '"
exit 1
fi
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
MERGED_BRANCH=${GIT_REFLOG_ACTION##* }
BASELINE_BRANCH_REGEX="^[0-9]\.[0-9]\.x$"
if [[ "$MERGED_BRANCH" = "main" && "$CURRENT_BRANCH" =~ $BASELINE_BRANCH_REGEX ]]; then
echo "Forbidden merge of 'main' into branch '${CURRENT_BRANCH}'"
echo "Run 'git merge --abort' to abort the merge"
exit 1
fi
exit 0
#!/usr/bin/env bash
# -------------------------------------------------------------------------#
# Avoid rebasing baseline branches on main #
# -------------------------------------------------------------------------#
#
# Put this file in your local repo, in the .git/hooks folder and make sure
# it is executable.
#
# The name of the file *must* be "pre-rebase" for Git to pick it up.
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
BASE_BRANCH="$1"
BASELINE_BRANCH_REGEX="^[0-9]\.[0-9]\.x$"
echo "Base branch: $BASE_BRANCH"
echo "Current branch $CURRENT_BRANCH"
if [[ "$BASE_BRANCH" = "main" || "$BASE_BRANCH" = */main ]]; then
if [[ "$CURRENT_BRANCH" =~ $BASELINE_BRANCH_REGEX ]]; then
echo "Forbidden rebase of '$CURRENT_BRANCH' on '$BASE_BRANCH'"
exit 1
fi
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment