This section shows how to "undo" a previous commit. Git accomplishes this by applying the reverse changes, hence the entire commit history is intact.
Revert is doing a commit
Git has the principle of protecting data integrity. Hence if you decide to roll back, instead of truncating the commit history, it's adding the reverse change as a new commit. Git infers the reverse changes from the commit you want to undo.
In action
Let's create a new file, then revert it.
First, create a new file and make a commit.
D:\Work\git-prj (master)
λ echo import this > anotherfile.py
D:\Work\git-prj (master)
λ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
anotherfile.py
nothing added to commit but untracked files present (use "git add" to track)
D:\Work\git-prj (master)
λ git add anotherfile.py
D:\Work\git-prj (master)
λ git commit -m "Added another file"
[master 35ac407] Added another file
1 file changed, 1 insertion(+)
create mode 100644 anotherfile.py
D:\Work\git-prj (master)
λ git log --oneline
35ac407 (HEAD -> master) Added another file
ee7ebbd Print out the std dev
b1e55d3 Print out the mean
c96c526 First commit
D:\Work\git-prj (master)
λ ls
anotherfile.py myfile.py
We can see at the end, we have anotherfile.py. Now, if we revert this commit::
D:\Work\git-prj (master)
λ git revert 35ac407c88d
[master a37231a] Revert "Added another file"
1 file changed, 1 deletion(-)
delete mode 100644 anotherfile.py
D:\Work\git-prj (master)
λ git status
On branch master
nothing to commit, working tree clean
D:\Work\git-prj (master)
λ ls
myfile.py
We can see anotherfile.py is gone. The reversion annihilates the file creation in this commit.
Information is still there
If we look at the commit history:
D:\Work\git-prj (master)
λ git log --oneline
a37231a (HEAD -> master) Revert "Added another file"
35ac407 Added another file
ee7ebbd Print out the std dev
b1e55d3 Print out the mean
c96c526 First commit
We can see the original commit to create the file (35ac407) is in the commit history. This means if we check out the corresponding commit, we can still see anotherfile.py:
D:\Work\git-prj (master)
λ git checkout 35ac407
Note: switching to '35ac407'.
You are in 'detached HEAD' state. ...
D:\Work\git-prj (HEAD detached at 35ac407)
λ ls
anotherfile.py myfile.py
The undo is performed, while data integrity is not compromised.