Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ A Lua project (`scriptMode: lua`) can change the code of a running single-player
> 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`.
`run --hot` builds the map with the compiler's `-luaHotReload` flag, prepares a hot reload session for `_build`, and 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. The new session and its saved build options become active only after the launcher succeeds. If launching fails, the previous session, unread payloads, and saved map/settings are restored. This requires a compiler supporting staged hot reload launches. 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 <dir>` 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`.

Expand Down
54 changes: 44 additions & 10 deletions src/main/kotlin/file/SetupApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1198,7 +1198,7 @@ object SetupApp {
return client
}

/** The compiler's command line entry point for hot reload sessions (`start`, `send`). */
/** The compiler's command line entry point for hot reload sessions and staged launches. */
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. */
Expand All @@ -1212,7 +1212,10 @@ object SetupApp {
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") }
val target = hotRunRecord()
val partial = target.resolveSibling(target.fileName.toString() + ".tmp")
Files.newBufferedWriter(partial, StandardCharsets.UTF_8).use { properties.store(it, "Written by grill run --hot") }
Files.move(partial, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
}

/** `reload` builds with the map and `--dev` of the hot run, unless the command names another map. */
Expand Down Expand Up @@ -1246,17 +1249,38 @@ object SetupApp {
return result
}

private fun startHotReloadSession(): Boolean {
val result = runHotReloadSession("start")
private fun prepareHotReloadSession(): Boolean {
val result = runHotReloadSession("prepare")
if (result.exitCode != 0) {
fail("❌ Could not start the hot reload session; Warcraft III was not launched.")
fail("❌ Could not prepare 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 activateHotReloadSession() {
val result = runHotReloadSession("activate")
if (result.exitCode != 0) {
fail("Warcraft III launched, but the hot reload session could not be activated.")
ExitHandler.exit(1)
}
try {
recordHotRunBuildArgs()
} catch (e: IOException) {
fail("Warcraft III launched, but its hot-run settings could not be saved: ${e.message}")
if (setup.debug) e.printStackTrace()
ExitHandler.exit(1)
}
progress("Hot reload session started. After an edit, run `grill reload`.")
}

private fun abortHotReloadLaunch() {
val result = runHotReloadSession("abort")
if (result.exitCode != 0) {
fail("Could not restore the previous hot reload session (rollback exited ${result.exitCode}).")
}
}

private fun sendHotReloadPayload(): Nothing {
val result = runHotReloadSession("send")
if (result.exitCode == 0) {
Expand Down Expand Up @@ -1310,16 +1334,26 @@ object SetupApp {
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()) {
// Hide old payloads before polling starts, but keep the active baseline until launch succeeds.
if (hot && !prepareHotReloadSession()) {
ExitHandler.exit(1)
}
try {
launchMap(client, map)
pass("Warcraft III launched.")
} catch (e: Exception) {
if (hot) {
try {
abortHotReloadLaunch()
} catch (cleanup: Exception) {
fail("Could not restore the previous hot reload session: ${cleanup.message}")
if (setup.debug) cleanup.printStackTrace()
}
}
launchFailed(e)
}
// A failure here is after the new map launched: never restore obsolete payloads into it.
if (hot) activateHotReloadSession()
pass("Warcraft III launched.")
}
ExitHandler.exit(0)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,41 @@ public static void main(String[] args) throws Exception {
Files.write(project.resolve("session-arguments.txt"), List.of(String.join("|", args)),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Path session = buildDir.resolve("luaHotReload/session.json");
Path staged = session.resolveSibling("session-staged.json");
Path folder = customMapData.resolve("Wurst");
Path aside = folder.resolve("hotreload-set-aside");
if (Files.exists(project.resolve("fail-" + args[0]))) {
System.out.println("fixture " + args[0] + " failure");
System.exit(1);
}
if (args[0].equals("prepare")) {
Files.createDirectories(session.getParent());
Files.writeString(staged, "{}");
if (Files.isDirectory(folder)) {
Files.createDirectories(aside);
for (Path file : deliveries(folder)) Files.move(file, aside.resolve(file.getFileName()));
}
System.out.println("session prepared");
return;
}
if (args[0].equals("activate")) {
Files.move(staged, session, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
if (Files.isDirectory(aside)) {
for (Path file : deliveries(aside)) Files.delete(file);
Files.delete(aside);
}
System.out.println("session activated");
return;
}
if (args[0].equals("abort")) {
Files.deleteIfExists(staged);
if (Files.isDirectory(aside)) {
for (Path file : deliveries(aside)) Files.move(file, folder.resolve(file.getFileName()));
Files.delete(aside);
}
System.out.println("previous session restored");
return;
}
if (args[0].equals("start")) {
Files.createDirectories(session.getParent());
Files.writeString(session, "{}");
Expand All @@ -39,4 +74,10 @@ public static void main(String[] args) throws Exception {
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");
}
private static List<Path> deliveries(Path folder) throws java.io.IOException {
try (var files = Files.list(folder)) {
return files.filter(p -> Files.isRegularFile(p) && p.getFileName().toString().startsWith("hotreload-")
&& (p.toString().endsWith(".pld") || p.toString().endsWith(".pld.tmp"))).sorted().toList();
}
}
}
112 changes: 103 additions & 9 deletions src/test/kotlin/HotReloadTests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import org.testng.Assert
import org.testng.annotations.Test
import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.io.IOException
import java.nio.channels.FileChannel
import java.nio.file.StandardOpenOption
import java.nio.file.Files
Expand All @@ -28,7 +29,7 @@ class HotReloadTests {
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 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"))
Expand Down Expand Up @@ -61,7 +62,8 @@ class HotReloadTests {
}

/** Each launch, with the session calls made before it. */
fun grill(vararg args: String, launches: MutableList<Pair<Path, List<String>>> = mutableListOf()): Outcome {
fun grill(vararg args: String, launches: MutableList<Pair<Path, List<String>>> = mutableListOf(),
launchFailure: Exception? = null): Outcome {
val previousInstall = System.getProperty("wurst.install.dir")
val previousExit = ExitHandler.handler
val previousLauncher = SetupApp.launchMap
Expand All @@ -73,7 +75,10 @@ class HotReloadTests {
try {
System.setProperty("wurst.install.dir", install.parent.toString())
ExitHandler.handler = { throw TestExit(it) }
SetupApp.launchMap = { _, map -> launches.add(map to sessionCalls()) }
SetupApp.launchMap = { _, map ->
launches.add(map to sessionCalls())
launchFailure?.let { throw it }
}
System.setOut(PrintStream(out))
System.setErr(PrintStream(err))
try {
Expand Down Expand Up @@ -111,17 +116,17 @@ class HotReloadTests {
}

@Test
fun hotRunBuildsWithLuaHotReloadAndStartsTheSessionBeforeLaunching() {
fun hotRunPreparesBeforeLaunchingAndActivatesAfterward() {
val project = Project()
val launches = mutableListOf<Pair<Path, List<String>>>()
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))
val paths = "${project.root.resolve("_build").toAbsolutePath()}|${project.customMapData.toAbsolutePath()}"
Assert.assertEquals(project.sessionCalls(), listOf("prepare|$paths", "activate|$paths"))
Assert.assertEquals(launches.map { it.second }, listOf(listOf("prepare|$paths")))
Assert.assertTrue(Files.exists(project.root.resolve("_build/luaHotReload/session.json")))
}

@Test
Expand All @@ -144,7 +149,7 @@ class HotReloadTests {
}

@Test
fun failedSessionStartPreventsLaunch() {
fun failedSessionPreparationPreventsLaunch() {
// A compiler without hot reload has no session class.
val project = Project(withSession = false)
val launches = mutableListOf<Pair<Path, List<String>>>()
Expand All @@ -154,6 +159,95 @@ class HotReloadTests {
Assert.assertEquals(launches, emptyList<Pair<Path, List<String>>>())
}

@Test
fun failedHotLaunchPreservesActiveSessionPayloadsAndBuildOptions() {
val project = Project()
val session = project.root.resolve("_build/luaHotReload/session.json")
Files.createDirectories(session.parent)
Files.writeString(session, "active session version 7")
val options = project.root.resolve("_build/grill/hot-run.properties")
Files.createDirectories(options.parent)
Files.writeString(options, "map=Input.w3x\ndev=true\n")
val oldOptions = Files.readAllBytes(options)
val payload = project.customMapData.resolve("Wurst/hotreload-8.pld")
Files.createDirectories(payload.parent)
Files.writeString(payload, "unread payload")
val partial = payload.resolveSibling("hotreload-9.pld.tmp")
Files.writeString(partial, "partial payload")
Files.writeString(project.root.resolve("Other.w3x"), "other map")

val outcome = project.grill("run", "--hot", "Other.w3x", launchFailure = IOException("fixture launch failure"))
Assert.assertEquals(outcome.code, 1, outcome.err)
Assert.assertTrue(outcome.err.contains("fixture launch failure"), outcome.err)
Assert.assertEquals(Files.readString(session), "active session version 7")
Assert.assertEquals(Files.readString(payload), "unread payload")
Assert.assertEquals(Files.readString(partial), "partial payload")
Assert.assertEquals(Files.readAllBytes(options), oldOptions)

Assert.assertEquals(project.grill("reload").code, 0)
val arguments = project.compilerArguments()
Assert.assertTrue(arguments.contains("-dev"), arguments.toString())
Assert.assertTrue(Files.isSameFile(Path.of(arguments[arguments.indexOf("-inputmap") + 1]),
project.root.resolve("./Input.w3x")))
}

@Test
fun preparationFailureLeavesTheActiveSessionAndPreventsLaunch() {
val project = Project()
val session = project.root.resolve("_build/luaHotReload/session.json")
Files.createDirectories(session.parent)
Files.writeString(session, "active session")
Files.writeString(project.root.resolve("fail-prepare"), "fixture")
val launches = mutableListOf<Pair<Path, List<String>>>()
val outcome = project.grill("run", "--hot", "Input.w3x", launches = launches)
Assert.assertEquals(outcome.code, 1)
Assert.assertEquals(launches.size, 0)
Assert.assertEquals(Files.readString(session), "active session")
Assert.assertTrue(outcome.err.contains("fixture prepare failure"), outcome.err)
}

@Test
fun activationFailureDoesNotRestoreOldPayloadsIntoTheLaunchedMap() {
val project = Project()
Files.writeString(project.root.resolve("fail-activate"), "fixture")
val launches = mutableListOf<Pair<Path, List<String>>>()
val outcome = project.grill("run", "--hot", "Input.w3x", launches = launches)
Assert.assertEquals(outcome.code, 1)
Assert.assertEquals(launches.size, 1)
Assert.assertTrue(outcome.err.contains("Warcraft III launched"), outcome.err)
Assert.assertEquals(project.sessionCalls().map { it.substringBefore('|') }, listOf("prepare", "activate"))
}

@Test
fun rollbackFailureReportsBothTheLaunchAndRecoveryFailures() {
val project = Project()
Files.writeString(project.root.resolve("fail-abort"), "fixture")
val outcome = project.grill("run", "--hot", "Input.w3x", launchFailure = IOException("fixture launch failure"))
Assert.assertEquals(outcome.code, 1)
Assert.assertTrue(outcome.err.contains("fixture launch failure"), outcome.err)
Assert.assertTrue(outcome.err.contains("Could not restore the previous hot reload session"), outcome.err)
Assert.assertTrue(outcome.err.contains("fixture abort failure"), outcome.err)
Assert.assertFalse(outcome.out.contains("previous session restored"), outcome.out)
Assert.assertEquals(project.sessionCalls().map { it.substringBefore('|') }, listOf("prepare", "abort"))
}

@Test
fun settingsFailureAfterLaunchNeverAbortsTheActivatedSession() {
val project = Project()
val options = project.root.resolve("_build/grill/hot-run.properties")
Files.createDirectories(options.parent)
Files.writeString(options, "map=Input.w3x\ndev=true\n")
val original = Files.readAllBytes(options)
Files.createDirectory(options.resolveSibling("hot-run.properties.tmp"))
val launches = mutableListOf<Pair<Path, List<String>>>()
val outcome = project.grill("run", "--hot", "Input.w3x", launches = launches)
Assert.assertEquals(outcome.code, 1)
Assert.assertEquals(launches.size, 1)
Assert.assertTrue(outcome.err.contains("hot-run settings could not be saved"), outcome.err)
Assert.assertEquals(Files.readAllBytes(options), original)
Assert.assertEquals(project.sessionCalls().map { it.substringBefore('|') }, listOf("prepare", "activate"))
}

@Test
fun plainRunNeitherBuildsForHotReloadNorStartsASession() {
val project = Project()
Expand Down
Loading