Skip to content

Instantly share code, notes, and snippets.

@13rac1
Created October 7, 2023 22:49
Show Gist options
  • Save 13rac1/d65c4d1e2f4deda5c5be8b1965f8f9a5 to your computer and use it in GitHub Desktop.
Save 13rac1/d65c4d1e2f4deda5c5be8b1965f8f9a5 to your computer and use it in GitHub Desktop.
Incrementally rebases a feature branch against a target branch commit by commit to reduce the severity and complexity of the rebase merge conflicts
#!/bin/bash
help() {
echo "Usage: $0 <main_branch> <feature_branch>"
echo
echo "Incrementally rebases a feature branch against a target branch commit by commit to reduce"
echo "the severity and complexity of the rebase merge conflicts."
echo
echo "Arguments:"
echo " main_branch The name of the main branch you want to rebase against."
echo " feature_branch The name of the feature branch you want to rebase."
echo
echo "Example:"
echo "1. $0 main feature"
echo "2. Resolve rebase conflicts"
echo "3. git add ."
echo "4. git rebase --continue"
echo "5. Back to #1, until current"
}
if [ -z "$1" ] || [ -z "$2" ]; then
help
exit 1
fi
# Name of the main branch
main_branch=$1
# Name of the feature branch
feature_branch=$2
# Check if the working directory is clean
if ! git diff --quiet && ! git diff --cached --quiet; then
echo "Working directory is not clean. Please commit or stash your changes before proceeding."
exit 1
fi
# Find the common ancestor of the main and feature branches
base_commit=$(git merge-base $main_branch $feature_branch)
# Check if the base_commit exists
if ! git cat-file -e $base_commit; then
echo "Base commit not found: $base_commit"
exit 1
fi
echo "Found common base commit: $base_commit"
git log -n1 $base_commit
# Get the list of commit hashes in the main branch, starting from the base commit
commits=$(git log --reverse --ancestry-path --pretty=format:"%H" $base_commit..$main_branch)
# Check out the feature branch
git checkout $feature_branch
# Make a backup of the feature branch
git checkout -b ${feature_branch}-`date +%s`
# Check out the feature branch
git checkout $feature_branch
# Loop through the commits
for commit in $commits
do
echo "Rebasing to: $commit"
git log -n1 $commit
# Check if the commit has more than one parent
if [ $(git rev-list --parents -n 1 $commit | wc -w) -gt 2 ]
then
echo "Skipping merge commit $commit"
continue
fi
# Try to rebase the feature branch onto the commit
if ! git rebase $commit; then
echo "Failed to rebase onto commit: $commit. Please fix the problem and run this script again."
exit 1
fi
done
# Print a success message
echo "Successfully rebased $feature_branch onto $main_branch"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment