diff --git a/README.md b/README.md
index 721bd21..c2ee138 100644
--- a/README.md
+++ b/README.md
@@ -125,6 +125,20 @@ Like `build`, `run` accepts map archives or folders and auto-detects the input w
Grill selects Warcraft III from `--wc3-path`, then a valid `.vscode/settings.json` path (`wurst.wc3path`), then automatic detection. It warns about project/client patch mismatches; use `--wc3-path` to choose another client. The built map is passed via `-loadfile`; Reforged also receives `-launch` and `-editor` to preserve the authentication session. Older clients receive a copy in `Maps/Test/GrillRunMap.w3x`, under the installation for 1.27 and older or the Warcraft III documents folder for 1.28–1.31. Linux launches through Wine and respects `WINEPREFIX` for the documents location. Build failures prevent launch. The command returns after starting Warcraft III.
+### Hot reloading a Lua map
+
+A Lua project (`scriptMode: lua`) can change the code of a running single-player game without restarting it:
+
+```cmd
+> grill run --hot ExampleMap.w3x
+ ... edit the Wurst code ...
+> grill reload
+```
+
+`run --hot` builds the map with the compiler's `-luaHotReload` flag, starts a hot reload session for `_build`, and then launches Warcraft III with a copy of the map in `_build/grill/hot-run`, so that the game does not hold the file each reload builds again. After each edit, `reload` builds the project again, with the map and `--dev` setting of the hot run unless you name another map, and writes the next payload for the running map to pick up. It prints the payload and any warnings. When the edit cannot be hot reloaded (for example a field's type changed), or no map was started with `run --hot` (or a hot run from VS Code), it prints the reasons, writes nothing and exits with 1; rebuild and restart with `run --hot`.
+
+Payloads go to the `CustomMapData` folder of the Warcraft III documents folder (the same documents folder `run` uses), unless `--custom-map-data
` or the VS Code setting `wurst.customMapDataPath` names another folder. Hot reload is Lua only: Jass projects are rejected; use Jass Hot Code Reload (JHCR) for them. What can be reloaded is described in the compiler's `docs/LUA_HOT_RELOAD.md`.
+
## How it works
### Wurst Installation
diff --git a/src/main/kotlin/config/WurstProjectConfig.kt b/src/main/kotlin/config/WurstProjectConfig.kt
index 6b17a4e..46cda17 100644
--- a/src/main/kotlin/config/WurstProjectConfig.kt
+++ b/src/main/kotlin/config/WurstProjectConfig.kt
@@ -151,14 +151,19 @@ object WurstProjectConfig {
Files.write(projectRoot.resolve(CONFIG_FILE_NAME), projectYaml.toByteArray())
}
- fun configuredGamePath(projectRoot: Path): Path? {
+ fun configuredGamePath(projectRoot: Path): Path? = configuredPath(projectRoot, "wurst.wc3path")
+
+ /** The VS Code extension's `wurst.customMapDataPath`, which the language server's hot reload also uses. */
+ fun configuredCustomMapDataPath(projectRoot: Path): Path? = configuredPath(projectRoot, "wurst.customMapDataPath")
+
+ private fun configuredPath(projectRoot: Path, setting: String): Path? {
val settings = projectRoot.resolve(".vscode").resolve("settings.json")
if (!Files.isRegularFile(settings)) {
return null
}
return try {
MAPPER.readTree(Files.readString(settings))
- ?.get("wurst.wc3path")
+ ?.get(setting)
?.asText()
?.takeIf(String::isNotBlank)
?.let(Paths::get)
diff --git a/src/main/kotlin/file/CLICommand.kt b/src/main/kotlin/file/CLICommand.kt
index d088e8f..b681fc0 100644
--- a/src/main/kotlin/file/CLICommand.kt
+++ b/src/main/kotlin/file/CLICommand.kt
@@ -14,6 +14,7 @@ enum class CLICommand {
PATCH,
BUILD,
RUN,
+ RELOAD,
EXPORTOBJECTS,
SELF_UPDATE
}
@@ -99,6 +100,16 @@ enum class GlobalOptions(val optionName: String = "", val argCount: Int = 0) {
}
}
},
+ HOT("--hot") {
+ override fun runOption(setupMain: SetupMain, args: List) {
+ setupMain.hotReload = true
+ }
+ },
+ CUSTOM_MAP_DATA("--custom-map-data", 1) {
+ override fun runOption(setupMain: SetupMain, args: List) {
+ setupMain.customMapDataPath = java.nio.file.Paths.get(args[0])
+ }
+ },
WC3_PATH("--wc3-path", 1) {
override fun runOption(setupMain: SetupMain, args: List) {
setupMain.gamePath = java.nio.file.Paths.get(args[0])
diff --git a/src/main/kotlin/file/SetupApp.kt b/src/main/kotlin/file/SetupApp.kt
index 68170af..18d51c9 100644
--- a/src/main/kotlin/file/SetupApp.kt
+++ b/src/main/kotlin/file/SetupApp.kt
@@ -17,6 +17,7 @@ import net.ConnectionManager
import org.slf4j.LoggerFactory
import org.eclipse.jgit.api.Git
import java.awt.GraphicsEnvironment
+import java.io.IOException
import java.net.URL
import java.nio.charset.StandardCharsets
import java.nio.file.Files
@@ -126,6 +127,7 @@ object SetupApp {
setup.command == CLICommand.TYPECHECK ||
setup.command == CLICommand.BUILD ||
setup.command == CLICommand.RUN ||
+ setup.command == CLICommand.RELOAD ||
setup.command == CLICommand.EXPORTOBJECTS -> {
// Only needs to know a compiler is present; skip the version subprocess and update check.
InstallationManager.verifyInstallation(probeVersion = false)
@@ -154,6 +156,7 @@ object SetupApp {
| grill test
| grill build ExampleMap.w3x
| grill run ExampleMap.w3x
+ | grill run --hot ExampleMap.w3x, then grill reload after each edit (Lua)
|
|Project commands:
| install [dep|wurstscript|grill] Install/update dependencies, WurstScript compiler, or Grill itself
@@ -165,6 +168,7 @@ object SetupApp {
| patch [align] Compare project/client patches; align config and stdlib on request
| build Build the project using the given map archive or folder
| run [mapfile|map-folder] Build and launch the map in Warcraft III
+ | reload [mapfile|map-folder] Rebuild and send the edit to the map started by `run --hot` (Lua)
| exportobjects Export object editor data to Wurst source
|
|Global options:
@@ -176,6 +180,10 @@ object SetupApp {
|
|Run options (also accepts build options):
| --wc3-path Override the configured/detected Warcraft III installation
+ | --hot Build for Lua hot reload and start a session for `grill reload`
+ |
+ |Run --hot and reload options:
+ | --custom-map-data Warcraft III CustomMapData folder that payloads are written to
|
|Generate options:
| --script-mode lua|jass Script mode (default: lua)
@@ -290,7 +298,16 @@ object SetupApp {
handlePatchAlignment(configData)
}
}
- setup.command == CLICommand.BUILD || setup.command == CLICommand.RUN -> {
+ setup.command == CLICommand.BUILD || setup.command == CLICommand.RUN || setup.command == CLICommand.RELOAD -> {
+ val hot = setup.command == CLICommand.RELOAD || (setup.command == CLICommand.RUN && setup.hotReload)
+ if (hot && configData != null && configData.scriptMode != ScriptMode.LUA) {
+ fail("❌ Hot reload needs a Lua project (`scriptMode: lua` in wurst.build). " +
+ "For Jass maps use Jass Hot Code Reload (JHCR), a separate tool.")
+ ExitHandler.exit(1)
+ }
+ if (setup.command == CLICommand.RELOAD) {
+ applyHotRunBuildArgs()
+ }
progress("🔨 Building project...")
val mapArg = if (setup.commandArg.isBlank()) {
val maps = Files.list(setup.projectRoot).use { stream ->
@@ -312,7 +329,7 @@ object SetupApp {
} else {
setup.commandArg = mapArg
val client = if (setup.command == CLICommand.RUN) resolveRunClient(configData) else null
- buildProject(configData, client)
+ buildProject(configData, client, hot)
}
}
}
@@ -1181,11 +1198,90 @@ object SetupApp {
return client
}
- private fun buildProject(configData: WurstProjectConfigData, client: Wc3ClientDetector.ClientInfo? = null) {
+ /** The compiler's command line entry point for hot reload sessions (`start`, `send`). */
+ private const val HOT_RELOAD_SESSION_CLASS = "de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession"
+
+ /** Starts Warcraft III with a built map; replaced in tests, which must never launch the game. */
+ internal var launchMap: (Wc3ClientDetector.ClientInfo, Path) -> Unit = Wc3MapRunner::launch
+
+ /** What `run --hot` built with, so that `reload` builds the same script. */
+ private fun hotRunRecord(): Path = compilerOutputDir().resolve("hot-run.properties")
+
+ private fun recordHotRunBuildArgs() {
+ val properties = Properties()
+ properties.setProperty("map", setup.commandArg)
+ properties.setProperty("dev", setup.devBuild.toString())
+ Files.createDirectories(compilerOutputDir())
+ Files.newBufferedWriter(hotRunRecord()).use { properties.store(it, "Written by grill run --hot") }
+ }
+
+ /** `reload` builds with the map and `--dev` of the hot run, unless the command names another map. */
+ private fun applyHotRunBuildArgs() {
+ val record = hotRunRecord()
+ if (!Files.isRegularFile(record)) return
+ val properties = Properties()
+ Files.newBufferedReader(record).use { properties.load(it) }
+ val map = properties.getProperty("map").orEmpty()
+ if (setup.commandArg.isBlank() && map.isNotBlank()) {
+ setup.commandArg = map
+ }
+ if (properties.getProperty("dev").toBoolean() && setup.commandArg == map) {
+ setup.devBuild = true
+ }
+ }
+
+ private fun runHotReloadSession(action: String): WurstProcessResult {
+ val command = InstallationManager.compilerClassCommand(HOT_RELOAD_SESSION_CLASS, action,
+ setup.projectRoot.resolve("_build").toAbsolutePath().toString(),
+ Wc3MapRunner.customMapDataPath(setup).toAbsolutePath().toString())
+ val result = runWurstProcess(ArrayList(command), compactFallback = false)
+ if (setup.quiet) {
+ // The session prints only what the user needs: the payload and its warnings, or why it was refused.
+ val stream = if (result.exitCode == 0) System.out else System.err
+ result.output.forEach(stream::println)
+ }
+ if (result.exitCode != 0 && result.output.any { it.contains("Could not find or load main class") }) {
+ detail("The installed compiler has no Lua hot reload. Try: grill install wurstscript")
+ }
+ return result
+ }
+
+ private fun startHotReloadSession(): Boolean {
+ val result = runHotReloadSession("start")
+ if (result.exitCode != 0) {
+ fail("❌ Could not start the hot reload session; Warcraft III was not launched.")
+ return false
+ }
+ recordHotRunBuildArgs()
+ progress("Hot reload session started. After an edit, run `grill reload`.")
+ return true
+ }
+
+ private fun sendHotReloadPayload(): Nothing {
+ val result = runHotReloadSession("send")
+ if (result.exitCode == 0) {
+ pass("✅ Hot reload payload written.")
+ ExitHandler.exit(0)
+ }
+ fail("❌ Hot reload refused; no payload was written.")
+ if (result.output.any { it.contains("no map was started with hot run") }) {
+ detail("Try: start the map with `grill run --hot` first.")
+ } else {
+ detail("Try: rebuild and restart the map with `grill run --hot`.")
+ }
+ ExitHandler.exit(1)
+ }
+
+ private fun buildProject(configData: WurstProjectConfigData, client: Wc3ClientDetector.ClientInfo? = null,
+ hot: Boolean = false) {
val args = commonArgs(configData)
args.add("-build")
+ if (hot) {
+ args.add("-luaHotReload")
+ }
+
if (setup.devBuild) {
args.add("-dev")
}
@@ -1204,15 +1300,25 @@ object SetupApp {
when (result.exitCode) {
0 -> {
pass("✅ Map built.")
+ if (setup.command == CLICommand.RELOAD) {
+ sendHotReloadPayload()
+ }
if (client != null) {
+ val built = try {
+ Wc3MapRunner.builtMap(setup.projectRoot, configData, result.output)
+ } catch (e: Exception) {
+ launchFailed(e)
+ }
+ val map = if (hot) hotRunMap(built) else built
+ // The session goes first: it deletes an earlier session's payloads, which the new map would read.
+ if (hot && !startHotReloadSession()) {
+ ExitHandler.exit(1)
+ }
try {
- val map = Wc3MapRunner.builtMap(setup.projectRoot, configData, result.output)
- Wc3MapRunner.launch(client, map)
+ launchMap(client, map)
pass("Warcraft III launched.")
} catch (e: Exception) {
- fail("Could not launch Warcraft III: ${e.message}. Select another installation with --wc3-path .")
- if (setup.debug) e.printStackTrace()
- ExitHandler.exit(1)
+ launchFailed(e)
}
}
ExitHandler.exit(0)
@@ -1224,6 +1330,29 @@ object SetupApp {
}
}
+ /**
+ * The map a hot run launches: a copy of the built map, because the game keeps the map it runs open and each
+ * `reload` builds the map again.
+ */
+ private fun hotRunMap(built: Path): Path {
+ val target = compilerOutputDir().resolve("hot-run").resolve(built.fileName)
+ try {
+ Files.createDirectories(target.parent)
+ Files.copy(built, target, StandardCopyOption.REPLACE_EXISTING)
+ } catch (e: IOException) {
+ fail("❌ Could not copy the map for the hot run: ${e.message}. Close Warcraft III if it still runs an earlier hot run.")
+ if (setup.debug) e.printStackTrace()
+ ExitHandler.exit(1)
+ }
+ return target.toAbsolutePath().normalize()
+ }
+
+ private fun launchFailed(e: Exception): Nothing {
+ fail("Could not launch Warcraft III: ${e.message}. Select another installation with --wc3-path .")
+ if (setup.debug) e.printStackTrace()
+ ExitHandler.exit(1)
+ }
+
private fun exportObjects(mapPath: Path) {
val args = ArrayList(InstallationManager.compilerLaunchCommand().toList())
args.add("-exportobjects")
diff --git a/src/main/kotlin/file/SetupMain.kt b/src/main/kotlin/file/SetupMain.kt
index 4347c19..35cff59 100644
--- a/src/main/kotlin/file/SetupMain.kt
+++ b/src/main/kotlin/file/SetupMain.kt
@@ -17,6 +17,12 @@ class SetupMain {
var devBuild = false
+ /** `run --hot`: build for Lua hot reload and start a hot reload session before launching. */
+ var hotReload = false
+
+ /** Overrides the Warcraft III CustomMapData folder that hot reload payloads are written to. */
+ var customMapDataPath: Path? = null
+
var projectRoot: Path = SetupApp.DEFAULT_DIR
var gamePath: Path? = null
@@ -101,12 +107,18 @@ class SetupMain {
opt.runOption(this, argsList.subList(i + 1, argEnd))
i += 1 + opt.argCount
} else {
+ // A map may follow the flags (`grill run --hot Map.w3x`).
+ if (commandArg.isEmpty() && command in MAP_COMMANDS && !argsList[i].startsWith("-")) {
+ commandArg = argsList[i]
+ }
i++
}
}
}
companion object {
+ private val MAP_COMMANDS = setOf(CLICommand.BUILD, CLICommand.RUN, CLICommand.RELOAD)
+
@JvmStatic
fun main(args: Array) {
SetupMain().doMain(args)
diff --git a/src/main/kotlin/file/Wc3MapRunner.kt b/src/main/kotlin/file/Wc3MapRunner.kt
index d33023d..77f95be 100644
--- a/src/main/kotlin/file/Wc3MapRunner.kt
+++ b/src/main/kotlin/file/Wc3MapRunner.kt
@@ -66,6 +66,16 @@ internal object Wc3MapRunner {
return target.toAbsolutePath().normalize()
}
+ /**
+ * Where a hot reload writes its payloads for the running map to read: `--custom-map-data`, then the VS Code setting
+ * `wurst.customMapDataPath`, then `CustomMapData` in the Warcraft III documents folder (as the language server).
+ */
+ fun customMapDataPath(setup: SetupMain, documentsRoot: () -> Path = ::warcraftDocumentsRoot): Path {
+ setup.customMapDataPath?.let { return it }
+ WurstProjectConfig.configuredCustomMapDataPath(setup.projectRoot)?.let { return it }
+ return documentsRoot().resolve("CustomMapData")
+ }
+
private fun warcraftDocumentsRoot(): Path {
return when {
System.getProperty("os.name").startsWith("Linux", ignoreCase = true) -> {
diff --git a/src/main/kotlin/global/InstallationManager.kt b/src/main/kotlin/global/InstallationManager.kt
index de7e9c9..217d662 100644
--- a/src/main/kotlin/global/InstallationManager.kt
+++ b/src/main/kotlin/global/InstallationManager.kt
@@ -196,6 +196,12 @@ object InstallationManager {
return arrayOf(java, "-jar", compiler.toAbsolutePath().toString(), *extraArgs)
}
+ /** Runs [mainClass] from the installed compiler jar, for its entry points other than the compiler's main. */
+ fun compilerClassCommand(mainClass: String, vararg extraArgs: String): List {
+ val compiler = detectCompilerJar() ?: compilerJar
+ return listOf(bundledJavaCommand(), "-cp", compiler.toAbsolutePath().toString(), mainClass, *extraArgs)
+ }
+
private fun bundledJavaCommand(): String {
return if (Files.exists(bundledJava) && Files.isExecutable(bundledJava)) {
bundledJava.toAbsolutePath().toString()
diff --git a/src/test/java/de/peeeq/wurstio/languageserver/requests/LuaHotReloadSession.java b/src/test/java/de/peeeq/wurstio/languageserver/requests/LuaHotReloadSession.java
new file mode 100644
index 0000000..b36d562
--- /dev/null
+++ b/src/test/java/de/peeeq/wurstio/languageserver/requests/LuaHotReloadSession.java
@@ -0,0 +1,42 @@
+package de.peeeq.wurstio.languageserver.requests;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.List;
+
+/**
+ * Stands in for the compiler's hot reload session class (same name, so Grill's command line reaches it) without a
+ * running map: it records each call and answers as the compiler does.
+ */
+public class LuaHotReloadSession {
+ public static void main(String[] args) throws Exception {
+ Path buildDir = Path.of(args[1]);
+ Path customMapData = Path.of(args[2]);
+ Path project = buildDir.getParent();
+ Files.write(project.resolve("session-arguments.txt"), List.of(String.join("|", args)),
+ StandardOpenOption.CREATE, StandardOpenOption.APPEND);
+ Path session = buildDir.resolve("luaHotReload/session.json");
+ if (args[0].equals("start")) {
+ Files.createDirectories(session.getParent());
+ Files.writeString(session, "{}");
+ System.out.println("session started");
+ return;
+ }
+ if (!Files.exists(session)) {
+ System.out.println("The edit cannot be hot reloaded, rebuild and restart the map:\n"
+ + " no map was started with hot run (or -luaHotReload): start the map with hot run first");
+ System.exit(1);
+ }
+ if (Files.exists(project.resolve("refuse-reload"))) {
+ System.out.println("The edit cannot be hot reloaded, rebuild and restart the map:\n"
+ + " the type of field Hello_Unit_hp changed");
+ System.exit(1);
+ }
+ Path file = customMapData.resolve("Wurst/hotreload-1.pld");
+ Files.createDirectories(file.getParent());
+ Files.writeString(file, "payload");
+ System.out.println("payload 1 (Hello_greet) written to " + file);
+ System.out.println("warning: closure Hello_init_closure1 was removed; instances made before keep their old body");
+ }
+}
diff --git a/src/test/kotlin/HotReloadTests.kt b/src/test/kotlin/HotReloadTests.kt
new file mode 100644
index 0000000..c213209
--- /dev/null
+++ b/src/test/kotlin/HotReloadTests.kt
@@ -0,0 +1,259 @@
+import file.CLICommand
+import file.ExitHandler
+import file.SetupApp
+import file.SetupMain
+import file.Wc3ClientDetector
+import file.Wc3MapRunner
+import org.testng.Assert
+import org.testng.annotations.Test
+import java.io.ByteArrayOutputStream
+import java.io.PrintStream
+import java.nio.channels.FileChannel
+import java.nio.file.StandardOpenOption
+import java.nio.file.Files
+import java.nio.file.Path
+import java.util.jar.Attributes
+import java.util.jar.JarEntry
+import java.util.jar.JarOutputStream
+import java.util.jar.Manifest
+
+/**
+ * `grill run --hot` and `grill reload` against a stand-in compiler (`RunCompilerFixture`) and session class
+ * (`de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession` in the test sources). Nothing launches Warcraft III:
+ * the launch is replaced by a recorder.
+ */
+class HotReloadTests {
+ private class TestExit(val code: Int) : RuntimeException()
+
+ private data class Outcome(val code: Int, val out: String, val err: String)
+
+ private class Project(scriptMode: String = "lua", withSession: Boolean = true) {
+ val root: Path = Files.createTempDirectory("grill-hot")
+ val install: Path = Files.createDirectories(root.resolve("install/wurst-compiler"))
+ val customMapData: Path = root.resolve("CustomMapData")
+ val client: Path = Files.createDirectories(root.resolve("Game/_retail_/x86_64"))
+
+ init {
+ val manifest = Manifest().apply {
+ mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0"
+ mainAttributes[Attributes.Name.MAIN_CLASS] = "RunCompilerFixture"
+ }
+ JarOutputStream(Files.newOutputStream(install.resolve("wurstscript.jar")), manifest).use { jar ->
+ val session = "de/peeeq/wurstio/languageserver/requests/LuaHotReloadSession.class"
+ for (entry in listOf("RunCompilerFixture.class") + (if (withSession) listOf(session) else emptyList())) {
+ jar.putNextEntry(JarEntry(entry))
+ javaClass.getResourceAsStream("/$entry")!!.use { it.copyTo(jar) }
+ jar.closeEntry()
+ }
+ }
+ Files.writeString(root.resolve("wurst.build"), "projectName: Example\nscriptMode: $scriptMode\nwc3Patch: v3.0\n")
+ Files.writeString(root.resolve("Input.w3x"), "input map")
+ // Avoid fetching core JASS: the fixture records invocations rather than compiling Wurst.
+ val jassdoc = Files.createDirectories(root.resolve("_build/dependencies/jassdoc"))
+ Files.writeString(jassdoc.resolve("common.j"), "")
+ Files.writeString(client.resolve("Warcraft III.exe"), "not a game")
+ }
+
+ fun compilerArguments(): List = Files.readAllLines(root.resolve("compiler-arguments.txt"))
+
+ fun sessionCalls(): List = root.resolve("session-arguments.txt").let {
+ if (Files.exists(it)) Files.readAllLines(it) else emptyList()
+ }
+
+ /** Each launch, with the session calls made before it. */
+ fun grill(vararg args: String, launches: MutableList>> = mutableListOf()): Outcome {
+ val previousInstall = System.getProperty("wurst.install.dir")
+ val previousExit = ExitHandler.handler
+ val previousLauncher = SetupApp.launchMap
+ val previousOut = System.out
+ val previousErr = System.err
+ val out = ByteArrayOutputStream()
+ val err = ByteArrayOutputStream()
+ var code = -1
+ try {
+ System.setProperty("wurst.install.dir", install.parent.toString())
+ ExitHandler.handler = { throw TestExit(it) }
+ SetupApp.launchMap = { _, map -> launches.add(map to sessionCalls()) }
+ System.setOut(PrintStream(out))
+ System.setErr(PrintStream(err))
+ try {
+ SetupMain().apply { projectRoot = root }.doMain(arrayOf(*args, "--quiet",
+ "--custom-map-data", customMapData.toString(), "--wc3-path", client.toString()))
+ } catch (exit: TestExit) {
+ code = exit.code
+ }
+ } finally {
+ System.setOut(previousOut)
+ System.setErr(previousErr)
+ SetupApp.launchMap = previousLauncher
+ ExitHandler.handler = previousExit
+ if (previousInstall == null) System.clearProperty("wurst.install.dir")
+ else System.setProperty("wurst.install.dir", previousInstall)
+ }
+ return Outcome(code, out.toString(), err.toString())
+ }
+ }
+
+ @Test
+ fun parsesHotFlagMapAfterFlagsAndCustomMapData() {
+ val run = SetupMain()
+ run.parseArgs(listOf("run", "--hot", "Map with spaces.w3x", "--dev"))
+ Assert.assertEquals(run.command, CLICommand.RUN)
+ Assert.assertTrue(run.hotReload)
+ Assert.assertEquals(run.commandArg, "Map with spaces.w3x")
+ Assert.assertTrue(run.devBuild)
+
+ val reload = SetupMain()
+ reload.parseArgs(listOf("reload", "--custom-map-data", "D:/CMD", "Other.w3x"))
+ Assert.assertEquals(reload.command, CLICommand.RELOAD)
+ Assert.assertEquals(reload.commandArg, "Other.w3x")
+ Assert.assertEquals(reload.customMapDataPath.toString().replace('\\', '/'), "D:/CMD")
+ }
+
+ @Test
+ fun hotRunBuildsWithLuaHotReloadAndStartsTheSessionBeforeLaunching() {
+ val project = Project()
+ val launches = mutableListOf>>()
+ val outcome = project.grill("run", "--hot", "Input.w3x", "--dev", launches = launches)
+ Assert.assertEquals(outcome.code, 0, outcome.err)
+ val arguments = project.compilerArguments()
+ Assert.assertTrue(arguments.containsAll(listOf("-build", "-lua", "-luaHotReload", "-dev")), arguments.toString())
+ val start = listOf("start|${project.root.resolve("_build").toAbsolutePath()}|${project.customMapData.toAbsolutePath()}")
+ Assert.assertEquals(project.sessionCalls(), start)
+ // The session is in place before the map starts polling.
+ Assert.assertEquals(launches.map { it.second }, listOf(start))
+ }
+
+ @Test
+ fun hotRunLaunchesACopySoThatReloadsCanRebuildTheMap() {
+ // The game holds the map it runs open, and each reload builds the map again: the two must be different files.
+ val project = Project()
+ val launches = mutableListOf>>()
+ Assert.assertEquals(project.grill("run", "--hot", "Input.w3x", launches = launches).code, 0)
+ val built = project.root.resolve("_build/Actual output.w3x").toAbsolutePath().normalize()
+ val launched = launches.single().first
+ Assert.assertNotEquals(launched, built)
+ Assert.assertEquals(launched.fileName, built.fileName)
+ Assert.assertEquals(Files.readString(launched), "fixture map")
+ FileChannel.open(launched, StandardOpenOption.READ, StandardOpenOption.WRITE).use { running ->
+ running.lock().use {
+ val outcome = project.grill("reload")
+ Assert.assertEquals(outcome.code, 0, outcome.err)
+ }
+ }
+ }
+
+ @Test
+ fun failedSessionStartPreventsLaunch() {
+ // A compiler without hot reload has no session class.
+ val project = Project(withSession = false)
+ val launches = mutableListOf>>()
+ val outcome = project.grill("run", "--hot", "Input.w3x", launches = launches)
+ Assert.assertEquals(outcome.code, 1)
+ Assert.assertTrue(outcome.err.contains("The installed compiler has no Lua hot reload"), outcome.err)
+ Assert.assertEquals(launches, emptyList>>())
+ }
+
+ @Test
+ fun plainRunNeitherBuildsForHotReloadNorStartsASession() {
+ val project = Project()
+ val launches = mutableListOf>>()
+ Assert.assertEquals(project.grill("run", "Input.w3x", launches = launches).code, 0)
+ Assert.assertFalse(project.compilerArguments().contains("-luaHotReload"))
+ Assert.assertEquals(project.sessionCalls(), emptyList())
+ Assert.assertEquals(launches.size, 1)
+ }
+
+ @Test
+ fun reloadRebuildsWithTheHotRunsArgumentsAndPrintsThePayload() {
+ val project = Project()
+ Assert.assertEquals(project.grill("run", "--hot", "Input.w3x", "--dev").code, 0)
+ Files.delete(project.root.resolve("compiler-arguments.txt"))
+ val outcome = project.grill("reload")
+ Assert.assertEquals(outcome.code, 0, outcome.err)
+ val arguments = project.compilerArguments()
+ Assert.assertTrue(arguments.containsAll(listOf("-build", "-lua", "-luaHotReload", "-dev")), arguments.toString())
+ Assert.assertEquals(arguments[arguments.indexOf("-inputmap") + 1], project.root.resolve("Input.w3x").toAbsolutePath().toString())
+ Assert.assertEquals(project.sessionCalls().last(), "send|${project.root.resolve("_build")}|${project.customMapData}")
+ Assert.assertTrue(outcome.out.contains("payload 1 (Hello_greet) written to"), outcome.out)
+ Assert.assertTrue(outcome.out.contains("warning: closure Hello_init_closure1 was removed"), outcome.out)
+ Assert.assertTrue(Files.exists(project.customMapData.resolve("Wurst/hotreload-1.pld")))
+ }
+
+ @Test
+ fun refusedReloadExitsNonZeroWithTheReasons() {
+ val project = Project()
+ Assert.assertEquals(project.grill("run", "--hot", "Input.w3x").code, 0)
+ Files.writeString(project.root.resolve("refuse-reload"), "")
+ val outcome = project.grill("reload", "Input.w3x")
+ Assert.assertEquals(outcome.code, 1)
+ Assert.assertTrue(outcome.err.contains("the type of field Hello_Unit_hp changed"), outcome.err)
+ Assert.assertTrue(outcome.err.contains("Hot reload refused"), outcome.err)
+ Assert.assertFalse(outcome.out.contains("payload"), outcome.out)
+ }
+
+ @Test
+ fun reloadWithoutAHotRunExitsNonZero() {
+ val project = Project()
+ val outcome = project.grill("reload", "Input.w3x")
+ Assert.assertEquals(outcome.code, 1)
+ Assert.assertTrue(outcome.err.contains("no map was started with hot run"), outcome.err)
+ Assert.assertTrue(outcome.err.contains("grill run --hot"), outcome.err)
+ }
+
+ @Test
+ fun failedReloadBuildWritesNoPayload() {
+ val project = Project()
+ Assert.assertEquals(project.grill("run", "--hot", "Input.w3x").code, 0)
+ Files.writeString(project.root.resolve("fail-build"), "")
+ val outcome = project.grill("reload", "Input.w3x")
+ Assert.assertEquals(outcome.code, 1)
+ Assert.assertTrue(outcome.err.contains("Wurst build failed"), outcome.err)
+ Assert.assertEquals(project.sessionCalls().count { it.startsWith("send|") }, 0)
+ }
+
+ @Test
+ fun jassProjectsAreRejectedBeforeBuilding() {
+ for (command in listOf(arrayOf("run", "--hot", "Input.w3x"), arrayOf("reload", "Input.w3x"))) {
+ val project = Project(scriptMode = "jass")
+ val outcome = project.grill(*command)
+ Assert.assertEquals(outcome.code, 1, command.joinToString(" "))
+ Assert.assertTrue(outcome.err.contains("Lua"), outcome.err)
+ Assert.assertTrue(outcome.err.contains("JHCR"), outcome.err)
+ Assert.assertFalse(Files.exists(project.root.resolve("compiler-arguments.txt")), "Nothing is built")
+ Assert.assertEquals(project.sessionCalls(), emptyList())
+ }
+ }
+
+ @Test
+ fun customMapDataFollowsOptionThenVsCodeSettingThenDocuments() {
+ val project = Files.createTempDirectory("grill-hot-cmd")
+ val documents = project.resolve("Documents/Warcraft III")
+ val setup = SetupMain().apply { projectRoot = project }
+ Assert.assertEquals(Wc3MapRunner.customMapDataPath(setup) { documents }, documents.resolve("CustomMapData"))
+ Files.createDirectories(project.resolve(".vscode"))
+ val configured = project.resolve("Configured CMD")
+ Files.writeString(project.resolve(".vscode/settings.json"),
+ "{\"wurst.customMapDataPath\":\"${configured.toString().replace("\\", "\\\\")}\"}")
+ Assert.assertEquals(Wc3MapRunner.customMapDataPath(setup) { documents }, configured)
+ setup.customMapDataPath = project.resolve("Explicit")
+ Assert.assertEquals(Wc3MapRunner.customMapDataPath(setup) { Assert.fail("An explicit folder wins"); documents },
+ project.resolve("Explicit"))
+ }
+
+ @Test
+ fun sessionCommandUsesTheInstalledCompilerJar() {
+ val project = Project()
+ val previousInstall = System.getProperty("wurst.install.dir")
+ System.setProperty("wurst.install.dir", project.install.parent.toString())
+ try {
+ val command = global.InstallationManager.compilerClassCommand(
+ "de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession", "send", "a b", "c")
+ Assert.assertEquals(command.drop(1), listOf("-cp", project.install.resolve("wurstscript.jar").toAbsolutePath().toString(),
+ "de.peeeq.wurstio.languageserver.requests.LuaHotReloadSession", "send", "a b", "c"))
+ } finally {
+ if (previousInstall == null) System.clearProperty("wurst.install.dir")
+ else System.setProperty("wurst.install.dir", previousInstall)
+ }
+ }
+}