Skip to content

Instantly share code, notes, and snippets.

@seanbecker15
Last active May 25, 2023 22:33
Show Gist options
  • Save seanbecker15/e659425fb1bc70910bf92c298ce4b135 to your computer and use it in GitHub Desktop.
Save seanbecker15/e659425fb1bc70910bf92c298ce4b135 to your computer and use it in GitHub Desktop.
Cleaning up branches before merging

Overview

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.

Scenarios

Forked off of a branch that was squash merged

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?

  1. 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.
  2. 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.

Create a new branch and cherry pick your changes

# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment