-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathStandardProjectConfigurations.kt
1194 lines (1088 loc) · 45 KB
/
StandardProjectConfigurations.kt
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) 2022 Slack Technologies, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package slack.gradle
import com.android.build.api.artifact.SingleArtifact
import com.android.build.api.dsl.CommonExtension
import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import com.android.build.api.variant.HasAndroidTestBuilder
import com.android.build.api.variant.LibraryAndroidComponentsExtension
import com.android.build.gradle.AppExtension
import com.android.build.gradle.BaseExtension
import com.android.build.gradle.LibraryExtension
import com.android.build.gradle.internal.dsl.BaseAppModuleExtension
import com.android.build.gradle.internal.dsl.BuildType
import com.autonomousapps.DependencyAnalysisSubExtension
import com.diffplug.gradle.spotless.SpotlessExtension
import com.google.common.base.CaseFormat
import com.google.devtools.ksp.gradle.KspExtension
import io.gitlab.arturbosch.detekt.Detekt
import io.gitlab.arturbosch.detekt.DetektCreateBaselineTask
import io.gitlab.arturbosch.detekt.extensions.DetektExtension
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import net.ltgt.gradle.errorprone.CheckSeverity
import net.ltgt.gradle.errorprone.errorprone
import net.ltgt.gradle.nullaway.nullaway
import org.gradle.api.Action
import org.gradle.api.GradleException
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.logging.Logger
import org.gradle.api.plugins.JavaBasePlugin
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.testing.Test
import org.gradle.jvm.toolchain.JavaCompiler
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.gradle.jvm.toolchain.JavaToolchainService
import org.gradle.jvm.toolchain.JavaToolchainSpec
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.exclude
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.named
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.kotlin.dsl.withGroovyBuilder
import org.gradle.kotlin.dsl.withType
import org.gradle.language.base.plugins.LifecycleBasePlugin
import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension
import org.jetbrains.kotlin.gradle.plugin.KaptExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import slack.dependencyrake.RakeDependencies
import slack.gradle.AptOptionsConfig.AptOptionsConfigurer
import slack.gradle.AptOptionsConfigs.invoke
import slack.gradle.dependencies.KotlinBuildConfig
import slack.gradle.dependencies.SlackDependencies
import slack.gradle.permissionchecks.PermissionChecks
import slack.gradle.tasks.AndroidTestApksTask
import slack.gradle.tasks.CheckManifestPermissionsTask
import slack.gradle.util.booleanProperty
private const val LOG = "SlackPlugin:"
private fun Logger.logWithTag(message: String) {
debug("$LOG $message")
}
/**
* Standard [Project] configurations. This class will be iterated on over time as we grow out our
* bootstrapping options for Gradle subprojects.
*
* Principles:
* - Avoid duplicating work and allocations. This runs at configuration time and should be as low
* overhead as possible.
* - Do not resolve dependencies at configuration-time. Use appropriate callback APIs!
* - Support Kotlin, Android, and Java projects.
* - One-off configuration should be left to individual projects to declare.
* - Use debug logging.
*/
@Suppress("TooManyFunctions")
internal class StandardProjectConfigurations {
private val kotlinCompilerArgs =
mutableListOf<String>()
.apply {
addAll(KotlinBuildConfig.kotlinCompilerArgs)
// Left as a toe-hold for any future dynamic arguments
}
.distinct()
fun applyTo(project: Project) {
val slackProperties = SlackProperties(project)
val globalConfig = project.slackTools().globalConfig
project.applyJvmConfigurations(globalConfig, slackProperties)
}
@Suppress("unused")
private fun Project.javaCompilerFor(version: Int): Provider<JavaCompiler> {
return extensions.getByType<JavaToolchainService>().compilerFor {
languageVersion.set(JavaLanguageVersion.of(version))
}
}
private fun Project.applyJvmConfigurations(
globalConfig: GlobalConfig,
slackProperties: SlackProperties
) {
if (!slackProperties.noPlatform) {
applyPlatforms(slackProperties)
if (slackProperties.enableAnalysisPlugin) {
val buildFile = project.buildFile
// This can run on some intermediate middle directories, like `carbonite` in
// `carbonite:carbonite`
if (buildFile.exists()) {
// Configure rake
plugins.withId("com.autonomousapps.dependency-analysis") {
val isNoApi = slackProperties.rakeNoApi
val rakeDependencies =
tasks.register<RakeDependencies>("rakeDependencies") {
buildFileProperty.set(project.buildFile)
noApi.set(isNoApi)
identifierMap.set(
project.provider {
project.getVersionsCatalog(slackProperties).identifierMap().mapValues { (_, v)
->
"libs.$v"
}
}
)
}
configure<DependencyAnalysisSubExtension> {
registerPostProcessingTask(rakeDependencies)
}
}
}
}
}
val slackExtension = extensions.create<SlackExtension>("slack")
configureSpotless(slackProperties)
checkAndroidXDependencies(slackProperties)
configureAnnotationProcessors()
val jdkVersion = jdkVersion()
val jvmTargetVersion = jvmTargetVersion()
pluginManager.onFirst(JVM_PLUGINS) {
slackProperties.versions.bundles.commonAnnotations.ifPresent {
dependencies.add("implementation", it)
}
slackProperties.versions.bundles.commonTest.ifPresent {
dependencies.add("testImplementation", it)
}
}
// TODO always configure compileOptions here
configureAndroidProjects(globalConfig, slackExtension, jvmTargetVersion, slackProperties)
configureKotlinProjects(globalConfig, jdkVersion, jvmTargetVersion, slackProperties)
configureJavaProject(jdkVersion, jvmTargetVersion, slackProperties)
slackExtension.configureFeatures(this, slackProperties)
// TODO would be nice if we could apply this _only_ if compile-testing is on the test classpath
tasks.withType<Test>().configureEach {
// Required for Google compile-testing to work.
// https://github.com/google/compile-testing/issues/222
jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED")
}
}
/**
* Applies platform()/bom dependencies for projects, right now only on known
* [Configurations.Groups.PLATFORM].
*/
private fun Project.applyPlatforms(slackProperties: SlackProperties) {
configurations.matching { isPlatformConfigurationName(it.name) }.configureEach {
dependencies {
for (bom in slackProperties.versions.boms) {
add(name, platform(bom))
}
add(name, platform(slackProperties.slackPlatformProject))
}
}
}
/**
* We reject new `com.android.support` dependencies to eliminate the dependence on Jetifier. Note
* we apply this on all projects (not just android projects) because some android dependencies are
* plain jars that can be used in standard JVM projects.
*/
private fun Project.checkAndroidXDependencies(slackProperties: SlackProperties) {
if (!slackProperties.skipAndroidxCheck) {
configurations.configureEach {
resolutionStrategy {
eachDependency {
if (requested.group == "com.android.support") {
throw IllegalArgumentException(
"Legacy support library dependencies are no longer " +
"supported. To trace this dependency, run './gradlew " +
"checkJetifier -Pandroid.enableJetifier=true --no-configuration-cache"
)
}
}
}
}
}
}
/** Configures Spotless for formatting. Note we do this per-project for improved performance. */
private fun Project.configureSpotless(slackProperties: SlackProperties) {
pluginManager.withPlugin("com.diffplug.spotless") {
configure<SpotlessExtension> {
format("misc") {
target("*.md", ".gitignore")
trimTrailingWhitespace()
endWithNewline()
}
val ktlintVersion = slackProperties.versions.ktlint
val ktlintUserData = mapOf("indent_size" to "2", "continuation_indent_size" to "2")
kotlin {
target("src/**/*.kt")
ktlint(ktlintVersion).userData(ktlintUserData)
trimTrailingWhitespace()
endWithNewline()
}
kotlinGradle {
target("src/**/*.kts")
ktlint(ktlintVersion).userData(ktlintUserData)
trimTrailingWhitespace()
endWithNewline()
}
java {
target("src/**/*.java")
googleJavaFormat(slackProperties.versions.gjf).reflowLongStrings()
trimTrailingWhitespace()
endWithNewline()
}
json {
target("src/**/*.json", "*.json")
target("*.json")
gson().indentWithSpaces(2).version(slackProperties.versions.gson)
}
}
}
}
/** Adds common configuration for Java projects. */
private fun Project.configureJavaProject(
jdkVersion: Int,
jvmTargetVersion: Int,
slackProperties: SlackProperties
) {
plugins.withType<JavaBasePlugin>().configureEach {
extensions.configure<JavaPluginExtension> {
val version = JavaVersion.toVersion(jvmTargetVersion)
sourceCompatibility = version
targetCompatibility = version
}
if (jdkVersion >= 9) {
tasks.configureEach<JavaCompile> {
if (!isAndroid) {
logger.logWithTag("Configuring release option for $path")
options.release.set(jvmTargetVersion)
}
}
}
}
val javaToolchains by lazy { project.serviceOf<JavaToolchainService>() }
tasks.withType<JavaCompile>().configureEach {
// Keep parameter names, this is useful for annotation processors and static analysis tools
options.compilerArgs.addAll(listOf("-parameters"))
// Android is our lowest JVM target, so if we're an android project we'll always use that
// source target.
// TODO is this late enough to be safe?
// TODO if we set it in android, does the config from this get safely ignored?
// TODO re-enable in android at all after AGP 7.1
if (!isAndroid) {
val target = if (isAndroid) jvmTargetVersion else jdkVersion
logger.logWithTag("Configuring toolchain for $path to $jdkVersion")
javaCompiler.set(
javaToolchains.compilerFor { languageVersion.set(JavaLanguageVersion.of(target)) }
)
}
}
configureErrorProne(slackProperties)
}
/**
* Adds common configuration for error prone on Java projects. Note that this still uses
* application of the error prone plugin as an opt-in marker for now, and is not applied to every
* project.
*/
private fun Project.configureErrorProne(slackProperties: SlackProperties) {
val autoPatchEnabled = slackProperties.errorProneAutoPatch
pluginManager.withPlugin("net.ltgt.nullaway") {
val nullawayBaseline = slackProperties.nullawayBaseline
val nullawayDep =
slackProperties.versions.catalog.findLibrary("errorProne-nullaway").orElseThrow {
IllegalStateException("Could not find errorProne-nullaway in the catalog")
}
dependencies { add("errorprone", nullawayDep) }
tasks.withType<JavaCompile>().configureEach {
val nullAwaySeverity =
if (name.contains("test", ignoreCase = true)) {
CheckSeverity.OFF
} else {
CheckSeverity.ERROR
}
options.errorprone.nullaway {
severity.set(nullAwaySeverity)
annotatedPackages.add("slack")
checkOptionalEmptiness.set(true)
if (autoPatchEnabled && nullawayBaseline) {
suggestSuppressions.set(true)
autoFixSuppressionComment.set("Nullability issue auto-patched by NullAway.")
castToNonNullMethod.set("slack.commons.JavaPreconditions.castToNotNull")
}
}
}
}
pluginManager.withPlugin("net.ltgt.errorprone") {
dependencies.add("errorprone", SlackDependencies.ErrorProne.core)
val isAndroidProject = isAndroid
tasks.withType<JavaCompile>().configureEach {
options.errorprone {
disableWarningsInGeneratedCode.set(true)
excludedPaths.set(".*/build/generated/.*") // The EP flag alone isn't enough
// https://github.com/google/error-prone/issues/2092
disable("HidingField")
error(*slackTools().globalConfig.errorProneCheckNamesAsErrors.toTypedArray())
if (isAndroidProject) {
options.compilerArgs.add("-XDandroidCompatible=true")
}
// Enable autopatching via "-PepAutoPatch=true". This patches in-place and requires a
// recompilation after.
// This could be useful to enable on CI + a git porcelain check to see if there's any
// patchable error prone
// fixes.
if (autoPatchEnabled) {
// Always log this verbosely
logger.lifecycle("Enabling error-prone auto-patching on ${project.path}:$name")
errorproneArgs.addAll(
"-XepPatchChecks:${ERROR_PRONE_CHECKS.joinToString(",")}",
"-XepPatchLocation:IN_PLACE"
)
}
}
}
}
}
@Suppress("LongMethod")
private fun Project.configureAndroidProjects(
globalConfig: GlobalConfig,
slackExtension: SlackExtension,
jvmTargetVersion: Int,
slackProperties: SlackProperties
) {
val javaVersion = JavaVersion.toVersion(jvmTargetVersion)
val lintErrorsOnly = slackProperties.lintErrorsOnly
val commonComponentsExtension =
Action<AndroidComponentsExtension<*, *, *>> {
val variantsToDisable =
slackProperties.disabledVariants?.splitToSequence(",")?.associate {
val (flavorName, buildType) = it.split("+")
flavorName to buildType
}
?: emptyMap()
if (variantsToDisable.isNotEmpty()) {
val isApp = this is ApplicationAndroidComponentsExtension
for ((flavorName, buildType) in variantsToDisable) {
val selector =
selector().withBuildType(buildType).withFlavor("environment" to flavorName)
beforeVariants(selector) { builder ->
builder.enable = false
builder.enableUnitTest = false
if (builder is HasAndroidTestBuilder) {
builder.enableAndroidTest =
slackExtension.androidHandler.featuresHandler.androidTest.getOrElse(false)
}
}
}
if (isApp) {
beforeVariants { builder -> builder.enableUnitTest = false }
}
}
}
val shouldApplyCacheFixPlugin = slackProperties.enableAndroidCacheFix
val commonBaseExtensionConfig: BaseExtension.() -> Unit = {
if (shouldApplyCacheFixPlugin) {
apply(plugin = "org.gradle.android.cache-fix")
}
compileSdkVersion(slackProperties.compileSdkVersion)
ndkVersion = slackProperties.ndkVersion
defaultConfig {
// TODO this won't work with SDK previews but will fix in a followup
minSdk = slackProperties.minSdkVersion.toInt()
vectorDrawables.useSupportLibrary = true
// Default to the standard android runner, but note this is overridden in :app
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility = javaVersion
targetCompatibility = javaVersion
isCoreLibraryDesugaringEnabled = true
}
dependencies.add(
Configurations.CORE_LIBRARY_DESUGARING,
SlackDependencies.Google.coreLibraryDesugaring
)
testOptions {
animationsDisabled = true
if (booleanProperty("orchestrator")) {
logger.info(
"[android.testOptions]: Configured to run tests with Android Test Orchestrator"
)
execution = "ANDROIDX_TEST_ORCHESTRATOR"
} else {
logger.debug(
"[android.testOptions]: Configured to run tests without Android Test Orchestrator"
)
}
// Added to avoid unimplemented exceptions in some of the unit tests that have simple
// android dependencies like checking whether code is running on main thread.
// See https://developer.android.com/training/testing/unit-testing/local-unit-tests
// #error-not-mocked for more details
unitTests.isReturnDefaultValues = true
unitTests.isIncludeAndroidResources = true
// Configure individual Tests tasks.
unitTests.all(
typedClosureOf {
//
// Note that we can't configure this to _just_ be enabled for robolectric projects
// based on dependencies unfortunately, as the task graph is already wired by the time
// dependencies start getting resolved.
//
logger.debug("Configuring $name test task to depend on Robolectric jar downloads")
dependsOn(globalConfig.updateRobolectricJarsTask)
// Necessary for some OkHttp-using tests to work on JDK 11 in Robolectric
// https://github.com/robolectric/robolectric/issues/5115
systemProperty("javax.net.ssl.trustStoreType", "JKS")
}
)
}
}
val objenesis2Version = slackProperties.versions.objenesis
val prepareAndroidTestConfigurations = {
configurations.matching { it.name.contains("androidTest", ignoreCase = true) }.configureEach {
// Cover for https://github.com/Kotlin/kotlinx.coroutines/issues/2023
exclude("org.jetbrains.kotlinx", "kotlinx-coroutines-debug")
// Cover for https://github.com/mockito/mockito/pull/2024, as objenesis 3.x is not
// compatible with Android SDK <26
resolutionStrategy.force("org.objenesis:objenesis:$objenesis2Version")
}
}
val composeCompilerVersion = slackProperties.versions.composeCompiler
pluginManager.withPlugin("com.android.base") {
if (slackProperties.enableCompose) {
dependencies.add("implementation", SlackDependencies.Androidx.Compose.runtime)
}
}
pluginManager.withPlugin("com.android.application") {
// Add slack-lint as lint checks source
slackProperties.versions.bundles.commonLint.ifPresent { dependencies.add("lintChecks", it) }
prepareAndroidTestConfigurations()
configure<ApplicationAndroidComponentsExtension> {
commonComponentsExtension.execute(this)
// Disable unit tests on release variants, since it's unused
// TODO maybe we want to disable release androidTest by default? (i.e. for slack kit
// playground, samples, etc)
// TODO would be nice if we could query just non-debuggable build types.
project.configure<ApplicationAndroidComponentsExtension> {
beforeVariants { builder ->
if (builder.buildType == "release") {
builder.enableUnitTest = false
}
}
}
}
configure<BaseAppModuleExtension> {
commonBaseExtensionConfig()
if (slackProperties.enableCompose) {
configureCompose(project, isApp = true, composeCompilerVersion = composeCompilerVersion)
}
defaultConfig {
// TODO this won't work with SDK previews but will fix in a followup
targetSdk = slackProperties.targetSdkVersion.toInt()
}
lint {
lintConfig = rootProject.layout.projectDirectory.file("config/lint/lint.xml").asFile
sarifReport = true
}
lint {
// This check is _never_ up to date and makes network requests!
disable += "NewerVersionAvailable"
// These store qualified gradle caches in their paths and always change in baselines
disable += "ObsoleteLintCustomCheck"
// https://groups.google.com/g/lint-dev/c/Bj0-I1RIPyU/m/mlP5Jpe4AQAJ
error += "ImplicitSamInstance"
ignoreWarnings = lintErrorsOnly
checkDependencies = true
absolutePaths = false
// Lint is weird in that it will generate a new baseline file and fail the build if a new
// one was generated, even if empty.
// If we're updating baselines, always take the baseline so that we populate it if absent.
project
.layout
.projectDirectory
.file("config/lint/baseline.xml")
.asFile
.takeIf { it.exists() || slackProperties.lintUpdateBaselines }
?.let { baseline = it }
}
packagingOptions {
resources.excludes +=
setOf(
"META-INF/LICENSE.txt",
"META-INF/LICENSE",
"META-INF/NOTICE.txt",
".readme",
"META-INF/maven/com.google.guava/guava/pom.properties",
"META-INF/maven/com.google.guava/guava/pom.xml",
"META-INF/DEPENDENCIES",
"**/*.pro",
"**/*.proto",
// Metadata for coroutines not relevant to release builds
"DebugProbesKt.bin",
// Weird bazel build metadata brought in by Tink
"build-data.properties",
"LICENSE_*",
// We don't know where this comes from but it's 5MB
// https://slack-pde.slack.com/archives/C8EER3C04/p1621353426001500
"annotated-jdk/**"
)
jniLibs.pickFirsts +=
setOf(
// Some libs like Flipper bring their own copy of common native libs (like C++) and we
// need to de-dupe
"**/*.so"
)
}
buildTypes {
getByName("debug") {
// For upstream android libraries that just have a single release variant, use that.
matchingFallbacks += "release"
// Debug should be the default build type. This helps inform studio.
isDefault = true
}
}
signingConfigs.configureEach {
enableV3Signing = true
enableV4Signing = true
}
applicationVariants.configureEach {
mergeAssetsProvider.configure {
// This task is too expensive to cache while we have embedded emoji fonts
outputs.cacheIf { false }
}
}
PermissionChecks.configure(
project = project,
allowListActionGetter = { slackExtension.androidHandler.appHandler.allowlistAction }
) { taskName, file, allowListProvider ->
tasks.register<CheckManifestPermissionsTask>(taskName) {
group = LifecycleBasePlugin.VERIFICATION_GROUP
description =
"Checks merged manifest permissions against a known allowlist of permissions."
permissionAllowlistFile.set(file)
permissionAllowlist.set(allowListProvider)
}
}
pluginManager.withPlugin("com.bugsnag.android.gradle") {
// See SlackGradleUtil.shouldEnableBugsnagPlugin for more details on this logic
buildTypes.configureEach {
// We use withGroovyBuilder here because for the life of me I can't understand where to
// set this in a strongly typed language.
withGroovyBuilder {
getProperty("ext").withGroovyBuilder {
setProperty(
"enableBugsnag",
!isDebuggable && globalConfig.shouldEnableBugsnagOnRelease
)
}
}
}
}
}
slackExtension.androidHandler.configureFeatures(project, slackProperties)
}
pluginManager.withPlugin("com.android.library") {
// Add slack-lint as lint checks source
slackProperties.versions.bundles.commonLint.ifPresent { dependencies.add("lintChecks", it) }
prepareAndroidTestConfigurations()
val isLibraryWithVariants = slackProperties.libraryWithVariants
configure<LibraryAndroidComponentsExtension> {
commonComponentsExtension.execute(this)
if (!isLibraryWithVariants) {
beforeVariants { variant ->
when (variant.buildType) {
"debug" -> {
// Even in AGP 4 we can't fully remove this yet due to
// https://issuetracker.google.com/issues/153684320
variant.enable = false
}
}
}
}
// Disable androidTest tasks in libraries unless they opt-in
beforeVariants { builder ->
builder.enableAndroidTest =
slackExtension.androidHandler.featuresHandler.androidTest.getOrElse(false)
}
// Contribute these libraries to Fladle if they opt into it
val androidTestApksAggregator =
project.rootProject.tasks.named<AndroidTestApksTask>(AndroidTestApksTask.NAME)
onVariants { variant ->
val excluded =
slackExtension.androidHandler.featuresHandler.androidTestExcludeFromFladle.getOrElse(
false
)
if (!excluded) {
variant.androidTest?.artifacts?.get(SingleArtifact.APK)?.let { apkArtifactsDir ->
// Wire this up to the aggregator
androidTestApksAggregator.configure { androidTestApkDirs.from(apkArtifactsDir) }
}
}
}
// namespace is not a property but we can hook into DSL finalizing to set it at the end
// if the build script didn't declare one prior
finalizeDsl { libraryExtension ->
if (libraryExtension.namespace == null) {
libraryExtension.namespace =
"slack" +
project
.path
.asSequence()
.mapNotNull {
when (it) {
// Skip dashes and underscores. We could camelcase but it looks weird in a
// package name
'-',
'_' -> null
// Use the project path as the real dot namespacing
':' -> '.'
else -> it
}
}
.joinToString("")
}
}
}
configure<LibraryExtension> {
commonBaseExtensionConfig()
if (slackProperties.enableCompose) {
configureCompose(project, isApp = false, composeCompilerVersion = composeCompilerVersion)
}
if (isLibraryWithVariants) {
buildTypes {
getByName("debug") {
// For upstream android libraries that just have a single release variant, use that.
matchingFallbacks += "release"
// Debug should be the default build type. This helps inform studio.
isDefault = true
}
}
} else {
buildTypes {
getByName("release") {
// Release should be the default build type. This helps inform studio.
isDefault = true
}
}
// Default testBuildType is "debug", but AGP doesn't relocate the testBuildType to
// "release" automatically even if there's only one.
testBuildType = "release"
}
// We don't set targetSdkVersion in libraries since this is controlled by the app.
}
slackExtension.androidHandler.configureFeatures(project, slackProperties)
}
}
private fun configureCompose(project: Project, isApp: Boolean, composeCompilerVersion: String) {
val commonExtensionConfig: CommonExtension<*, *, *, *>.() -> Unit = {
buildFeatures { compose = true }
composeOptions { kotlinCompilerExtensionVersion = composeCompilerVersion }
}
if (isApp) {
project.configure<BaseAppModuleExtension> { commonExtensionConfig() }
} else {
project.configure<LibraryExtension> { commonExtensionConfig() }
}
}
@Suppress("LongMethod")
private fun Project.configureKotlinProjects(
globalConfig: GlobalConfig,
jdkVersion: Int?,
jvmTargetVersion: Int,
slackProperties: SlackProperties
) {
val actualJvmTarget =
if (jvmTargetVersion == 8) {
"1.8"
} else {
jvmTargetVersion.toString()
}
val onKotlinPluginApplied = {
configure<KotlinProjectExtension> { kotlinDaemonJvmArgs = globalConfig.kotlinDaemonArgs }
@Suppress("SuspiciousCollectionReassignment")
tasks.configureEach<KotlinCompile> {
kotlinOptions {
if (!slackProperties.allowWarnings && !name.contains("test", ignoreCase = true)) {
allWarningsAsErrors = true
}
jvmTarget = actualJvmTarget
freeCompilerArgs += kotlinCompilerArgs
if (slackProperties.enableCompose && isAndroid) {
freeCompilerArgs += "-Xskip-prerelease-check"
// Flag to disable Compose's kotlin version check because they're often behind
freeCompilerArgs +=
listOf(
"-P",
"plugin:androidx.compose.compiler.plugins.kotlin:suppressKotlinVersionCompatibilityCheck=true"
)
}
// Potentially useful for static analysis or annotation processors
javaParameters = true
}
}
if (jdkVersion != null) {
configure<KotlinProjectExtension> {
jvmToolchain {
(this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(jdkVersion))
}
}
}
// Set Detekt's jvmTarget
tasks.configureEach<Detekt> { jvmTarget = actualJvmTarget }
configureFreeKotlinCompilerArgs()
if (slackProperties.strictMode && slackProperties.strictValidateKtFilePresence) {
// Verify that at least one `.kt` file is present in the project's `main` source set. This
// is important for IC, as otherwise IC will not work!
// https://youtrack.jetbrains.com/issue/KT-30980
if (project.file("src/main").walkBottomUp().none { it.extension == "kt" }) {
throw AssertionError(
"""
'${project.path}' is a Kotlin project but does not contain any `.kt` files!
Kotlin projects _must_ have at least one `.kt` file in the `src/main` source set! This
is necessary in order for incremental compilation to work correctly (see
https://youtrack.jetbrains.com/issue/KT-30980).
If you have no files to add (resources-only projects, for instance), you can add a dummy
compilation marker file like so:
```
/**
* This class exists solely to force kotlinc to produce incremental compilation
* information. If we ever add meaningful Kotlin sources to this project, we can then
* remove this class.
*
* Ref: https://youtrack.jetbrains.com/issue/KT-30980
*/
@Suppress("UnusedPrivateClass")
private abstract class ${
CaseFormat.LOWER_HYPHEN.to(
CaseFormat.UPPER_CAMEL,
project.name
)
}CompilationMarker
```
""".trimIndent()
)
}
}
}
pluginManager.withPlugin("io.gitlab.arturbosch.detekt") {
// Configuration examples https://arturbosch.github.io/detekt/kotlindsl.html
configure<DetektExtension> {
toolVersion = slackProperties.versions.detekt
config.from("$rootDir/config/detekt/detekt.yml")
config.from("$rootDir/config/detekt/detekt-all.yml")
baseline =
if (globalConfig.mergeDetektBaselinesTask != null) {
tasks.withType<DetektCreateBaselineTask>().configureEach {
globalConfig.mergeDetektBaselinesTask.configure { baselineFiles.from(baseline) }
}
file("$buildDir/intermediates/detekt/baseline.xml")
} else {
file("$rootDir/config/detekt/baseline.xml")
}
}
}
pluginManager.withPlugin("org.jetbrains.kotlin.jvm") {
onKotlinPluginApplied()
// Enable linting on pure JVM projects
apply(plugin = "com.android.lint")
// Add slack-lint as lint checks source
slackProperties.versions.bundles.commonLint.ifPresent { dependencies.add("lintChecks", it) }
}
pluginManager.withPlugin("org.jetbrains.kotlin.android") {
onKotlinPluginApplied()
// Configure kotlin sources in Android projects
configure<BaseExtension> {
sourceSets.configureEach {
val nestedSourceDir = "src/$name/kotlin"
val dir = File(projectDir, nestedSourceDir)
if (dir.exists()) {
// Standard source set
// Only added if it exists to avoid potentially adding empty source dirs
java.srcDirs(layout.projectDirectory.dir(nestedSourceDir))
}
}
}
}
pluginManager.withPlugin("org.jetbrains.kotlin.android.extensions") {
throw GradleException(
"Don't use the deprecated 'android.extensions' plugin, switch to " +
"'plugin.parcelize' instead."
)
}
pluginManager.withPlugin("org.jetbrains.kotlin.kapt") {
configure<KaptExtension> {
// By default, Kapt replaces unknown types with `NonExistentClass`. This flag asks kapt
// to infer the type, which is useful for processors that reference to-be-generated
// classes.
// https://kotlinlang.org/docs/reference/kapt.html#non-existent-type-correction
correctErrorTypes = true
// Maps source errors to Kotlin sources rather than Java stubs
// Disabled because this triggers a bug in kapt on android 30
// https://github.com/JetBrains/kotlin/pull/3610
mapDiagnosticLocations = false
}
// See doc on the property for details
if (!slackProperties.enableKaptInTests) {
tasks
.matching { task ->
task.name.startsWith("kapt") && task.name.endsWith("TestKotlin", ignoreCase = true)
}
.configureEach { enabled = false }
}
}
pluginManager.withPlugin("com.google.devtools.ksp") {
configure<KspExtension> {
// Don't run other plugins like Anvil in KSP's task
blockOtherCompilerPlugins = true
}
}
}
/** Common configuration for annotation processors, such as standard options. */
private fun Project.configureAnnotationProcessors() {
logger.debug("Configuring any annotation processors on $path")
val configs =
APT_OPTION_CONFIGS.mapValues { (_, value) ->
value.newConfigurer(this@configureAnnotationProcessors)
}
configurations
.matching { configuration ->
// Try common case first
configuration.name in Configurations.Groups.APT ||
// Try custom configs like testKapt, debugAnnotationProcessor, etc.
Configurations.Groups.APT.any { configuration.name.endsWith(it, ignoreCase = true) }
}
.configureEach {
val context = ConfigurationContext(project, this@configureEach)
incoming.afterResolve {
dependencies.forEach { dependency -> configs[dependency.name]?.configure(context) }
}
}
}
/**
* Configures per-dependency free Kotlin compiler args. This is necessary because otherwise
* kotlinc will emit angry warnings.
*/
private fun Project.configureFreeKotlinCompilerArgs() {
logger.debug("Configuring specific Kotlin compiler args on $path")
val once = AtomicBoolean()
configurations
.matching { isKnownConfiguration(it.name, Configurations.Groups.RUNTIME) }
.configureEach {
incoming.afterResolve {
dependencies.forEach { dependency ->
KotlinArgConfigs.ALL[dependency.name]?.let { config ->
if (once.compareAndSet(false, true)) {
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
@Suppress("SuspiciousCollectionReassignment") // This isn't suspicious
freeCompilerArgs += config.args
}
}
}
}
}
}
}
}
companion object {
private val APT_OPTION_CONFIGS: Map<String, AptOptionsConfig> =
AptOptionsConfigs().associateBy { it.targetDependency }
/** Top-level JVM plugin IDs. Usually only one of these is applied. */
private val JVM_PLUGINS =
setOf(
"application",
"java",
"java-library",
"org.jetbrains.kotlin.jvm",
"com.android.library",
"com.android.application"
)
private fun isKnownConfiguration(configurationName: String, knownNames: Set<String>): Boolean {
// Try trimming the flavor by just matching the suffix
return knownNames.any { platformConfig ->
configurationName.endsWith(platformConfig, ignoreCase = true)
}
}
/**
* Best effort fuzzy matching on known configuration names that we want to opt into platforming.
* We don't blanket apply them to all configurations because
*/
internal fun isPlatformConfigurationName(name: String): Boolean {
// Kapt/ksp/compileOnly are special cases since they can be combined with others
val isKaptOrCompileOnly =