如何恢复较新提交所做的一些更改?

时间:2015-12-23 18:30:36

标签: git

我想要撤消我在一个文件中使用最新提交所做的一些但不是全部的更改。 优选地,部分还原的文件应该驻留在我的工作目录中。

我对checkout --patch filename感到困惑,最好的方法是什么?

5 个答案:

答案 0 :(得分:1)

正如你自己所说,git checkout --patch是实现这一目标的最佳方式。您可能会感到困惑,因为您需要指定要从中检出的树形对象(提交或分支)。在您的特定示例中,您需要git checkout --patch HEAD~1

git checkout --patchgit add --patch的行为非常相似,只是它从另一个树添加到工作目录而不是工作目录到索引。

当您输入要检出的树和路径时会发生什么情况,git会在您的文件和要检出的文件之间显示一块一块的差异。然后,您可以指定是要应用块,拒绝块还是将块拆分为更小的块。在此交互式工具中按?以获取您可以执行的操作的完整列表。

看起来应该是这样的:

$ # git checkout --patch <tree>  <path>
$   git checkout --patch 9e881cb conf/nginx.conf 
diff --git b/conf/nginx.conf a/conf/nginx.conf
index ff0454a..a3c3ed7 100644
--- b/conf/nginx.conf
+++ a/conf/nginx.conf
@@ -1,12 +1,8 @@
 server {
   server_name strikeskids.com;
+  root /www/strikeskids;

   location / {
-    root /www/strikeskids/jekyll;
     try_files $uri $uri.html $uri/index.html =404;
   }
-
-  location /up/ {
-    root /www/strikeskids;
-  }
 }
Apply this hunk to index and worktree [y,n,q,a,d,/,s,e,?]? s <=== split 
                             chunk into smaller pieces
Split into 3 hunks.
@@ -1,4 +1,5 @@
 server {
   server_name strikeskids.com;
+  root /www/strikeskids;

   location / {
Apply this hunk to index and worktree [y,n,q,a,d,/,j,J,g,e,?]? y <=== include
                             this chunk in the checkout
@@ -3,5 +4,4 @@

   location / {
-    root /www/strikeskids/jekyll;
     try_files $uri $uri.html $uri/index.html =404;
   }
Apply this hunk to index and worktree [y,n,q,a,d,/,K,j,J,g,e,?]? n <=== do not
                             include this chunk in the checkout
@@ -6,7 +6,3 @@
     try_files $uri $uri.html $uri/index.html =404;
   }
-
-  location /up/ {
-    root /www/strikeskids;
-  }
 }
Apply this hunk to index and worktree [y,n,q,a,d,/,K,g,e,?]? q <== finish now, 
                             including the chunks I've specified but not any others

答案 1 :(得分:1)

git checkout HEAD~1 path/to/file为您提供该文件的先前版本。然后你可以撤消你想要保留的更改(因此,使文件看起来像你想要的那样),然后像往常一样提交更改。

答案 2 :(得分:0)

如果您被允许重写您的历史记录(例如,如果您的提交未被推送到远程存储库):

# undo your commit
git reset HEAD~
# now remove the changes you didn't want in your last commit
# and commit again
git commit 

答案 3 :(得分:0)

有两种方法可以实现这一目标:

1)由于您已经提交了代码,请使用

git reset --soft HEAD ^

这将取消提交代码,现在您可以根据您的要求修改文件。

2)对于像Git这样的版本控制系统,您不必担心提交,因为它基本上包含了您的所有历史记录。 您可以继续在此提交之上进行更改,以基本上删除您错误提交的代码。

但是,只有在必须修改少量代码时才更喜欢选项2,否则请选择选项1。

答案 4 :(得分:0)

也许你会对How to undo (almost) anything with Git上github博客上非常好的帖子感兴趣...