使用Gradle

Lint

lint是android插件的一部分,但是默认的不会在新的项目中进行配置,如果想使用它,需要添加如下代码在build文件中的android片段中

lintOptions{
  warningsAsErrors true //把所有警告信息作为错误
  abortOnError true //如果有任何error就停止build
  htmlReport true 
  lintConfig file("${rootDir}/config/lint/lint-config.xml")
  htmlOutput file("${buildDir}/reports/lint/lint.html")
}

Gradle的android插件提供了一些预定义的任务,你可以使用选项任务获得完整的列表。

Andresguard tasks
-----------------
resguardDebug - Assemble Resource Proguard APK
resguardDev - Assemble Resource Proguard APK
resguardDevDebug - Assemble Resource Proguard APK
resguardDevRelease - Assemble Resource Proguard APK
resguardOffical - Assemble Resource Proguard APK
resguardOfficalDebug - Assemble Resource Proguard APK
resguardOfficalRelease - Assemble Resource Proguard APK
resguardRelease - Assemble Resource Proguard APK

Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project. //显示项目中的依赖项
signingReport - Displays the signing info for each variant. //显示签名信息
sourceSets - Prints out all the source sets defined in this project.//打印项目中定义的所有源代码集

Build tasks
-----------
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleDev - Assembles all Dev builds.
assembleOffical - Assembles all Offical builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileDevDebugAndroidTestSources
compileDevDebugSources
compileDevDebugUnitTestSources
compileDevReleaseSources
compileDevReleaseUnitTestSources
compileOfficalDebugAndroidTestSources
compileOfficalDebugSources
compileOfficalDebugUnitTestSources
compileOfficalReleaseSources
compileOfficalReleaseUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
compileRetrolambda - Converts all java 8 class files to java 6 or 7
extractDebugAnnotations - Extracts Android annotations for the debug variant into the archive file
extractReleaseAnnotations - Extracts Android annotations for the release variant into the archive file
mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'yingshibao'.
components - Displays the components produced by root project 'yingshibao'. [incubating]
dependencies - Displays all dependencies declared in root project 'yingshibao'.
dependencyInsight - Displays the insight into a specific dependency in root project 'yingshibao'.
dependentComponents - Displays the dependent components of components in root project 'yingshibao'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'yingshibao'. [incubating]
projects - Displays the sub-projects of root project 'yingshibao'.
properties - Displays the properties of root project 'yingshibao'.
tasks - Displays the tasks runnable from root project 'yingshibao' (some of the displayed tasks may belong to subprojects).

Install tasks
-------------
installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
installDevDebug - Installs the DebugDev build.
installDevDebugAndroidTest - Installs the android (on device) tests for the DevDebug build.
installDevRelease - Installs the ReleaseDev build.
installOfficalDebug - Installs the DebugOffical build.
installOfficalDebugAndroidTest - Installs the android (on device) tests for the OfficalDebug build.
installOfficalRelease - Installs the ReleaseOffical build.
uninstallAll - Uninstall all applications.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
uninstallDevDebug - Uninstalls the DebugDev build.
uninstallDevDebugAndroidTest - Uninstalls the android (on device) tests for the DevDebug build.
uninstallDevRelease - Uninstalls the ReleaseDev build.
uninstallOfficalDebug - Uninstalls the DebugOffical build.
uninstallOfficalDebugAndroidTest - Uninstalls the android (on device) tests for the OfficalDebug build.
uninstallOfficalRelease - Uninstalls the ReleaseOffical build.

Verification tasks
------------------
check - Runs all checks. 运行所有的检查
connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.//安装和运行测试代码
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
connectedDevDebugAndroidTest - Installs and runs the tests for devDebug on connected devices.
connectedOfficalDebugAndroidTest - Installs and runs the tests for officalDebug on connected devices.
deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintDevDebug - Runs lint on the DevDebug build.
lintDevRelease - Runs lint on the DevRelease build.
lintOfficalDebug - Runs lint on the OfficalDebug build.
lintOfficalRelease - Runs lint on the OfficalRelease build.
lintRelease - Runs lint on the Release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testDevDebugUnitTest - Run unit tests for the devDebug build.
testDevReleaseUnitTest - Run unit tests for the devRelease build.
testOfficalDebugUnitTest - Run unit tests for the officalDebug build.
testOfficalReleaseUnitTest - Run unit tests for the officalRelease build.
testReleaseUnitTest - Run unit tests for the release build.

运行检查

./gradlew check

代码分析

接下来使用PMD,Findbugs,Infer

PMD:是一个源代码分析器,他会发现代码中常见的缺陷,比如未使用的变量,空catch块,不必要的对象创建,PMD工作在源代码上,因此会发现以下问题比如:违反命名规定,缺少花括号,错放空指针检查,长参数列表,不必要的构造函数,switch中缺少break,PMD还会告诉你代码的循环复杂性等。

添加PMD作为一个分析器,我们将如下代码添加到build.gradle文件中

apply plugin: 'pmd'
def configDir = "${project.rootDir}/config"
def reportsDir = "${project.buildDir}/reports"
check.dependsOn 'pmd' 
task pmd(type: Pmd, dependsOn: "assembleDebug"){
  ignoreFailures = false
  ruleSetFiles = files("$configDir/pmd/pmd-ruleset.xml")
  ruleSets=[]
  source 'src/main/java'
  include '**/*.java'
  exclude '**/gen/**'
  reports {
    xml.enabled = true
    xml.enabled = true
    xml{
      destination "$reportsDir/pmd/pmd.xml"
    }
    html{
      destination "$reportsDir/pmd/pmd.html"
    }
  }
}
  • check.dependsOn 'pmd' 此行将PMD任务与检查链接,这意味着,当我们调用gradle check的时候,它会调用pmd作为依赖性任务。

  • ruleSetFiles 定义规则和细节的集合

  • reports 块 根据要扫描的内容,定义报告的位置

FindBugs

FindBugs是一个检测java程序可能的bug,潜在的错误的分析器,潜在错误分为四个等级,这是对开发人员的一种暗示,FindBugs使用java字节码,而不是源代码。

apply plugin: 'findbugs'

def configDir = "${project.rootDir}/config"
def reportsDir = "${project.buildDir}/reports"
check.dependsOn 'findbugs'
task findbugs(type: FindBugs, dependsOn:"assembleDebug")
    ignoreFailures = false
    effort = "max"
    reportLevel = "high"
    excludeFilter = new File("$configDir/findbugs/findbugs-filter.xml")
    classes = files("${buildDir}/intermediates/classes")
    source 'src/main/java'
    include '**/*.java'
    exclude '**/gen/**'
    reports {
        xml.enabled = true
        html.enabled = false
        xml{
            destination "$reportsDir/findbugs/findbugs.xml"
        }
        html{
            destination "$reportsDir/findbugs/findbugs.html"
        }
      classpath = files()
    }

说明

  • check.dependsOn 'findbugs' 与上面一样,链接到check
  • reportLevel="max" 他指定问题的优先级,如果设置为low,则不会使用confidence来过滤错误,如果设置为medium,则低可信度问题被抑制,如果设置为high,则仅报告高confidence问题。
  • effort 设置分析工作水平,启用分析,增加精度并发现更多的错误,可能需要花费更多内存和时间来处理。
  • reports 报告的保存位置。

Infer

infer是一个用于java,OC,C的静态分析工具,可以对@Nullable和@NonNull进行双重检查,并且可以执行一些Android的特定检查,Infer是一个独立的工具,默认情况下它不与Gradle集成,但是Uber为Infer开发了一个Gradle插件。
添加如下代码到你的build进程中:

apply plugin: 'com.uber.infer.android'
check.dependsOn 'inferDubug'
check.dependsOn 'eradicateDebug'
inferPlugin {
  infer{
    include = project.files("src/main")
    exclude = project.filese("build/")
  }
  eradicate{
    include=project.files("src/main")
    exclude = project.filese("build/")
  }
}

定义这个插件是非常简单的,我们只需要定义从检查中包含和排除的源。
现在我们添加了一下分析器,调用./gradlew check看看会发生什么。
在繁多的日志中,你将会看到类似于以下的内容。

生成文档

实现Gradle javaDoc插件

task javadoc(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    title = "Library SDK"
    classpath = files(project.android.getBootClasspath())
    destinationDir = file("${buildDir}/reports/javadoc/analytics-sdk/")
    options {
        links "http://docs.oracle.com/javase/7/docs/api/"
        linksOffline "http://d.android.com/reference","${android.sdkDirectory}/docs/reference"
    }
    exclude '**/BuildConfig.java'
    exclude '**/R.java'
}
afterEvaluate {
    // fixes issue where javadoc can't find android symbols ref: http://stackoverflow.com/a/34572606
    androidJavadocs.classpath += files(android.libraryVariants.collect { variant ->
        variant.javaCompile.classpath.files
    })
}

现在,调用./gradlew javadoc就会在build/reports/javadoc文件夹中找到完整的javadoc

代码覆盖率报告

我们需要使用Jacoco,一个java标准

apply plugin: 'jacoco'
jacoco {
    toolVersion = "0.7.5.201505241946"
}
task coverage(type: JacocoReport, dependsOn: "testDebugUnitTest") {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."
    reports {
        xml.enabled = true
        html.enabled = true
        html.destination "${buildDir}/reports/codecoverage"
    }
    def ignoredFilter = [
            '**/R.class',
            '**/R$*.class',
            '**/BuildConfig.*',
            '**/Manifest*.*',
            'android/**/*.*',
            'com.android/**/*.*',
            'com.google/**/*.*'
    ]
    def debugTree = fileTree(dir:"${project.buildDir}/intermediates/classes/debug", excludes: ignoredFilter)
    sourceDirectories = files(android.sourceSets.main.java.srcDirs)
    classDirectories = files([debugTree])
    additionalSourceDirs = files([
            "${buildDir}/generated/source/buildConfig/debug",
            "${buildDir}/generated/source/r/debug"
    ])
    executionData = fileTree(dir: project.projectDir, includes: ['**/*.exec', '**/*.ec'])
}

同样的需要调用./gradlew coverage 然后再build/reports/coverage中将会得到一个代码覆盖率文件。
一个重要的事情,如果调试过程中,注释掉了一下代码,之后还会使用的话,需要定义如下规则

<module name="Regexp">
    <property name="format" value="System\.err\.print" />
    <property name="illegalPattern" value="true" />
    <property name="message" value="Bad Move, You should not use System.err.println" />
</module>
<module name="Regexp">
    <property name="format" value="\.printStacktrace" />
    <property name="illegalPattern" value="true" />
    <property name="message" value="Bad Move, You should not use System.err.println" />
</module>
<!--Check for commented out code-->
<module name="Regexp">
    <property name="format" value="^\s*//.*;\s*$" />
    <property name="illegalPattern" value="true" />
    <property name="message" value="Bad Move, Commented out code detected, it smells." />
</module>

最后执行如下命令

./gradlew check // run unit tests
./gradlew javadoc // generate javadoc
./gradlew coverage // generate coverage reports
./gradlew assemble // assemble all build flavors

参考内容

原文地址:https://medium.com/contentsquare-engineering-blog/make-or-break-with-gradle-dac2e858868d

demo地址:https://github.com/smarkovik/make-or-break

Google Java Style Guide:http://checkstyle.sourceforge.net/reports/google-java-style-20170228.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,681评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,710评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,623评论 0 334
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,202评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,232评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,368评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,795评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,461评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,647评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,476评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,525评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,226评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,785评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,857评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,090评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,647评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,215评论 2 341

推荐阅读更多精彩内容