The 'git revert' option undoes a commit by creating another commit. This is important if your repo is being worked on with other collaboraters becasue it doesn't alter the commit history by re-writing the commit you want to remove.
To get it all back into sync, we need to do a force push. With a force push we simply push all our local changes and overwrite whatever is on the remote branch. It sounds scary and it is! Because we simply rewrite everything on the remote branch this is a destructive operation so you should handle with care.
Git prevents you from pulling files to your local machine if any unsaved or untracked changes would be overwritten by the merge operation . You can use the force pull method to force Git to pull the changes you want to receive on your local computer.
The --force option for git push allows you to override this rule: the commit history on the remote will be forcefully overwritten with your own local history. This is a rather dangerous process, because it's very easy to overwrite (and thereby lose) commits from your colleagues.
If you want to discard your work, fetch
and reset
. For example, if you have a remote named origin
and a branch named master
:
$ git fetch origin
$ git reset --hard origin/master # Destroys your work
If you don't want to throw away your work, you will have to do a git rebase --onto
. Suppose the old origin
looks like this:
A ---> B ---> C
^
origin/master
And you have this:
A ---> B ---> C ---> X ---> Y ---> Z
^ ^
| master
origin/master
Now, the upstream changes change things:
A ---> B ---> C ---> X ---> Y ---> Z
\ ^
---> B'---> C' master
^
origin/master
You would have to run git rebase --onto origin/master <C> master
, where <C>
is the SHA-1 of the old origin/master
branch before upstream changes. This gives you this:
A ---> B ---> C ---> X ---> Y ---> Z
\
---> B'---> C'---> X'---> Y'---> Z'
^ ^
| master
origin/master
Notice how B, C, X, Y, and Z are now "unreachable". They will eventually be removed from your repository by Git. In the meantime (90 days), Git will keep a copy in the reflog in case it turns out you made a mistake.
If you git reset
or git rebase
wrong and accidentally lose some local changes, you can find the changes in the reflog.
In the comments, a user is suggesting git reflog expire
with --expire=now
but DO NOT RUN THIS COMMAND because this will DESTROY your safety net. The whole purpose of having a reflog is so that Git will sometimes save your neck when you run the wrong command.
Basically, what this command will do is immediately destroy the B, C, X, Y, and Z commits in the examples above so you can't get them back. There's no real benefit to running this command, except it might save a little bit of disk space, but Git will already purge the data after 90 days so this benefit is short-lived.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With