191

在编码时,我将打印语句添加到一些文件中以跟踪正在发生的事情。

完成后,是否可以还原某些文件中的更改,但提交我实际处理的文件?

假设我在 file 中添加了 print A,但我修改了 file BB是我想提交的A,我想恢复到原来的状态。

4

6 回答 6

297

根据您对文件 A 所做的更改,有三种基本方法可以做到这一点。如果您尚未将更改添加到索引或提交它们,那么您只想使用 checkout 命令 - 这将改变与存储库匹配的工作副本的状态:

git checkout A

如果您已经将其添加到索引中,请使用重置:

git reset A

如果你已经提交了它,那么你使用 revert 命令:

# the -n means, do not commit the revert yet
git revert -n <sha1>
# now make sure we are just going to commit the revert to A
git reset B
git commit

另一方面,如果您已经提交了它,但提交涉及的文件相当多,您也不想恢复,那么上述方法可能涉及很多“重置 B”命令。在这种情况下,您可能希望使用此方法:

# revert, but do not commit yet
git revert -n <sha1>
# clean all the changes from the index
git reset
# now just add A
git add A
git commit

另一种方法,需要使用 rebase -i 命令。如果您有多个要编辑的提交,这可能会很有用:

# use rebase -i to cherry pick the commit you want to edit
# specify the sha1 of the commit before the one you want to edit
# you get an editor with a file and a bunch of lines starting with "pick"
# change the one(s) you want to edit to "edit" and then save the file
git rebase -i <sha1>
# now you enter a loop, for each commit you set as "edit", you get to basically redo that commit from scratch
# assume we just picked the one commit with the erroneous A commit
git reset A
git commit --amend
# go back to the start of the loop
git rebase --continue
于 2009-06-01T02:16:14.540 回答
20

来源: http: //git-scm.com/book/en/Git-Basics-Undoing-Things

git checkout -- modifiedfile.java


1)$ git 状态

你会看到修改后的文件

2)$git checkout -- modifiedfile.java

3)$git 状态

于 2013-09-11T21:07:36.933 回答
7
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
于 2009-06-01T02:16:56.067 回答
6

人 git-checkoutgit checkout A

于 2009-06-01T02:11:04.690 回答
3

是的;

git commit FILE

将只提交文件。然后你可以使用

git reset --hard

撤消其他文件中的本地更改。

可能还有其他我不知道的方法...

编辑:或者,正如 NicDumZ 所说, git-checkout 只是要撤消更改的文件(最佳解决方案取决于是否有更多文件要提交或更多文件要撤消:-)

于 2009-06-01T02:13:49.473 回答
1

为什么你不能简单地使用“ git add <file> ”(甚至“git add --interactive”或具有交互式提交选项的“git gui”)标记你想要在提交中进行的更改,然后使用“git commit”而不是“git commit -a”?

在您的情况下(对于您的示例),它将是:

prompt> git add B
prompt> git commit

只会提交对文件 B 的更改,而文件 A 将保持“脏”状态,即在工作区版本中使用那些打印语句。当您想删除那些打印语句时,使用它就足够了

prompt> git reset A

或者

prompt> git checkout HEAD -- A

恢复到提交的版本(来自 HEAD 的版本,即“git show HEAD:A”版本)。

于 2009-06-02T12:14:12.600 回答