首页 > 解决方案 > 带有行号和正确代码对齐/缩进的 git diff

问题描述

我在这里从其他人那里获得了这个代码示例:

  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}'

并希望它输出正确对齐的行。不幸的是,它可能会像这样输出行号git diff

+240:+ some code here
(241,257): some code here

而不是强制对齐:

+240     :+some code here
(241,257): some code here

这是我尝试过的一件事,认为printf可能会成功(例如:)printf "-%-8s:"

  git diff HEAD~..HEAD --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~/^-/{printf "-%-8s:" left++ line;next};\
      bare~/^[+]/{printf "+%-8s:" right++ line;next};\
      {print "("left++","right++"): "line;next}'

但它会产生这个错误:

gawk: cmd. line:5: (FILENAME=- FNR=9) fatal: not enough arguments to satisfy format string
    `-%-8s:151-    STR_GIT_LOG="" #######'
        ^ ran out for this one

这个 bash 脚本目前只是在我的脑海中,我已经修改了很长一段时间。也许有人可以帮助我?

此外,数字和 +/- 符号应分别为绿色和红色,就像在正常git diff输出中一样。


由 Ed Morton 编辑 - 通过使用gawk -o-gawk 5.0.1 进行漂亮打印,使 OPs 代码可读:

$ gawk -o- '{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}'

.

{
    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
}

标签: linuxgitawk

解决方案


它应该是一个小错字(很可能),因为printf()在格式说明符之后awk需要一个,

printf "-%-8s:", left++ line
#             ^^^

推荐阅读