Git allows you to build up your history in a way so that it has an actual value instead of just being a bunch of hashes with meaningless descriptions.
One of the easier possibilities to keep your history clean is by using git commit —amend
.
touch a.txt
git add a.txt
git commit -m 'Add files'
git log
> 175ec0b 4 seconds ago Dani (HEAD -> master) Add files
touch b.txt
git add b.txt
git commit --amend
git log
> d5538f2 48 seconds ago Dani (HEAD -> master) Add files
So here we’re amending our previous commit with the added file. But, what if we made a mistake while changing our commit by adding stuff that shouldn’t be added or amended to the last commit?
Shadow world
The hashes in the example above made very clear, that our amend
did not actually change the commit, instead it created a new one (175ec0b and d5538f2).
You won’t lose anything in Git that you’ve committed once. So also the first commit from above (175ec0b).
Our graph for the example now looks like this:
The commit 175ec0b is still around, but it is not reachable through the graph. With this information, it’s pretty easy and obvious how we can undo our amend.:
git reset 175ec0b --soft
git status
> (...)
> Untracked files:
> b.txt
Or without using the hash explicitly with offsets on the head pointer:
git reset 'HEAD@{1}' --soft
So we’re resetting to one commit before the current HEAD. The changes are now unstaged again and you can commit them again.
Of course, you can also use git reflog
to locate the commit.
Now the graph looks the opposite:
Again: the commit which was the result from the amend operation is still existing. So the falsely amended commit is still present but orphaned.
Top comments (0)