Can I undo commits?

Suppose we have a repository and 5 commits:

  • commit 1
  • commit 2
  • commit 3
  • commit 4
  • commit 5

And now I understand that commits 4 and 5 are a bad idea. I want to completely remove all changes committed in commit 4 and 5. How to do this?

+7
git
source share
3 answers

If commits 4 and 5 are only in your repository and have not been clicked or pulled out by another repository, you can simply:

git reset --hard SHA1_HASH_OF_COMMIT_3

You can find out the SHA1 hash of the commit using git log , or you can use more advanced naming methods, see git help rev-parse , in particular the "INDICATING REVISIONS" section.

Using this command leaves commit 4 and 5 unattainable from the tip of the branch. However, commits will not be lost because these commits are stored in the branch. You can use git reflog to determine an unreachable commit. Then recovery can be done using another git reset --hard . This page here describes it all pretty well.

It is recommended that you run git gc regularly; some teams also do this automatically for you. This essentially does the “housekeeping” in the repository, for example, “compresses file changes (reduces disk space and improves performance) and deletes inaccessible objects”. Inaccessible objects are truncated from the repository after (default) 30 days. This can be changed using the gc.reflogExpireUnreachable configuration gc.reflogExpireUnreachable .

+6
source share

git revert commit_hash

Returns the given commit. Note that revert is another commit that flushes changes from commit_hash without removing the commit from the repository.

+4
source share

I would probably create a new branch from commit 3.

 git checkout -b commit3 

and then reinstall the wizard from this commit

http://git-scm.com/docs/git-rebase

Of course, you use branches so that your branches are split up until you know that they are a good idea, right?

+3
source share

All Articles