With the introduction of GitHub's Squash and Merge feature, this has become less prevelant, however it's still useful in scenarios where GitHub's interface is unavailable.
Let's talk through two ways to do a squash and merge on the command line.
When to use it
- When you have not merged main into your feature branch
- There are no merge conflicts
- When you want to retain the original committer on the squashed commit
Steps
You are working on branch feat-fuu
. You want to create a single squashed commit to push to your remote feat-fuu
branch on GitHub.
git checkout main
git pull
git checkout feat-fuu
git checkout feat-fuu-backup
- Optional but recommended - make a backup version of your branch
git checkout feat-fuu
EDITOR='code -w' git rebase -i main
- Setting
EDITOR
is optional, and depends on your editor of choice. With the case of VSCode or Sublime Text, the-w
flag tells the editor to "wait" until the file exits before closing.
- Setting
- In your editor, edit all of the additional commits to
squash
. Leave the first commit in the list alone - Save and exit your editor
- Rewrite a nice single commit message for the commit
- Check the history.
feat-fuu
will now contain a single commmit ahead ofmain
git push -f origin feat-fuu
- Please be careful with this step, as it overwrites your original remote branch on GitHub
When to use it
- You have merged main into your branch and resolved conflicts
- You don't care about the author of the original commits (you will be rewriting it)
You are working on branch feat-fuu
. You want to create a single squashed commit to push to your remote feat-fuu
branch on GitHub.
git checkout main
git pull
git checkout feat-fuu
git checkout feat-fuu-backup
git checkout main
git branch -D feat-fuu
- You are deleting your original branch. Ensure you have created
feat-fuu-backup
beforehand and it has your full commit history.
- You are deleting your original branch. Ensure you have created
git checkout -b feat-fuu
- This creates a fresh branch from main
git merge --squash feat-fuu-backup
- You are merging and squashing your original work into a single commit. This is where the magic happens.
- Rewrite a nice single commit message for the commit
- Check the history. You should see a single commmit on your branch that branched from
main
git push -f -u origin feat-fuu
- Please be careful with this step, as it overwrites your original branch on GitHub
- This Stack Overflow Post has additional detail about the differences between these two approaches.
That's a very good explanation! Thank you.
Did you mean to use
instead of