Skip to content

Instantly share code, notes, and snippets.

@robballou
Created February 6, 2025 17:48
Show Gist options
  • Save robballou/f2a76e2cc7eda312066a4c02a64268d8 to your computer and use it in GitHub Desktop.
Save robballou/f2a76e2cc7eda312066a4c02a64268d8 to your computer and use it in GitHub Desktop.
#!/bin/zsh
# Script that tests if a TEST_BRANCH can be merged successfully into
# a TARGET_BRANCH.
#
# Usage: git_merge_test.sh [-i] [TARGET_BRANCH] [TEST_BRANCH]
#
# Example: git_merge_test.sh dev feature-new-stuff
#
# Inspect conflicts: the script will clean up automatically unless you
# pass -i. Then it will stop at the merge so you can see what conflicts (or not).
#
# Notes:
# - force creates a branch with the name: testmerge-TARGET-TEST ... so if that exists
# running this script will break things for you
testMerge() {
# make a branch from the origin's version of the target branch
# (forced in case it exists)
git checkout -B testmerge-$1-$2 origin/$1
# make the merge happen, but don't follow or commit cause we just
# want to trash this
git merge --no-ff --no-commit $2
# determine success/failure
if [[ "$?" -ne 0 ]]; then
echo '❌ Merge FAILED. Attempting to cleanup and go back to' $current_branch
else
echo '✅ Merge SUCCESS. Cleaning up and going back to' $current_branch
fi
}
main() {
# get the branch name we're currently on
current_branch=$(git rev-parse --abbrev-ref HEAD)
# make sure we have all changes
git fetch
testMerge $1 $2
# I want out of here
git merge --abort
# switch back to the branch we started from
git switch $current_branch
# cleanup our testmerge branch
git branch --delete --force testmerge-$1-$2
}
review() {
# get the branch name we're currently on
current_branch=$(git rev-parse --abbrev-ref HEAD)
# make sure we have all changes
git fetch
testMerge $1 $2
echo "To cleanup:"
echo " git merge --abort && git switch $current_branch && git branch --delete --force testmerge-$1-$2"
}
if [[ "$#" -lt 2 ]]; then
echo 'Usage:' $0 'TARGET_BRANCH TEST_BRANCH'
exit 1
fi
target_branch="unknown"
test_branch="unknown"
review=0
# figure out if any of the arguments are -i
for var in "$@"
do
if [[ $var == "-i" ]]; then
review=1
elif [[ $target_branch == "unknown" ]]; then
target_branch=$var
elif [[ $test_branch == "unknown" ]]; then
test_branch=$var
fi
done
if [[ $review == 0 ]]; then
main $target_branch $test_branch
else
review $target_branch $test_branch
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment