Git与行号的差异(Git日志与行号)

当我做一个git diff或者一个git log -p ,如何获得输出内联的源文件的行号?

我试图查找它的man git-diff | grep "line numbers" man git-diff | grep "line numbers" ,我尝试了谷歌search,但没有得到什么快速。

你不能用git diff获得可读的行数

目前还没有任何选项可以在git diff的一侧垂直显示行号。

统一的差异格式

这些信息在(c)hunk头文件中可以用于比较diff中的每一个变化,它只是在统一比较格式中 :

 @@ -start,count +start,count @@ 

文件的原始状态用-表示,新状态用+表示(它们并不意味着在hunk头文件中增加和删除, start表示每个版本的起始行号, count表示包括从起点开始的许多行。

 diff --git a/osx/.gitconfig b/osx/.gitconfig index 4fd8f04..fcd220c 100644 --- a/osx/.gitconfig +++ b/osx/.gitconfig @@ -11,7 +11,7 @@ <== HERE! [color "branch"] upstream = cyan [color "diff"] - meta = yellow + meta = cyan plain = white dim old = red bold new = green bold 

大块头

 @@ -11,7 +11,7 @@ 

说,该文件的以前版本从第11行开始,包括7行:

 11 [color "branch"] 12 upstream = cyan 13 [color "diff"] 14 - meta = yellow 14 + meta = cyan 15 plain = white dim 16 old = red bold 17 new = green bold 

而下一个版本的文件也从第11行开始,还包括7行。

统一差异格式不是真的供人使用

正如你可能会说,统一差异格式不容易找出行号(至less如果你不是一台机器)。 如果你真的想要你可以阅读的行号,你需要使用一个差异化工具来显示它们。

额外阅读

  • 官方的git-diff(1)手册页

这里有两个解决scheme,扩展Andy Talkowski的代码。

纯文本:

  git diff | gawk 'match($0,"^@@ -([0-9]+),[0-9]+ [+]([0-9]+),[0-9]+ @@",a){left=a[1];right=a[2];next};\ /^(---|\+\+\+|[^-+ ])/{print;next};\ {line=substr($0,2)};\ /^-/{print "-" left++ ":" line;next};\ /^[+]/{print "+" right++ ":" line;next};\ {print "(" left++ "," right++ "):"line}' 

彩色文本,假设\ 033 [66m是颜色代码的格式:

  git diff --color=always | \ gawk '{bare=$0;gsub("\033[[][0-9]*m","",bare)};\ match(bare,"^@@ -([0-9]+),[0-9]+ [+]([0-9]+),[0-9]+ @@",a){left=a[1];right=a[2];next};\ bare ~ /^(---|\+\+\+|[^-+ ])/{print;next};\ {line=gensub("^(\033[[][0-9]*m)?(.)","\\2\\1",1,$0)};\ bare~/^-/{print "-"left++ ":" line;next};\ bare~/^[+]/{print "+"right++ ":" line;next};\ {print "("left++","right++"):"line;next}' 

该代码将以“ – ”或“+”开始的行更改为“-1: – ”或“+1:+”,以及以“”开始的行为“(5,6):”。 数字是来自相应文件的行号。

这是一个脚本,试图解决这个问题 – 没有在愤怒testing,但似乎确定。 它依靠git diff产生的logging,并使用awk来维护行数。

 # Massage the @@ counts so they are usable function prep1() { cat | awk -F',' 'BEGIN { convert = 0; } /^@@ / { convert=1; } /^/ { if ( convert == 1 ) { print $1,$2,$3; } else { print $0; } convert=0; }' } # Extract all new changes added with the line count function prep2() { cat | awk 'BEGIN { display=0; line=0; left=0; out=1;} /^@@ / { out=0; inc=0; line=$4; line--; display=line; left=line; } /^[-]/ { left++; display=left; inc=0; } /^[+]/ { line++; display=line; inc=0; } /^[-+][-+][-+] / { out=0; inc=0; } /^/ { line += inc; left += inc; display += inc; if ( out == 1 ) { print display,$0; } else { print $0; } out = 1; inc = 1; display = line; }' } git diff $1 | prep1 | prep2 

你可以试试

 git blame 

在文件上。 它向您显示文件中每行的提交者,提交id和行号。