devlog - git squash
Sometimes you need to squash - do it properly. Short devlog so I stick it in my mind forever and you as a reader get a zero-bullshit guide to git squash.
1.) First forget about Github's and similar services "Rebase and merge" button and what that does - we do Git here.
2.) Start your work on a new feature - either from master or develop - we go from develop because that's how we flow:
git checkout develop
git pull
git checkout -b feature/xyz
3.) Do some hard work and commit as you wish. Sometimes you do stupid commits - that's why you wanna squash - to hide your shame of failure and laziness out of commits messages:
git commit -m "Add cat icon to submit button"
git commit -m "Linter :("
git commit -m "Forgot something"
4.) Ok it was easy task, we are done. Let's fetch and start our interactive rebase against develop:
git fetch
git rebase --interactive origin/develop
Interactive rebase starts an interactive interface in your shell, that looks something like this:
pick a23b543 Add cat icon to submit button
pick fafa34c Linter
pick fdfd8a6 Forgot something
# more commented junk below here
Focus on the lines that start with pick - this are your commits. Pick one that will become the base and change other "pick"s into "squash" - so they get squashed into the picked one:
pick a23b543 Add cat icon to submit button
squash fafa34c Linter
squash fdfd8a6 Forgot something
Save and rebase will continue.
5.) If merge conflict occurs first curse and then check what, who, where:
git status
Fix conflicted file with whatever is your favorite way to solve conflicts. When you solve save and:
git add <file>
(no need to commit - rebase handles it)
6.) Then continue with rebase:
git rebase --continue
Once your commits have been squashed, Git will prompt you to write a commit message for your new squashed commit. Ask your coworkers how they want it to look or use your logic (there are guides on internet how to write good commit messages - if you do it properly certain popular git services will pre-fill their web interface from your message and save you time).
7.) Now we push - here we have 2 scenarios:
a.) First push of this new branch:
Push to origin as always:
git push --set-upstream origin feature/xyz
b.) Already pushed this branch before, but you forgot a lot of important stuff, did more work and now you wanna squash and hide your poor work performance from git history:
We force push (yes - FORCE - don't panic - all good and legal - we are on our own branch).
git push --force origin feature/xyz
8.) Open a pull request targeting develop (or whatever you branched from).
Success.
You are done like a pro - single commit message - rebased - entire feature implemented - no bugs - off we go.