linux - 带有行号和正确代码对齐/缩进的 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
}
解决方案
它应该是一个小错字(很可能),因为printf()
在格式说明符之后awk
需要一个,
printf "-%-8s:", left++ line
# ^^^
推荐阅读
- python - 我如何摆脱 datetime 函数中的时间?
- django - 无法导入 view_production.views。错误是:没有名为 reportlab.graphics.shapes 的模块
- javascript - 嵌套 React 条件渲染的问题
- javascript - 让匿名用户通过 api 在我自己的个人 google 议程中创建事件
- postgresql - 如何检索 PostgreSQL 数据库和表静态数据并加载到 Power BI 仪表板?
- grep - 在 R 中使用 grep 进行数据清理
- c# - 如何在 Xamarin.Forms 页面中使用 Spotlight Xamarin.Android 库
- sql - 尽管编码设置与 DBI 相同,但 RODBC 未读取 unicode
- python - 按索引熊猫删除列
- python - MagicMock 对象的计算结果为 False