XCode 使用 PMD 扫描重复代码

作者: gaookey | 来源:发表于2021-07-03 11:04 被阅读0次

    使用 HomeBrew 安装 PMD

    brew install pmd
    
    image.png

    XcodeBuild Phases 中,我们增加一个新的 Run Script

    #检测swift代码
    #pmd cpd --files ${EXECUTABLE_NAME} --minimum-tokens 50 --language swift --encoding UTF-8 --format net.sourceforge.pmd.cpd.XMLRenderer > cpd-output.xml --failOnViolation true
    
    #检测objective-c代码
    pmd cpd --files ${EXECUTABLE_NAME} --minimum-tokens 20 --language objectivec --encoding UTF-8 --format net.sourceforge.pmd.cpd.XMLRenderer > cpd-output.xml --failOnViolation true
    
    # Running script
    php ./cpd_script.php -cpd-xml cpd-output.xml
    
    image.png image.png

    上面的脚本中使用 pmd 进行复制粘贴检查, 检查结果会存放在 cpd-output.xml 文件中。
    --minimum-tokens 的值是一个经验值,这个需要根据具体情况确定。

    另外脚本中需要 php 对输出脚本进行分析并显示到 Xcode 中,如果没有安装 php,则需要安装。安装PHP参考文章

    MAC HomeBrew 安装 php

    还有需要的 cpd_script.php 文件, 需要放到工程根目录,它的作用是利用之前生成的检查结果文件,将检查的结果显示到 Xcode 中,在工程主目录下,创建 cpd_script.php 文件

    <?php
    foreach (simplexml_load_file('cpd-output.xml')->duplication as $duplication) {
        $files = $duplication->xpath('file');
        foreach ($files as $file) {
            echo $file['path'].':'.$file['line'].':1: warning: '.$duplication['lines'].' copy-pasted lines from: '
                .implode(', ', array_map(function ($otherFile) { return $otherFile['path'].':'.$otherFile['line']; },
                array_filter($files, function ($f) use (&$file) { return $f != $file; }))).PHP_EOL;
        }
    }
    ?>
    

    php 脚本可以参考: https://link.jianshu.com/?t=https://krakendev.io/blog/generating-warnings-in-xcode

    测试

    新建空的 demo 工程,command + b 编译项目,工程目录下会出现 cpd-output.xml 文件,此时文件内容为空

    image.png

    在项目中添加相同代码

    image.png

    再次编译项目,cpd-output.xml 文件则会出现重复代码提示信息,项目中代码也同样会给出警告提示信息

    image.png image.png

    相关文章

      网友评论

        本文标题:XCode 使用 PMD 扫描重复代码

        本文链接:https://www.haomeiwen.com/subject/gynyeltx.html