我刚刚阅读了 git-blame手册页再次注意到这部分:
A particularly useful way is to see if an added file has lines created by copy-and-paste from existing files. Sometimes this indicates that the developer was being sloppy and did not refactor the code properly. You can first find the commit that introduced the file with:
git log --diff-filter=A --pretty=short -- foo
and then annotate the change between the commit and its parents, using commit^! notation:
git blame -C -C -f $commit^! -- foo
这听起来很有趣,但我不太明白它是如何工作的,以及为什么。我想知道是否可以在 git 钩子(Hook)中使用它来检测复制和粘贴的代码。
一些 git 专家能否解释一下同时使用上述 git 命令的效果,以及是否可以使用类似的东西让 git 显示是否存在代码重复(可能通过使用 git 似乎计算的“相似性指数”重命名文件时)?
最佳答案
您可以单独分解命令。
$ git log --diff-filter=A --pretty=short -- foo
显示文件“foo”的日志。 --diff-filter
选项仅显示添加文件的提交(“A”),并以压缩格式显示(--pretty=short
选项). (--
是一种标准,表示“后面没有任何内容是一个选项”,之后的所有内容都是应该应用日志的文件名列表。)
然后:
$ git blame -C -C -f $commit^! -- foo
git blame
用上次提交的信息注释文件的每一行。双 -C -C
选项积极检查从其他文件复制的行。 -f
选项显示原始提交的文件名(这意味着如果一行是从另一个文件复制的,您会看到它被复制的文件的名称)。 $commit^!
是 $commit 的符号; ^!
后缀表示排除所有 $commit 的父项。
基本上,第一个命令 (git log
) 可以帮助您找到引入复制行的提交;第二个 (git blame
) 帮助您找到 source git log
返回的任何可疑提交。
关于git - 如何使用 git 检测复制和粘贴的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1939635/