-
Notifications
You must be signed in to change notification settings - Fork 345
/
Copy pathbuild.gradle
executable file
·1029 lines (913 loc) · 43.5 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017 Proton AG
*
* This file is part of ProtonVPN.
*
* ProtonVPN 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
* (at your option) any later version.
*
* ProtonVPN 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 ProtonVPN. If not, see <https://www.gnu.org/licenses/>.
*/
import com.android.build.api.dsl.ApplicationBuildType
import com.android.build.api.dsl.VariantDimension
import com.android.build.gradle.internal.dsl.BaseFlavor
import configuration.EnvironmentConfigSettings
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.json.StringEscapeUtils
import io.gitlab.arturbosch.detekt.Detekt
buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
mavenCentral()
}
}
plugins {
id 'com.android.application'
id 'com.github.triplet.play' version '3.10.1'
id 'io.sentry.android.gradle' version '3.14.0'
id 'org.jetbrains.kotlin.plugin.serialization'
id 'me.proton.core.gradle-plugins.environment-config' version '1.3.1'
id 'com.google.devtools.ksp'
id 'androidx.room'
id 'org.jetbrains.kotlin.plugin.compose'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-parcelize'
apply plugin: 'jacoco'
apply plugin: 'com.jaredsburrows.license'
apply plugin: 'dagger.hilt.android.plugin'
apply plugin: 'io.gitlab.arturbosch.detekt'
apply plugin: 'me.proton.core.gradle-plugins.environment-config'
apply plugin: 'com.android.compose.screenshot'
dependencyCheck {
formats = ["SARIF", "HTML", "JUNIT"]
}
jacoco {
toolVersion = '0.8.8'
}
// There is no dependency on unit tests because coverage is run in a separate CI job and we want to
// avoid building and running the tests again.
tasks.register("jacocoTestReport", JacocoReport) {
reports {
xml.required = true
html.required = true
}
def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*']
def debugTree = fileTree(dir: "$project.buildDir/tmp/kotlin-classes/blackGooglePlayStoreDebug", excludes: fileFilter)
def mainSrc = files(["src/main/java","src/google/java"])
sourceDirectories.setFrom files([mainSrc])
classDirectories.setFrom files([debugTree])
executionData.setFrom fileTree(dir: "$project.projectDir", includes: [
"**/*.exec",
"**/*.ec"
])
}
tasks.register("coverageReport") {
dependsOn jacocoTestReport
def reportFile = project.file("build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml")
inputs.file(reportFile)
doLast {
def slurper = new XmlSlurper()
slurper.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
slurper.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
def xml = slurper.parse(reportFile)
def counter = xml.counter.find {
node -> node.@type == 'INSTRUCTION'
}
def missed = [email protected]()
def covered = [email protected]()
def total = missed + covered
def percentage = covered / total * 100
printf "Missed %.2f branches%n", missed
printf "Covered %.2f branches%n", covered
printf "Total coverage: %.2f%%%n", percentage
}
}
tasks.withType(Test).configureEach {
jacoco.includeNoLocationClasses = true
jacoco.excludes = ['jdk.internal.*']
}
tasks.register("updateLicensesJson") {
dependsOn 'licenseProductionGooglePlayStoreReleaseReport'
doLast {
File json = new File("$project.projectDir/build/reports/licenses/licenseProductionGooglePlayStoreReleaseReport.json")
File out = new File("$project.projectDir/src/main/assets/open_source_licenses.js")
out.text = 'dependencies = ' + json.text
}
}
licenseReport {
generateCsvReport = false
generateHtmlReport = false
generateJsonReport = true
copyHtmlReportToAssets = false
copyJsonReportToAssets = false
}
def sentryDsn = System.getenv("PROTONVPN_SENTRY_DSN") ? sentryDsn : ""
def accountSentryDsn = System.getenv("ACCOUNT_SENTRY_DSN") ?: ""
def preferencesSalt = System.getenv("DEPRECATED_PREF_SALT") ?: "Salt"
def preferencesKey = System.getenv("DEPRECATED_PREF_KEY") ?: "Key"
def serviceAccountCredentialsPath = project.hasProperty('serviceAccountFilePath') ? serviceAccountFilePath : "service_account.json"
def testAccountPassword = System.getenv("TEST_ACCOUNT_PASS") ?: project.hasProperty('testAccountPassword') ? testAccountPassword : "Pass"
def appId = project.hasProperty('appId') ? appId : "ch.protonvpn.android"
def supportedLocales = ['b+es+419', 'be', 'cs', 'de', 'el', 'en', 'es-rES', 'es-rMX', 'fa', 'fi', 'fr', 'in', 'it', 'ja', 'ka', 'ko', 'nb-rNO', 'nl', 'pl', 'pt-rBR', 'pt-rPT', 'ro', 'ru', 'sk', 'sl', 'sv-rSE', 'tr', 'uk', 'zh-rTW']
def helpers = new Helpers(rootDir, providers)
def debugKeystorePath = System.getenv("DEBUG_KEYSTORE_FILE")
android {
namespace "com.protonvpn.android"
testNamespace 'com.protonvpn'
buildToolsVersion "34.0.0"
ndkVersion rootProject.ext.compileNdkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
useLibrary 'org.apache.http.legacy'
signingConfigs {
if (debugKeystorePath) {
debug {
storeFile file(debugKeystorePath)
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
}
buildFeatures {
buildConfig true
compose true
viewBinding true
}
defaultConfig {
applicationId appId
minSdkVersion rootProject.ext.minSdkVersion // See also build flavors.
targetSdkVersion 34
multiDexEnabled true
versionName helpers.fullVersionName
versionCode helpers.getVersionCode()
archivesBaseName = helpers.archivesBaseName
testInstrumentationRunner "com.protonvpn.TestsRunner"
testInstrumentationRunnerArguments clearPackageData: 'true' // Clear app data between tests.
testInstrumentationRunnerArguments useTestStorageService: 'true'
vectorDrawables.useSupportLibrary = true
resourceConfigurations = supportedLocales
manifestPlaceholders = ["gwpAsanMode": "default"]
def availableLocalesJava = supportedLocales.collect { "\"$it\"" }.join(", ")
buildConfigField "String[]", "SUPPORTED_LOCALES", "{$availableLocalesJava}"
buildConfigField "String", "Sentry_DSN", "\"${StringEscapeUtils.escapeJava(sentryDsn)}\""
buildConfigField "String", "ACCOUNT_SENTRY_DSN", "\"${StringEscapeUtils.escapeJava(accountSentryDsn)}\""
buildConfigField "String", "PREF_SALT", "\"${StringEscapeUtils.escapeJava(preferencesSalt)}\""
buildConfigField "String", "PREF_KEY", "\"${StringEscapeUtils.escapeJava(preferencesKey)}\""
buildConfigField "String", "TEST_ACCOUNT_PASSWORD", "\"Pass\""
def ciBranchName = System.getenv("CI_COMMIT_BRANCH")
def commitFirstLine = System.getenv("CI_COMMIT_MESSAGE")?.split('\n')?.first()?.trim()
def specialCharPass = System.getenv("SPECIAL_CHAR_PASSWORD")
buildConfigField "String", "SPECIAL_CHAR_PASSWORD", "\"${StringEscapeUtils.escapeJava(specialCharPass)}\""
buildConfigField "String", "CI_BRANCH_NAME", "\"${StringEscapeUtils.escapeJava(ciBranchName)}\""
buildConfigField "String", "CI_COMMIT_MESSAGE", "\"${StringEscapeUtils.escapeJava(commitFirstLine)}\""
buildConfigField "String", "TEST_ASSET_OVERRIDE_SHA", "\"${helpers.readFileOrDefault("test_asset_override_sha", "db95210d57b90063bfa1cac9881c7a8df326e6e2")}\""
buildConfigField "String", "TEST_ASSET_OVERRIDE_KEY", "\"${helpers.readFileOrDefault("test_asset_override_key", "241b080fb0f1216e")}\""
buildConfigField "String", "TEST_SUITE_ASSET_OVERRIDE_KEY", "\"${helpers.readFileOrDefault("test_suite_asset_override_key", "3ea60f6a2fbfc015")}\""
buildConfigField "Boolean", "ALT_ROUTING_CERT_FOR_MAIN_ROUTE", "false"
buildConfigField "Boolean", "ALLOW_LOGCAT", "false"
buildConfigField "String[]", "API_TLS_PINS", "null"
buildConfigField "String[]", "API_ALT_TLS_PINS", "null"
buildConfigField "String[]", "DOH_SERVICES_URLS", "null"
buildConfigField "String", "VPN_SERVER_ROOT_CERT", "null"
Helpers.setAssetLinksResValue(it, "proton.me")
}
flavorDimensions = ["environment", "functionality", "distribution"]
productFlavors {
production {
dimension "environment"
getIsDefault().set(true)
helpers.protonEnvironmentConfig(it) {
// default host is 'proton.me'
apiPrefix = 'vpn-api'
}
}
black {
dimension "environment"
versionNameSuffix '-dev'
def blackToken = System.getenv("BLACK_TOKEN")
// Use either:
// - TEST_ENV_DOMAIN for regular test environments,
// - the BTI_* variables for the BTI environment.
def testEnvHost = System.getenv("TEST_ENV_DOMAIN")
def dohUrls, apiPinsString, altPinsString, altRoutingCertForMainRoute, customApiHost, customPrefix, customHv3Host
if (testEnvHost != null) {
dohUrls = null
// Disable cert pinning:
apiPinsString = "{}"
altPinsString = "{}"
altRoutingCertForMainRoute = false
customApiHost = testEnvHost
}
else {
def apiPins = System.getenv("BTI_API_TLS_PINNINGS")
def altPins = System.getenv("BTI_ALT_ROUTE_TLS_PINNINGS")
dohUrls = System.getenv("BTI_AR_DOH_URLS")
apiPinsString = "{${helpers.sanitizeStringListForBuildConfig(apiPins)}}"
altPinsString = altPins != null ? "{${helpers.sanitizeStringListForBuildConfig(altPins)}}" : null
altRoutingCertForMainRoute = true
customPrefix = System.getenv("BTI_PREFIX")
customApiHost = System.getenv("BTI_HOST")
customHv3Host = System.getenv("BTI_HV3_DOMAIN")
}
helpers.protonEnvironmentConfig(it) {
if (customApiHost != null)
host = StringEscapeUtils.escapeJava(customApiHost)
if (customPrefix != null)
apiPrefix = StringEscapeUtils.escapeJava(customPrefix)
if (customHv3Host != null)
hv3Host = StringEscapeUtils.escapeJava(customHv3Host)
proxyToken = StringEscapeUtils.escapeJava(blackToken)
}
if (customApiHost != null) {
Helpers.setAssetLinksResValue(it, customApiHost)
}
def vpnServerRootCert = System.getenv("BTI_SERVERS_ROOT_CERT")
buildConfigField "Boolean", "ALT_ROUTING_CERT_FOR_MAIN_ROUTE", "$altRoutingCertForMainRoute"
buildConfigField "String[]", "DOH_SERVICES_URLS", "{${helpers.sanitizeStringListForBuildConfig(dohUrls)}}"
buildConfigField "String[]", "API_TLS_PINS", apiPinsString
// Below are not mandatory
if (altPinsString != null) {
buildConfigField "String[]", "API_ALT_TLS_PINS", altPinsString
}
if (vpnServerRootCert != null) {
buildConfigField "String", "VPN_SERVER_ROOT_CERT", "\"${StringEscapeUtils.escapeJava(vpnServerRootCert)}\""
}
}
def additionalProguard = "proguard-rules-logcat.pro"
vanilla {
dimension "functionality"
}
google {
dimension "functionality"
getIsDefault().set(true)
}
playStore {
dimension "distribution"
getIsDefault().set(true)
buildConfigField "String", "STORE_SUFFIX", "\"+play\""
proguardFile additionalProguard
}
amazon {
dimension "distribution"
minSdkVersion rootProject.ext.minSdkVersionAmazon
buildConfigField "String", "STORE_SUFFIX", "\"+aws\""
proguardFile additionalProguard
}
direct {
dimension "distribution"
buildConfigField "String", "STORE_SUFFIX", "\"+apk\""
proguardFile additionalProguard
}
openSource {
dimension "distribution"
buildConfigField "String", "STORE_SUFFIX", "\"+os\""
proguardFile additionalProguard
}
dev {
dimension "distribution"
applicationIdSuffix '.dev'
buildConfigField "String", "STORE_SUFFIX", "\"\""
buildConfigField "Boolean", "ALLOW_LOGCAT", "true"
manifestPlaceholders = ["gwpAsanMode": "always"]
}
}
variantFilter { variant ->
def environment = variant.flavors[0].name
def functionality = variant.flavors[1].name
def dist = variant.flavors[2].name
if (dist == "dev")
return
if (environment == "black" && dist !in ["playStore", "direct"])
setIgnore(true) // We don't need all distributions for testing.
if (functionality == "google" && dist != "playStore" || functionality != "google" && dist == "playStore")
setIgnore(true)
}
buildTypes {
debug {
enableAndroidTestCoverage false
enableUnitTestCoverage = true
ext.alwaysUpdateBuildId = false
minifyEnabled false
signingConfig signingConfigs.debug
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "TEST_ACCOUNT_PASSWORD", "\"${StringEscapeUtils.escapeJava(testAccountPassword)}\""
manifestPlaceholders = ["gwpAsanMode": "always"]
}
release {
minifyEnabled true
signingConfig signingConfigs.debug
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
animationsDisabled true
unitTests {
includeAndroidResources = true
}
}
packagingOptions {
resources {
excludes += [
'DebugProbesKt.bin',
'META-INF/DEPENDENCIES.txt',
'META-INF/NOTICE.txt',
'META-INF/NOTICE.md',
'META-INF/LICENSE*',
'META-INF/DEPENDENCIES',
'META-INF/notice.txt',
'META-INF/license.txt',
'META-INF/dependencies.txt',
'META-INF/LGPL2.1',
'META-INF/AL2.0',
'MANIFEST.MF'
]
}
jniLibs {
useLegacyPackaging = true
}
}
experimentalProperties["android.experimental.enableScreenshotTest"] = true
sourceSets {
main.res.srcDirs += 'src/main/res_flags'
main {
assets.srcDirs = ['src/main/assets', 'assets', 'ovpnlibs/assets', '../openvpn/build/ovpnassets']
}
// Screenshot test does not automatically include app resources. Check if it's still needed when updating screenshot test module.
screenshotTest.res.srcDirs += 'src/main/res'
// Adds exported schema location as test app assets.
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
compileOptions {
targetCompatibility JavaVersion.VERSION_17
sourceCompatibility JavaVersion.VERSION_17
coreLibraryDesugaringEnabled = true
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_17.toString()
freeCompilerArgs += [
"-Xopt-in=kotlin.RequiresOptIn"
]
}
lint {
// In our process we might temporarily have extra translations that will get removed on
// next update.
disable 'ExtraTranslation', 'ImpliedQuantity', 'MissingDefaultResource', 'MissingTranslation'
ignoreWarnings = true
}
room {
schemaDirectory "$projectDir/schemas"
}
}
play {
serviceAccountCredentials.set(file(serviceAccountCredentialsPath))
track.set('internal')
artifactDir.set(file("signedArtifacts/"))
defaultToAppBundles.set(true)
releaseName.set(helpers.fullVersionName)
}
// The config file is downloaded by the downloadDetektConfig task.
def commonDetektConfigPath = "${rootProject.projectDir}/config/detekt/config.yml"
def projectDetektConfigPath = "${rootProject.projectDir}/config/detekt/custom-config.yml"
detekt {
config = files(commonDetektConfigPath, projectDetektConfigPath)
reports {
html.required.set(false)
xml.required.set(false)
txt.required.set(false)
sarif.required.set(false)
custom {
reportId = "outputreport.GitlabQualityOutputReport"
outputLocation.set(file("build/reports/detekt/detekt.json"))
}
}
}
sentry {
// This configuration uploads mapping files to Sentry and requires credentials either in a
// local file or environment variables.
// To disable the upload temporarily (e.g. when building locally) add "release" to
// ignoredBuildTypes (I wish there was a better way...).
includeProguardMapping = true
uploadNativeSymbols = true
ignoredBuildTypes = ["debug"]
// It would be best to set only the single dimension "openSource" but it doesn't work this way.
ignoredFlavors = ["productionVanillaOpenSource"]
// We don't want the sentry plugin to add anything to our builds:
tracingInstrumentation { enabled = false }
autoInstallation { enabled = false }
}
tasks.withType(Detekt).configureEach {
dependsOn "downloadDetektConfig"
dependsOn ":detekt-custom-rules:assemble"
dependsOn ":detekt-gitlab-output-plugin:assemble"
basePath = rootProject.projectDir.absolutePath
reports {
html.required.set(false)
xml.required.set(false)
txt.required.set(false)
sarif.required.set(false)
custom {
reportId = "GitlabQualityOutputReport"
outputLocation.set(file("build/reports/detekt/detekt.json"))
}
}
}
tasks.register("downloadDetektConfig") {
doLast {
def srcConfigFilePath = "config/detekt/config.yml"
def dstConfigFile = file(commonDetektConfigPath)
def dir = dstConfigFile.parentFile
if (!dir.exists() && !dir.mkdirs()) {
throw FilePermissionException("Cannot create directory ${dir.canonicalPath}")
}
println("Detekt rule-set file: $dstConfigFile")
def fileModificationDate = new Date(dstConfigFile.lastModified())
if (fileModificationDate.plus(1) > new Date()) {
println("Detekt rule-set is less than a day old, skipping download.")
return
}
def url = "https://raw.githubusercontent.com/ProtonMail/protoncore_android/master/$srcConfigFilePath"
println("Fetching Detekt rule-set from $url")
try {
def content = new URL(url).getText()
// Checking start of the file is enough, if some part is missing we would not be able to decode it
assert(content.startsWith("# Integrity check *")) : "Integrity check not passed"
dstConfigFile.text = content
} catch (Throwable t) {
println("Cannot download Detekt configuration: ${t.message}")
throw t
}
}
}
tasks.register("generateReleaseNotesForPublishing") {
doLast {
File releaseNotesDir = new File("$project.projectDir/src/main/play/release-notes/en-US")
releaseNotesDir.mkdirs()
File releaseNotesFile = new File(releaseNotesDir, "default.txt")
releaseNotesFile.newWriter().withWriter { w ->
// Limit of 500 chars on Google Play console for release notes
w << helpers.getReleaseNotes(490)
}
}
}
tasks.register("prepareGuestHoleServers") {
doLast {
def guestHoleUrl = System.getenv("GUEST_HOLE_URL")
def guestHoleHeaders = System.getenv("GUEST_HOLE_HEADERS")
if (guestHoleUrl == null || guestHoleHeaders == null)
throw new GradleException("GUEST_HOLE_URL and GUEST_HOLE_HEADERS need to be set for prepareGuestHoleServers")
def connection = new URL(guestHoleUrl).openConnection()
for (header in new JsonSlurper().parseText(guestHoleHeaders))
connection.setRequestProperty(header.key, header.value)
if (connection.getResponseCode() != 200)
throw new GradleException("Failed to fetch guest hole servers: ${connection.getResponseCode()} ${connection.getResponseMessage()}")
def allServers = new JsonSlurper().parse(connection.getInputStream())["LogicalServers"]
def candidateServers = allServers.stream().filter { s ->
def country = s["ExitCountry"]
def secureCore = (s["Features"] & 1) == 1
!secureCore && s["Status"] == 1 && !country.equalsIgnoreCase("se") && !country.equalsIgnoreCase("is")
}.collect()
Collections.shuffle(candidateServers)
def servers = candidateServers.take(10)
File dir = new File("$project.projectDir/src/main/assets")
File serversFile = new File(dir, "GuestHoleServers.json")
serversFile.newWriter().withWriter { w ->
w << JsonOutput.prettyPrint(new JsonOutput().toJson(servers))
}
}
}
tasks.withType(Test).configureEach {
testLogging {
events "skipped", "failed"
exceptionFormat "full"
showExceptions true
}
}
import org.gradle.internal.extensibility.DefaultExtraPropertiesExtension
class Helpers {
private File workingDir
private ProviderFactory providers
Helpers(File workingDir, ProviderFactory providers) {
this.workingDir = workingDir
this.providers = providers
}
// Versioning:
// Version name: M.m.D.R
// M.m (major.minor) come from the last tag on development branch of this form (e.g. "2.1")
// D - number of commits on development since M.m
// R - number of commits on release branch (from development)
// Version code: AMMmmDDRR as decimal integer
// A - hardcoded number 6. Because abi splits were used before
int getVersionCode() {
def name = fullVersionName
def versions = name.split("\\.")
def major = versions[0].toInteger()
def minor = versions[1].toInteger()
def dev = versions[2].toInteger()
def release = versions[3].toInteger()
// Max version code allowed by android is 2_000_000_000
assert major < 100 && minor < 100 && dev < 100 && release < 100
// 6 needs to be hardcoded as abi version before ended up at 5
def code = 6 * 100_000_000 +
major * 1_000_000 +
minor*10_000 +
dev * 100 +
release
// Just some sanity check because there's no turning back once we accidentally publish
// some large version code
assert code < 700_000_000 && major < 50
return code
}
String getFullVersionName() {
// To be used e.g. when we don't want the version on hotfix branch to change when adding
// CI-related fixes.
def override = System.getenv("OVERRIDE_VERSION_NAME")
if (override != null)
return override
def gitVersionProvider = providers.of(GitFullVersionNameSource.class) {
parameters {
workingDir = this.workingDir
}
}
return gitVersionProvider.get()
}
String readFileOrDefault(String path, String defaultValue) {
def file = new File(workingDir, path)
if (!file.exists())
return defaultValue
return file.text
}
boolean hasReleaseNotes() {
def lastSha = System.getenv("CI_COMMIT_BEFORE_SHA")
def branchName = System.getenv("CI_COMMIT_BRANCH")
def output = exec(["git", "branch", branchName, "--contains", lastSha], false)
return output != null
}
String getReleaseNotes(int trimAt) {
def lastSha = System.getenv("CI_COMMIT_BEFORE_SHA")
// CI_COMMIT_BEFORE_SHA is always 0000000000000000000000000000000000000000 for merge request
// pipelines, the first commit in pipelines for branches or tags, or when manually running a
// pipeline. Let's not fail the job if we ever need to run a pipeline manually to fix
// publishing.
if (lastSha == null || lastSha == "0000000000000000000000000000000000000000")
return "(failed fetching release notes for manual pipeline)"
def notes = exec(["git", "log", "${lastSha}..HEAD", "--pretty=format:- %s"])
if (notes.length() > trimAt)
return notes.take(trimAt) + "\n..."
return notes
}
void notifyPublishOnSlack() {
def hook = System.getenv("SLACK_PUBLISH_HOOK")
if (hook == null)
return
def sha = System.getenv("CI_COMMIT_SHA")
def json = new JsonOutput().toJson(["text": ":android: :protonvpn: ${getFullVersionName()} released to internal (SHA ${sha.take(8)}...)\n" +
"Release notes:\n" +
"${getReleaseNotes(1000)}"])
exec(["curl", "-X", "POST", "-H", "'Content-type: application/json'", "--data", json, hook])
}
String getArchivesBaseName() {
return "ProtonVPN-" + fullVersionName + "(" + getVersionCode() + ")"
}
String exec(ArrayList<String> cmd, boolean throwOnError = true) {
def out = new StringBuffer()
def err = new StringBuffer()
def proc = cmd.execute(null, workingDir)
proc.waitForProcessOutput(out, err)
if (proc.exitValue() != 0) {
if (throwOnError)
throw new GradleScriptException("Error executing: ${cmd}", new RuntimeException(err.toString()))
else
return null
}
return out.toString()
}
// We receive comma-separated string lists either with or without '"', support both notations
// and protects from injecting java code.
static String sanitizeStringListForBuildConfig(String s) {
if (s == null) return ""
return s.split(",")
.collect { it.trim().replace("\"", "") }
.collect { "\"${StringEscapeUtils.escapeJava(it)}\""}
.join(", ")
}
static void setAssetLinksResValue(VariantDimension variantDimension, String host) {
variantDimension.resValue(
/* type */ "string",
/* name */ "asset_statements",
/* value */ """
[{
"relation": ["delegate_permission/common.handle_all_urls", "delegate_permission/common.get_login_creds"],
"target": { "namespace": "web", "site": "https://$host" }
}]
""".stripIndent()
)
}
static void protonEnvironmentConfig(BaseFlavor flavor, Closure<?> configurator) {
setEnvironmentConfigExt(flavor.ext, flavor.name, configurator)
}
static void protonEnvironmentConfig(ApplicationBuildType buildType, Closure<EnvironmentConfigSettings> configurator) {
setEnvironmentConfigExt(buildType.ext, buildType.name, configurator)
}
private static void setEnvironmentConfigExt(
DefaultExtraPropertiesExtension ext,
String name,
Closure<EnvironmentConfigSettings> configurator
) {
def configSettings = new EnvironmentConfigSettings()
configurator.delegate = configSettings
configurator.resolveStrategy = Closure.DELEGATE_FIRST
configurator.call()
ext.set("""${name}ProtonEnvironmentConfig""", configSettings)
}
}
tasks.register("getVersionName"){
doLast {
println helpers.fullVersionName
}
}
tasks.register("notifyPublishOnSlack"){
doLast {
helpers.notifyPublishOnSlack()
}
}
tasks.register("getVersionCode"){
doLast {
println helpers.getVersionCode()
}
}
tasks.register("getArchivesName"){
doLast {
println archivesBaseName
}
}
tasks.register("getReleaseNotes"){
doLast {
if (helpers.hasReleaseNotes()) {
println helpers.getReleaseNotes(1000)
} else {
println "- Branch rebased"
}
}
}
repositories {
maven { url "https://clojars.org/repo/" }
google()
mavenCentral()
}
configurations {
detekt
}
configurations.configureEach {
exclude group: "me.proton.core", module: "notification-dagger"
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
debugImplementation 'com.squareup.leakcanary:leakcanary-object-watcher-android:2.14'
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
detektPlugins "io.gitlab.arturbosch.detekt:detekt-formatting:$detekt_version"
detektPlugins project(":detekt-gitlab-output-plugin")
detektPlugins project(":detekt-custom-rules")
coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:$desugar_jdk_version"
implementation(platform("org.jetbrains.kotlin:kotlin-bom:$kotlin_version"))
implementation 'dnsjava:dnsjava:3.6.2'
implementation "net.java.dev.jna:jna:5.13.0"
implementation 'commons-codec:commons-codec:1.15'
implementation 'com.google.android.material:material:1.12.0'
implementation 'com.google.code.gson:gson:2.11.0'
implementation 'androidx.recyclerview:recyclerview:1.3.2'
implementation 'androidx.core:core-ktx:1.15.0'
implementation "androidx.datastore:datastore:$datastore_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$androidx_lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$androidx_lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$androidx_lifecycle_version"
implementation 'androidx.activity:activity-ktx:1.9.3'
implementation 'androidx.fragment:fragment-ktx:1.8.5'
implementation 'androidx.window:window:1.3.0'
implementation 'io.sentry:sentry-android:6.34.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.vectordrawable:vectordrawable:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.2.0'
implementation 'com.scottyab:aes-crypto:0.0.5'
implementation 'com.squareup.retrofit2:retrofit:2.11.0'
implementation 'me.relex:circleindicator:2.1.6@aar'
implementation 'androidx.work:work-runtime:2.9.1'
implementation 'androidx.work:work-runtime-ktx:2.9.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinx_coroutines_version"
implementation 'com.github.lisawray.groupie:groupie:2.10.0'
implementation 'com.github.lisawray.groupie:groupie-viewbinding:2.10.0'
implementation 'com.github.tony19:logback-android:2.0.0'
implementation 'org.slf4j:slf4j-api:1.7.36'
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinx_serialization_json_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-cbor:$kotlinx_serialization_json_version"
implementation 'androidx.preference:preference-ktx:1.2.1'
implementation 'com.airbnb.android:lottie:6.6.2'
implementation 'com.airbnb.android:lottie-compose:6.6.2'
implementation 'com.google.android.flexbox:flexbox:3.0.0'
implementation "androidx.security:security-crypto:1.0.0"
implementation 'androidx.viewpager2:viewpager2:1.1.0'
implementation "androidx.core:core-splashscreen:1.0.1"
implementation 'com.github.seancfoley:ipaddress:5.5.1'
implementation 'com.caverock:androidsvg-aar:1.4'
// Compose
def composeBom = platform('androidx.compose:compose-bom:2024.10.01')
implementation composeBom
androidTestImplementation composeBom
def composeNavigationVersion = '2.8.5'
implementation 'androidx.compose.animation:animation-android'
implementation 'androidx.compose.material3:material3'
implementation 'androidx.compose.material3:material3-window-size-class'
implementation "androidx.compose.runtime:runtime-livedata"
implementation 'androidx.compose.ui:ui'
implementation "androidx.compose.ui:ui-viewbinding"
implementation "androidx.lifecycle:lifecycle-runtime-compose:$androidx_lifecycle_version"
implementation "androidx.navigation:navigation-compose:$composeNavigationVersion"
implementation 'com.google.accompanist:accompanist-systemuicontroller:0.36.0'
implementation 'sh.calvin.reorderable:reorderable:2.4.3'
implementation 'androidx.constraintlayout:constraintlayout-compose-android:1.1.0'
implementation("com.patrykandpatrick.vico:core:2.0.0-alpha.14")
implementation('com.patrykandpatrick.vico:compose:2.0.0-alpha.14')
implementation 'androidx.compose.ui:ui-tooling-preview'
debugImplementation 'androidx.compose.ui:ui-tooling'
screenshotTestImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'
testImplementation "androidx.compose.ui:ui-test-junit4"
androidTestImplementation "androidx.compose.ui:ui-test-junit4"
testImplementation "androidx.navigation:navigation-testing:$composeNavigationVersion"
androidTestImplementation "androidx.navigation:navigation-testing:$composeNavigationVersion"
// Play core
googleImplementation "com.google.android.play:app-update:2.1.0"
googleImplementation "com.google.android.play:app-update-ktx:2.1.0"
googleImplementation "com.google.android.play:review:2.0.2"
googleImplementation "com.google.android.play:review-ktx:2.0.2"
// Glide
implementation 'com.github.bumptech.glide:glide:4.16.0'
implementation 'com.github.bumptech.glide:compose:1.0.0-beta01'
ksp 'com.github.bumptech.glide:ksp:4.16.0'
// Widget
def glanceVersion = '1.1.1'
implementation "androidx.glance:glance-appwidget:$glanceVersion"
implementation "androidx.glance:glance-material3:$glanceVersion"
implementation "androidx.glance:glance-preview:$glanceVersion"
implementation "androidx.glance:glance-appwidget-preview:$glanceVersion"
testImplementation "androidx.glance:glance-testing:$glanceVersion"
testImplementation "androidx.glance:glance-appwidget-testing:$glanceVersion"
// Room
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
ksp "androidx.room:room-compiler:$room_version"
testImplementation "androidx.room:room-testing:$room_version"
// Proton Core libs
implementation "me.proton.vpn:go-vpn-lib:$govpnlib_version"
implementation "me.proton.core:domain:$core_version"
implementation "me.proton.core:network-data:$core_version"
implementation "me.proton.core:network-domain:$core_version"
implementation "me.proton.core:network-presentation:$core_version"
implementation "me.proton.core:notification-data:$core_version"
implementation "me.proton.core:notification-domain:$core_version"
implementation "me.proton.core:notification-presentation:$core_version"
implementation "me.proton.core:util-kotlin:$core_version"
implementation "me.proton.core:presentation:$core_version"
implementation "me.proton.core:presentation-compose:$core_version"
implementation "me.proton.core:presentation-compose-tv:$core_version"
implementation "me.proton.core:push:$core_version"
implementation "me.proton.core:human-verification-data:$core_version"
implementation "me.proton.core:human-verification-domain:$core_version"
implementation "me.proton.core:human-verification-presentation:$core_version"
implementation "me.proton.core:country:$core_version"
implementation "me.proton.core:user:$core_version"
implementation "me.proton.core:user-data:$core_version"
implementation "me.proton.core:user-recovery:$core_version"
implementation "me.proton.core:user-settings:$core_version"
implementation "me.proton.core:account:$core_version"
implementation "me.proton.core:account-manager-data:$core_version"
implementation "me.proton.core:account-manager-domain:$core_version"
implementation "me.proton.core:account-manager-presentation:$core_version"
implementation "me.proton.core:account-manager-presentation-compose:$core_version"
implementation "me.proton.core:account-recovery:$core_version"
implementation "me.proton.core:auth:$core_version"
implementation "me.proton.core:auth-fido-dagger:$core_version"
implementation "me.proton.core:auth-fido-domain:$core_version"
googleImplementation "me.proton.core:auth-fido-play:$core_version"
implementation "me.proton.core:challenge:$core_version"
implementation "me.proton.core:crypto:$core_version"
implementation "me.proton.core:crypto-validator:$core_version"
implementation "me.proton.core:domain:$core_version"
implementation "me.proton.core:event-manager:$core_version"
implementation "me.proton.core:feature-flag:$core_version"
implementation "me.proton.core:observability:$core_version"
implementation "me.proton.core:telemetry-data:$core_version"
implementation "me.proton.core:telemetry-domain:$core_version"
implementation "me.proton.core:payment:$core_version"
googleImplementation "me.proton.core:payment-iap:$core_version"
implementation "me.proton.core:plan:$core_version"
implementation "me.proton.core:key:$core_version"
implementation "me.proton.core:data:$core_version"
implementation "me.proton.core:data-room:$core_version"
implementation "me.proton.core:util-android-dagger:$core_version"
implementation "me.proton.core:util-android-datetime:$core_version"
implementation "me.proton.core:util-android-sentry:$core_version"
implementation "me.proton.core:util-android-shared-preferences:$core_version"
implementation "me.proton.core:configuration-data:$core_version"
debugImplementation "me.proton.core:configuration-dagger-content-resolver:$core_version"
releaseImplementation "me.proton.core:configuration-dagger-staticdefaults:$core_version"
testImplementation "me.proton.core:auth-test:$core_version"
androidTestImplementation "me.proton.core:account-recovery-test:$core_version"
androidTestImplementation "me.proton.core:auth-test:$core_version"
androidTestImplementation "me.proton.core:human-verification-test:$core_version"
androidTestImplementation "me.proton.core:notification-test:$core_version"
androidTestImplementation "me.proton.core:plan-test:$core_version"
androidTestImplementation "me.proton.core:test-quark:$core_version"
androidTestImplementation "me.proton.core:user-recovery-test:$core_version"
testImplementation("me.proton.core:test-kotlin:$core_version") {
// https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-debug#debug-agent-and-android
exclude group: "org.jetbrains.kotlinx", module: "kotlinx-coroutines-debug"
}
androidTestImplementation("me.proton.core:test-kotlin:$core_version") {
// https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-debug#debug-agent-and-android
exclude group: "org.jetbrains.kotlinx", module: "kotlinx-coroutines-debug"
// Use mockk-android from our own dependencies.
exclude group: "io.mockk", module: "mockk"
}
androidTestImplementation("me.proton.core:test-android-instrumented:$core_version") {
exclude group: "me.proton.core"
}
// Observability
implementation project(":observability:domain")
// TV
implementation "androidx.leanback:leanback:1.1.0-rc02"
implementation "androidx.leanback:leanback-preference:1.1.0-rc01"
// Wireguard
implementation 'me.proton.vpn:wireguard-android:1.0.20230512.29'
// Hilt
ksp "com.google.dagger:hilt-compiler:$hilt_version"
implementation "com.google.dagger:hilt-android:$hilt_version"
testImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
androidTestImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
kspAndroidTest "com.google.dagger:hilt-android-compiler:$hilt_version"
// Hilt for WorkManager
implementation 'androidx.hilt:hilt-work:1.2.0'
ksp "androidx.hilt:hilt-compiler:$hilt_compiler_version"
testImplementation 'junit:junit:4.13.2'
testImplementation "io.mockk:mockk:$mockk_version"
testImplementation "app.cash.turbine:turbine:$turbine_version"
testImplementation 'org.robolectric:robolectric:4.14.1'
androidTestImplementation "io.mockk:mockk-android:$mockk_version"
androidTestImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlinx_coroutines_version") {
// https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-debug#debug-agent-and-android
exclude group: "org.jetbrains.kotlinx", module: "kotlinx-coroutines-debug"
}
androidTestImplementation "androidx.lifecycle:lifecycle-runtime-testing:$androidx_lifecycle_version"
// Core library
testImplementation "androidx.arch.core:core-testing:2.2.0"
androidTestImplementation "androidx.arch.core:core-testing:2.2.0"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlinx_coroutines_version"
// debugImplementation as a workaround for ActivityScenario problem:
// https://github.com/android/android-test/issues/940#issuecomment-934406022
debugImplementation 'androidx.test:core:1.6.1'
testImplementation project(':shared-test-code')
androidTestImplementation project(':shared-test-code')
androidTestImplementation 'com.squareup.okhttp3:okhttp-tls:4.12.0'
// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.6.2'
androidTestImplementation 'androidx.test:rules:1.6.1'
androidTestUtil 'androidx.test:orchestrator:1.5.1'
androidTestUtil 'androidx.test.services:test-services:1.5.0'