davidmigloz/go-bees

View on GitHub
app/build.gradle

Summary

Maintainability
Test Coverage
/*
 * GoBees
 * Copyright (c) 2016 - 2017 David Miguel Lozano
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
 */

apply plugin: 'com.android.application'
apply plugin: 'jacoco-android'
apply plugin: 'realm-android'
apply plugin: 'io.fabric'
apply plugin: 'com.github.triplet.play'

// App version
ext.versionMajor = 1 // API Changes, adding big new feature, redesign the App
ext.versionMinor = 2 // New features in a backwards-compatible manner
ext.versionPatch = 0 // Backwards-compatible bug fixes
ext.versionClassifier = null // Pre-releases (alpha, beta, rc, SNAPSHOT...)

// Get signing config
def keystorePropertiesFile = rootProject.file("secrets/keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

android {

    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    signingConfigs {
        debug {
            keyAlias keystoreProperties['keyAliasDebug']
            keyPassword keystoreProperties['keyPasswordDebug']
            storeFile file(keystoreProperties['storeFileDebug'])
            storePassword keystoreProperties['storePasswordDebug']
        }
        relase {
            storeFile file(keystoreProperties['storeFileRelease'])
            storePassword keystoreProperties['storePasswordRelease']
            keyAlias keystoreProperties['keyAliasRelease']
            keyPassword keystoreProperties['keyPasswordRelease']
        }
    }

    playAccountConfigs {
        defaultAccountConfig {
            serviceAccountEmail = keystoreProperties['serviceAccountEmail']
            jsonFile = file(keystoreProperties['googlePlayKey'])
        }
    }

    play {
        track = 'beta'
    }

    defaultConfig {
        applicationId "com.davidmiguel.gobees"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode generateVersionCode()
        versionName generateVersionName()
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        manifestPlaceholders = [
                crashlyticsKey: keystoreProperties['CrashlyticsKey']
        ]
        buildConfigField 'String', 'COMMIT_HASH', "\"${getCommitHash()}\""
        buildConfigField 'String', 'BUILD_DATE', "\"${getBuildDate()}\""
        buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', keystoreProperties['OpenWeatherMapApiKey']
        playAccountConfig = playAccountConfigs.defaultAccountConfig
    }

    buildTypes {
        debug {
            testCoverageEnabled true
            aaptOptions {
                cruncherEnabled = false // No img optimization in debug
            }
        }
        release {
            shrinkResources true // Remove unused resources
            minifyEnabled true // Enable proguard (shrinks, optimizes and obfuscates code)
            debuggable false
            jniDebuggable false
            renderscriptDebuggable false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-guava.pro',
                    'proguard-mpandroidchart.pro',
                    'proguard-rounded-image-view.pro',
                    'proguard-realm.pro',
                    'proguard-rules.pro'
            testProguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguardTest-rules.pro'
            signingConfig signingConfigs.relase
        }
    }

    productFlavors {
        // Mock: mock data layer
        mock {
            applicationIdSuffix = ".mock"
            resValue('string', 'app_name', getAppName() + '-mock')
            ext.enableCrashlytics = false
        }
        // Dev: dev environment
        dev {
            applicationIdSuffix = ".dev"
            resValue('string', 'app_name', getAppName() + '-dev')
        }
        // Prod: production environment
        prod {
            resValue('string', 'app_name', getAppName())
        }
    }

    // Remove mockRelease as it's not needed.
    android.variantFilter { variant ->
        if (variant.buildType.name == 'release' && variant.getFlavors().get(0).name == 'mock') {
            variant.setIgnore(true);
        }
    }

    // android.jar methods return either null or zero, not throw exceptions
    testOptions {
        unitTests.returnDefaultValues = true
    }

    // Always show the result of every unit test, even if it passes
    testOptions.unitTests.all {
        testLogging {
            events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
        }
    }

    // Explicitly tells Gradle which version shall be compiled (due to Espresso conflicts)
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.2'
    }

    // Lint checks
    lintOptions {
        abortOnError false
        disable 'SetJavaScriptEnabled', 'MissingTranslation'
    }
}

sourceSets {
    test {
        java.srcDirs = ['src/test/res']
    }
}

dependencies {

    //----------------------------------------------------------------------------------------------
    // App Dependencies
    //----------------------------------------------------------------------------------------------

    // Support libraries : https://developer.android.com/topic/libraries/support-library/packages.html
    compile 'com.android.support:support-fragment:26.1.0'
    compile 'com.android.support:support-core-utils:26.1.0'
    compile 'com.android.support:support-core-ui:26.1.0'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'
    // Google Location and Activity Recognition : https://developers.google.com/android/guides/setup
    compile 'com.google.android.gms:play-services-location:11.4.0'
    // Firebase Analytics : https://firebase.google.com/docs/android/setup#available_libraries
    compile 'com.google.firebase:firebase-core:11.4.0'
    // OpenCV (computer vision) : https://github.com/davidmigloz/opencv-android-gradle-repo/
    compile 'com.github.davidmigloz:opencv-android-gradle-repo:3.2.0'
    // Guava (Google Core Libraries) : https://github.com/google/guava
    compile 'com.google.guava:guava:23.0-android'
    // RoundedImageView (ImageView that supports rounded corners) : https://github.com/vinc3m1/RoundedImageView
    compile 'com.makeramen:roundedimageview:2.3.0'
    // MPAndroidChart (chart view / graph view) : https://github.com/PhilJay/MPAndroidChart
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
    // VNTNumberPickerPreference (NumberPicker Preference) : https://github.com/vanniktech/VNTNumberPickerPreference
    compile 'com.vanniktech:vntnumberpickerpreference:1.0.0'
    // Permission Utils (check runtime permissions) : https://github.com/rebus007/PermissionUtils
    compile 'rebus:permission-utils:2.0.1'

    //----------------------------------------------------------------------------------------------
    // Debugging / logging dependencies
    //----------------------------------------------------------------------------------------------

    // Timber (logger) : https://github.com/JakeWharton/timber
    compile 'com.jakewharton.timber:timber:4.5.1'
    // Crashlytics (Crash reporting) : https://docs.fabric.io/android/changelog.html#crashlytics
    compile('com.crashlytics.sdk.android:crashlytics:2.7.0@aar') {
        transitive = true;
    }

    //----------------------------------------------------------------------------------------------
    // Testing Dependencies
    //----------------------------------------------------------------------------------------------

    // JUnit (unit testing framework) : http://junit.org/junit4/
    testCompile 'junit:junit:4.12'
    // Mockito (mocking framework) : http://site.mockito.org/
    testCompile 'org.mockito:mockito-core:2.10.0'
    // PowerMock (mocking framework) : https://github.com/powermock/powermock
    testCompile "org.powermock:powermock-module-junit4:1.7.1"
    testCompile "org.powermock:powermock-api-mockito2:1.7.1"
    testCompile 'org.slf4j:slf4j-api:1.7.22'
    testCompile 'org.slf4j:slf4j-log4j12:1.7.22'
    testCompile 'log4j:log4j:1.2.17'
    testCompile 'org.json:json:20160810'
    // Android Testing Support Library's runner and rules
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    // Dependencies for Android unit tests
    androidTestCompile 'junit:junit:4.12'
    androidTestCompile 'org.mockito:mockito-core:2.6.2'
    // Espresso UI Testing
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.2.2'
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'
    // Resolve conflicts between main and test APK:
    androidTestCompile 'com.android.support:support-v4:26.1.0'
    androidTestCompile 'com.android.support:support-annotations:26.1.0'

}

/*
All direct/transitive dependencies shared between your test and production APKs need to be
excluded from the test APK! This is necessary because both APKs will contain the same classes. Not
excluding these dependencies from your test configuration will result in an dex pre-verifier error
at runtime. More info in this tools bug: (https://code.google.com/p/android/issues/detail?id=192497)
*/
configurations.compile.dependencies.each { compileDependency ->
    println "Excluding compile dependency: ${compileDependency.getName()}"
    configurations.androidTestCompile.dependencies.each { androidTestCompileDependency ->
        configurations.androidTestCompile.exclude module: "${compileDependency.getName()}"
    }
}

/*
Copy test resources directory (test/mock/debug).
*/
task copyResDirectoryToTestMockDebugClasses(type: Copy) {
    from "${projectDir}/src/testMock/res"
    into "${buildDir}/intermediates/classes/test/mock/debug/res"
}

/*
Run copy test resources directory tasks before build.
*/
afterEvaluate {
    preBuild.dependsOn(copyResDirectoryToTestMockDebugClasses)
}

/*
SonarQube configuration.
*/
sonarqube {
    properties {
        property "sonar.projectName", "GoBees"
        property "sonar.projectKey", "com.davidmiguel.gobees"
        property "sonar.language", "java"
        property "sonar.projectVersion", "1.1"
        property "sonar.exclusions", "**/*.png,**/*.jpg"
        property "sonar.android.lint.report", "./build/outputs/lint-results-mockDebug.xml"
        property "sonar.junit.reportsPath", "./build/test-results/mockDebug"
        property "sonar.jacoco.reportPath", "./build/jacoco/testMockDebugUnitTest.exec"
        property "sonar.java.coveragePlugin", "jacoco"
        property "sonar.jacoco.reportMissing.force.zero", true
    }
}

/**
 * Returns the number of the current build in Travis.
 */
private static Integer getBuildNumber() {
    return System.getenv()["TRAVIS_BUILD_NUMBER"] as Integer ?: 1
}

/**
 * Version code: MMMmmppbbb
 */
private Integer generateVersionCode() {
    Integer versionCode = ext.versionMajor * 10000000 +
            ext.versionMinor * 100000 +
            ext.versionPatch * 1000 +
            (getBuildNumber() % 1000)
    println "Version code: " + versionCode
    return versionCode
}

/**
 * Version name: <major>.<minor>.<patch>
 * For mock, dev, tst and acc <build> is attached at the end.
 */
private String generateVersionName() {
    String versionName = "${ext.versionMajor}.${ext.versionMinor}.${ext.versionPatch}"
    if (ext.versionClassifier != null) {
        versionName += "-" + ext.versionClassifier
    }
    println "Version name: " + versionName
    return versionName;
}

/**
 * Returns git commit long hash.
 */
private String getCommitHash() {
    return 'git rev-parse HEAD'.execute([], project.rootDir).text.trim();
}

/**
 * Returns build date.
 */
private static String getBuildDate() {
    return new GregorianCalendar().format("yyyy-MM-dd'T'HH:mm.ss'Z'");
}

/**
 * Returns app name.
 */
private static String getAppName() {
    return "GoBees"
}

apply plugin: 'com.google.gms.google-services'