-
Notifications
You must be signed in to change notification settings - Fork 272
/
IntelliJPlugin.kt
1519 lines (1348 loc) · 75.3 KB
/
IntelliJPlugin.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 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij
import com.jetbrains.plugin.structure.intellij.version.IdeVersion
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.DependencySet
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.internal.artifacts.publish.ArchivePublishArtifact
import org.gradle.api.internal.plugins.DefaultArtifactPublicationSet
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.plugins.PluginInstantiationException
import org.gradle.api.tasks.ClasspathNormalizer
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.bundling.Zip
import org.gradle.api.tasks.testing.Test
import org.gradle.internal.jvm.Jvm
import org.gradle.internal.os.OperatingSystem
import org.gradle.kotlin.dsl.attributes
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.named
import org.gradle.language.jvm.tasks.ProcessResources
import org.gradle.plugins.ide.idea.model.IdeaModel
import org.gradle.plugins.ide.idea.model.IdeaProject
import org.gradle.tooling.BuildException
import org.jetbrains.gradle.ext.IdeaExtPlugin
import org.jetbrains.gradle.ext.ProjectSettings
import org.jetbrains.gradle.ext.TaskTriggersConfig
import org.jetbrains.intellij.BuildFeature.NO_SEARCHABLE_OPTIONS_WARNING
import org.jetbrains.intellij.BuildFeature.PAID_PLUGIN_SEARCHABLE_OPTIONS_WARNING
import org.jetbrains.intellij.BuildFeature.SELF_UPDATE_CHECK
import org.jetbrains.intellij.IntelliJPluginConstants.RELEASE_SUFFIX_EAP_CANDIDATE
import org.jetbrains.intellij.IntelliJPluginConstants.RELEASE_SUFFIX_SNAPSHOT
import org.jetbrains.intellij.dependency.IdeaDependency
import org.jetbrains.intellij.dependency.IdeaDependencyManager
import org.jetbrains.intellij.dependency.PluginDependency
import org.jetbrains.intellij.dependency.PluginDependencyManager
import org.jetbrains.intellij.dependency.PluginDependencyNotation
import org.jetbrains.intellij.dependency.PluginProjectDependency
import org.jetbrains.intellij.jbr.JbrResolver
import org.jetbrains.intellij.model.MavenMetadata
import org.jetbrains.intellij.model.XmlExtractor
import org.jetbrains.intellij.performanceTest.ProfilerName
import org.jetbrains.intellij.pluginRepository.PluginRepositoryFactory
import org.jetbrains.intellij.tasks.*
import org.jetbrains.intellij.utils.ArchiveUtils
import org.jetbrains.intellij.utils.DependenciesDownloader
import org.jetbrains.intellij.utils.LatestVersionResolver
import org.jetbrains.intellij.utils.ivyRepository
import org.jetbrains.intellij.utils.mavenRepository
import java.io.File
import java.net.URL
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.ChronoField
import java.util.EnumSet
import java.util.jar.Manifest
@Suppress("UnstableApiUsage")
open class IntelliJPlugin : Plugin<Project> {
private lateinit var archiveUtils: ArchiveUtils
private lateinit var dependenciesDownloader: DependenciesDownloader
private lateinit var context: String
override fun apply(project: Project) {
archiveUtils = project.objects.newInstance(ArchiveUtils::class.java)
dependenciesDownloader = project.objects.newInstance(DependenciesDownloader::class.java)
context = project.logCategory()
checkGradleVersion(project)
checkPluginVersion(project)
project.plugins.apply(JavaPlugin::class.java)
project.plugins.apply(IdeaExtPlugin::class.java)
project.pluginManager.withPlugin("org.jetbrains.gradle.plugin.idea-ext") {
project.idea {
// IdeaModel.project is available only for root project
this.project?.settings {
taskTriggers {
afterSync("setupDependencies")
}
}
}
}
val intellijExtension = project.extensions.create(
IntelliJPluginConstants.EXTENSION_NAME,
IntelliJPluginExtension::class.java,
)
intellijExtension.apply {
version.convention(project.provider {
if (!localPath.isPresent) {
throw GradleException(
"The value for the 'intellij.version' property was not specified, " +
"see: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#intellij-extension-version"
)
}
null
})
pluginName.convention(project.provider {
project.name
})
updateSinceUntilBuild.convention(true)
sameSinceUntilBuild.convention(false)
instrumentCode.convention(true)
sandboxDir.convention(project.provider {
File(project.buildDir, IntelliJPluginConstants.DEFAULT_SANDBOX).absolutePath
})
intellijRepository.convention(IntelliJPluginConstants.DEFAULT_INTELLIJ_REPOSITORY)
downloadSources.convention(!System.getenv().containsKey("CI"))
configureDefaultDependencies.convention(true)
type.convention("IC")
}
configureTasks(project, intellijExtension)
}
private fun checkGradleVersion(project: Project) {
if (Version.parse(project.gradle.gradleVersion) < Version.parse("6.7.1")) {
throw PluginInstantiationException("${IntelliJPluginConstants.NAME} requires Gradle 6.7.1 and higher")
}
}
private fun checkPluginVersion(project: Project) {
if (!project.isBuildFeatureEnabled(SELF_UPDATE_CHECK)) {
return
}
if (project.gradle.startParameter.isOffline) {
return
}
try {
val version = getCurrentVersion()?.let(Version::parse) ?: Version()
val latestVersion = LatestVersionResolver.fromGitHub(IntelliJPluginConstants.NAME, IntelliJPluginConstants.GITHUB_REPOSITORY)
if (version < Version.parse(latestVersion)) {
warn(
context,
"${IntelliJPluginConstants.NAME} is outdated: $version. Update `${IntelliJPluginConstants.ID}` to: $latestVersion"
)
}
} catch (e: Exception) {
error(context, e.message.orEmpty(), e)
}
}
private fun configureTasks(project: Project, extension: IntelliJPluginExtension) {
info(context, "Configuring plugin")
project.tasks.whenTaskAdded {
if (this is RunIdeBase) {
prepareConventionMappingsForRunIdeTask(project, extension, this, IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
}
if (this is RunIdeForUiTestTask) {
prepareConventionMappingsForRunIdeTask(
project,
extension,
this,
IntelliJPluginConstants.PREPARE_UI_TESTING_SANDBOX_TASK_NAME
)
}
}
configureSetupDependenciesTask(project, extension)
configureClassPathIndexCleanupTask(project)
configurePatchPluginXmlTask(project, extension)
configureRobotServerDownloadTask(project)
configurePrepareSandboxTasks(project, extension)
configureListProductsReleasesTask(project, extension)
configureRunPluginVerifierTask(project, extension)
configurePluginVerificationTask(project)
configureRunIdeTask(project)
configureRunIdePerformanceTestTask(project, extension)
configureRunIdeForUiTestsTask(project)
configureBuildSearchableOptionsTask(project)
configureJarSearchableOptionsTask(project)
configureBuildPluginTask(project)
configureSignPluginTask(project)
configurePublishPluginTask(project)
configureProcessResources(project)
configureInstrumentation(project, extension)
assert(!project.state.executed) { "afterEvaluate is a no-op for an executed project" }
project.afterEvaluate {
configureProjectAfterEvaluate(this, extension)
}
}
private fun configureProjectAfterEvaluate(project: Project, extension: IntelliJPluginExtension) {
project.subprojects.forEach { subproject ->
if (subproject.plugins.findPlugin(IntelliJPlugin::class.java) == null) {
subproject.extensions.findByType(IntelliJPluginExtension::class.java)?.let {
configureProjectAfterEvaluate(subproject, it)
}
}
}
configureTestTasks(project, extension)
}
private fun verifyJavaPluginDependency(project: Project, ideaDependency: IdeaDependency, plugins: List<Any>) {
val hasJavaPluginDependency = plugins.contains("java") || plugins.contains("com.intellij.java")
if (!hasJavaPluginDependency && File(ideaDependency.classes, "plugins/java").exists()) {
sourcePluginXmlFiles(project).forEach { file ->
parsePluginXml(file, context)?.dependencies?.forEach {
if (it.dependencyId == "com.intellij.modules.java") {
throw BuildException(
"The project depends on 'com.intellij.modules.java' module but doesn't declare a compile dependency on it.\n " +
"Please delete 'depends' tag from '${file.absolutePath}' or add 'java' plugin to Gradle dependencies " +
"(e.g. intellij { plugins = ['java'] })",
null,
)
}
}
}
}
}
private fun configureBuiltinPluginsDependencies(
project: Project,
dependencies: DependencySet,
resolver: PluginDependencyManager,
extension: IntelliJPluginExtension,
ideaDependency: IdeaDependency,
) {
val configuredPlugins = extension.getUnresolvedPluginDependencies().filter(PluginDependency::builtin).map(PluginDependency::id)
ideaDependency.pluginsRegistry.collectBuiltinDependencies(configuredPlugins).forEach {
val plugin = resolver.resolve(project, PluginDependencyNotation(it, null, null)) ?: return
configurePluginDependency(project, plugin, extension, dependencies, resolver)
}
}
private fun configurePluginDependency(
project: Project,
plugin: PluginDependency,
extension: IntelliJPluginExtension,
dependencies: DependencySet,
resolver: PluginDependencyManager,
) {
if (extension.configureDefaultDependencies.get()) {
resolver.register(project, plugin, dependencies)
}
extension.addPluginDependency(plugin)
project.tasks.withType(PrepareSandboxTask::class.java).configureEach {
configureExternalPlugin(plugin)
}
}
private fun configureProjectPluginTasksDependency(dependency: Project, taskProvider: TaskProvider<PrepareSandboxTask>) {
// invoke before tasks graph is ready
if (dependency.plugins.findPlugin(IntelliJPlugin::class.java) == null) {
throw BuildException("Cannot use '$dependency' as a plugin dependency. IntelliJ Plugin not found." + dependency.plugins, null)
}
dependency.tasks.named(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME) {
taskProvider.get().dependsOn(this)
}
}
private fun configureProjectPluginDependency(
project: Project,
dependency: Project,
dependencies: DependencySet,
extension: IntelliJPluginExtension,
) {
// invoke on demand, when plugins artifacts are needed
if (dependency.plugins.findPlugin(IntelliJPlugin::class.java) == null) {
throw BuildException("Cannot use '$dependency' as a plugin dependency. IntelliJ Plugin not found." + dependency.plugins, null)
}
dependencies.add(project.dependencies.create(dependency))
val prepareSandboxTaskProvider = dependency.tasks.named<PrepareSandboxTask>(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
val prepareSandboxTask = prepareSandboxTaskProvider.get()
val dependencyDirectory = File(prepareSandboxTask.destinationDir, prepareSandboxTask.pluginName.get())
val pluginDependency = PluginProjectDependency(dependencyDirectory, context)
extension.addPluginDependency(pluginDependency)
project.tasks.withType(PrepareSandboxTask::class.java).forEach {
it.configureCompositePlugin(pluginDependency)
}
}
private fun configurePatchPluginXmlTask(project: Project, extension: IntelliJPluginExtension) {
info(context, "Configuring patch plugin.xml task")
project.tasks.register(IntelliJPluginConstants.PATCH_PLUGIN_XML_TASK_NAME, PatchPluginXmlTask::class.java) {
val setupDependenciesTaskProvider =
project.tasks.named<SetupDependenciesTask>(IntelliJPluginConstants.SETUP_DEPENDENCIES_TASK_NAME)
val setupDependenciesTask = setupDependenciesTaskProvider.get()
group = IntelliJPluginConstants.GROUP_NAME
description = "Patches `plugin.xml` files with values provided to the task."
version.convention(project.provider {
project.version.toString()
})
pluginXmlFiles.convention(project.provider {
sourcePluginXmlFiles(project)
})
destinationDir.convention(project.layout.dir(project.provider {
File(project.buildDir, IntelliJPluginConstants.PLUGIN_XML_DIR_NAME)
}))
sinceBuild.convention(project.provider {
if (extension.updateSinceUntilBuild.get()) {
val ideVersion = IdeVersion.createIdeVersion(setupDependenciesTask.idea.get().buildNumber)
"${ideVersion.baselineVersion}.${ideVersion.build}"
} else {
null
}
})
untilBuild.convention(project.provider {
if (extension.updateSinceUntilBuild.get()) {
if (extension.sameSinceUntilBuild.get()) {
"${sinceBuild.get()}.*"
} else {
val ideVersion = IdeVersion.createIdeVersion(setupDependenciesTask.idea.get().buildNumber)
"${ideVersion.baselineVersion}.*"
}
} else {
null
}
})
dependsOn(setupDependenciesTaskProvider)
}
}
private fun configurePrepareSandboxTasks(project: Project, extension: IntelliJPluginExtension) {
val downloadPluginTaskProvider =
project.tasks.named<DownloadRobotServerPluginTask>(IntelliJPluginConstants.DOWNLOAD_ROBOT_SERVER_PLUGIN_TASK_NAME)
configurePrepareSandboxTask(project, extension, IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME, "")
configurePrepareSandboxTask(project, extension, IntelliJPluginConstants.PREPARE_TESTING_SANDBOX_TASK_NAME, "-test")
configurePrepareSandboxTask(project, extension, IntelliJPluginConstants.PREPARE_UI_TESTING_SANDBOX_TASK_NAME, "-uiTest") {
val downloadPluginTask = downloadPluginTaskProvider.get()
it.from(downloadPluginTask.outputDir.get())
it.dependsOn(downloadPluginTask)
}
}
private fun configureRobotServerDownloadTask(project: Project) {
info(context, "Configuring robot-server download Task")
project.tasks.register(IntelliJPluginConstants.DOWNLOAD_ROBOT_SERVER_PLUGIN_TASK_NAME, DownloadRobotServerPluginTask::class.java) {
group = IntelliJPluginConstants.GROUP_NAME
description = "Download `robot-server` plugin."
version.convention(IntelliJPluginConstants.VERSION_LATEST)
outputDir.convention(project.provider {
project.layout.projectDirectory.dir("${project.buildDir}/robotServerPlugin")
})
pluginArchive.convention(project.provider {
val resolvedVersion = resolveRobotServerPluginVersion(version.orNull)
val (group, name) = getDependency(resolvedVersion).split(':')
dependenciesDownloader.downloadFromRepository(logCategory(), {
create(
group = group,
name = name,
version = resolvedVersion,
)
}, {
mavenRepository(IntelliJPluginConstants.INTELLIJ_DEPENDENCIES) {
content { includeGroup(group) }
}
}).first()
})
}
}
private fun configurePrepareSandboxTask(
project: Project,
extension: IntelliJPluginExtension,
taskName: String,
testSuffix: String,
configure: ((it: PrepareSandboxTask) -> Unit)? = null,
) {
info(context, "Configuring $taskName task")
project.tasks.register(taskName, PrepareSandboxTask::class.java) {
val setupDependenciesTaskProvider =
project.tasks.named<SetupDependenciesTask>(IntelliJPluginConstants.SETUP_DEPENDENCIES_TASK_NAME)
val setupDependenciesTask = setupDependenciesTaskProvider.get()
group = IntelliJPluginConstants.GROUP_NAME
description = "Prepares sandbox directory with installed plugin and its dependencies."
pluginName.convention(extension.pluginName)
pluginJar.convention(project.layout.file(project.provider {
val jarTaskProvider = project.tasks.named<Jar>(JavaPlugin.JAR_TASK_NAME)
val jarTask = jarTaskProvider.get()
jarTask.run {
exclude("**/classpath.index")
manifest.attributes(
"Created-By" to "Gradle ${project.gradle.gradleVersion}",
"Build-JVM" to Jvm.current(),
"Version" to project.version,
"Build-Plugin" to IntelliJPluginConstants.NAME,
"Build-Plugin-Version" to (getCurrentVersion() ?: "0.0.0"),
"Build-OS" to OperatingSystem.current(),
"Build-SDK" to when (extension.localPath.orNull) {
null -> "${extension.getVersionType()}-${extension.getVersionNumber()}"
else -> setupDependenciesTask.idea.get().classes.let { ideaClasses ->
ideProductInfo(ideaClasses)
?.run { "$productCode-$version" }
// Fall back on build number if product-info.json is not present, this is the case
// for recent versions of Android Studio.
?: ideBuildNumber(ideaClasses)
}
},
)
archiveFile.orNull?.asFile
}
}))
defaultDestinationDir.convention(project.provider {
project.file("${extension.sandboxDir.get()}/plugins$testSuffix")
})
configDir.convention(project.provider {
"${extension.sandboxDir.get()}/config$testSuffix"
})
librariesToIgnore.convention(project.provider {
project.files(setupDependenciesTask.idea.get().jarFiles)
})
pluginDependencies.convention(project.provider {
extension.getPluginDependenciesList(project)
})
dependsOn(JavaPlugin.JAR_TASK_NAME)
dependsOn(project.configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME))
dependsOn(IntelliJPluginConstants.SETUP_DEPENDENCIES_TASK_NAME)
configure?.invoke(this)
}.let { taskProvider ->
project.afterEvaluate {
extension.plugins.get().filterIsInstance<Project>().forEach { dependency ->
if (dependency.state.executed) {
configureProjectPluginTasksDependency(dependency, taskProvider)
} else {
dependency.afterEvaluate {
configureProjectPluginTasksDependency(dependency, taskProvider)
}
}
}
}
}
}
private fun configureRunPluginVerifierTask(project: Project, extension: IntelliJPluginExtension) {
info(context, "Configuring run plugin verifier task")
project.tasks.register(IntelliJPluginConstants.RUN_PLUGIN_VERIFIER_TASK_NAME, RunPluginVerifierTask::class.java) {
val listProductsReleasesTaskProvider =
project.tasks.named<ListProductsReleasesTask>(IntelliJPluginConstants.LIST_PRODUCTS_RELEASES_TASK_NAME)
val listProductsReleasesTask = listProductsReleasesTaskProvider.get()
group = IntelliJPluginConstants.GROUP_NAME
description = "Runs the IntelliJ Plugin Verifier tool to check the binary compatibility with specified IDE builds."
failureLevel.convention(EnumSet.of(RunPluginVerifierTask.FailureLevel.COMPATIBILITY_PROBLEMS))
verifierVersion.convention(IntelliJPluginConstants.VERSION_LATEST)
distributionFile.convention(project.layout.file(project.provider {
resolveBuildTaskOutput(project)
}))
verificationReportsDir.convention(project.provider {
"${project.buildDir}/reports/pluginVerifier"
})
downloadDir.convention(project.provider {
ideDownloadDir().toString()
})
teamCityOutputFormat.convention(false)
subsystemsToCheck.convention("all")
ideDir.convention(project.provider {
val runIdeTaskProvider = project.tasks.named<RunIdeTask>(IntelliJPluginConstants.RUN_IDE_TASK_NAME)
val runIdeTask = runIdeTaskProvider.get()
runIdeTask.ideDir.get()
})
productsReleasesFile.convention(project.provider {
listProductsReleasesTask.outputFile.get().asFile
})
ides.convention(project.provider {
val ideVersions = ideVersions.get().takeIf(List<String>::isNotEmpty) ?: run {
when {
localPaths.get().isEmpty() -> productsReleasesFile.get().takeIf(File::exists)?.readLines()
else -> null
}
} ?: emptyList()
ideVersions.map { ideVersion ->
val downloadDir = File(downloadDir.get())
val context = logCategory()
resolveIdePath(ideVersion, downloadDir, context) { type, version, buildType ->
val name = "$type-$version"
val ideDir = downloadDir.resolve(name)
info(context, "Downloading IDE '$name' to: $ideDir")
val url = resolveIdeUrl(type, version, buildType, context)
val dependencyVersion = listOf(type, version, buildType).filterNot(String::isNullOrEmpty).joinToString("-")
val group = when (type) {
IntelliJPluginConstants.ANDROID_STUDIO_TYPE -> "com.android"
else -> "com.jetbrains"
}
debug(context, "Downloading IDE from $url")
try {
val ideArchive = dependenciesDownloader.downloadFromRepository(context, {
create(
group = group,
name = "ides",
version = dependencyVersion,
ext = "tar.gz",
)
}, {
ivyRepository(url)
}).first()
debug(context, "IDE downloaded, extracting...")
archiveUtils.extract(ideArchive, ideDir, context)
ideDir.listFiles()?.let { files ->
files.filter(File::isDirectory).forEach { container ->
container.listFiles()?.forEach { file ->
file.renameTo(ideDir.resolve(file.name))
}
container.deleteRecursively()
}
}
} catch (e: Exception) {
warn(context, "Cannot download '$type-$version' from '$buildType' channel: $url", e)
}
debug(context, "IDE extracted to: $ideDir")
ideDir
}
}.let { files -> project.files(files) }
})
verifierPath.convention(project.provider {
val resolvedVerifierVersion = resolveVerifierVersion(verifierVersion.orNull)
debug(context, "Using Verifier in '$resolvedVerifierVersion' version")
dependenciesDownloader.downloadFromRepository(logCategory(), {
create(
group = "org.jetbrains.intellij.plugins",
name = "verifier-cli",
version = resolvedVerifierVersion,
classifier = "all",
ext = "jar",
)
}, {
mavenRepository(IntelliJPluginConstants.PLUGIN_VERIFIER_REPOSITORY)
}).first().canonicalPath
})
jreRepository.convention(extension.jreRepository)
offline.set(project.gradle.startParameter.isOffline)
dependsOn(IntelliJPluginConstants.BUILD_PLUGIN_TASK_NAME)
dependsOn(IntelliJPluginConstants.VERIFY_PLUGIN_TASK_NAME)
dependsOn(IntelliJPluginConstants.LIST_PRODUCTS_RELEASES_TASK_NAME)
val isIdeVersionsEmpty = project.provider {
ideVersions.get().isEmpty() && localPaths.get().isEmpty()
}
listProductsReleasesTask.onlyIf { isIdeVersionsEmpty.get() }
outputs.upToDateWhen { false }
}
}
private fun configurePluginVerificationTask(project: Project) {
info(context, "Configuring plugin verification task")
project.tasks.register(IntelliJPluginConstants.VERIFY_PLUGIN_TASK_NAME, VerifyPluginTask::class.java) {
group = IntelliJPluginConstants.GROUP_NAME
description = "Validates completeness and contents of `plugin.xml` descriptors as well as plugin archive structure."
ignoreFailures.convention(false)
ignoreWarnings.convention(true)
pluginDir.convention(project.provider {
val prepareSandboxTaskProvider = project.tasks.named<PrepareSandboxTask>(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
val prepareSandboxTask = prepareSandboxTaskProvider.get()
val path = File(prepareSandboxTask.destinationDir, prepareSandboxTask.pluginName.get()).path
project.layout.projectDirectory.dir(path)
})
dependsOn(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
}
}
private fun configureRunIdeTask(project: Project) {
info(context, "Configuring run IDE task")
project.tasks.register(IntelliJPluginConstants.RUN_IDE_TASK_NAME, RunIdeTask::class.java) {
group = IntelliJPluginConstants.GROUP_NAME
description = "Runs the IDE instance with the developed plugin installed."
dependsOn(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
finalizedBy(IntelliJPluginConstants.CLASSPATH_INDEX_CLEANUP_TASK_NAME)
}
}
private fun configureRunIdePerformanceTestTask(project: Project, extension: IntelliJPluginExtension) {
info(context, "Configuring run IDE performance test task")
project.tasks.register(
IntelliJPluginConstants.RUN_IDE_PERFORMANCE_TEST_TASK_NAME,
RunIdePerformanceTestTask::class.java
) {
val setupDependenciesTaskProvider =
project.tasks.named<SetupDependenciesTask>(IntelliJPluginConstants.SETUP_DEPENDENCIES_TASK_NAME)
val setupDependenciesTask = setupDependenciesTaskProvider.get()
group = IntelliJPluginConstants.GROUP_NAME
description = "Runs performance tests on the IDE with the developed plugin installed."
artifactsDir.convention(project.provider {
"${project.buildDir}/reports/performance-test/${extension.type.get()}${extension.version.get()}-${project.version}-${
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmm"))
}"
})
profilerName.convention(ProfilerName.ASYNC)
with(project.configurations) {
val performanceTestConfiguration = create(IntelliJPluginConstants.PERFORMANCE_TEST_CONFIGURATION_NAME)
.setVisible(false)
.withDependencies {
val ideaDependency = setupDependenciesTask.idea.get()
val plugins = extension.plugins.get()
// Check that `runIdePerformanceTest` task was launched
// Check that `performanceTesting.jar` is absent (that means it's community version)
// Check that user didn't pass custom version of the performance plugin
if (IntelliJPluginConstants.RUN_IDE_PERFORMANCE_TEST_TASK_NAME in project.gradle.startParameter.taskNames &&
ideaDependency.pluginsRegistry.findPlugin(IntelliJPluginConstants.PERFORMANCE_PLUGIN_ID) == null &&
plugins.none { it is String && it.startsWith(IntelliJPluginConstants.PERFORMANCE_PLUGIN_ID) }
) {
val resolver = project.objects.newInstance(
PluginDependencyManager::class.java,
project.gradle.gradleUserHomeDir.absolutePath,
ideaDependency,
extension.getPluginsRepositories(),
archiveUtils,
context,
)
val resolvedPlugin = resolveLatestPluginUpdate(
IntelliJPluginConstants.PERFORMANCE_PLUGIN_ID,
ideaDependency.buildNumber,
)
val plugin = resolver.resolve(project, resolvedPlugin)
?: throw BuildException(with(resolvedPlugin) { "Failed to resolve plugin $id:$version@$channel" }, null)
configurePluginDependency(project, plugin, extension, this, resolver)
}
}
getByName(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME).extendsFrom(performanceTestConfiguration)
}
dependsOn(setupDependenciesTask)
dependsOn(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
finalizedBy(IntelliJPluginConstants.CLASSPATH_INDEX_CLEANUP_TASK_NAME)
}
}
private fun resolveLatestPluginUpdate(pluginId: String, buildNumber: String, channel: String = "") =
PluginRepositoryFactory
.create(IntelliJPluginConstants.MARKETPLACE_HOST)
.pluginManager
.searchCompatibleUpdates(listOf(pluginId), buildNumber, channel)
.first()
.let { PluginDependencyNotation(it.pluginXmlId, it.version, it.channel) }
private fun configureRunIdeForUiTestsTask(project: Project) {
info(context, "Configuring run IDE for UI tests task")
project.tasks.register(IntelliJPluginConstants.RUN_IDE_FOR_UI_TESTS_TASK_NAME, RunIdeForUiTestTask::class.java) {
group = IntelliJPluginConstants.GROUP_NAME
description = "Runs the IDE instance with the developed plugin and robot-server installed and ready for UI testing."
dependsOn(IntelliJPluginConstants.PREPARE_UI_TESTING_SANDBOX_TASK_NAME)
finalizedBy(IntelliJPluginConstants.CLASSPATH_INDEX_CLEANUP_TASK_NAME)
}
}
private fun configureBuildSearchableOptionsTask(project: Project) {
info(context, "Configuring build searchable options task")
project.tasks.register(IntelliJPluginConstants.BUILD_SEARCHABLE_OPTIONS_TASK_NAME, BuildSearchableOptionsTask::class.java) {
group = IntelliJPluginConstants.GROUP_NAME
description = "Builds an index of UI components (searchable options) for the plugin."
outputDir.convention(project.provider {
project.layout.projectDirectory.dir("${project.buildDir}/${IntelliJPluginConstants.SEARCHABLE_OPTIONS_DIR_NAME}")
})
showPaidPluginWarning.convention(project.provider {
project.isBuildFeatureEnabled(PAID_PLUGIN_SEARCHABLE_OPTIONS_WARNING) && run {
sourcePluginXmlFiles(project).any {
parsePluginXml(it, context)?.productDescriptor != null
}
}
})
dependsOn(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
onlyIf {
val number = ideBuildNumber(ideDir.get())
Version.parse(number.split('-').last()) >= Version.parse("191.2752")
}
}
}
private fun prepareConventionMappingsForRunIdeTask(
project: Project,
extension: IntelliJPluginExtension,
task: RunIdeBase,
prepareSandBoxTaskName: String,
) {
val prepareSandboxTaskProvider = project.tasks.named<PrepareSandboxTask>(prepareSandBoxTaskName)
val prepareSandboxTask = prepareSandboxTaskProvider.get()
val setupDependenciesTaskProvider = project.tasks.named<SetupDependenciesTask>(IntelliJPluginConstants.SETUP_DEPENDENCIES_TASK_NAME)
val setupDependenciesTask = setupDependenciesTaskProvider.get()
val taskContext = task.logCategory()
val pluginIds = sourcePluginXmlFiles(project).mapNotNull { parsePluginXml(it, taskContext)?.id }
task.ideDir.convention(project.provider {
val path = setupDependenciesTask.idea.get().classes.path
project.file(path)
})
task.requiredPluginIds.convention(project.provider {
pluginIds
})
task.configDir.convention(project.provider {
project.file(prepareSandboxTask.configDir.get())
})
task.pluginsDir.convention(project.provider {
val path = prepareSandboxTask.destinationDir.path
project.layout.projectDirectory.dir(path)
})
task.systemDir.convention(project.provider {
project.file("${extension.sandboxDir.get()}/system")
})
task.autoReloadPlugins.convention(project.provider {
val number = ideBuildNumber(task.ideDir.get())
Version.parse(number.split('-').last()) >= Version.parse("202.0")
})
task.projectWorkingDir.convention(project.provider {
project.file("${task.ideDir.get()}/bin/")
})
task.projectExecutable.convention(project.provider {
val jbrResolver = project.objects.newInstance(
JbrResolver::class.java,
extension.jreRepository.orNull.orEmpty(),
project.gradle.startParameter.isOffline,
archiveUtils,
dependenciesDownloader,
taskContext,
)
jbrResolver.resolveRuntime(
jbrVersion = task.jbrVersion.orNull,
jbrVariant = task.jbrVariant.orNull,
ideDir = task.ideDir.orNull,
)
})
task.dependsOn(setupDependenciesTaskProvider)
}
private fun configureJarSearchableOptionsTask(project: Project) {
info(context, "Configuring jar searchable options task")
project.tasks.register(IntelliJPluginConstants.JAR_SEARCHABLE_OPTIONS_TASK_NAME, JarSearchableOptionsTask::class.java) {
val prepareSandboxTaskProvider = project.tasks.named<PrepareSandboxTask>(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
val prepareSandboxTask = prepareSandboxTaskProvider.get()
group = IntelliJPluginConstants.GROUP_NAME
description = "Creates a JAR file with searchable options to be distributed with the plugin."
outputDir.convention(project.provider {
project.layout.projectDirectory.dir(project.buildDir.resolve(IntelliJPluginConstants.SEARCHABLE_OPTIONS_DIR_NAME).canonicalPath)
})
pluginName.convention(prepareSandboxTask.pluginName)
sandboxDir.convention(project.provider {
prepareSandboxTask.destinationDir.canonicalPath
})
archiveBaseName.convention("lib/searchableOptions")
destinationDirectory.convention(project.layout.buildDirectory.dir("libsSearchableOptions"))
noSearchableOptionsWarning.convention(project.isBuildFeatureEnabled(NO_SEARCHABLE_OPTIONS_WARNING))
dependsOn(IntelliJPluginConstants.BUILD_SEARCHABLE_OPTIONS_TASK_NAME)
dependsOn(IntelliJPluginConstants.PREPARE_SANDBOX_TASK_NAME)
onlyIf { outputDir.get().asFile.isDirectory }
}
}
private fun configureInstrumentation(project: Project, extension: IntelliJPluginExtension) {
info(context, "Configuring compile tasks")
val jarTaskProvider = project.tasks.named<Jar>(JavaPlugin.JAR_TASK_NAME)
val jarTask = jarTaskProvider.get()
if (extension.instrumentCode.get()) {
jarTask.duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
val setupInstrumentCodeTaskProvider =
project.tasks.register(IntelliJPluginConstants.SETUP_INSTRUMENT_CODE_TASK_NAME, SetupInstrumentCodeTask::class.java) {
instrumentationEnabled.convention(project.provider {
extension.instrumentCode.get()
})
instrumentedDir.convention(project.layout.buildDirectory.dir("instrumented"))
}
val setupInstrumentCodeTask = setupInstrumentCodeTaskProvider.get()
val sourceSets = project.extensions.findByName("sourceSets") as SourceSetContainer
sourceSets.forEach { sourceSet ->
val name = sourceSet.getTaskName("instrument", "code")
val instrumentTaskProvider =
project.tasks.register(name, IntelliJInstrumentCodeTask::class.java) {
val setupDependenciesTaskProvider =
project.tasks.named<SetupDependenciesTask>(IntelliJPluginConstants.SETUP_DEPENDENCIES_TASK_NAME)
val setupDependenciesTask = setupDependenciesTaskProvider.get()
val instrumentCodeProvider = project.provider { extension.instrumentCode.get() }
sourceDirs.from(project.provider {
sourceSet.allJava.srcDirs
})
formsDirs.from(project.provider {
sourceDirs.asFileTree.filter { it.name.endsWith(".form") }
})
classesDirs.from(project.provider {
(sourceSet.output.classesDirs as ConfigurableFileCollection).from.run {
project.files(this).filter { it.exists() }
}
})
sourceSetCompileClasspath.from(project.provider {
sourceSet.compileClasspath
})
compilerVersion.convention(project.provider {
val version by lazy { extension.getVersionNumber() }
val localPath = extension.localPath.orNull
val ideaDependency = setupDependenciesTask.idea.get()
if (localPath.isNullOrBlank() && version.endsWith(RELEASE_SUFFIX_SNAPSHOT)) {
val type = extension.getVersionType()
if (version == IntelliJPluginConstants.DEFAULT_IDEA_VERSION && listOf("CL", "RD", "PY").contains(type)) {
ideProductInfo(ideaDependency.classes)?.buildNumber?.let { buildNumber ->
Version.parse(buildNumber).let { v -> "${v.major}.${v.minor}$RELEASE_SUFFIX_EAP_CANDIDATE" }
} ?: version
} else {
when (type) {
"CL" -> "CLION-$version"
"RD" -> "RIDER-$version"
"PY" -> "PYCHARM-$version"
else -> version
}
}
} else {
val isEap = localPath?.let { ideProductInfo(ideaDependency.classes)?.versionSuffix == "EAP" } ?: false
val eapSuffix = IntelliJPluginConstants.RELEASE_SUFFIX_EAP.takeIf { isEap }.orEmpty()
IdeVersion.createIdeVersion(ideaDependency.buildNumber)
.stripExcessComponents()
.asStringWithoutProductCode() + eapSuffix
}
})
ideaDependency.convention(setupDependenciesTask.idea)
javac2.convention(project.provider {
project.file("${setupDependenciesTask.idea.get().classes}/lib/javac2.jar").takeIf(File::exists)
})
compilerClassPathFromMaven.convention(project.provider {
val compilerVersion = compilerVersion.get()
if (compilerVersion == IntelliJPluginConstants.DEFAULT_IDEA_VERSION ||
Version.parse(compilerVersion) >= Version(183, 3795, 13)
) {
val downloadCompiler = { version: String ->
dependenciesDownloader.downloadFromMultipleRepositories(logCategory(), {
create(
group = "com.jetbrains.intellij.java",
name = "java-compiler-ant-tasks",
version = version,
)
}, {
listOf(
"${extension.intellijRepository.get()}/${releaseType(version)}",
IntelliJPluginConstants.INTELLIJ_DEPENDENCIES,
).map(::mavenRepository)
}, true)
}
listOf(
{
runCatching {
downloadCompiler(compilerVersion)
}.fold(
onSuccess = { it },
onFailure = {
warn(logCategory(), "Cannot resolve java-compiler-ant-tasks in version: $compilerVersion")
null
},
)
},
{
/**
* Try falling back on the version without the -EAP-SNAPSHOT suffix if the download
* for it fails - not all versions have a corresponding -EAP-SNAPSHOT version present
* in the snapshot repository.
*/
if (compilerVersion.endsWith(IntelliJPluginConstants.RELEASE_SUFFIX_EAP)) {
val nonEapVersion = compilerVersion.replace(
IntelliJPluginConstants.RELEASE_SUFFIX_EAP, ""
)
runCatching {
downloadCompiler(nonEapVersion)
}.fold(
onSuccess = {
warn(logCategory(), "Resolved non-EAP java-compiler-ant-tasks version: $nonEapVersion")
it
},
onFailure = {
warn(logCategory(), "Cannot resolve java-compiler-ant-tasks in version: $nonEapVersion")
null
},
)
} else {
null
}
},
{
/**
* Get the list of available packages and pick the closest lower one.
*/
val closestCompilerVersion = URL(IntelliJPluginConstants.JAVA_COMPILER_ANT_TASKS_MAVEN_METADATA)
.openStream().use { inputStream ->
val version = Version.parse(compilerVersion)
XmlExtractor<MavenMetadata>()
.unmarshal(inputStream)
.versioning?.versions?.let { versions ->
versions
.map(Version::parse)
.filter { it <= version }
.maxOf { it }.version
}
}
if (closestCompilerVersion == null) {
warn(logCategory(), "Cannot resolve java-compiler-ant-tasks Maven metadata")
null
} else {
runCatching {
downloadCompiler(closestCompilerVersion)
}.fold(
onSuccess = {
warn(
logCategory(),
"Resolved closest lower java-compiler-ant-tasks version: $closestCompilerVersion"
)
it
},
onFailure = {
warn(
logCategory(),
"Cannot resolve java-compiler-ant-tasks in version: $closestCompilerVersion"
)
null
},
)
}
},
)
.asSequence()
.mapNotNull { it() }
.firstOrNull()
} else {
warn(
logCategory(),
"Compiler in '$compilerVersion' version can't be resolved from Maven. Minimal version supported: 2018.3+. Use higher 'intellij.version' or specify the 'compilerVersion' property manually.",
)
null
}
})
outputDir.convention(setupInstrumentCodeTask.instrumentedDir.map {
it.dir(name)
})
dependsOn(sourceSet.classesTaskName)
dependsOn(setupDependenciesTask)
dependsOn(setupInstrumentCodeTask)
onlyIf { instrumentCodeProvider.get() }