generated from JetBrains/intellij-platform-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
568 lines (495 loc) · 23.5 KB
/
build.gradle.kts
File metadata and controls
568 lines (495 loc) · 23.5 KB
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
/*
* Copyright (c) 2025 Florian Hehlen & Óscar Otero
* All rights reserved.
*/
import org.jetbrains.changelog.Changelog
import org.jetbrains.changelog.markdownToHTML
import org.jetbrains.intellij.platform.gradle.TestFrameworkType
import org.jlleitschuh.gradle.ktlint.tasks.KtLintCheckTask
import org.jlleitschuh.gradle.ktlint.tasks.KtLintFormatTask
plugins {
id("java")
id("org.jetbrains.kotlin.jvm") version "2.3.0"
id("org.jetbrains.intellij.platform") version "2.10.5"
id("org.jetbrains.grammarkit") version "2023.3.0.1"
id("org.jlleitschuh.gradle.ktlint") version "14.0.1"
id("org.jetbrains.changelog") version "2.5.0"
}
group = providers.gradleProperty("pluginGroup").get()
version = providers.gradleProperty("pluginVersion").get()
kotlin { jvmToolchain(21) }
repositories {
mavenCentral()
intellijPlatform { defaultRepositories() }
}
// Configure source sets to include generated sources
sourceSets {
main {
java.srcDirs("src/main/gen")
resources.srcDirs("src/main/resources")
}
}
// Task to copy images from docs/assets to plugin resources
val copyImagesToResources =
tasks.register<Copy>("copyImagesToResources") {
from(layout.projectDirectory.dir("assets"))
into(layout.buildDirectory.dir("resources/main/assets"))
include("*.png", "*.jpg", "*.jpeg", "*.svg", "*.gif")
}
// Task to prepare cleaned .flex files for generation
val prepareFlexFiles =
tasks.register<Task>("prepareFlexFiles") {
val sourceDir = layout.projectDirectory.dir("src/main/jflex")
val tempDir = layout.buildDirectory.dir("tmp/jflex-cleaned")
inputs.dir(sourceDir)
outputs.dir(tempDir)
doLast {
val sourceDirFile = sourceDir.asFile
val tempDirFile = tempDir.get().asFile
// Clean and recreate temp directory
tempDirFile.deleteRecursively()
tempDirFile.mkdirs()
// Process include files to extract blocks
val includeFiles =
sourceDirFile
.walkTopDown()
.filter { it.isFile && it.extension == "flex" && it.path.contains("includes/") }
val block1Lines = mutableSetOf<String>()
val block2Lines = mutableSetOf<String>()
val includeRuleContent = mutableMapOf<String, String>()
// Track duplicates across include files
val block1DupAcrossIncludes = mutableSetOf<String>()
val block2DupAcrossIncludes = mutableSetOf<String>()
includeFiles.forEach { includeFile ->
val content = includeFile.readText()
val relativePath = includeFile.relativeTo(sourceDirFile).path
// Extract BLOCK 1 content (imports) and deduplicate
val block1Regex = Regex("""// BLOCK 1 - START\s*\n(.*?)\n// BLOCK 1 - END""", RegexOption.DOT_MATCHES_ALL)
block1Regex.find(content)?.let { match ->
val blockContent = match.groupValues[1].trim()
if (blockContent.isNotEmpty()) {
// Split by lines and add to set for deduplication
blockContent.lines().forEach { line ->
val trimmedLine = line.trim()
if (trimmedLine.isNotEmpty()) {
if (!block1Lines.add(trimmedLine)) {
block1DupAcrossIncludes.add(trimmedLine)
}
}
}
}
}
// Extract BLOCK 2 content (states) and deduplicate
val block2Regex = Regex("""// BLOCK 2 - START\s*\n(.*?)\n// BLOCK 2 - END""", RegexOption.DOT_MATCHES_ALL)
block2Regex.find(content)?.let { match ->
val blockContent = match.groupValues[1].trim()
if (blockContent.isNotEmpty()) {
// Split by lines and add to set for deduplication
blockContent.lines().forEach { line ->
val trimmedLine = line.trim()
if (trimmedLine.isNotEmpty()) {
if (!block2Lines.add(trimmedLine)) {
block2DupAcrossIncludes.add(trimmedLine)
}
}
}
}
}
// Extract rule content (everything after second %%)
val parts = content.split("%%")
if (parts.size >= 3) {
val ruleContent = parts.drop(2).joinToString("%%").trim()
includeRuleContent[relativePath] = ruleContent
}
}
// Process root VentoLexer.flex file
val rootFile = File(sourceDirFile, "VentoLexer.flex")
if (rootFile.exists()) {
val rootContent = rootFile.readText()
val parts = rootContent.split("%%")
if (parts.size >= 3) {
val beforeFirstPercent = parts[0]
val betweenPercents = parts[1]
val afterSecondPercent = parts.drop(2).joinToString("%%")
// Build merged content with de-duplication against root and among includes
// Extract existing items from root declarations section (between the first and second %%)
val existingImportLinesInRoot =
beforeFirstPercent
.lines()
.map { it.trim() }
.filter { it.startsWith("import ") }
.toSet()
val trimmedBetweenLines = betweenPercents.lines().map { it.trim() }.toList()
val existingBetweenSet = trimmedBetweenLines.toSet()
val stateDeclRegex = Regex("^%state\\s+(.+)$")
val macroRegex = Regex("^([A-Z_][A-Z0-9_]*)\\s*=.*$")
// Collect existing macro names and state names from root
val existingMacroNames =
trimmedBetweenLines
.mapNotNull { line -> macroRegex.matchEntire(line)?.groupValues?.get(1) }
.toMutableSet()
val existingStateNames =
trimmedBetweenLines
.flatMap { line ->
stateDeclRegex
.matchEntire(line)
?.groupValues
?.get(1)
?.trim()
?.split(Regex("\\s+"))
?.filter { it.isNotBlank() }
?: emptyList()
}.toMutableSet()
// Prepare include BLOCK 1 imports: filter out those already present in root
val dedupBlock1Imports =
block1Lines
.filter { it.isNotBlank() }
.filterNot { existingImportLinesInRoot.contains(it.trim()) }
.toSortedSet()
// Imports dropped because they already exist in root
val importsDupAgainstRoot =
block1Lines
.filter { existingImportLinesInRoot.contains(it.trim()) }
.toSortedSet()
// Prepare include BLOCK 2: split into states, macros (by name), and others; filter by existing
val includeStateNames = linkedSetOf<String>()
val includeMacrosByName = linkedMapOf<String, String>()
val includeOtherLines = linkedSetOf<String>()
// Track duplicates against root and across includes for BLOCK 2
val statesDupAgainstRoot = mutableSetOf<String>()
val macrosDupAgainstRoot = mutableSetOf<String>()
val macrosDupAcrossIncludesByName = mutableSetOf<String>()
val otherDupAgainstRoot = mutableSetOf<String>()
block2Lines.forEach { rawLine ->
val line = rawLine.trim()
if (line.isEmpty()) return@forEach
val stateMatch = stateDeclRegex.matchEntire(line)
if (stateMatch != null) {
val names =
stateMatch.groupValues[1]
.trim()
.split(Regex("\\s+"))
.filter { it.isNotBlank() }
names.forEach { name ->
if (existingStateNames.contains(name)) {
statesDupAgainstRoot.add(name)
} else {
includeStateNames.add(name)
}
}
} else {
val macroMatch = macroRegex.matchEntire(line)
if (macroMatch != null) {
val name = macroMatch.groupValues[1]
when {
existingMacroNames.contains(name) -> macrosDupAgainstRoot.add(name)
includeMacrosByName.containsKey(name) -> macrosDupAcrossIncludesByName.add(name)
else -> includeMacrosByName[name] = line
}
} else {
// keep non-macro, non-state lines if they are not already in root between %%
if (existingBetweenSet.contains(line)) {
otherDupAgainstRoot.add(line)
} else {
includeOtherLines.add(line)
}
}
}
}
// Report duplicates as warnings
if (block1DupAcrossIncludes.isNotEmpty()) {
logger.warn(
"prepareFlexFiles: Duplicate import lines across include files were deduplicated: ${
block1DupAcrossIncludes.joinToString(
", ",
)
}",
)
}
if (importsDupAgainstRoot.isNotEmpty()) {
logger.warn(
"prepareFlexFiles: Import lines skipped because they already exist in root VentoLexer.flex: ${
importsDupAgainstRoot.joinToString(
", ",
)
}",
)
}
if (block2DupAcrossIncludes.isNotEmpty()) {
logger.warn(
"prepareFlexFiles: Duplicate declaration lines across include files were deduplicated: ${
block2DupAcrossIncludes.joinToString(
", ",
)
}",
)
}
if (statesDupAgainstRoot.isNotEmpty()) {
logger.warn(
"prepareFlexFiles: State names skipped because they already exist in root VentoLexer.flex: ${
statesDupAgainstRoot.toSortedSet().joinToString(
", ",
)
}",
)
}
if (macrosDupAgainstRoot.isNotEmpty()) {
logger.warn(
"prepareFlexFiles: Macro names skipped because they already exist in root VentoLexer.flex: ${
macrosDupAgainstRoot.toSortedSet().joinToString(
", ",
)
}",
)
}
if (macrosDupAcrossIncludesByName.isNotEmpty()) {
val duplicates = macrosDupAcrossIncludesByName.toSortedSet().joinToString(", ")
logger.error(
"prepareFlexFiles: Macro names duplicated across include files: $duplicates",
)
throw GradleException(
"Build failed: Duplicate macro names with different values found across include files: $duplicates",
)
}
if (otherDupAgainstRoot.isNotEmpty()) {
val duplicates = otherDupAgainstRoot.toSortedSet().joinToString(", ")
logger.error(
"prepareFlexFiles: Lines skipped because they already exist in root declarations: $duplicates",
)
throw GradleException(
"Build failed: Lines skipped because they already exist in root declarations: $duplicates",
)
}
val mergedContent =
buildString {
// Original content before first %%
append(beforeFirstPercent.trimEnd())
// Add BLOCK 1 content (imports) if any
if (dedupBlock1Imports.isNotEmpty()) {
append("\n\n// Merged imports from include files\n")
dedupBlock1Imports.forEach { line ->
append(line)
append("\n")
}
}
append("\n%%")
// Original content between %% markers
append(betweenPercents)
// Add BLOCK 2 content (states/macros) if any
if (includeStateNames.isNotEmpty() || includeMacrosByName.isNotEmpty() || includeOtherLines.isNotEmpty()) {
append("\n// Merged states from include files\n")
includeStateNames.toSortedSet().forEach { state ->
append("%state ")
append(state)
append("\n")
}
includeMacrosByName.toSortedMap().values.forEach { macroLine ->
append(macroLine)
append("\n")
}
includeOtherLines.forEach { line ->
append(line)
append("\n")
}
}
append("\n%%")
// Process content after second %%, replacing %include directives
val processedAfterContent =
afterSecondPercent
.lines()
.joinToString("\n") { line ->
val trimmedLine = line.trim()
if (trimmedLine.startsWith("%include ")) {
val includePath = trimmedLine.removePrefix("%include ").trim()
val ruleContent = includeRuleContent[includePath]
if (ruleContent != null) {
"\n// Content from $includePath\n$ruleContent"
} else {
"// Warning: Could not find content for $includePath"
}
} else {
line
}
}
append(processedAfterContent)
}
// Write merged file
val targetFile = File(tempDirFile, "VentoLexer.flex")
targetFile.writeText(mergedContent)
println("Created merged VentoLexer.flex with content from ${includeFiles.count()} include files")
}
}
}
}
// Configure GrammarKit to generate the lexer
tasks {
generateLexer {
dependsOn("prepareFlexFiles")
sourceFile.set(file("build/tmp/jflex-cleaned/VentoLexer.flex"))
targetOutputDir.set(file("src/main/gen/org/js/vento/plugin/lexer"))
purgeOldFiles.set(true)
}
// Ensure lexer is generated and moved before compilation
compileKotlin {
dependsOn(generateLexer)
}
compileJava {
dependsOn(generateLexer)
}
// Ensure images are copied before processing resources
processResources {
dependsOn(copyImagesToResources)
}
// Enable JUnit Platform for tests (Jupiter + Vintage)
test {
useJUnitPlatform()
// Ensure cleaned flex file is created before tests
dependsOn("prepareFlexFiles")
// Forward system properties to test JVM
systemProperty("idea.tests.overwrite.data", System.getProperty("idea.tests.overwrite.data", "false"))
systemProperty("dumpAstTypeNames", System.getProperty("dumpAstTypeNames", "false"))
}
// Make KtLint tasks depend on lexer generation
withType<KtLintCheckTask> {
dependsOn("generateLexer")
}
// If you also have KtLint format tasks, add the same dependency
withType<KtLintFormatTask> {
dependsOn("generateLexer")
}
publishPlugin {
dependsOn("patchChangelog")
}
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
// JUnit 6 (Jupiter) for tests
testImplementation(platform("org.junit:junit-bom:6.0.2"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
// Support for legacy JUnit 3/4 tests (e.g., classes extending TestCase)
testImplementation("junit:junit:4.13.2")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:6.0.2")
// Kotlin test assertions routed to JUnit Platform
testImplementation(kotlin("test"))
intellijPlatform {
intellijPlatform {
// Use latest IU EAP as the IDE to run against
// intellijIdeaUltimate("2025.2")
webstorm("2025.3")
// Platform plugins from gradle.properties
bundledPlugins(
providers
.gradleProperty("platformBundledPlugins")
.map { it.split(',') },
)
plugins(
providers
.gradleProperty("platformPlugins")
.map { it.split(',') },
)
// Tools
testFramework(TestFrameworkType.Platform)
pluginVerifier()
zipSigner()
instrumentationTools()
}
}
intellijPlatform {
testFramework(TestFrameworkType.Platform)
}
testImplementation("junit:junit:4.13.2")
}
intellijPlatform {
signing {
certificateChain = providers.environmentVariable("CERTIFICATE_CHAIN")
privateKey = providers.environmentVariable("PRIVATE_KEY")
password = providers.environmentVariable("PRIVATE_KEY_PASSWORD")
}
publishing {
token = providers.environmentVariable("JETBRAINS_PUBLISH_TOKEN")
channels =
providers
.gradleProperty("pluginVersion")
.map { listOf(it.substringAfter('-', "").substringBefore('.').ifEmpty { "default" }) }
}
// Configure plugin verifier IDEs
pluginVerification {
ides {
// Webstorm
create("WS", "2024.3")
create("WS", "2025.2")
// IntelliJ Ultimate
create("IU", "2024.3")
create("IU", "2025.2")
// create("IU", "253.17525.95")
}
}
pluginConfiguration {
name = providers.gradleProperty("pluginName")
version = providers.gradleProperty("pluginVersion")
// Extract the <!-- Plugin description --> section from README.md and provide for the plugin's manifest
description =
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
val start = "<!-- Plugin description -->"
val end = "<!-- Plugin description end -->"
with(it.lines()) {
if (!containsAll(listOf(start, end))) {
throw GradleException("Plugin description section not found in README.md:\n$start ... $end")
}
val descriptionText = subList(indexOf(start) + 1, indexOf(end)).joinToString("\n")
// Replace docs/assets/ paths with plugin-relative paths
val updatedText =
descriptionText.replace(
Regex("""assets/([^"'\s)]+)"""),
"assets/$1",
)
markdownToHTML(updatedText)
}
}
val changelog = project.changelog // local variable for configuration cache compatibility
// Get the latest available change notes from the changelog file
changeNotes =
providers.gradleProperty("pluginVersion").map { pluginVersion ->
with(changelog) {
renderItem(
(getOrNull(pluginVersion) ?: getUnreleased())
.withHeader(false)
.withEmptySections(false),
Changelog.OutputType.HTML,
)
}
}
ideaVersion {
sinceBuild = providers.gradleProperty("pluginSinceBuild")
}
}
}
// Configure Gradle Changelog Plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin
changelog {
groups.empty()
repositoryUrl = providers.gradleProperty("pluginRepositoryUrl").get()
}
tasks { wrapper { gradleVersion = providers.gradleProperty("gradleVersion").get() } }
tasks.jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.withType<Copy> {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
// Ktlint: Add formatting and linting tasks
tasks {
// Make the standard 'check' task run ktlint checks as well
named("check") { dependsOn("ktlintCheck") }
// Convenience alias to format Kotlin sources
register<DefaultTask>("formatKotlin") { dependsOn("ktlintFormat") }
}
tasks.test {
exclude("**/FrontmatterHighlightToggleTest.class")
}
tasks.withType<Test> {
jvmArgs("-Xshare:off")
}
fun ext(name: String): String =
rootProject.extensions[name] as? String
?: error("Property `$name` is not defined")