Cleaning up branches before merging code on a team can be non-trivial. The goal of this gist is to discuss some of the common scenarios that occur as we are cleaning up our branch in preparation to merge.
In this scenario, imagine that we start with 2 branches: main
and a
. Branch a
has several commits that are not yet in main
. We branch off of a
to create branch b
. Branch a
is squash merged into main
, leaving b
with several commits that no longer need to be merged. When we are ready to merge b
, how do we avoid merging all of these commits?
- Squash merge
b
- When people review the PR, they will see all of the commits from
a
while reviewing. This leads to a less than desirable code review experience. - Looking at the history of branch
b
in the future will be quite confusing.
- When people review the PR, they will see all of the commits from
- Create a new branch and cherry pick your changes
- If the branch wasn't that long lasting, this isn't really that difficult.
- If the branch has a lot in it, it's probably better to just squash merge and call it a day.
# Find range of commits (-n 10 shows 10 commits, adjust this to show approximately how many commits you think you made)
git checkout b
git log -n 10 --oneline | tail
# Create a fresh branch
git checkout main
git pull
git checkout -b off-main
# Cherry pick all of your commits (https://gist.github.com/seanbecker15/ab32fcb9758baf5543b1ab3aa40b1445)
git cherry-pick $(git log sha1^..sha2 --reverse --pretty=format:"%h")
# Diff with old branch to verify. You shouldn't see any changes.
git diff b
# Recreate branch `b` and force-push
git branch -D b
git checkout -b b
git push --set-upstream origin b --force