XCode 使用 PMD 掃描重復代碼

使用 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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容