How can I roll back 1 commit?

I have 2 commits that I did not push:

$ git status
# On branch master
# Your branch is ahead of 'faves/master' by 2 commits.

How can I roll back my first one (the oldest one), but keep the second one?

 $ git log
commit 3368e1c5b8a47135a34169c885e8dd5ba01af5bb
...

commit baf8d5e7da9e41fcd37d63ae9483ee0b10bfac8e
...

From here:

http://friendfeed.com/harijay/742631ff/git-question-how-do-i-rollback-commit-just-want

Do I just need to do:

git reset --hard baf8d5e7da9e41fcd37d63ae9483ee0b10bfac8e

That is?


Solution 1:

The safest and probably cleanest way to go is to rebase interactively.

git rebase -i HEAD^^

Or,

git rebase -i baf8d5e7da9e41fcd37d63ae9483ee0b10bfac8e^

From there you can squash commits, which puts one or more commits together into the previous commit. To completely delete a commit from the history, delete the line from the list.

You can revert a commit with git revert but its going to add more commit messages to the history, which may be undesirable. Use the -n parameter to tell Git not to commit the revert right away. You can rebase interactively and squash those on up to a previous commmit to keep things clean.

If the two commits you're working with here affect the same file(s), you may see a merge conflict.

Resetting the repository with git reset --hard should be done with care, as it cannot be undone.

Rewriting history should be done with care.

Solution 2:

This if from http://nakkaya.com/2009/09/24/git-delete-last-commit/ and it worked for me

Git Delete Last Commit

Once in a while late at night when I ran out of coffee, I commit stuff that I shouldn't have. Then I spend the next 10 - 15 minutes googling how to remove the last commit I made. So after third time I wanted to make a record of it so I can refer to it later.

If you have committed junk but not pushed,

git reset --hard HEAD~1

HEAD~1 is a shorthand for the commit before head. Alternatively you can refer to the SHA-1 of the hash you want to reset to. Note that when using --hard any changes to tracked files in the working tree since the commit before head are lost.

If you don't want to wipe out the work you have done, you can use --soft option that will delete the commit but it will leave all your changed files "Changes to be committed", as git status would put it.

Now if you already pushed and someone pulled which is usually my case, you can't use git reset. You can however do a git revert,

git revert HEAD

This will create a new commit that reverses everything introduced by the accidental commit.