git - 如何使用 git 检测复制和粘贴的代码?

标签 git copy-paste

我刚刚阅读了 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/

相关文章:

git - 如何设置 magit 提交作者?

linux - 如何更改 docker id 和名称

visual-studio-2008 - 如何在Visual Studio 2008中自定义复制/粘贴行为?

linux - Vim同时写入两个寄存器

bash - 将整个内容从一个文件夹复制到另一个 shell 脚本

regex - Powershell正则表达式组正则表达式匹配但没有我的组。缺少了什么?

git - 使用多个 GIT 存储库构建 TFS

git - 将 git 用于具有很多很多 repos 的项目

Excel 宏 - 仅将非空单元格从一张工作表粘贴到另一张工作表

vim - 将多行字符串粘贴到光标位置的GVIM中