微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在提交中只获取新添加/修改的行的 git 命令是什么?

如何解决在提交中只获取新添加/修改的行的 git 命令是什么?

我想编写shell脚本来解析java源文件,并根据一些规则找出源代码中的常见违规行为。这个脚本应该在添加/修改的新代码上运行,这不应该得到旧代码。我的代码仓库是 git。

如何从 git 中获取添加/修改的行。然后我可以在上面执行我的脚本。

解决方法

如果你想对代码应用一些解析操作,你最好解析整个文件而不是只发现修改过的行。最重要的是,“添加行”的概念在很大程度上取决于 diff 中实现的启发式方法,并且通常会给您提供与您预期不符的结果。


我没有从您的问题中获得上下文,尤其是您打算比较的内容:

  • 要列出修改过的文件,请使用 git diff --name-onlygit diff --name-status :
# list of tracked files modified on disk since last commit :
git diff --name-status HEAD

# list of files modified between 2 commits :
git diff --name-status <commit1> <commit2>

# list of files modified in branch 'feature' since it forked from 'master' :
# (this will give you the same list as in a PR view)
git diff --name-status master...feature  # 3 dots,not a typo

# list files modified in a specific commit :
# compare it to its parent (add a '^' at the end)
git diff --name-status <commit>^ <commit>

如果您需要针对合并提交(有多个父项),git show 会尽量聪明一些,可能会给您更好的结果:

git show --format="" --name-only <commit>

如果你真的只想要修改/添加的行:只需从 git diff

grep 它们

对于每个修改过的文件,运行如下:

# get lines starting with '+',but drop the extra '+++ the/file' line added
# by git
git diff <a> <b> -- the/file | grep '^+' | grep -v '^+++'

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。