我想编写shell脚本来解析java源文件并根据一些规则找出源代码中的常见违规行为。这个脚本应该在添加/修改的新代码上运行,这不应该得到旧代码。我的代码库是 git。
如何从 git 获取新添加/修改的行。然后我可以在上面执行我的脚本。
如果您想对代码应用一些解析操作,您最好解析整个文件,而不是只发现修改过的行。最重要的是,“附加线”的概念很大程度上取决于在 中实施的启发式方法diff
,并且通常会给您提供与您期望的结果不符的结果。
我没有从您的问题中获得上下文,尤其是您打算比较的内容:
git diff --name-only
or git 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>
如果您真的只想要修改/添加的行:只需 grep 它们git diff
对于每个修改过的文件,运行类似:
# get lines starting with '+', but drop the extra '+++ the/file' line added
# by git
git diff <a> <b> -- the/file | grep '^+' | grep -v '^+++'