How to undo/redo commit in Git?
Opened this issue · 0 comments
BensonLiao commented
When using Git, we sometimes do commit unintentionally or want to track and test on different version of codebase.
We can do it base on 3 commands: revert
, rebase
and reset
Let's quickly look at its description,
first are revert
:
Revert some existing commits.
Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them. This requires your working tree to be clean (no modifications from the HEAD commit).
Here's a illustration about the behavior:
If u want to revert by the last n commits, try git revert <rev>~<n>
If u want to revert the specific commit, try git revert <sha1-id>
.
can be full 40 digits or a leading substring that is unique within the repository.
Note. like any type of parameter above, this will revert to the 's parent commit object, so actually the commands will revert to the earlier one commit of the commit object
There are more parameter can be used, see https://git-scm.com/docs/gitrevisions
rebase
:
Reapply commits on top of another base tip. Keep it mind that rebase
are not rewrite history but append with it.
Here's 2 illustrations about the behavior:
reset
:
Reset current HEAD to the specified state. There's 2 option to do reset, soft and hard. And as the name implies, the soft option are not actually delete those commit history while the hard does. So be carefully with the hard option, and the default option is soft.
Here's 2 illustrations about the behavior:
If you want to undo a commit other than the latest on a branch, git revert
is your friend.
But if you want to test or restore on certain point of the entire codebase for a branch, use git rebase
or git reset
.
For test safety we should always create a new branch to do that.
- Create and copy from the branch we want to test:
git branch test_branch
- (Optional) Or use
git checkout -b test_branch
to skip step 2.
- (Optional) Or use
- Switch to the branch we created:
git checkout test_branch
git rebase <sha1-id>
orgit reset --hard <sha1-id>
- That's it, we are good to test!
For restore a branch, skip the first 2 steps of course.
There are also have more parameter can be used, see https://git-scm.com/docs/gitrevisions
to be continue...