The danger of rewriting history on a public repository
In the previous chapter about history, we learned how to amend commits, revert changes, and reset branches. These operations all involve rewriting the commit history in some way. While this is fine for local branches and private repositories, it can cause problems when working with public repositories and collaborators.
Imagine you've pushed a series of commits to a public repository. Your collaborators have pulled these commits and started working on top of them. Now, if you go back and amend, revert, or reset any of these commits, you're essentially changing the foundation that your collaborators' work is built on.
The next time your collaborators try to push their changes, they'll get an error because the history of their local branch doesn't match the history of the remote branch anymore. They'll have to manually reconcile the divergent histories, which can be a confusing and frustrating process.
The golden rule is: never rewrite public history. Once you've pushed a commit to a public repository, consider it etched in stone. If you need to fix something, use git revert
to create a new commit that undoes the changes, rather than trying to modify the existing commit.
If you absolutely must rewrite history (for example, to remove sensitive data that was accidentally committed), communicate with your collaborators first. Make sure everyone has pulled the latest changes and is on the same page. Then, after you've rewritten history, everyone will need to reset their local branches to match the new history on the remote.
One more thing: be careful with git push --force
. This command overwrites the remote branch with your local branch, disregarding any conflicts. It's like saying "I don't care what's on the remote, make it look exactly like my local branch". This can cause collaborators to lose their work if they had pushed commits that you didn't pull before force pushing.
The --force
option does have legitimate uses, but it should be used with extreme caution, and only when you fully understand the consequences. If you're not sure, it's better to use git push --force-with-lease
, which will at least warn you if the remote branch has changes that you didn't expect.
Hi! I'm Alex, creator of GitByBit.
This page is a part of the interactive course about Git version control.
It's a one-of-a-kind course that is integrated into the VS Code code editor. Learning directly in VS Code lets you operate Git exactly as you would in real life, doing real jobs, writing real code.
In addition, the course has access to your actual terminal, so it can point out mistakes, suggest workarounds, etc.
The course is FREE, there are no Ads or other bullshit. There are optional premium add-ons you can purchase, mainly to support my work (regrettably, I have to eat every day), but that's totally up to you.