列出GIT历史中给定行号的所有版本

  • 本文关键字:版本 GIT 历史 列出 git
  • 更新时间 :
  • 英文 :


在Git中,是否可以按行号列出文件中给定行的所有以前版本?

我觉得它有用的原因是能够更容易地根据记录的堆栈跟踪报告来解决问题。

即,我在给定文件的第100行记录了CCD_ 1。该文件包含在大量提交中,这导致给定的行可能在文件中上下移动,即使没有对其进行任何更改。

如何在最后x次提交中打印出给定文件第100行的内容?

这将为每个有意义的修订调用git blame,以显示文件$FILE:的第$LINE

git log --format=format:%H $FILE | xargs -L 1 git blame $FILE -L $LINE,$LINE

和往常一样,指责在每行的开头显示修订号。您可以附加

| sort | uniq -c

为了获得聚合结果,类似于更改此行的提交列表。(不完全是这样,如果代码只被移动过,这可能会对行的不同内容显示两次相同的提交ID。为了进行更详细的分析,你必须对相邻提交的git blame结果进行滞后比较。有人吗?)

这并不是你想要的,但使用git blame <file>,你可以看到最后一次修改每一行的提交。

第一列显示提交ID

$ git blame my-file.txt
65126918 (David Pärsson 2013-07-22 12:53:02 +0200 1) Heading
c6e6d36d (David Pärsson 2013-07-22 12:53:10 +0200 2) =======
65126918 (David Pärsson 2013-07-22 12:53:02 +0200 3) 
13e293e3 (David Pärsson 2013-07-22 12:49:33 +0200 4) Text on first line
8b3d2e15 (David Pärsson 2013-07-22 12:49:49 +0200 5) Text on second line
13e293e3 (David Pärsson 2013-07-22 12:49:33 +0200 6) Text on third line

您可以通过提供修订版(例如)来查看上次修改之后的

$ git blame 8b3d2e15 my-file.txt

您还可以使用-L参数选择特定的行,如下所示:

$ git blame my-file.txt -L 4,+3
13e293e3 (David Pärsson 2013-07-22 12:49:33 +0200 4) Text on first line
8b3d2e15 (David Pärsson 2013-07-22 12:49:49 +0200 5) Text on second line
13e293e3 (David Pärsson 2013-07-22 12:49:33 +0200 6) Text on third line

更多细节和巧妙的技巧可以在git指责手册页面上找到。

也可以看看这个简短的教程:http://zsoltfabok.com/blog/2012/02/git-blame-line-history/
基本上,它通过git blamegit show的组合来指导您查看哪一个提交更改了特定的行(undefined method exception0,特别是在David Parsson的回答中已经提出)以及该行是如何更改的(git show <commit-id>)。因此,迭代提交交替的git blame <commit-id>git show <commit-id>将为您提供文件特定行的完整历史记录
另外,不要忘记git blame -M,以防您怀疑该行是从另一个文件复制的。从…起https://www.kernel.org/pub/software/scm/git/docs/git-blame.html

-M|num|
检测文件中移动或复制的行。当提交移动或复制行块时(例如,原始文件有a,然后是B,提交将其更改为B,然后是a),传统的指责算法只注意到移动的一半,通常将向上移动的行(即B)归咎于父提交,并将向下移动的行的指责(即a)分配给子提交。使用此选项,通过运行额外的检查过程,两组行都会被归咎于父行

num是可选的,但它是git在文件中移动/复制时必须检测到的字母数字字符数的下限,以便将这些行与父提交相关联。默认值为20。

git blame <file> -L <line>,<line>

Git附带了一个奇特的GUI,它可以很容易地在时间上来回移动,以查看特定行是如何变化的。尝试

git gui blame <file>

你可以点击"穿越时空"链接旁边的修订版。

我认为您在git blame之后,它会告诉添加每一行的提交。

因此,运行git blame the-file-that-has-that-line.txt并转到第100行,它将告诉您是什么提交添加了它(以及何时提交,由谁提交)。

使用git blame实现

看看它是否工作

NAME
       git-blame - Show what revision and author last modified each line of a file
SYNOPSIS
       git blame [-c] [-b] [-l] [--root] [-t] [-f] [-n] [-s] [-e] [-p] [-w] [--incremental] [-L n,m]
                   [-S <revs-file>] [-M] [-C] [-C] [-C] [--since=<date>] [--abbrev=<n>]
                   [<rev> | --contents <file> | --reverse <rev>] [--] <file>
DESCRIPTION
       Annotates each line in the given file with information from the revision which last modified the line. Optionally, start annotating from the given revision.

最新更新