使用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

    原文作者:小菜鸟程序媛
    原文地址: https://www.jianshu.com/p/4152105485ba
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞