- When to undo a commit and when to revert a commit in git?
- What are the git commands to do both of them?
- How to perform both tasks using VS code (UI)?
Question posted in Visual Studio Code
View the official documentation.
View the official documentation.
2
Answers
A-undo commit (most recent(s))
Git commands:
To undo a
local commit
in Git, you can use thegit reset
command.Types/Options:
1. --mixed: undo commit +
unstaged the changes
and puts them back into theworking directory
.or
or
2. --soft: undo commit + keep the changes in the
staging area (index)
.3. --hard: undo commit +
discard/remove
all the changes.Note1: In all the
reset
commands, thebranch pointer
of your current branch will be moved to the previous commit (HEAD~
refers to the commit before the current one) as shown in the above image. Now if you want your changes in :working directory
use--mixed
option,staging area (index)
use--soft
option, anddiscard/remove
changes use--hard
option.Note2:
Undo commit **DOES NOT** creates a new commit
.Note3: You should undo commit(s) if your commit(s) is/are
local
, means you did not pushed intoremote
.B-revert commit
Git commands:
To undo a
published/remote commit
in Git, you can use thegit revert
command.Types/Options:
1. --no-edit: undo commit + creates a new commit (changes discarded in this commit)
Undo is to ditch last commit. It will not exists anymore in the current branch.
Command(s depending on how it is implemented in VSCode):
Or (to not keep changes in staging area):
Revert is creating a new commit that contains all the opposite changes of the commit you will revert. So original commit and new reverting commit are in the current branch.
Command:
Both strategies have pros and cons. Read about it.
The main idea is if it’s to fix an error just made and the commit has still not been pushed, undo is perfectly fine.
If commit/history has been pushed, except special cases, revert is more likely the way to go…
PS: another solution instead of undo could be just to amend the last commit…