使用 git 比较两个提交中的一个文件
我有一个文件在某处损坏了,并且我找到了它仍然被修复的最后一个点。
我想知道如何使用 git 比较两个提交中的一个文件,或者这是否是玩这个游戏的最佳方式!
I have a file that has broken somewhere down the line, and I have found the last point in which it was still fixed.
I would like to know how, using git, I can compare one file from two commits, or indeed if that is the best way to play this!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了直接回答您的问题,假设您想比较当前
master
和旧提交f4l4f3l
之间的文件src/toaster.c
,您可以这样做:作为替代方案,您可以使用以下命令查看对该文件的所有更改:
然而,更一般地说,如果您试图找到引入特定错误的提交,git 有一个很棒的工具可以做到这一点,称为git bisect。如果您告诉该工具一个有效和无效的提交,它将使用二分搜索策略为您提供一系列提交以在这些提交之间进行测试。
您将开始使用以下命令进行二等分:
然后,如果您当前的提交有错误,您只需执行以下操作:
接下来,您需要找到一个肯定没有错误的旧提交。这可能有一个特定的标签,或者您可能只是选择几个月前的提交。假设其中一个名为
a12b3d
,那么您会这样做:此时,git 将计算出您需要测试的下一个提交,并执行
git checkout
来移动你的承诺。 (这些签出都将带有“分离的 HEAD”,因此您的原始分支指针不会更改。)然后测试该提交,并运行 git bisect good 或 git bisect bad 。取决于它是否有错误。修订版之间的二分搜索将快速缩小到第一个错误提交,并报告它是哪一个。然后回到你正在做的事情,你可以这样做:To directly answer your question, suppose you want to compare the file
src/toaster.c
between your currentmaster
and the old commitf4l4f3l
, you can just do:As an alternative, you can just look through all the changes to that file with:
More generally, however, if you're trying to find the commit where a particular bug was introduced, git has a marvellous tool for this, called git bisect. If you tell this tool a working and non-working commit, it will give you a series of commits to test in between those, using a binary search strategy.
You would start bisecting with the command:
Then if your current commit has the bug, you just do:
Next, you need to find an older commit that definitely didn't have the bug. This might have a particular tag, or perhaps you'll just pick a commit that was some months ago. Suppose that one is called
a12b3d
, then you would do:At that point, git will work out the next commit you'll need to test, and do
git checkout
to move you to that commit. (These checkouts will all be with "detached HEAD", so your original branch pointer is unchanged.) You then test that commit, and rungit bisect good
orgit bisect bad
depending on whether it has the bug or not. This binary search between the revisions will quickly narrow down to the first bad commit, and report which one it is. Then to go back to what you were doing, you can do:例如,您会看到文件
file.c
现在与两次提交之间的差异For instance, you see the difference for a file
file.c
between now and two commits back