Skip to content

Instantly share code, notes, and snippets.

@Broxzier
Created May 11, 2022 16:56
Show Gist options
  • Save Broxzier/645648135bb8e4dd7383115bce97c519 to your computer and use it in GitHub Desktop.
Save Broxzier/645648135bb8e4dd7383115bce97c519 to your computer and use it in GitHub Desktop.
A shell script to easily swap the parents of a merge commit, so that you can avoid having files that you changed be touched and force a rebuild. Place this in your `~/bin` folder and you can simply use `git swap-merge`
#!/bin/bash
# Check if HEAD is a merge commit
numParents=$(git show -s --format=%p HEAD | wc -w)
if [[ "$numParents" != "2" ]]; then
echo "HEAD is not a merge commit"
exit 1
fi
# Format the new commit message
lastCommitMsg=$(git log --pretty=%B -1)
newCommitMsg=$(echo $lastCommitMsg | sed -re 's/^Merge .*?branch (.+) into (.+)$/Merge branch \2 into \1/g')
if [[ "$lastCommitMsg" == "$newCommitMsg" ]]; then
echo "HEAD does not have a standard merge commit message"
exit 2
fi
# Create a new commit with the parents swapped, and reset HEAD to this
git reset $(git commit-tree -p HEAD^2 -p HEAD^1 -m "$newCommitMsg" "HEAD^{tree}")
# Success
exit 0
@Broxzier
Copy link
Author

With this, you can simply merge the main branch into your feature branch, then swap the parents, to avoid having your files touched again.

git checkout feature/my-feature
git merge --no-ff develop
git swap-merge

Before swap -> After swap

 * merge branch develop into 'feature/my-feature'      |      * merge branch 'feature/my-feature' into develop
 |\                                                    |      |\
 * | Commit 2 on feature branch                        |      | * Commit 2 on feature branch
 | * Commit on develop                                 |      * | Commit on develop
 * | Commit 1 on feature branch                        |      | * Commit 1 on feature branch
 |/                                                    |      |/
 * Base                                                |      * Base
 * ...                                                 |      * ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment