DEV Community

Discussion on: Squashing commits in Git!

Collapse
 
recursivefaults profile image
Ryan Latta

I'll give my hot take here.

You almost never want to do a forced push. The reason is that when you do, you've informed git that it's version of history is incorrect and you wish to change it. While that is fine if you work alone, if you work with others you'll be re-writing their history as well.

Under the covers git works a little bit like a linked list. One commit points to the next and so on. A forced push rewrites that list which will like mean everyone else's work no longer exists in that list.

This brings me back to the rebase command. Rebase is the command that rewrites git's history. It isn't so much that it changes commits, it fundamentally changes how they exist. An accident rebasing can be a tricky thing to recover from (Hint: Look at ref-log). The general rule is that you rebase only things you've not pushed or shared. That way you are only manipulating your history and not someone else's.

Collapse
 
yeganathan profile image
Yeganathan S • Edited

First of all thanks for sharing your thoughts!
I would like to add a few tops of it. When we squash commits, our local version would probably be changed so git won't allow us to do push those since both remote and local are different versions. Only force push works in this case, also when we work with others only if the person pulls, the changes come to his local, and if he force pushes directly then his changes would be reflected as before squashing.

Collapse
 
recursivefaults profile image
Ryan Latta

You only need to force push when you have to overwrite a remote's history of commits. If you only rebase commits that you've not pushed, you'll find you never have to force push.

Give it a try. Make a bunch of commits without pushing them. Do your interactive rebase on ONLY those commits. You'll have no problem pushing because you'd be pushing 1 squash commit. The remote repo never knew or cared you have others before the rebase. When you rebased you rewrote that history to never exist. When you push it looks like you only ever had 1 commit.

For fun clone the repo somewhere else. and do it again only this time do a few commits, and push them one at a time. Somewhere in the middle of pushing pull to your 2nd repo. Add a few commits in that 2nd repo. Go back to your original and squash those commits and force push. Go to your 2nd repo and do a pull. See what happens.

Knowing how this works will be a pretty important thing. Someone you work with will mess up a repo at some point. Good to know how it looks and how to fix it. Its a super power.