简体   繁体   English

Git:恢复单个文件上的旧提交

[英]Git: Revert old commit on single file

I'm pretty new to using revert in git, and I'm wondering if something like the following can be done. 我在git中使用revert非常新,我想知道是否可以完成以下操作。 Let's say I have made a few commits already, and I have a (self-explanitory) text file which looks like the following: 假设我已经进行了几次提交,并且有一个(自说明)文本文件,如下所示:

This line was added at commit AAAAA
This line was added at commit BBBBB
This line was added at commit CCCCC

I would like to use revert to remove the changes made by commit BBBBB, to get a file that looks like this: 我想使用还原删除由提交BBBBB所做的更改,以获取如下所示的文件:

This line was added at commit AAAAA
This line was added at commit CCCCC

However, reverting commit BBBBB results in a merge conflict. 但是,还原提交BBBBB会导致合并冲突。 Is there any way to avoid the conflict? 有什么办法可以避免冲突?

However, reverting commit BBBBB results in a merge conflict. 但是,还原提交BBBBB会导致合并冲突。 Is there any way to avoid the conflict? 有什么办法可以避免冲突?

To find out exactly what's causing the conflict, do 要找出导致冲突的确切原因,请执行

git checkout --merge --conflict=diff3 -- path/to/file

which will show you the original and both changed versions of the text git's unwilling to automerge. 这将向您显示文本git不想自动合并的原始版本和两个更改版本。

What boils down to is, git is merging the change from the reverted commit to its parent with the change from the reverted commit to the current version: 归结为,git将合并的还原提交到其父级与变更的提交合并到当前版本:

 bbbbb verson -> aaaaa version,

and

 bbbbb version -> cccccc version (+ whatever else)

and the change hunks overlap, so, git's not going to automerge. 并且更改块重叠,因此git不会自动合并。

As a practical matter, given the amount of merging being done in several huge projects, you can be sure any automerging git refuses to do produces bad results too often to tolerate. 实际上,考虑到在多个大型项目中进行的合并数量,您可以确保任何自动合并的git拒绝这样做都会导致不良后果,而这是经常容忍的。

if you want to revert changes only on single file, assuming, that you want to revert part of the last commit, you can just checkout the version of file from previous commit 如果您只想还原单个文件上的更改(假设您想还原上一次提交的一部分),则只需从上一次提交中签出文件的版本

git checkout HEAD~1 directory/path/file.txt
git add directory/path/file.txt
git commit -m "directory/path/file.txt reverted"

Basically git checkout HEAD . 基本上是git checkout HEAD . reset all files from working directory or only specified directories or only single files, to specified state of given commit. 将所有文件从工作目录或仅指定目录或仅单个文件重置为给定提交的指定状态。

Also if you want to revert one directory to state of 3 commits ago, you can: 另外,如果要将目录还原到3次提交之前的状态,则可以:

git checkout HEAD~3 some/directory/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM