Search code examples
git

How do I undo a revert in Git?


I've been working on a large project. I made an initial commit and didn't commit again for a while. My project is almost done so I decided to mess around with git again and commit the new files in my project, which I did, but didn't push.

I read right after that that it's preferred to make small commits, so I decided to delete my last commit and practice making smaller commits from my project. I used git revert <last commit> and it deleted most of my files!

I read online to 'revert the revert' and used git revert <reverted commit>. It said failed to commit and that I needed to commit changes in my project, so I did and tried again, making sure to include the correct commit, it failed.

Here's the git log:

commit 286f067d7ff46385af05381cfe1b657e60204393 (HEAD -> master)
Author: my username <my email

Date:   Thu Jun 30 19:18:45 2022 -0400

trying to fix this

commit 27dd527567348acecc31cbababa9ddc2a31eacdc
Author: my username <my email>
Date:   Thu Jun 30 16:39:31 2022 -0400

reverted commit

Solution

  • My favorite way (the cleanest possible) to revert a commit is to use git reset

    Basically, these are the steps I follow:

    1. Get the commit code to revert to (either with git log or going to the repository's history)
    2. git reset <code> --hard to return to that commit
    3. Backup the entire project somewhere else in the computer
    4. git pull to return to the latest commit
    5. Erase everything and paste the previous backup
    6. git add . (at this point, all the changes that have been made since the commit you've hard-resetted to, need to be staged)
    7. git commit
    8. git push

    I know it may take some time meanwhile some codes do this automatically, but I think it's the safest way if you don't have permission to force-push.

    If you can force-push (and this is very dangerous, since you actually erase all history from the repo after the commit you are returning to), you simply have to hard reset (just like point 2 above) and run the command git push --force