強制執(zhí)行Lint規(guī)范代碼

Lint

開發(fā)中使用靜態(tài)代碼檢測工具對代碼進行檢查,達到規(guī)范代碼減少bug的目的。常用的檢測工具有FindBugs、PMD、Coverity,Checkstyle。
Android工程使用Lint是最方便。Lint作為官方配套工具,功能完善,自定義擴展性強,常規(guī)需求基本可以做到無需修改。
自定義Lint網(wǎng)上相關(guān)文章也很多,不在本篇討論范圍之中。

現(xiàn)實

雖然Lint很好,能夠在代碼中實時提示,但只要不影響到編譯流程,改不改,全看開發(fā)者自覺。所以我們需要增加一些強制性,不修改就不能繼續(xù)。

  1. 將Lint任務(wù)部署到CI中,Pull Request進行Lint任務(wù),不通過則不允許提交
  2. hook到git commit,在git commit時執(zhí)行Lint任務(wù)
  3. 本地編譯時執(zhí)行Lint任務(wù),不通過中斷編譯

根據(jù)實際情況選擇即可,下面對方案3講解一下

插入到編譯過程中

眾所周知,apk生成或者aar生成會執(zhí)行assemble任務(wù),子module時在不輸出aar并不會執(zhí)行這個任務(wù),經(jīng)過
觀察會執(zhí)行bundleLibRuntimeToDirxxxx任務(wù),所以可以把Lint任務(wù)插入到這兩個任務(wù)之前執(zhí)行。

common.gradle, 基于AGP7.0+

/**當設(shè)置為true時每次運行都會進行l(wèi)int,設(shè)置為false時只會在發(fā)布版本時檢查*/
def lintAlways = true

def isAppModule = plugins.hasPlugin('com.android.application')
def isLibraryModule = plugins.hasPlugin('com.android.library')

//lint檢測
if (isAppModule) {
    android.applicationVariants.all { variant ->
        def lintTask = tasks["lint${variant.name.capitalize()}"]
        variant.assembleProvider.get().dependsOn lintTask
    }
} else if (isLibraryModule) {
    android.libraryVariants.all { variant ->
        def lintTask = tasks["lint${variant.name.capitalize()}"]
        if (lintAlways) {
            def runTask = tasks["bundleLibRuntimeToDir${variant.name.capitalize()}"]
            if (runTask != null) {
                //直接運行時也進行l(wèi)int
                runTask.dependsOn lintTask
            }
        }
        //打包成aar
        variant.assembleProvider.get().dependsOn lintTask
    }
}

最后在每個模塊引入這個gradle即可。

Lint配置

只有error或者fatal級別的issue,才會中斷編譯。如果我們想修改issue等級或者我們想忽略某些文件錯誤??梢栽诠こ谈夸浱砑?code>lint.xml文件,

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!-- Disable the given check in this project -->
    <issue id="IconMissingDensityFolder" severity="ignore" />

    <!-- Ignore the ObsoleteLayoutParam issue in the specified files -->
    <issue id="ObsoleteLayoutParam">
        <ignore path="res/layout/activation.xml" />
        <ignore path="res/layout-xlarge/activation.xml" />
    </issue>

    <!-- Ignore the UselessLeaf issue in the specified file -->
    <issue id="UselessLeaf">
        <ignore path="res/layout/main.xml" />
    </issue>

    <!-- Change the severity of hardcoded strings to "error" -->
    <issue id="HardcodedText" severity="error" />
</lint>

配置好后,當有error級別的issue未解決時就不編譯不通過,督促開發(fā)人員進行修改。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容