-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSetupApp.kt
More file actions
1271 lines (1153 loc) · 52.5 KB
/
Copy pathSetupApp.kt
File metadata and controls
1271 lines (1153 loc) · 52.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
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
package file
import config.CONFIG_FILE_NAME
import config.ScriptMode
import config.WurstProjectConfig
import config.WurstProjectBuildMapData
import config.WurstProjectConfigData
import config.newProjectConfig
import config.withAddedDependency
import config.withRemovedDependency
import config.withWc3Patch
import global.InstallationManager
import global.Log
import logging.KotlinLogging
import net.ConnectionManager
import org.slf4j.LoggerFactory
import org.eclipse.jgit.api.Git
import java.awt.GraphicsEnvironment
import java.net.URL
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import javax.swing.JOptionPane
object SetupApp {
val DEFAULT_DIR: Path = Paths.get(".")
private val log = KotlinLogging.logger {}
lateinit var setup: SetupMain
private data class WurstProcessResult(val exitCode: Int, val output: List<String>)
internal const val AGENTS_TEMPLATE_VERSION = "2026-08-08"
private const val AGENTS_TEMPLATE_MARKER_PREFIX = "<!-- WURST_AGENTS_TEMPLATE_VERSION:"
private const val AGENTS_TEMPLATE_MARKER = "<!-- WURST_AGENTS_TEMPLATE_VERSION: $AGENTS_TEMPLATE_VERSION -->"
private const val AGENTS_TEMPLATE_SOURCE_HINT = "WurstScript Warcraft III map project notes"
fun handleArgs(setup: SetupMain) {
this.setup = setup
DependencyManager.debug = setup.debug
configureQuietLogging()
updateGrillJar()
if (setup.isGUILaunch) {
val helpText = """
Grill is now CLI-first. Use the command line to interact with Grill.
Example commands:
grill generate MyProject Generate a new Wurst project
grill generate MyProject --with-ci Include GitHub Actions workflow
grill generate MyProject --script-mode jass --wc3-patch pre1.29
grill install Install/update project dependencies
grill install wurstscript Install the WurstScript compiler
grill build ExampleMap.w3x Build your project map
grill test Run project unit tests
grill help Show all available commands
""".trimIndent()
if (GraphicsEnvironment.isHeadless()) {
log.info(helpText)
} else {
JOptionPane.showMessageDialog(null, helpText, "Grill — CLI First", JOptionPane.INFORMATION_MESSAGE)
}
ExitHandler.exit(0)
} else {
progress("🔥 Grill ${CompileTimeInfo.version}")
handleCMD()
}
}
private fun configureQuietLogging() {
val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME)
if (rootLogger is ch.qos.logback.classic.Logger) {
rootLogger.level = if (setup.quiet) ch.qos.logback.classic.Level.ERROR else ch.qos.logback.classic.Level.INFO
}
}
private fun progress(message: String) {
if (!setup.quiet) {
log.info(message)
}
}
private fun pass(message: String) {
if (setup.quiet) {
println(message)
} else {
log.info(message)
}
}
private fun fail(message: String) {
if (setup.quiet) {
System.err.println(message)
} else {
log.error(message)
}
}
private fun detail(message: String) {
if (setup.quiet) {
System.err.println(message)
} else {
log.info(message)
}
}
private fun handleCMD() {
// Cold-start lever: only spend network round-trips and a compiler subprocess on commands
// that actually consult the installation. help/generate avoid installation checks and stay fast.
when {
setup.command == CLICommand.INSTALL && setup.commandArg.equals("wurstscript", ignoreCase = true) -> {
// Needs to know whether a newer compiler is available online.
ConnectionManager.checkWurstBuild()
InstallationManager.verifyInstallation()
}
setup.command == CLICommand.TEST ||
setup.command == CLICommand.TYPECHECK ||
setup.command == CLICommand.BUILD ||
setup.command == CLICommand.EXPORTOBJECTS -> {
// Only needs to know a compiler is present; skip the version subprocess and update check.
InstallationManager.verifyInstallation(probeVersion = false)
}
}
handleRunArgs()
}
private fun handleRunArgs() {
log.debug("handle runargs")
val configFile = setup.projectRoot.resolve(CONFIG_FILE_NAME)
var configData: WurstProjectConfigData? = null
if (Files.exists(configFile)) {
configData = WurstProjectConfig.loadProject(configFile)!!
}
when {
setup.command == CLICommand.HELP -> {
log.info("""
|Common:
| grill generate MyProject
| grill install
| grill test
| grill build ExampleMap.w3x
|
|Project commands:
| install [dep|wurstscript|grill] Install/update dependencies, WurstScript compiler, or Grill itself
| remove [dep|wurstscript] Remove a dependency or uninstall WurstScript
| generate <name> Generate a new Wurst project in a subfolder
| test [filter] Run unit tests, optionally filtered by package/function name
| typecheck Typecheck the project without building a map
| outdated Check whether project dependencies are up to date
| build <mapfile> Build the project using the given input map
| exportobjects <mapfile|folder> Export object editor data to Wurst source
|
|Global options:
| --quiet Suppress wurst output; only print errors and final result
| --debug Print full stack traces for troubleshooting
|
|Build options:
| --dev Build with compiletime isProductionBuild() = false
|
|Generate options:
| --script-mode lua|jass Script mode (default: lua)
| --wc3-patch <patch> WC3 patch target: reforged, pre1.29, or jass-history version
| --wc3-path <dir> Warcraft III install folder for VS Code/run
| --with-agents / --no-agents Include AGENTS.md (default: no)
| --with-ci / --no-ci Include GitHub Actions workflow (default: no)
| --with-dep <id> Add a curated dependency (repeatable; ids: ${CuratedDependencies.ids.joinToString(", ")})
""".trimMargin())
}
setup.command == CLICommand.INSTALL -> {
if (setup.commandArg.isBlank()) {
if (configData != null) {
configData = ensureProjectPatchRecorded(configData)
handleUpdateProject(configData)
} else {
missingProject()
}
} else if (setup.commandArg.lowercase() == "wurstscript") {
handleInstallWurst()
} else if (setup.commandArg.lowercase() == "grill") {
handleUpdateGrill()
} else {
if (configData != null) {
configData = handleInstallDep(configData)
configData = ensureProjectPatchRecorded(configData)
WurstProjectConfig.saveProjectConfig(setup.projectRoot, configData)
handleUpdateProject(configData)
} else {
missingProject()
}
}
}
setup.command == CLICommand.REMOVE -> {
if (setup.commandArg.lowercase() == "wurstscript") {
handleRemoveWurst()
} else {
if (configData != null) {
configData = handleRemoveDep(configData)
WurstProjectConfig.saveProjectConfig(setup.projectRoot, configData)
} else {
missingProject()
}
}
}
setup.command == CLICommand.GENERATE -> {
if (!prepareGenerate(setup)) {
return
}
log.info("✈ Generating project...")
val projectDir = DEFAULT_DIR.resolve(setup.commandArg)
val projectName = projectDir.fileName?.toString() ?: setup.commandArg
val stdlibUrl = stdlibDependencyForPatch(setup.wc3Patch)
val curatedUrls = setup.curatedDependencyIds.mapNotNull { CuratedDependencies.findById(it)?.url }
val projectConfig = newProjectConfig(
projectName = projectName,
dependencies = (listOf(stdlibUrl) + curatedUrls).distinct(),
buildMapData = generatedBuildMapData(projectName),
scriptMode = setup.scriptMode,
wc3Patch = setup.wc3Patch
)
val gameRoot = resolveGenerateGamePath(setup, projectConfig.wc3Patch)
WurstProjectConfig.handleCreate(projectDir, gameRoot, projectConfig)
ensureCoreJassFiles(projectDir, projectConfig.wc3Patch)
if (Files.exists(projectDir)) {
if (setup.addAgents) downloadAgentsMd(projectDir)
if (setup.addGithubWorkflow) writeCiWorkflow(projectDir)
printGenerateNextSteps(projectDir, projectConfig, setup.addAgents, setup.addGithubWorkflow, gameRoot)
}
}
setup.command == CLICommand.TEST -> {
progress("⚗️ Running tests...")
if (InstallationManager.status != InstallationManager.InstallationStatus.NOT_INSTALLED && configData != null) {
testProject(configData)
} else if (configData == null) {
missingProject()
}
}
setup.command == CLICommand.TYPECHECK -> {
progress("🔍 Typechecking project...")
if (InstallationManager.status != InstallationManager.InstallationStatus.NOT_INSTALLED && configData != null) {
typecheckProject(configData)
} else if (configData == null) {
missingProject()
}
}
setup.command == CLICommand.OUTDATED -> {
if (configData == null) {
missingProject()
}
checkProjectOutdated(configData)
}
setup.command == CLICommand.BUILD -> {
progress("🔨 Building project...")
val mapArg = if (setup.commandArg.isBlank()) {
val maps = Files.list(setup.projectRoot).use { stream ->
stream.filter { p -> p.fileName.toString().let { it.endsWith(".w3x") || it.endsWith(".w3m") } }.toList()
}
when (maps.size) {
0 -> { missingMap(); null }
1 -> { log.info("📦 Auto-detected map: ${maps[0].fileName}"); maps[0].fileName.toString() }
else -> { multipleMaps(maps); null }
}
} else setup.commandArg
if (mapArg != null) {
if (!Files.exists(setup.projectRoot.resolve(mapArg))) {
missingMap(mapArg)
} else if (InstallationManager.status != InstallationManager.InstallationStatus.NOT_INSTALLED && configData != null) {
setup.commandArg = mapArg
buildProject(configData)
} else if (configData == null) {
missingProject()
}
}
}
setup.command == CLICommand.EXPORTOBJECTS -> {
progress("Exporting object editor data...")
val mapArg = if (setup.commandArg.isBlank()) {
val maps = findMaps()
when (maps.size) {
0 -> { missingMap(); null }
1 -> { log.info("Auto-detected map: ${maps[0].fileName}"); maps[0].fileName.toString() }
else -> { multipleMaps(maps); null }
}
} else setup.commandArg
if (mapArg != null) {
val mapPath = setup.projectRoot.resolve(mapArg)
if (!Files.exists(mapPath)) {
missingMap(mapArg)
} else if (InstallationManager.status != InstallationManager.InstallationStatus.NOT_INSTALLED) {
exportObjects(mapPath)
}
}
}
setup.command == CLICommand.SELF_UPDATE -> {
log.info("🔄 Updating...")
try {
log.info("✅ Update succeeded.")
InstallationManager.ensureGrillJarInstalled()
ExitHandler.exit(0)
} catch(e: Exception) {
log.error("Grill update failed. Original files might still be in use.")
}
}
}
}
private fun missingProject(): Nothing {
log.error("❌ This folder is not a Grill project.")
log.info("Expected: ${setup.projectRoot.resolve(CONFIG_FILE_NAME).toAbsolutePath()}")
log.info("Try: run `grill generate MyProject` to create a new project, or pass `-projectDir <path>`.")
ExitHandler.exit(1)
}
private fun missingMap(requestedMap: String? = null): Nothing {
if (requestedMap == null) {
log.error("❌ No input map specified and no .w3x/.w3m file was found in the project root.")
log.info("Try: put a map in the project root, or run `grill build YourMap.w3x`.")
} else {
log.error("❌ Map not found: $requestedMap")
log.info("Expected: ${setup.projectRoot.resolve(requestedMap).toAbsolutePath()}")
val maps = findMaps()
if (maps.isNotEmpty()) {
log.info("Available maps: ${maps.joinToString { it.fileName.toString() }}")
}
}
ExitHandler.exit(1)
}
private fun multipleMaps(maps: List<Path>): Nothing {
log.error("❌ Multiple maps found: ${maps.joinToString { it.fileName.toString() }}")
log.info("Try: grill build ${maps.first().fileName}")
ExitHandler.exit(1)
}
private fun findMaps(): List<Path> {
return Files.list(setup.projectRoot).use { stream ->
stream.filter { p -> p.fileName.toString().let { it.endsWith(".w3x") || it.endsWith(".w3m") } }.toList()
}
}
private fun printGenerateNextSteps(
projectDir: Path,
projectConfig: WurstProjectConfigData,
addAgents: Boolean,
addGithubWorkflow: Boolean,
gameRoot: Path?
) {
val curated = CuratedDependencies.matching(projectConfig.dependencies)
val curatedSummary = if (curated.isEmpty()) "none" else curated.joinToString(", ") { it.label }
log.info("""
|✅ Created ${projectDir.fileName}
|
|Choices:
| Script mode: ${(projectConfig.scriptMode ?: ScriptMode.LUA).name.lowercase()}
| WC3 patch: ${CoreJassProvider.describePatch(projectConfig.wc3Patch ?: CoreJassProvider.DEFAULT_PATCH)}
| Warcraft III: ${gameRoot?.toAbsolutePath()?.normalize() ?: "not configured"}
| Stdlib: ${if (projectConfig.dependencies.any { it.endsWith(":pre1.29") }) "pre1.29" else "current"}
| Curated dependencies: $curatedSummary
| AGENTS.md: ${yesNo(addAgents)}
| GitHub Actions CI: ${yesNo(addGithubWorkflow)}
|
|Next:
| code ./${projectDir.fileName}
""".trimMargin())
}
private fun resolveGenerateGamePath(setup: SetupMain, wc3Patch: String?): Path? {
if (setup.gamePathOptedOut) {
log.info("Warcraft III path: not configured by choice.")
return null
}
val gameRoot = setup.gamePath ?: Wc3ClientDetector.detectGameRoot()
val clientInfo = Wc3ClientDetector.inspectGameRoot(gameRoot)
if (clientInfo == null) {
if (setup.gamePathExplicit) {
log.warn("Warcraft III path was set to ${setup.gamePath}, but no supported executable was found there.")
} else {
log.info("Warcraft III path: not detected. Set it later in VS Code or rerun generate with --wc3-path <dir>.")
}
return null
}
// The success path is reported once in the final generate summary, so only surface
// a client/patch mismatch here (an actionable issue) rather than re-logging the path.
Wc3ClientDetector.mismatchMessage(wc3Patch, clientInfo)?.let { log.warn(it) }
return clientInfo.root
}
private fun yesNo(value: Boolean): String {
return if (value) "yes" else "no"
}
private fun printCompilerFailure(commandName: String, result: WurstProcessResult) {
if (printPjassFailure(result.output)) {
return
}
if (setup.quiet) {
val diagnostics = quietCompilerFailureOutput(result.output, setup.debug)
diagnostics.forEach { System.err.println(it) }
fail("❌ Wurst $commandName failed. (Errors: ${quietCompilerErrorCount(result.output, diagnostics)})")
return
}
fail("❌ Wurst $commandName failed.")
detail("Exit code: ${result.exitCode}")
detail("Try: rerun with `--quiet` for a shorter error log, or `--debug` for troubleshooting details.")
}
private fun printPjassFailure(output: List<String>): Boolean {
val text = output.joinToString("\n")
val isPjassFailure = text.contains("Pjass execution error", true) ||
(text.contains("Cannot run program", true) && text.contains("pjass", true))
if (!isPjassFailure) {
return false
}
val tried = Regex("Cannot run program \"([^\"]+)\"").find(text)?.groupValues?.get(1)
val reason = output.firstOrNull {
it.contains("Permission denied", true) ||
it.contains("posix_spawn failed", true) ||
it.contains("Cannot run program", true)
}?.trim()
fail("❌ PJass failed to run.")
if (tried != null) {
detail("Tried: $tried")
}
if (reason != null) {
detail("Reason: $reason")
}
detail("Try: check that the bundled pjass binary is executable and that its temp directory allows execution.")
detail("Tip: rerun with `--debug` if you need the full Java error.")
return true
}
internal fun quietCompilerFailureOutput(output: List<String>, debug: Boolean): List<String> {
return if (debug) output else quietCompilerDiagnostics(output)
}
internal fun quietCompilerDiagnostics(output: List<String>): List<String> {
val diagnostics = ArrayList<String>()
var pendingVerboseError: MatchResult? = null
var preservingTestFailureDetails = false
for (rawLine in output) {
val line = rawLine.trimEnd()
if (line.isBlank() || isNoisyCompilerVersionLine(line) || isQuietCompilerNoiseLine(line)) {
continue
}
val verboseError = Regex("""^Error in File (.+):(\d+):\s*$""").find(line.trim())
if (verboseError != null) {
pendingVerboseError = verboseError
continue
}
if (pendingVerboseError != null) {
diagnostics.add(
"Error ${pendingVerboseError.groupValues[1]}:${pendingVerboseError.groupValues[2]}: ${line.trim()}"
)
pendingVerboseError = null
continue
}
if (preservingTestFailureDetails && isQuietTestFailureDetailLine(line)) {
diagnostics.add(line)
continue
}
if (isQuietCompilerDiagnosticLine(line)) {
diagnostics.add(line)
if (isQuietTestFailureHeader(line)) {
preservingTestFailureDetails = true
}
}
}
return diagnostics.distinct()
}
internal fun quietCompilerErrorCount(
output: List<String>,
diagnostics: List<String> = quietCompilerDiagnostics(output)
): Int {
output.asSequence()
.map { Regex("""^Errors:\s*(\d+)\s*$""").find(it.trim()) }
.filterNotNull()
.firstOrNull()
?.let { return it.groupValues[1].toIntOrNull() ?: diagnostics.size.coerceAtLeast(1) }
return diagnostics.count {
it.startsWith("Error ", ignoreCase = true) ||
it.startsWith("FAILED ", ignoreCase = true) ||
it.contains(" exception", ignoreCase = true) ||
it.contains("Pjass", ignoreCase = true)
}.coerceAtLeast(1)
}
private fun isQuietCompilerDiagnosticLine(line: String): Boolean {
return line.startsWith("Error ", ignoreCase = true) ||
line.startsWith("FAILED ", ignoreCase = true) ||
line.contains(" assertion", ignoreCase = true) ||
line.contains("Exception", ignoreCase = true) ||
line.contains("Pjass", ignoreCase = true)
}
private fun isQuietTestFailureHeader(line: String): Boolean {
return line.trim().equals("FAILED assertion:", ignoreCase = true)
}
private fun isQuietTestFailureDetailLine(line: String): Boolean {
val trimmed = line.trim()
return trimmed.startsWith("Test failed:", ignoreCase = true) ||
trimmed.contains(" inside call ", ignoreCase = true) ||
trimmed.contains(" when calling ", ignoreCase = true)
}
private fun isQuietCompilerNoiseLine(line: String): Boolean {
val trimmed = line.trim()
return trimmed.startsWith("Warning", ignoreCase = true) ||
trimmed.matches(Regex("""^Errors:\s*\d+\s*$""")) ||
trimmed.matches(Regex("""^Warnings:\s*\d+\s*$""")) ||
trimmed.matches(Regex("""^Tests:\s*\d+/\d+\s+passed\s*$""", RegexOption.IGNORE_CASE)) ||
trimmed.startsWith("compilation finished", ignoreCase = true) ||
trimmed.startsWith("Running tests", ignoreCase = true) ||
trimmed.startsWith("Finished running tests", ignoreCase = true)
}
private fun isNoisyCompilerVersionLine(line: String): Boolean {
val trimmed = line.trim()
return trimmed == "Warning: Ignoring unknown wc3Patch in wurst.build: ${CoreJassProvider.DEFAULT_PATCH}" ||
trimmed.startsWith("Warning: Ignoring unknown wc3Patch in wurst.build:") ||
trimmed.startsWith("Warning: Wurst compiler failed to determine game version") ||
trimmed.contains("VersionExtractionException: Failed to extract executable version data") ||
trimmed.startsWith("at net.moonlightflower.wc3libs.misc.exeversion.") ||
trimmed.startsWith("at net.moonlightflower.wc3libs.bin.GameExe.") ||
trimmed.startsWith("at net.moonlightflower.wc3libs.port.") ||
trimmed.startsWith("at de.peeeq.wurstio.utils.W3InstallationData.discoverVersion") ||
trimmed.startsWith("at de.peeeq.wurstio.utils.W3InstallationData.<init>") ||
trimmed.startsWith("at de.peeeq.wurstio.languageserver.requests.MapRequest.getBestW3InstallationData") ||
trimmed.startsWith("at de.peeeq.wurstio.languageserver.requests.MapRequest.<init>") ||
trimmed.startsWith("at de.peeeq.wurstio.languageserver.requests.CliBuildMap.<init>") ||
trimmed.startsWith("at de.peeeq.wurstio.Main.main") ||
trimmed.startsWith("at dorkbox.peParser.PE") ||
trimmed.startsWith("Caused by: java.lang.NullPointerException") ||
trimmed.matches(Regex("""\.\.\. \d+ more"""))
}
internal var generatePrompt: ((String, String?) -> String?)? = null
internal var installPatchPrompt: ((String, String?) -> String?)? = null
internal fun prepareGenerate(setup: SetupMain): Boolean {
val prompt = generatePrompt ?: terminalPrompt()
while (setup.commandArg.isBlank()) {
val projectName = prompt("Project name", null)?.trim() ?: return false
if (projectName.isBlank()) {
log.error("Project name cannot be empty.")
} else {
setup.commandArg = projectName
}
}
runWizard(setup, prompt, useInteractiveMenus = generatePrompt == null && TerminalMenu.canUseInteractive())
return true
}
private fun terminalPrompt(): (String, String?) -> String? {
val console = System.console()
if (console == null) {
// Non-console stdin is script input; keep EOF/default generation quiet.
return prompt@ { _, default ->
val input = readlnOrNull()?.trim() ?: return@prompt default
input.ifEmpty { default }
}
}
return { message, default ->
if (default == null) {
console.writer().print("$message: ")
} else {
console.writer().print("$message [$default]: ")
}
console.writer().flush()
val input = console.readLine()?.trim() ?: ""
input.ifEmpty { default }
}
}
private fun runWizard(setup: SetupMain, prompt: (String, String?) -> String?, useInteractiveMenus: Boolean) {
setup.scriptMode = selectScriptMode(prompt, setup.scriptMode, useInteractiveMenus)
setup.wc3Patch = selectPatchVersion(
prompt,
intro = "WC3 patch choices:",
useInteractiveMenus = useInteractiveMenus,
currentPatch = setup.wc3Patch
)
setup.gamePathOptedOut = false
setup.gamePath = selectGamePath(setup, prompt, setup.wc3Patch, setup.gamePath)
val agentsDefault = if (setup.addAgents) "Y" else "N"
val agentsInput = prompt("Add AGENTS.md?", agentsDefault) ?: agentsDefault
setup.addAgents = agentsInput.lowercase() == "y"
val ciDefault = if (setup.addGithubWorkflow) "Y" else "N"
val ciInput = prompt("Add GitHub Actions CI?", ciDefault) ?: ciDefault
setup.addGithubWorkflow = ciInput.lowercase() == "y"
setup.curatedDependencyIds = selectCuratedDependencies(prompt, setup.curatedDependencyIds).toMutableList()
}
private fun selectCuratedDependencies(
prompt: (String, String?) -> String?,
preselectedIds: List<String>
): List<String> {
val catalog = CuratedDependencies.all
if (catalog.isEmpty()) {
return preselectedIds
}
log.info("Curated dependencies (optional extras beyond the standard library):")
val selected = LinkedHashSet(preselectedIds)
for (dependency in catalog) {
val default = if (selected.contains(dependency.id)) "Y" else "N"
val answer = prompt("Add ${dependency.summary}?", default) ?: default
if (answer.trim().lowercase() == "y") {
selected.add(dependency.id)
} else {
selected.remove(dependency.id)
}
}
return selected.toList()
}
private fun selectGamePath(
setup: SetupMain,
prompt: (String, String?) -> String?,
wc3Patch: String?,
currentPath: Path?
): Path? {
val detected = currentPath ?: Wc3ClientDetector.detectGameRoot()
val detectedInfo = Wc3ClientDetector.inspectGameRoot(detected)
if (detectedInfo != null) {
log.info("Detected Warcraft III: ${Wc3ClientDetector.describe(detectedInfo)}")
Wc3ClientDetector.mismatchMessage(wc3Patch, detectedInfo)?.let { log.warn(it) }
} else {
log.info("No Warcraft III installation was detected automatically.")
}
val default = detected?.toAbsolutePath()?.normalize()?.toString() ?: "none"
val answer = prompt("Warcraft III directory (or none)", default)?.trim() ?: return detected
if (answer.equals("none", ignoreCase = true) || answer.equals("skip", ignoreCase = true)) {
setup.gamePathOptedOut = true
return null
}
val selected = Paths.get(answer).toAbsolutePath().normalize()
val selectedInfo = Wc3ClientDetector.inspectGameRoot(selected)
if (selectedInfo == null) {
log.warn("No supported Warcraft III executable found in $selected. You can fix wurst.wc3path later in .vscode/settings.json.")
setup.gamePathOptedOut = true
return null
}
Wc3ClientDetector.mismatchMessage(wc3Patch, selectedInfo)?.let { log.warn(it) }
return selectedInfo.root
}
internal fun stdlibDependencyForPatch(wc3Patch: String?): String {
// wurstStdlib2 keeps era-specific branches. pre-1.24 must come first: it is a subset of pre-1.29,
// and those oldest patches need the further-reduced pre1.24 stdlib (no APIs added in 1.24+).
return when {
CoreJassProvider.isPre124(wc3Patch) -> "https://github.com/wurstscript/wurstStdlib2:pre1.24"
CoreJassProvider.isPre129Patch(wc3Patch) -> "https://github.com/wurstscript/wurstStdlib2:pre1.29"
else -> "https://github.com/wurstscript/wurstStdlib2"
}
}
internal fun generatedBuildMapData(projectName: String): WurstProjectBuildMapData {
val mapName = projectName.trim().ifBlank { "Unnamed" }
return WurstProjectBuildMapData(
mapName,
"$mapName.w3x",
defaultAuthorName(),
null,
null,
emptyList(),
emptyList()
)
}
private fun defaultAuthorName(): String {
val systemUser = System.getProperty("user.name").orEmpty().trim()
if (systemUser.isNotBlank()) {
return systemUser
}
return Paths.get(System.getProperty("user.home").orEmpty()).fileName?.toString()?.ifBlank { "Unknown" } ?: "Unknown"
}
private fun selectScriptMode(
prompt: (String, String?) -> String?,
defaultMode: ScriptMode,
useInteractiveMenus: Boolean
): ScriptMode {
if (useInteractiveMenus) {
TerminalMenu.choose(
title = "Script mode",
choices = listOf(
TerminalMenu.Choice(ScriptMode.LUA, "lua"),
TerminalMenu.Choice(ScriptMode.JASS, "jass")
),
defaultIndex = if (defaultMode == ScriptMode.JASS) 1 else 0
)?.let { return it }
}
log.info("Script mode choices:")
log.info(" 1. lua")
log.info(" 2. jass")
while (true) {
val defaultValue = defaultMode.name.lowercase()
val answer = prompt("Script mode (number/name)", defaultValue)?.trim()
if (answer.isNullOrBlank()) {
return defaultMode
}
when (answer.lowercase()) {
"1", "lua" -> return ScriptMode.LUA
"2", "jass" -> return ScriptMode.JASS
else -> log.error("Unsupported script mode: $answer. Choose 1/lua or 2/jass.")
}
}
}
private fun ensureProjectPatchRecorded(configData: WurstProjectConfigData): WurstProjectConfigData {
val currentPatch = configData.wc3Patch
if (currentPatch.isNullOrBlank()) {
val selectedPatch = selectPatchVersionForInstall()
log.info("WC3 patch recorded in wurst.build: $selectedPatch")
return configData.withWc3Patch(selectedPatch)
}
val normalizedPatch = CoreJassProvider.normalizePatchInput(currentPatch)
return if (normalizedPatch != currentPatch) {
configData.withWc3Patch(normalizedPatch)
} else {
configData
}
}
internal fun selectPatchVersionForInstall(): String {
return selectPatchVersion(
installPatchPrompt ?: terminalPrompt(),
intro = "No WC3 patch is recorded in wurst.build yet.",
useInteractiveMenus = installPatchPrompt == null,
currentPatch = null
)
}
private fun selectPatchVersion(
prompt: (String, String?) -> String?,
intro: String,
useInteractiveMenus: Boolean,
currentPatch: String?
): String {
val bundledVersions = CoreJassProvider.supportedPatches
val recommended = CoreJassProvider.recommendedPatchOptions(bundledVersions)
val patchTargets = CoreJassProvider.supportedPatches
val exactVersions by lazy { CoreJassProvider.fetchJassHistoryVersions() }
val normalizedCurrentPatch = currentPatch?.let(CoreJassProvider::normalizePatchInput)
val defaultPatch = when {
normalizedCurrentPatch != null && CoreJassProvider.isSupportedPatch(normalizedCurrentPatch) -> normalizedCurrentPatch
else -> recommended.firstOrNull() ?: CoreJassProvider.DEFAULT_PATCH
}
val browseAll = "__browse_all__"
val visibleRecommended = (listOf(defaultPatch) + recommended).distinct()
if (useInteractiveMenus) {
while (true) {
val choices = visibleRecommended.map { TerminalMenu.Choice(it, CoreJassProvider.describePatch(it)) } +
TerminalMenu.Choice(browseAll, "Browse all supported patch targets...") +
TerminalMenu.Choice("__browse_exact__", "Advanced: browse exact jass-history dumps...")
val selection = TerminalMenu.choose(
title = intro,
choices = choices,
defaultIndex = visibleRecommended.indexOf(defaultPatch).takeIf { it >= 0 } ?: 0
)
when {
selection == null -> return defaultPatch
selection == browseAll -> browsePatchVersionsInteractive("WC3 patch targets", patchTargets)?.let { return it }
selection == "__browse_exact__" -> browsePatchVersionsInteractive("Exact jass-history dumps", exactVersions)?.let { return it }
else -> return selection
}
}
}
log.info(intro)
log.info("Recommended patch choices:")
visibleRecommended.forEachIndexed { index, patch ->
log.info(" ${index + 1}. ${CoreJassProvider.describePatch(patch)}")
}
if (patchTargets.isNotEmpty()) {
log.info("Type `more` to browse supported patch targets.")
}
log.info("Type `exact` to browse raw jass-history dump folders.")
log.info("Enter a listed number, press Enter for the default, or type `more`.")
while (true) {
val answer = prompt("WC3 patch version (number/version/more)", defaultPatch)?.trim()
if (answer.isNullOrBlank()) {
return defaultPatch
}
val topIndex = answer.toIntOrNull()
if (topIndex != null && topIndex in 1..visibleRecommended.size) {
return visibleRecommended[topIndex - 1]
}
when (answer.lowercase()) {
"more", "list", "all" -> browsePatchVersions(
title = "WC3 patch targets",
versions = patchTargets,
prompt = prompt,
exactVersions = exactVersions
)?.let { return it }
"exact", "raw", "dumps" -> browsePatchVersions(
title = "Exact jass-history dumps",
versions = exactVersions,
prompt = prompt,
exactVersions = emptyList()
)?.let { return it }
"q", "quit", "cancel" -> return defaultPatch
else -> {
val normalized = CoreJassProvider.normalizePatchInput(answer)
val directSelection = visibleRecommended.firstOrNull {
it.equals(normalized, ignoreCase = true) ||
CoreJassProvider.normalizePatchInput(it).equals(normalized, ignoreCase = true)
}
if (directSelection != null) {
return directSelection
}
log.error("Unsupported patch selection: $answer")
log.info("Choose one of the listed numbers, type `more`, or type `exact` for raw dump folders.")
}
}
}
}
private fun browsePatchVersions(
title: String,
versions: List<String>,
prompt: (String, String?) -> String?,
exactVersions: List<String>
): String? {
if (versions.isEmpty()) {
log.info("Could not load jass-history versions right now. You can still type a version folder manually.")
return null
}
val pageSize = 20
var page = 0
while (true) {
val start = page * pageSize
val visibleVersions = versions.drop(start).take(pageSize)
if (visibleVersions.isEmpty()) {
page = 0
continue
}
log.info("$title ${start + 1}-${start + visibleVersions.size} of ${versions.size}:")
visibleVersions.forEachIndexed { index, version ->
log.info(" ${index + 1}. ${CoreJassProvider.describePatch(version)}")
}
if (exactVersions.isNotEmpty()) {
log.info("Type `exact` for raw jass-history dump folders.")
}
val answer = prompt("Select version (number/version, n next, p previous, q back)", null)?.trim()
if (answer.isNullOrBlank()) {
return null
}
val pageIndex = answer.toIntOrNull()
if (pageIndex != null && pageIndex in 1..visibleVersions.size) {
return visibleVersions[pageIndex - 1]
}
when (answer.lowercase()) {
"n", "next" -> page = if (start + pageSize >= versions.size) 0 else page + 1
"p", "prev", "previous" -> page = if (page == 0) (versions.size - 1) / pageSize else page - 1
"q", "back", "cancel" -> return null
"exact", "raw", "dumps" -> browsePatchVersions(
title = "Exact jass-history dumps",
versions = exactVersions,
prompt = prompt,
exactVersions = emptyList()
)?.let { return it }
else -> {
val normalized = CoreJassProvider.normalizePatchInput(answer)
val directSelection = versions.firstOrNull {
it.equals(normalized, ignoreCase = true) ||
CoreJassProvider.normalizePatchInput(it).equals(normalized, ignoreCase = true)
}
if (directSelection != null) {
return directSelection
}
log.error("Unsupported patch selection: $answer")
log.info("Choose a number from the current page, use `n`/`p`, type `exact`, or type `q` to go back.")
}
}
}
}
private fun browsePatchVersionsInteractive(title: String, versions: List<String>): String? {
if (versions.isEmpty()) {
return null
}
return TerminalMenu.choose(
title = title,
choices = versions.map { TerminalMenu.Choice(it, CoreJassProvider.describePatch(it)) },
defaultIndex = 0
)
}
private fun downloadAgentsMd(projectDir: Path) {
try {
val content = withAgentsTemplateMarker(URL("https://raw.githubusercontent.com/wurstscript/WurstSetup/master/templates/AGENTS.md").readText())
Files.writeString(projectDir.resolve("AGENTS.md"), content, StandardCharsets.UTF_8)
log.info("✔ AGENTS.md written.")
} catch (e: Exception) {
log.warn("⚠️ Could not download AGENTS.md: ${e.message}. Continuing without it.")
}
}
internal fun withAgentsTemplateMarker(content: String): String {
return if (content.contains(AGENTS_TEMPLATE_MARKER_PREFIX)) {
content
} else {
"$AGENTS_TEMPLATE_MARKER\n$content"
}
}
internal fun agentsTemplateWarning(content: String): String? {
val markerLine = content.lineSequence().firstOrNull { it.startsWith(AGENTS_TEMPLATE_MARKER_PREFIX) }
if (markerLine == AGENTS_TEMPLATE_MARKER) {
return null
}
if (markerLine != null) {
return "AGENTS.md was generated from an older WurstSetup template ($markerLine). Consider refreshing it from templates/AGENTS.md and re-applying project-local notes."
}
if (content.contains(AGENTS_TEMPLATE_SOURCE_HINT)) {
return "AGENTS.md looks like an older WurstSetup template without a version marker. Consider refreshing it from templates/AGENTS.md and re-applying project-local notes."
}
return null
}
private fun warnIfAgentsTemplateStale(projectDir: Path) {
val agents = projectDir.resolve("AGENTS.md")
if (!Files.exists(agents)) {
return
}
try {
agentsTemplateWarning(Files.readString(agents, StandardCharsets.UTF_8))?.let { log.warn("⚠️ $it") }
} catch (e: Exception) {
log.warn("⚠️ Could not inspect AGENTS.md template marker: ${e.message}")
}
}
fun writeCiWorkflow(projectDir: Path) {
val workflowDir = projectDir.resolve(".github/workflows")
Files.createDirectories(workflowDir)
Files.write(workflowDir.resolve("grill.yml"), CI_WORKFLOW.toByteArray())
log.info("✔ GitHub Actions workflow written.")
}
private fun handleUpdateGrill() {
InstallationManager.ensureGrillJarInstalled()
log.info("Grill was refreshed from the running binary.")
}
private fun buildProject(configData: WurstProjectConfigData) {
val args = commonArgs(configData)
args.add("-build")
if (setup.devBuild) {
args.add("-dev")
}
if (setup.measure) {
args.add("-measure")
}
args.add("-workspaceroot")
args.add(setup.projectRoot.toAbsolutePath().toString())
args.add("-inputmap")
args.add(setup.projectRoot.resolve(setup.commandArg).toAbsolutePath().toString())
val result = startWurstProcess(args)
when (result.exitCode) {
0 -> { pass("✅ Map built."); ExitHandler.exit(0) }
else -> {
printCompilerFailure("build", result)
ExitHandler.exit(1)
}
}
}