Reputation: 7666
Is there a danger of using git push --force
if I am working on a project alone? I know there are danger when I am working with a team. But what if I am alone?
Upvotes: 7
Views: 20641
Reputation: 31107
The main danger when you use git push --force
is indeed to loose pushed by others developers. So it should not happen.
But you still can loose your own commits by mistake...
As @Prihex mentioned it rightfully in the comments, in this specific case where you loose one of your own commit by mistake, you will still be able to retrieve it by looking at the git reflog
of the branch that you git push --force
PS: Also, be aware that it is a best practice to use git push --force-with-lease
or git push --force-if-includes
to reduce the probability to unexpectly loose commits (See documentation )
Upvotes: 11
Reputation: 36700
Not only you could loose your own work, but also there is a risk you don't know what code has been released if you force push to a branch which is deployed already, e.g master or main. That will make finding a issue in production a very difficult.
So don't force push on your branch which you use for releasing. Also not when you're the only developer.
Most of the git hosting could block force pushes on special branches. Recommended to enable that to prevent this danger.
Upvotes: 2
Reputation: 12159
As Philippe mentioned, you're pretty much fine an although you can lose own commits (e.g. by git rebase
or simply git reset HEAD~
and git push --force
afterwards), not everything will be lost so keep that in mind.
If you notify the users (in case you have some), it's still easy to maintain in a relatively small user-base. The larger the user-base, the more painful it gets because git pull --force
is not automatic and the message from ordinary git pull
may seem cryptic for a beginner.
It may be for the best to first try git fetch
prior to git push --force
and see if the tree hasn't been changed (by somebody else or by you on a different machine) to prevent accidental removal of already new commits on a remote repo.
Note that unless you trim the repo afterwards, the commits are still there therefore you can restore the previous state with ease just by remembering (or having a log of in your console/gui/screenshot/...) the HEAD
commit (7 chars mostly suffice, in small repo I could get away with 3 or 2 even) or simply at least one commit from the tree you remove and simply
git checkout <hash>
git checkout -b my-restored-branch
git push -u origin my-restored-branch
However, once you trim the repo (or is trimmed automatically due to size/configuration) the things get really complicated and will require manual attention as in working with raw git objects (to my knowledge).
Upvotes: 3