/
KspSubplugin.kt
866 lines (788 loc) · 38.6 KB
/
KspSubplugin.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
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* 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
*
* http://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.
*/
package com.google.devtools.ksp.gradle
import com.google.devtools.ksp.gradle.model.builder.KspModelBuilder
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.UnknownTaskException
import org.gradle.api.artifacts.Configuration
import org.gradle.api.attributes.Attribute
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.ClasspathNormalizer
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.language.jvm.tasks.ProcessResources
import org.gradle.process.CommandLineArgumentProvider
import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry
import org.gradle.util.GradleVersion
import org.gradle.work.ChangeType
import org.gradle.work.InputChanges
import org.jetbrains.kotlin.buildtools.api.SourcesChanges
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.gradle.dsl.KotlinVersion
import org.jetbrains.kotlin.gradle.internal.kapt.incremental.CLASS_STRUCTURE_ARTIFACT_TYPE
import org.jetbrains.kotlin.gradle.internal.kapt.incremental.ClasspathSnapshot
import org.jetbrains.kotlin.gradle.internal.kapt.incremental.KaptClasspathChanges
import org.jetbrains.kotlin.gradle.internal.kapt.incremental.StructureTransformAction
import org.jetbrains.kotlin.gradle.internal.kapt.incremental.StructureTransformLegacyAction
import org.jetbrains.kotlin.gradle.plugin.CompilerPluginConfig
import org.jetbrains.kotlin.gradle.plugin.FilesSubpluginOption
import org.jetbrains.kotlin.gradle.plugin.InternalSubpluginOption
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilationWithResources
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilerPluginSupportPlugin
import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.SubpluginArtifact
import org.jetbrains.kotlin.gradle.plugin.SubpluginOption
import org.jetbrains.kotlin.gradle.plugin.getKotlinPluginVersion
import org.jetbrains.kotlin.gradle.plugin.mpp.*
import org.jetbrains.kotlin.gradle.tasks.*
import org.jetbrains.kotlin.incremental.isJavaFile
import org.jetbrains.kotlin.incremental.isKotlinFile
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import java.io.File
import java.util.concurrent.Callable
import javax.inject.Inject
class KspGradleSubplugin @Inject internal constructor(private val registry: ToolingModelBuilderRegistry) :
KotlinCompilerPluginSupportPlugin {
companion object {
const val KSP_PLUGIN_ID = "com.google.devtools.ksp.symbol-processing"
const val KSP_API_ID = "symbol-processing-api"
const val KSP_COMPILER_PLUGIN_ID = "symbol-processing"
const val KSP_COMPILER_PLUGIN_ID_NON_EMBEDDABLE = "symbol-processing-cmdline"
const val KSP_GROUP_ID = "com.google.devtools.ksp"
const val KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME = "kspPluginClasspath"
const val KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME_NON_EMBEDDABLE = "kspPluginClasspathNonEmbeddable"
@JvmStatic
fun getKspOutputDir(project: Project, sourceSetName: String, target: String) =
File(project.project.buildDir, "generated/ksp/$target/$sourceSetName")
@JvmStatic
fun getKspClassOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "classes")
@JvmStatic
fun getKspJavaOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "java")
@JvmStatic
fun getKspKotlinOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "kotlin")
@JvmStatic
fun getKspResourceOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "resources")
@JvmStatic
fun getKspCachesDir(project: Project, sourceSetName: String, target: String) =
File(project.project.buildDir, "kspCaches/$target/$sourceSetName")
@JvmStatic
private fun getSubpluginOptions(
project: Project,
kspExtension: KspExtension,
sourceSetName: String,
target: String,
isIncremental: Boolean,
allWarningsAsErrors: Boolean,
commandLineArgumentProviders: ListProperty<CommandLineArgumentProvider>,
commonSources: List<File>,
): List<SubpluginOption> {
val options = mutableListOf<SubpluginOption>()
options +=
InternalSubpluginOption("classOutputDir", getKspClassOutputDir(project, sourceSetName, target).path)
options +=
InternalSubpluginOption("javaOutputDir", getKspJavaOutputDir(project, sourceSetName, target).path)
options +=
InternalSubpluginOption("kotlinOutputDir", getKspKotlinOutputDir(project, sourceSetName, target).path)
options += InternalSubpluginOption(
"resourceOutputDir",
getKspResourceOutputDir(project, sourceSetName, target).path
)
options += InternalSubpluginOption("cachesDir", getKspCachesDir(project, sourceSetName, target).path)
options += InternalSubpluginOption("kspOutputDir", getKspOutputDir(project, sourceSetName, target).path)
options += SubpluginOption("incremental", isIncremental.toString())
options += SubpluginOption(
"incrementalLog",
project.findProperty("ksp.incremental.log")?.toString() ?: "false"
)
options += InternalSubpluginOption("projectBaseDir", project.project.projectDir.canonicalPath)
options += SubpluginOption("allWarningsAsErrors", allWarningsAsErrors.toString())
// Turn this on by default to work KT-30172 around. It is off by default in the compiler plugin.
options += SubpluginOption(
"returnOkOnError",
project.findProperty("ksp.return.ok.on.error")?.toString() ?: "true"
)
commonSources.ifNotEmpty {
options += FilesSubpluginOption("commonSources", this)
}
kspExtension.apOptions.forEach {
options += SubpluginOption("apoption", "${it.key}=${it.value}")
}
options += SubpluginOption(
"excludedProcessors",
kspExtension.excludedProcessors.joinToString(":")
)
options += SubpluginOption(
"mapAnnotationArgumentsInJava",
project.findProperty("ksp.map.annotation.arguments.in.java")?.toString() ?: "false"
)
commandLineArgumentProviders.get().forEach {
it.asArguments().forEach { argument ->
if (!argument.matches(Regex("\\S+=\\S+"))) {
throw IllegalArgumentException("KSP apoption does not match \\S+=\\S+: $argument")
}
options += InternalSubpluginOption("apoption", argument)
}
}
return options
}
}
private lateinit var kspConfigurations: KspConfigurations
override fun apply(target: Project) {
target.extensions.create("ksp", KspExtension::class.java)
kspConfigurations = KspConfigurations(target)
registry.register(KspModelBuilder())
}
override fun isApplicable(kotlinCompilation: KotlinCompilation<*>): Boolean {
val project = kotlinCompilation.target.project
val kspVersion = ApiVersion.parse(KSP_KOTLIN_BASE_VERSION)!!
val kotlinVersion = ApiVersion.parse(project.getKotlinPluginVersion())!!
// Check version and show warning by default.
val noVersionCheck = project.findProperty("ksp.version.check")?.toString()?.toBoolean() == false
if (!noVersionCheck) {
if (kspVersion < kotlinVersion) {
project.logger.warn(
"ksp-$KSP_VERSION is too old for kotlin-$kotlinVersion. " +
"Please upgrade ksp or downgrade kotlin-gradle-plugin to $KSP_KOTLIN_BASE_VERSION."
)
}
if (kspVersion > kotlinVersion) {
project.logger.warn(
"ksp-$KSP_VERSION is too new for kotlin-$kotlinVersion. " +
"Please upgrade kotlin-gradle-plugin to $KSP_KOTLIN_BASE_VERSION."
)
}
}
return true
}
// TODO: to be future proof, protect with `synchronized`
// Map from default input source set to output source set
private val sourceSetMap: MutableMap<KotlinSourceSet, KotlinSourceSet> = mutableMapOf()
override fun applyToCompilation(kotlinCompilation: KotlinCompilation<*>): Provider<List<SubpluginOption>> {
val project = kotlinCompilation.target.project
val kotlinCompileProvider: TaskProvider<AbstractKotlinCompileTool<*>> =
project.locateTask(kotlinCompilation.compileKotlinTaskName) ?: return project.provider { emptyList() }
val kspExtension = project.extensions.getByType(KspExtension::class.java)
val kspConfigurations = kspConfigurations.find(kotlinCompilation)
val nonEmptyKspConfigurations = kspConfigurations.filter { it.allDependencies.isNotEmpty() }
if (nonEmptyKspConfigurations.isEmpty()) {
return project.provider { emptyList() }
}
if (kotlinCompileProvider.name == "compileKotlinMetadata") {
return project.provider { emptyList() }
}
if ((kotlinCompilation as? KotlinSharedNativeCompilation)?.platformType == KotlinPlatformType.common) {
return project.provider { emptyList() }
}
val target = kotlinCompilation.target.name
val sourceSetName = kotlinCompilation.defaultSourceSet.name
val classOutputDir = getKspClassOutputDir(project, sourceSetName, target)
val javaOutputDir = getKspJavaOutputDir(project, sourceSetName, target)
val kotlinOutputDir = getKspKotlinOutputDir(project, sourceSetName, target)
val resourceOutputDir = getKspResourceOutputDir(project, sourceSetName, target)
val kspOutputDir = getKspOutputDir(project, sourceSetName, target)
val kspClasspathCfg = project.configurations.maybeCreate(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME
).markResolvable()
project.dependencies.add(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME,
"$KSP_GROUP_ID:$KSP_API_ID:$KSP_VERSION"
)
project.dependencies.add(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME,
"$KSP_GROUP_ID:$KSP_COMPILER_PLUGIN_ID:$KSP_VERSION"
)
val kspClasspathCfgNonEmbeddable = project.configurations.maybeCreate(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME_NON_EMBEDDABLE
).markResolvable()
project.dependencies.add(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME_NON_EMBEDDABLE,
"$KSP_GROUP_ID:$KSP_API_ID:$KSP_VERSION"
)
project.dependencies.add(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME_NON_EMBEDDABLE,
"$KSP_GROUP_ID:$KSP_COMPILER_PLUGIN_ID_NON_EMBEDDABLE:$KSP_VERSION"
)
findJavaTaskForKotlinCompilation(kotlinCompilation)?.configure { javaCompile ->
val generatedJavaSources = javaCompile.project.fileTree(javaOutputDir)
generatedJavaSources.include("**/*.java")
javaCompile.source(generatedJavaSources)
javaCompile.classpath += project.files(classOutputDir)
}
val processingModel = project.findProperty("ksp.experimental.processing.model")?.toString() ?: "traditional"
assert(kotlinCompileProvider.name.startsWith("compile"))
val kspTaskName = kotlinCompileProvider.name.replaceFirst("compile", "ksp")
val processorClasspath = project.configurations.maybeCreate("${kspTaskName}ProcessorClasspath")
.extendsFrom(*nonEmptyKspConfigurations.toTypedArray()).markResolvable()
fun configureAsKspTask(kspTask: KspTask, isIncremental: Boolean) {
// depends on the processor; if the processor changes, it needs to be reprocessed.
kspTask.dependsOn(processorClasspath.buildDependencies)
kspTask.commandLineArgumentProviders.addAll(kspExtension.commandLineArgumentProviders)
kspTask.options.addAll(
kspTask.project.provider {
getSubpluginOptions(
project,
kspExtension,
sourceSetName,
target,
isIncremental,
kspExtension.allWarningsAsErrors,
kspTask.commandLineArgumentProviders,
emptyList(),
)
}
)
kspTask.inputs.property("apOptions", kspExtension.arguments)
kspTask.inputs.files(processorClasspath).withNormalizer(ClasspathNormalizer::class.java)
}
fun configureAsAbstractKotlinCompileTool(kspTask: AbstractKotlinCompileTool<*>) {
kspTask.destinationDirectory.set(kspOutputDir)
disableRunViaBuildToolsApi(kspTask)
kspTask.outputs.dirs(
kotlinOutputDir,
javaOutputDir,
classOutputDir,
resourceOutputDir
)
val kotlinCompileTask = kotlinCompileProvider.get()
if (kspExtension.allowSourcesFromOtherPlugins) {
fun setSource(source: FileCollection) {
// kspTask.setSource(source) would create circular dependency.
// Therefore we need to manually extract input deps, filter them, and tell kspTask.
kspTask.setSource(project.provider { source.files })
kspTask.dependsOn(project.provider { source.nonSelfDeps(kspTaskName) })
}
setSource(
kotlinCompileTask.sources.filter {
!kotlinOutputDir.isParentOf(it) && !javaOutputDir.isParentOf(it)
}
)
if (kotlinCompileTask is KotlinCompile) {
setSource(
kotlinCompileTask.javaSources.filter {
!kotlinOutputDir.isParentOf(it) && !javaOutputDir.isParentOf(it)
}
)
}
} else {
val filteredTasks =
kspExtension.excludedSources.buildDependencies.getDependencies(null).map { it.name }
kotlinCompilation.allKotlinSourceSetsObservable.forAll { sourceSet ->
kspTask.setSource(
sourceSet.kotlin.srcDirs.filter {
!kotlinOutputDir.isParentOf(it) && !javaOutputDir.isParentOf(it) &&
it !in kspExtension.excludedSources
}
)
kspTask.dependsOn(sourceSet.kotlin.nonSelfDeps(kspTaskName).filter { it.name !in filteredTasks })
}
}
kspTask.libraries.setFrom(
kotlinCompileTask.project.files(
Callable {
kotlinCompileTask.libraries.filter {
// manually exclude KAPT generated class folder from class path snapshot.
// TODO: remove in 1.9.0.
!kspOutputDir.isParentOf(it) && !(it.isDirectory && it.listFiles()?.isEmpty() == true)
}
}
)
)
// kotlinc's incremental compilation isn't compatible with symbol processing in a few ways:
// * It doesn't consider private / internal changes when computing dirty sets.
// * It compiles iteratively; Sources can be compiled in different rounds.
(kspTask as? AbstractKotlinCompile<*>)?.incremental = false
}
fun maybeBlockOtherPlugins(kspTask: BaseKotlinCompile) {
if (kspExtension.blockOtherCompilerPlugins) {
kspTask.pluginClasspath.setFrom(kspClasspathCfg)
kspTask.pluginOptions.set(emptyList())
}
}
fun configurePluginOptions(kspTask: BaseKotlinCompile) {
kspTask.pluginOptions.add(
project.provider {
CompilerPluginConfig().apply {
(kspTask as KspTask).options.get().forEach {
addPluginArgument(KSP_PLUGIN_ID, it)
}
}
}
)
}
fun configureLanguageVersion(kspTask: KotlinCompilationTask<*>) {
kspTask.compilerOptions.useK2.value(false)
val languageVersion = kotlinCompilation.compilerOptions.options.languageVersion
val progressiveMode = kotlinCompilation.compilerOptions.options.progressiveMode
kspTask.compilerOptions.languageVersion.value(
project.provider {
languageVersion.orNull?.let { version ->
if (version >= KotlinVersion.KOTLIN_2_0) {
KotlinVersion.KOTLIN_1_9
} else {
version
}
} ?: KotlinVersion.KOTLIN_1_9
}
)
// Turn off progressive mode if we need to downgrade language version.
kspTask.compilerOptions.progressiveMode.value(
project.provider {
val compileLangVer = languageVersion.orNull ?: KotlinVersion.DEFAULT
if (compileLangVer >= KotlinVersion.KOTLIN_2_0) {
false
} else {
progressiveMode.orNull
}
}
)
}
val isIncremental = project.findProperty("ksp.incremental")?.toString()?.toBoolean() ?: true
val isIntermoduleIncremental =
(project.findProperty("ksp.incremental.intermodule")?.toString()?.toBoolean() ?: true) && isIncremental
val useKSP2 = project.findProperty("ksp.useKSP2")?.toString()?.toBoolean() ?: false
// Create and configure KSP tasks.
val kspTaskProvider = if (useKSP2) {
KspAATask.registerKspAATask(
kotlinCompilation,
kotlinCompileProvider,
processorClasspath,
kspExtension
)
} else {
when (kotlinCompilation.platformType) {
KotlinPlatformType.jvm, KotlinPlatformType.androidJvm -> {
KotlinFactories.registerKotlinJvmCompileTask(project, kspTaskName, kotlinCompilation).also {
it.configure { kspTask ->
val kotlinCompileTask = kotlinCompileProvider.get() as KotlinCompile
maybeBlockOtherPlugins(kspTask as BaseKotlinCompile)
configureAsKspTask(kspTask, isIncremental)
configureAsAbstractKotlinCompileTool(kspTask as AbstractKotlinCompileTool<*>)
configurePluginOptions(kspTask)
configureLanguageVersion(kspTask)
if (kspTask.classpathSnapshotProperties.useClasspathSnapshot.get() == false) {
kspTask.compilerOptions.moduleName.convention(
kotlinCompileTask.compilerOptions.moduleName.map { "$it-ksp" }
)
}
kspTask.destination.value(kspOutputDir)
val classStructureFiles = getClassStructureFiles(project, kspTask.libraries)
kspTask.incrementalChangesTransformers.add(
createIncrementalChangesTransformer(
isIncremental,
isIntermoduleIncremental,
getKspCachesDir(project, sourceSetName, target),
project.provider { classStructureFiles },
project.provider { kspTask.libraries },
project.provider { processorClasspath }
)
)
}
// Don't support binary generation for non-JVM platforms yet.
// FIXME: figure out how to add user generated libraries.
kotlinCompilation.output.classesDirs.from(classOutputDir)
}
}
KotlinPlatformType.js, KotlinPlatformType.wasm -> {
KotlinFactories.registerKotlinJSCompileTask(project, kspTaskName, kotlinCompilation).also {
it.configure { kspTask ->
val kotlinCompileTask = kotlinCompileProvider.get() as Kotlin2JsCompile
maybeBlockOtherPlugins(kspTask as BaseKotlinCompile)
configureAsKspTask(kspTask, isIncremental)
configureAsAbstractKotlinCompileTool(kspTask as AbstractKotlinCompileTool<*>)
configurePluginOptions(kspTask)
configureLanguageVersion(kspTask)
kspTask.incrementalChangesTransformers.add(
createIncrementalChangesTransformer(
isIncremental,
false,
getKspCachesDir(project, sourceSetName, target),
project.provider { project.files() },
project.provider { project.files() },
project.provider { processorClasspath }
)
)
}
}
}
KotlinPlatformType.common -> {
KotlinFactories.registerKotlinMetadataCompileTask(project, kspTaskName, kotlinCompilation).also {
it.configure { kspTask ->
maybeBlockOtherPlugins(kspTask as BaseKotlinCompile)
configureAsKspTask(kspTask, isIncremental)
configureAsAbstractKotlinCompileTool(kspTask as AbstractKotlinCompileTool<*>)
configurePluginOptions(kspTask)
configureLanguageVersion(kspTask)
kspTask.incrementalChangesTransformers.add(
createIncrementalChangesTransformer(
isIncremental,
false,
getKspCachesDir(project, sourceSetName, target),
project.provider { project.files() },
project.provider { project.files() },
project.provider { processorClasspath }
)
)
}
}
}
KotlinPlatformType.native -> {
KotlinFactories.registerKotlinNativeCompileTask(project, kspTaskName, kotlinCompilation).also {
it.configure { kspTask ->
val kotlinCompileTask = kotlinCompileProvider.get() as KotlinNativeCompile
configureAsKspTask(kspTask, false)
configureAsAbstractKotlinCompileTool(kspTask)
val useEmbeddable = project.findProperty("kotlin.native.useEmbeddableCompilerJar")
?.toString()?.toBoolean() ?: true
val classpathCfg = if (useEmbeddable) {
kspClasspathCfg
} else {
kspClasspathCfgNonEmbeddable
}
// KotlinNativeCompile computes -Xplugin=... from compilerPluginClasspath.
if (kspExtension.blockOtherCompilerPlugins) {
kspTask.compilerPluginClasspath = classpathCfg
} else {
kspTask.compilerPluginClasspath =
classpathCfg + kotlinCompileTask.compilerPluginClasspath!!
kspTask.compilerPluginOptions.addPluginArgument(kotlinCompileTask.compilerPluginOptions)
}
kspTask.commonSources.from(kotlinCompileTask.commonSources)
kspTask.options.add(
FileCollectionSubpluginOption.create(
project = project,
name = "apclasspath",
classpath = processorClasspath
)
)
kspTask.compilerOptions.freeCompilerArgs.addAll(
kspTask.options.map {
it.flatMap { listOf("-P", it.toArg()) }
}
)
kspTask.compilerOptions.freeCompilerArgs.addAll(
kotlinCompileTask.compilerOptions.freeCompilerArgs
)
configureLanguageVersion(kspTask)
// Cannot use lambda; See below for details.
// https://docs.gradle.org/7.2/userguide/validation_problems.html#implementation_unknown
kspTask.doFirst(object : Action<Task> {
override fun execute(t: Task) {
kspOutputDir.deleteRecursively()
}
})
}
}
}
// No else; The cases should be exhaustive
}
}
val generatedSources = arrayOf(
project.files(kotlinOutputDir).builtBy(kspTaskProvider),
project.files(javaOutputDir).builtBy(kspTaskProvider),
)
if (kotlinCompilation is KotlinCommonCompilation) {
// Do not add generated sources to common source sets.
// They will be observed by downstreams and violate current build scheme.
kotlinCompileProvider.configure { it.source(*generatedSources) }
} else {
kotlinCompilation.defaultSourceSet.kotlin.srcDirs(*generatedSources)
}
kotlinCompileProvider.configure { kotlinCompile ->
when (kotlinCompile) {
is AbstractKotlinCompile<*> -> kotlinCompile.libraries.from(project.files(classOutputDir))
// is KotlinNativeCompile -> TODO: support binary generation?
}
}
val processResourcesTaskName =
(kotlinCompilation as? KotlinCompilationWithResources)?.processResourcesTaskName ?: "processResources"
project.locateTask<ProcessResources>(processResourcesTaskName)?.let { provider ->
provider.configure { resourcesTask ->
resourcesTask.from(project.files(resourceOutputDir).builtBy(kspTaskProvider))
}
}
if (kotlinCompilation is KotlinJvmAndroidCompilation) {
AndroidPluginIntegration.syncSourceSets(
project = project,
kotlinCompilation = kotlinCompilation,
kspTaskProvider = kspTaskProvider,
javaOutputDir = javaOutputDir,
kotlinOutputDir = kotlinOutputDir,
classOutputDir = classOutputDir,
resourcesOutputDir = project.files(resourceOutputDir)
)
}
return project.provider { emptyList() }
}
override fun getCompilerPluginId() = KSP_PLUGIN_ID
override fun getPluginArtifact(): SubpluginArtifact =
SubpluginArtifact(
groupId = "com.google.devtools.ksp",
artifactId = KSP_COMPILER_PLUGIN_ID,
version = KSP_VERSION
)
override fun getPluginArtifactForNative(): SubpluginArtifact? =
SubpluginArtifact(
groupId = "com.google.devtools.ksp",
artifactId = KSP_COMPILER_PLUGIN_ID_NON_EMBEDDABLE,
version = KSP_VERSION
)
}
// Copied from kotlin-gradle-plugin, because they are internal.
internal inline fun <reified T : Task> Project.locateTask(name: String): TaskProvider<T>? =
try {
tasks.withType(T::class.java).named(name)
} catch (e: UnknownTaskException) {
null
}
// Copied from kotlin-gradle-plugin, because they are internal.
internal fun findJavaTaskForKotlinCompilation(compilation: KotlinCompilation<*>): TaskProvider<out JavaCompile>? =
when (compilation) {
is KotlinJvmAndroidCompilation -> compilation.compileJavaTaskProvider
is KotlinWithJavaCompilation<*, *> -> compilation.compileJavaTaskProvider
is KotlinJvmCompilation -> compilation.compileJavaTaskProvider // may be null for Kotlin-only JVM target in MPP
else -> null
}
internal val artifactType = Attribute.of("artifactType", String::class.java)
internal fun maybeRegisterTransform(project: Project) {
// Use the same flag with KAPT, so as to share the same transformation in case KAPT and KSP are both enabled.
if (!project.extensions.extraProperties.has("KaptStructureTransformAdded")) {
val transformActionClass =
if (GradleVersion.current() >= GradleVersion.version("5.4"))
StructureTransformAction::class.java
else
StructureTransformLegacyAction::class.java
project.dependencies.registerTransform(transformActionClass) { transformSpec ->
transformSpec.from.attribute(artifactType, "jar")
transformSpec.to.attribute(artifactType, CLASS_STRUCTURE_ARTIFACT_TYPE)
}
project.dependencies.registerTransform(transformActionClass) { transformSpec ->
transformSpec.from.attribute(artifactType, "directory")
transformSpec.to.attribute(artifactType, CLASS_STRUCTURE_ARTIFACT_TYPE)
}
project.extensions.extraProperties["KaptStructureTransformAdded"] = true
}
}
internal fun getClassStructureFiles(
project: Project,
libraries: ConfigurableFileCollection,
): FileCollection {
maybeRegisterTransform(project)
val classStructureIfIncremental = project.configurations.detachedConfiguration(
project.dependencies.create(project.files(project.provider { libraries }))
).markResolvable()
return classStructureIfIncremental.incoming.artifactView { viewConfig ->
viewConfig.attributes.attribute(artifactType, CLASS_STRUCTURE_ARTIFACT_TYPE)
}.files
}
// Reuse Kapt's infrastructure to compute affected names in classpath.
// This is adapted from KaptTask.findClasspathChanges.
internal fun findClasspathChanges(
changes: SourcesChanges,
cacheDir: File,
allDataFiles: Set<File>,
libs: List<File>,
processorCP: List<File>,
): KaptClasspathChanges {
cacheDir.mkdirs()
val changedFiles =
(changes as? SourcesChanges.Known)?.let { it.modifiedFiles + it.removedFiles }?.toSet() ?: allDataFiles
val loadedPrevious = ClasspathSnapshot.ClasspathSnapshotFactory.loadFrom(cacheDir)
val previousAndCurrentDataFiles = lazy { loadedPrevious.getAllDataFiles() + allDataFiles }
val allChangesRecognized = changedFiles.all {
val extension = it.extension
if (extension.isEmpty() || extension == "kt" || extension == "java" || extension == "jar" ||
extension == "class"
) {
return@all true
}
// if not a directory, Java source file, jar, or class, it has to be a structure file, in order to understand changes
it in previousAndCurrentDataFiles.value
}
val previousSnapshot = if (allChangesRecognized) {
loadedPrevious
} else {
ClasspathSnapshot.ClasspathSnapshotFactory.getEmptySnapshot()
}
val currentSnapshot =
ClasspathSnapshot.ClasspathSnapshotFactory.createCurrent(
cacheDir,
libs,
processorCP,
allDataFiles
)
val classpathChanges = currentSnapshot.diff(previousSnapshot, changedFiles)
if (classpathChanges is KaptClasspathChanges.Unknown || changes is SourcesChanges.Unknown) {
cacheDir.deleteRecursively()
cacheDir.mkdirs()
}
currentSnapshot.writeToCache()
return classpathChanges
}
internal fun SourcesChanges.hasNonSourceChange(): Boolean {
if (this !is SourcesChanges.Known)
return true
return !(this.modifiedFiles + this.removedFiles).all {
it.isKotlinFile(listOf("kt")) || it.isJavaFile()
}
}
fun KaptClasspathChanges.toSubpluginOptions(): List<SubpluginOption> {
return if (this is KaptClasspathChanges.Known) {
this.names.map { it.replace('/', '.').replace('$', '.') }.ifNotEmpty {
listOf(SubpluginOption("changedClasses", joinToString(":")))
} ?: emptyList()
} else {
emptyList()
}
}
fun SourcesChanges.toSubpluginOptions(): List<SubpluginOption> {
return if (this is SourcesChanges.Known) {
val options = mutableListOf<SubpluginOption>()
this.modifiedFiles.filter { it.isKotlinFile(listOf("kt")) || it.isJavaFile() }.ifNotEmpty {
options += SubpluginOption("knownModified", map { it.path }.joinToString(File.pathSeparator))
}
this.removedFiles.filter { it.isKotlinFile(listOf("kt")) || it.isJavaFile() }.ifNotEmpty {
options += SubpluginOption("knownRemoved", map { it.path }.joinToString(File.pathSeparator))
}
options
} else {
emptyList()
}
}
// Return a closure that captures required arguments only.
internal fun createIncrementalChangesTransformer(
isKspIncremental: Boolean,
isIntermoduleIncremental: Boolean,
cacheDir: File,
classpathStructure: Provider<FileCollection>,
libraries: Provider<FileCollection>,
processorCP: Provider<FileCollection>,
): (SourcesChanges) -> List<SubpluginOption> = { changedFiles ->
val options = mutableListOf<SubpluginOption>()
val apClasspath = processorCP.get().files.toList()
if (isKspIncremental) {
if (isIntermoduleIncremental) {
// findClasspathChanges may clear caches, if there are
// 1. unknown changes, or
// 2. changes in annotation processors.
val classpathChanges = findClasspathChanges(
changedFiles,
cacheDir,
classpathStructure.get().files,
libraries.get().files.toList(),
apClasspath
)
options += classpathChanges.toSubpluginOptions()
} else {
if (changedFiles.hasNonSourceChange()) {
cacheDir.deleteRecursively()
}
}
} else {
cacheDir.deleteRecursively()
}
options += changedFiles.toSubpluginOptions()
options += FilesSubpluginOption("apclasspath", apClasspath)
options
}
internal fun getCPChanges(
inputChanges: InputChanges,
incrementalProps: List<FileCollection>,
cacheDir: File,
classpathStructure: FileCollection,
libraries: FileCollection,
processorCP: FileCollection,
): List<String> {
val apClasspath = processorCP.files.toList()
val changedFiles = if (!inputChanges.isIncremental) {
SourcesChanges.Unknown
} else {
incrementalProps.fold(mutableListOf<File>() to mutableListOf<File>()) { (modified, removed), prop ->
inputChanges.getFileChanges(prop).forEach {
when (it.changeType) {
ChangeType.ADDED, ChangeType.MODIFIED -> modified.add(it.file)
ChangeType.REMOVED -> removed.add(it.file)
else -> Unit
}
}
modified to removed
}.run {
SourcesChanges.Known(first, second)
}
}
val classpathChanges = findClasspathChanges(
changedFiles,
cacheDir,
classpathStructure.files,
libraries.files.toList(),
apClasspath
)
return if (classpathChanges is KaptClasspathChanges.Known) {
classpathChanges.names.map {
it.replace('/', '.').replace('$', '.')
}
} else {
emptyList()
}
}
internal fun Configuration.markResolvable(): Configuration = apply {
isCanBeResolved = true
isCanBeConsumed = false
isVisible = false
}
/**
* A [SubpluginOption] that returns the joined path for files in the given [fileCollection].
*/
internal class FileCollectionSubpluginOption(
key: String,
val fileCollection: ConfigurableFileCollection
) : SubpluginOption(
key = key,
lazyValue = lazy {
val files = fileCollection.files
files.joinToString(File.pathSeparator) { it.normalize().absolutePath }
}
) {
companion object {
fun create(
project: Project,
name: String,
classpath: Configuration
): FileCollectionSubpluginOption {
val fileCollection = project.objects.fileCollection()
fileCollection.from(classpath)
return FileCollectionSubpluginOption(
key = name,
fileCollection = fileCollection
)
}
}
}
internal fun FileCollection.nonSelfDeps(selfTaskName: String): List<Task> =
buildDependencies.getDependencies(null).filterNot {
it.name == selfTaskName
}