2017年9月7日 星期四

[ Git 常見問題 ] Reset or revert a specific file to a specific revision using Git?

Source From Here 
Question 
I have made some changes to a file which has been committed a few times as part of a group of files, but now want to reset/revert the changes on it back to a previous version. I have done a git log along with a git diff to find the revision I need, but just have no idea how to get the file back to its former state in the past. 

How-To 
Assuming the hash of the commit you want is c5f567: 
# git checkout c5f567 -- file1/to/restore file2/to/restore

The git checkout main page gives more information. If you want to revert changes made to the files in commit c5f567 and subsequent commits, you have to pass the commit just before it. You can use refer to that commit as c5f567~1. As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual destructive things (discarding changes in the working directory). 

Below is a demonstration on above description: 
# vi Test // Add line "This is for revert testing" 
# git add Test 
# git commit -m 'R1' 
[master dbc6fb1] R1 
1 file changed, 2 insertions(+)
 

# vi Test // Add line "This is for revert testing again" 
# git add Test 
# git commit -m 'R2' 
[master 32e38df] R2 
1 file changed, 1 insertion(+)
 

# git log // Check commitment history 
commit 32e38df9489f9c24b6621b59c9109fb7f991e329 
Author: johnklee  
Date: Fri Sep 8 09:09:57 2017 +0800 

R2 

commit dbc6fb157236990cb0450d7355a6faa6c044f2b9 
Author: johnklee  
Date: Fri Sep 8 09:09:36 2017 +0800 

R1 
...
 

# git checkout dbc6fb157236990cb0450d7355a6faa6c044f2b9 -- Test // Revert file Test back to version 'R1' 
# git checkout dbc6fb157236990cb0450d7355a6faa6c044f2b9~1 -- Test // Revert file Test back to the version just before 'R1' 
# git diff 32e38df9489f9c24b6621b59c9109fb7f991e329 -- Test // Check the diff with version 'R2' by file Test 
diff --git a/Test b/Test 
index fcdc1cb..e9f5ce3 100644 
--- a/Test 
+++ b/Test 
@@ -10,6 +10,3 @@ This line is added by branch test (1) 

@ Update from test branch (4) 
@ Update from test branch (5) 
- 
-This is for revert testing 
-This is for revert testing again


沒有留言:

張貼留言

[ FP In Python ] Ch1. (Avoiding) Flow Control

Preface   In typical imperative Python programs—including those that make use of classes and methods to hold their imperative code—a block...