This repository has been archived by the owner on Jul 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathbuild.gradle
649 lines (535 loc) · 23.1 KB
/
build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'findbugs'
apply plugin: 'jacoco'
apply plugin: 'jacoco-android'
apply plugin: 'pmd'
apply plugin: 'checkstyle'
apply plugin: 'com.icesmith.androidtextresolver'
apply plugin: 'com.google.gms.oss.licenses.plugin'
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.android-text-resolver:buildSrc:1.1.0"
}
}
android {
compileSdkVersion Versions.compile_sdk
buildToolsVersion Versions.build_tools
defaultConfig {
applicationId "org.mozilla"
minSdkVersion Versions.min_sdk
targetSdkVersion Versions.target_sdk
resConfigs "en", "in"
versionCode Versions.version_code
versionName Versions.version_name
testInstrumentationRunner "org.mozilla.focus.test.runner.CustomTestRunner"
testInstrumentationRunnerArgument 'disableAnalytics', 'true'
testInstrumentationRunnerArguments clearPackageData: 'true'
multiDexEnabled true
def buddy_build_number = System.getenv("BUDDYBUILD_BUILD_NUMBER")
if (buddy_build_number?.trim()) {
versionCode buddy_build_number.toInteger()
versionNameSuffix "(" + buddy_build_number + ")"
}
def nevercode_build = System.getenv()["NEVERCODE_BUILD"]
if (nevercode_build) {
// bump 2000 to avoid build number collision with buddybuild
def nevercode_build_number = String.valueOf(System.getenv()["NEVERCODE_BUILD_NUMBER"].toInteger() + 2000)
versionCode nevercode_build_number.toInteger()
versionNameSuffix "(" + nevercode_build_number + ")"
}
def bitrise_build_number = System.getenv("BITRISE_BUILD_NUMBER")
if (bitrise_build_number?.trim()) {
def bitrise_build_number_with_offset = bitrise_build_number.toInteger() + 2200
versionCode bitrise_build_number_with_offset
versionNameSuffix "(" + bitrise_build_number_with_offset + ")"
}
// used by Room, to test migrations
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dexOptions {
preDexLibraries true
}
// We have a three dimensional build configuration:
// BUILD TYPE (debug, beta, release)
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
matchingFallbacks = ["firebase"]
}
beta {
initWith release
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
matchingFallbacks = ["release", "firebase"]
}
debug {
def userName = System.getenv("USER")
applicationIdSuffix ".debug." + userName
versionNameSuffix applicationIdSuffix
matchingFallbacks = ["firebase_no_op"]
}
// Use a separate buildType for coverage: testCoverageEnabled produces slower code (4-5x slower
// in places that I've benchmarked), and more importantly seems to break debugging with Android Studio
// for some developers (i.e. variables can't be inspected or seen).
coverage {
initWith debug
applicationIdSuffix ".coverage"
testCoverageEnabled true
matchingFallbacks = ["debug", "firebase_no_op"]
}
// special build type to develop Firebase related stuff
firebase {
initWith debug
applicationIdSuffix ".debug.firebase"
versionNameSuffix applicationIdSuffix
matchingFallbacks = ["debug", "firebase"]
}
}
testBuildType "firebase"
testOptions {
unitTests.returnDefaultValues = true
unitTests.includeAndroidResources = true
unitTests.all {
jacoco {
includeNoLocationClasses = true
}
}
execution 'ANDROID_TEST_ORCHESTRATOR'
}
// used by Room, to test migrations
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
flavorDimensions "product", "engine"
productFlavors {
focus {
dimension "product"
applicationIdSuffix ".rocket"
}
preview {
dimension "product"
applicationId "gro.allizom.zelda.beta"
applicationIdSuffix ""
versionNameSuffix ".nightly"
}
// We can build with two engines: webkit or gecko
webkit {
dimension "engine"
}
}
variantFilter { variant ->
def flavors = variant.flavors*.name
// We only need a gecko debug and beta build for now.
if (flavors.contains("preview") && variant.buildType.name != "beta") {
setIgnore(true)
}
}
sourceSets {
test {
resources {
// Make the default asset folder available as test resource folder. Robolectric seems
// to fail to read assets for our setup. With this we can just read the files directly
// and do not need to rely on Robolectric.
srcDir "${projectDir}/src/main/assets/"
}
}
focusWebkitRelease {
java.srcDir 'src/focusRelease/java'
manifest.srcFile 'src/focusRelease/AndroidManifest.xml'
}
previewWebkitBeta.res.srcDir 'src/preview/res'
// used by Room, to test migrations
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
}
jacocoAndroidUnitTestReport {
csv.enabled false
html.enabled true
xml.enabled true
}
repositories {
flatDir {
dirs 'libs'
}
mavenCentral()
}
dependencies {
implementation project(':third_party:subsampling-scale-image-view')
implementation project(':third_party:glide:annotation')
implementation project(':third_party:glide:library')
kapt "com.github.bumptech.glide:compiler:${Versions.glide}"
implementation project(':firebase')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Versions.kotlin}"
implementation "com.android.support:support-v4:${Versions.support}"
implementation "com.android.support:appcompat-v7:${Versions.support}"
implementation "com.android.support:design:${Versions.support}"
implementation "com.android.support:cardview-v7:${Versions.support}"
implementation "com.android.support:recyclerview-v7:${Versions.support}"
implementation "com.android.support.constraint:constraint-layout:${Versions.constraint}"
// Architecture components
implementation "android.arch.lifecycle:extensions:${Versions.lifecycle}"
implementation "android.arch.lifecycle:common-java8:${Versions.lifecycle}"
implementation "android.arch.persistence.room:runtime:${Versions.room}"
kapt "android.arch.persistence.room:compiler:${Versions.room}"
implementation("com.google.code.findbugs:annotations:${Versions.findbugs}", {
// We really only need the SuppressFBWarnings annotation, everything else can be ignored.
// Without this we get weird failures due to dependencies.
transitive = false
})
implementation "org.mozilla.components:telemetry:${Versions.telemetry}"
implementation "com.adjust.sdk:adjust-android:${Versions.adjust}"
implementation "com.google.android.gms:play-services-analytics:${Versions.firebase}" // Required by Adjust
implementation "com.airbnb.android:lottie:${Versions.lottie}"
testImplementation "junit:junit:${Versions.junit}"
testImplementation "org.robolectric:robolectric:${Versions.robolectric}"
testImplementation "org.mockito:mockito-core:${Versions.mockito}"
androidTestImplementation("com.android.support.test.espresso:espresso-core:${Versions.espresso}", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation "com.android.support.test:runner:${Versions.test_runner}"
androidTestImplementation "com.android.support.test.espresso:espresso-idling-resource:${Versions.espresso}"
androidTestImplementation "com.android.support:support-annotations:${Versions.support}"
androidTestImplementation "com.android.support.test.uiautomator:uiautomator-v18:${Versions.uiautomator}"
androidTestImplementation "com.squareup.okhttp3:mockwebserver:${Versions.mockwebserver}"
androidTestImplementation "android.arch.persistence.room:testing:${Versions.room}"
androidTestImplementation "android.arch.core:core-testing:${Versions.arch_core}"
androidTestImplementation("com.android.support.test.espresso:espresso-contrib:${Versions.espresso}", {
exclude group: 'com.android.support', module: 'appcompat'
exclude group: 'com.android.support', module: 'support-v4'
exclude module: 'recyclerview-v7'
})
androidTestImplementation "com.android.support.test.espresso:espresso-web:${Versions.espresso}"
androidTestImplementation "com.android.support.test.espresso:espresso-intents:${Versions.espresso}"
androidTestUtil "com.android.support.test:orchestrator:${Versions.test_runner}"
// LeakCanary
debugImplementation "com.squareup.leakcanary:leakcanary-android:${Versions.leakcanary}"
betaImplementation "com.squareup.leakcanary:leakcanary-android-no-op:${Versions.leakcanary}"
coverageImplementation "com.squareup.leakcanary:leakcanary-android-no-op:${Versions.leakcanary}"
releaseImplementation "com.squareup.leakcanary:leakcanary-android-no-op:${Versions.leakcanary}"
firebaseImplementation "com.squareup.leakcanary:leakcanary-android:${Versions.leakcanary}"
}
// -------------------------------------------------------------------------------------------------
// LeakCanary - Ensure the no-op dependency is always used in JVM tests.
// -------------------------------------------------------------------------------------------------
configurations.all { config ->
if (config.name.contains('UnitTest') || config.name.contains('AndroidTest')) {
config.resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.squareup.leakcanary' && details.requested.name == 'leakcanary-android') {
details.useTarget(group: details.requested.group, name: 'leakcanary-android-no-op', version: details.requested.version)
}
}
}
}
// -------------------------------------------------------------------------------------------------
// Generate blocklists
// -------------------------------------------------------------------------------------------------
def blockListOutputDir = 'src/webkit/res/raw'
task buildBlocklists(type: Copy) {
from('../shavar-prod-lists') {
include '*.json'
}
into blockListOutputDir
// Android can't handle dashes in the filename, so we need to rename:
rename 'disconnect-blacklist.json', 'blocklist.json'
rename 'disconnect-entitylist.json', 'entitylist.json'
// google_mapping.json already has an expected name
}
clean.doLast {
file(blockListOutputDir).deleteDir()
}
tasks.whenTaskAdded { task ->
def name = task.name
if (name.contains("generate") && name.contains("Config") && name.contains("Webkit")) {
task.dependsOn buildBlocklists
}
}
// -------------------------------------------------------------------------------------------------
// Adjust: Read token from environment variable (Only release builds)
// -------------------------------------------------------------------------------------------------
android.applicationVariants.all { variant ->
def variantName = variant.getName()
print(variantName + ": ")
if (variantName.contains("Release") && variantName.contains("focus")) {
def token = System.getenv("ADJUST_TOKEN_FOCUS") ?: null
if (token != null) {
buildConfigField 'String', 'ADJUST_TOKEN', '"' + token + '"'
println "Added adjust token set from environment variable"
} else {
buildConfigField 'String', 'ADJUST_TOKEN', 'null'
println("Not setting adjust token (environment variable not set)")
}
} else {
buildConfigField 'String', 'ADJUST_TOKEN', 'null'
println("Not setting adjust token (Not a focus release build)")
}
if (variant.buildType.name == "release" || variant.buildType.name == "beta"|| variant.buildType.name == "firebase") {
variant.assemble.doFirst {
if (SystemEnv.google_app_id == null || SystemEnv.default_web_client_id == null ||
SystemEnv.firebase_database_url == null || SystemEnv.gcm_defaultSenderId == null ||
SystemEnv.google_api_key == null || SystemEnv.google_crash_reporting_api_key == null ||
SystemEnv.project_id == null) {
logger.warn("If you want to enable Firebase, please follow the steps:")
logger.warn("1. Download google-services.json and put it in the folder where you run below command.")
logger.warn("2. Run 'python./tools/firebase/firebase_setup.py' and follow the steps.\n")
}
}
}
}
// -------------------------------------------------------------------------------------------------
// L10N: Initialize Strings
// -------------------------------------------------------------------------------------------------
task stringsSetup(type: Exec) {
group = 'Localization'
description = 'Setup L10N repository for importing and exporting strings.'
workingDir '..'
commandLine 'git', 'clone', 'https://github.com/mozilla-l10n/zerda-android-l10n.git', 'l10n-repo'
}
// -------------------------------------------------------------------------------------------------
// L10N: Export Strings
// -------------------------------------------------------------------------------------------------
task stringsExport(type: Exec) {
group = 'Localization'
description = 'Export strings to L10N repository.'
workingDir '..'
commandLine 'python', 'tools/l10n/android2po/a2po.py', 'export'
}
// -------------------------------------------------------------------------------------------------
// L10N: Import Strings
// -------------------------------------------------------------------------------------------------
task stringsImport {
group = 'Localization'
description = 'Import strings from L10N repository.'
doLast {
exec {
workingDir '..'
commandLine 'python', 'tools/l10n/android2po/a2po.py', 'import'
}
exec {
workingDir '../tools/l10n/'
commandLine 'sh', 'fix_locale_folders.sh'
}
}
}
// -------------------------------------------------------------------------------------------------
// L10N: Create commits
// -------------------------------------------------------------------------------------------------
task stringsCommit(type: Exec) {
group = 'Localization'
description = 'Create commits for exported strings.'
workingDir '../tools/l10n/'
commandLine 'sh', 'create_commits.sh'
}
// -------------------------------------------------------------------------------------------------
// L10N: Clean and update
// -------------------------------------------------------------------------------------------------
task stringsCleanUpdate() {
group = 'Localization'
description = 'Fetch L10N changes and remove all local modifications.'
doLast {
exec {
workingDir '../l10n-repo/'
commandLine 'git', 'fetch', 'origin'
}
exec {
workingDir '../l10n-repo/'
commandLine 'git', 'reset', '--hard', 'origin/master'
}
}
}
// -------------------------------------------------------------------------------------------------
// L10N: Generate list of locales
// Focus provides its own (Android independent) locale switcher. That switcher requires a list
// of locale codes. We generate that list here to avoid having to manually maintain a list of locales:
// -------------------------------------------------------------------------------------------------
def getEnabledLocales() {
def resDir = file('src/main/res')
def potentialLanguageDirs = resDir.listFiles(new FilenameFilter() {
@Override
boolean accept(File dir, String name) {
return name.startsWith("values-")
}
})
def langs = potentialLanguageDirs.findAll {
// Only select locales where strings.xml exists
// Some locales might only contain e.g. sumo URLS in urls.xml, and should be skipped (see es vs es-ES/es-MX/etc)
return file(new File(it, "strings.xml")).exists()
}.collect {
// And reduce down to actual values-* names
return it.name
}.collect {
return it.substring("values-".length())
}.collect {
if (it.length() > 3 && it.contains("-r")) {
// Android resource dirs add an "r" prefix to the region - we need to strip that for java usage
// Add 1 to have the index of the r, without the dash
def regionPrefixPosition = it.indexOf("-r") + 1
return it.substring(0, regionPrefixPosition) + it.substring(regionPrefixPosition + 1)
} else {
return it
}
}.collect {
return '"' + it + '"'
}
// en-US is the default language (in "values") and therefore needs to be added separately
langs << "\"en-US\""
// Remove zh-CN since we have it in our source code but we currently don't want it packaged.
langs.remove("\"zh-CN\"")
return langs
}
def generatedLocaleListDir = 'src/main/java/org/mozilla/focus/generated'
def generatedLocaleListFilename = 'LocaleList.java'
task generateLocaleList {
doLast {
def dir = file(generatedLocaleListDir)
dir.mkdir()
def localeList = file(new File(dir, generatedLocaleListFilename))
localeList.delete()
localeList.createNewFile()
localeList << "package org.mozilla.focus.generated;" << "\n" << "\n"
localeList << "import java.util.Arrays;" << "\n"
localeList << "import java.util.Collections;" << "\n"
localeList << "import java.util.List;" << "\n"
localeList << "\n"
localeList << "public class LocaleList {" << "\n"
// findbugs doesn't like "public static final String[]", see http://findbugs.sourceforge.net/bugDescriptions.html#MS_MUTABLE_ARRAY
localeList << " public static final List<String> BUNDLED_LOCALES = Collections.unmodifiableList(Arrays.asList(new String[] { "
localeList << getEnabledLocales().join(", ") + " }));" << "\n"
localeList << "}" << "\n"
}
}
tasks.whenTaskAdded { task ->
if (name.contains("compile")) {
task.dependsOn generateLocaleList
}
}
clean.doLast {
file(generatedLocaleListDir).deleteDir()
}
// -------------------------------------------------------------------------------------------------
// L10N: Verify locales
// -------------------------------------------------------------------------------------------------
// Fetches the available locales - this doesn't always match the actually available locales (getEnabledLocales()),
// e.g. if there were import problems:
def getTranslatedLocales() {
def localesDir = file('../l10n-repo/locales')
def potentialLanguageDirs = localesDir.listFiles(new FilenameFilter() {
@Override
boolean accept(File dir, String name) {
return !name.equals("templates")
}
})
def langs = potentialLanguageDirs.collect {
// Reduce from list of files to actual names
return it.name
}.collect {
switch (it) {
case "id":
return "in"
case "he":
return "iw"
default:
return it
}
}.collect {
return '"' + it + '"'
}
langs << "\"en-US\""
return langs
}
task verifyLocales << {
group = 'Localization'
description = 'Verify that all locales in the L10N repository were imported'
def l10nRepo = file("../l10n-repo")
if (!l10nRepo.isDirectory()) {
throw new GradleException('l10n-repo does not exist, ensure you have run |gradle stringsSetup|')
}
def availableLocales = getTranslatedLocales()
def successfullyImportedLocales = getEnabledLocales()
def missingLocales = availableLocales.clone()
missingLocales.removeAll(successfullyImportedLocales)
if (missingLocales.size > 0) {
throw new GradleException('The following locales were not successfully imported: ' + missingLocales.join(","))
}
def unexpectedLocales = successfullyImportedLocales.clone()
unexpectedLocales.removeAll(availableLocales)
if (unexpectedLocales.size > 0) {
throw new GradleException('Project has additional locales: ' + unexpectedLocales.join(","))
}
}
// Ensure we always check locale import imported all locales:
stringsImport.doLast {
tasks.verifyLocales.execute()
}
// -------------------------------------------------------------------------------------------------
// Static Analysis: findbugs and pmd
// -------------------------------------------------------------------------------------------------
findbugs {
ignoreFailures = false
effort = "max"
// This selects what level of bugs to report: low means low priority issues will be reported
// (in addition to medium+high), which corresponds to warning about everything.
// TODO: boost this to low once low priority issues are fixed.
reportLevel = "medium"
excludeFilter = new File("${project.rootDir}/quality/findbugs-exclude.xml")
}
task findbugs(type: FindBugs, dependsOn: "assemble", group: 'verification') {
classes = files("$projectDir.absolutePath/build/intermediates/classes")
source = fileTree('src/main/java')
classpath = files()
// Only one report format is supported. Html is easier to read, so let's use that
// (xml is the one that's enabled by default).
reports {
xml.enabled = false
html.enabled = true
}
}
pmd {
toolVersion = '5.5.2'
ignoreFailures = true
ruleSetFiles = files("${project.rootDir}/quality/pmd-rules.xml")
ruleSets = []
}
task pmd(type: Pmd, group: 'verification') {
source 'src'
include '**/*.java'
exclude('**/gen/**',
'**/debug/**',
'**/androidTest/**',
'**/test**/**')
reports {
xml.enabled = false
html.enabled = true
html {
destination "$projectDir.absolutePath/build/reports/pmd/pmd.html"
}
}
}
task checkstyle(type: Checkstyle) {
configFile file("${project.rootDir}/quality/checkstyle.xml")
source 'src'
include '**/*.java'
exclude '**/gen/**'
classpath = files()
}
afterEvaluate {
check.dependsOn 'findbugs', 'pmd', 'checkstyle'
}