• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wurstscript / WurstScript / 228

29 Nov 2023 05:00PM UTC coverage: 62.48% (-0.09%) from 62.574%
228

push

circleci

web-flow
Show dialog for choosing game path, cleanup (#1083)

* show dialog for choosing game path

* cleanup code

* remove logs and refactor

* remove confusing mpq error, make some mpq loads readonly

17295 of 27681 relevant lines covered (62.48%)

0.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/MapRequest.java
1
package de.peeeq.wurstio.languageserver.requests;
2

3
import com.google.common.base.Charsets;
4
import com.google.common.io.Files;
5
import config.WurstProjectConfigData;
6
import de.peeeq.wurstio.Pjass;
7
import de.peeeq.wurstio.TimeTaker;
8
import de.peeeq.wurstio.UtilsIO;
9
import de.peeeq.wurstio.WurstCompilerJassImpl;
10
import de.peeeq.wurstio.languageserver.ModelManager;
11
import de.peeeq.wurstio.languageserver.ProjectConfigBuilder;
12
import de.peeeq.wurstio.languageserver.WFile;
13
import de.peeeq.wurstio.languageserver.WurstLanguageServer;
14
import de.peeeq.wurstio.mpq.MpqEditor;
15
import de.peeeq.wurstio.mpq.MpqEditorFactory;
16
import de.peeeq.wurstio.utils.W3InstallationData;
17
import de.peeeq.wurstscript.RunArgs;
18
import de.peeeq.wurstscript.WLogger;
19
import de.peeeq.wurstscript.ast.CompilationUnit;
20
import de.peeeq.wurstscript.ast.WImport;
21
import de.peeeq.wurstscript.ast.WPackage;
22
import de.peeeq.wurstscript.ast.WurstModel;
23
import de.peeeq.wurstscript.attributes.CompileError;
24
import de.peeeq.wurstscript.gui.WurstGui;
25
import de.peeeq.wurstscript.jassAst.JassProg;
26
import de.peeeq.wurstscript.jassprinter.JassPrinter;
27
import de.peeeq.wurstscript.luaAst.LuaCompilationUnit;
28
import de.peeeq.wurstscript.parser.WPos;
29
import de.peeeq.wurstscript.utils.LineOffsets;
30
import de.peeeq.wurstscript.utils.Utils;
31
import net.moonlightflower.wc3libs.bin.app.W3I;
32
import net.moonlightflower.wc3libs.port.Orient;
33
import org.apache.commons.lang.StringUtils;
34
import org.eclipse.lsp4j.MessageParams;
35
import org.eclipse.lsp4j.MessageType;
36
import org.eclipse.lsp4j.services.LanguageClient;
37
import org.jetbrains.annotations.Nullable;
38

39
import java.io.File;
40
import java.io.FileNotFoundException;
41
import java.io.IOException;
42
import java.nio.channels.NonWritableChannelException;
43
import java.nio.charset.StandardCharsets;
44
import java.nio.file.Path;
45
import java.nio.file.Paths;
46
import java.time.Duration;
47
import java.util.List;
48
import java.util.Objects;
49
import java.util.Optional;
50
import java.util.Set;
51
import java.util.concurrent.CompletableFuture;
52
import java.util.concurrent.atomic.AtomicReference;
53
import java.util.stream.Collectors;
54

55
public abstract class MapRequest extends UserRequest<Object> {
56
    protected final WurstLanguageServer langServer;
57
    protected final @Nullable
58
    Optional<File> map;
59
    protected final List<String> compileArgs;
60
    protected final WFile workspaceRoot;
61
    protected final RunArgs runArgs;
62
    protected final Optional<String> wc3Path;
63
    protected final W3InstallationData w3data;
64
    protected final TimeTaker timeTaker;
65

66
    /**
67
     * makes the compilation slower, but more safe by discarding results from the editor and working on a copy of the model
68
     */
69
    protected SafetyLevel safeCompilation = SafetyLevel.KindOfSafe;
×
70

71
    public TimeTaker getTimeTaker() {
72
        return timeTaker;
×
73
    }
74

75

76
    enum SafetyLevel {
×
77
        QuickAndDirty, KindOfSafe
×
78
    }
79

80
    public static class CompilationResult {
×
81
        public File script;
82
        public File w3i;
83
    }
84

85
    public MapRequest(WurstLanguageServer langServer, Optional<File> map, List<String> compileArgs, WFile workspaceRoot,
86
                      Optional<String> wc3Path) {
×
87
        this.langServer = langServer;
×
88
        this.map = map;
×
89
        this.compileArgs = compileArgs;
×
90
        this.workspaceRoot = workspaceRoot;
×
91
        this.runArgs = new RunArgs(compileArgs);
×
92
        this.wc3Path = wc3Path;
×
93
        this.w3data = getBestW3InstallationData();
×
94
        if (runArgs.isMeasureTimes()) {
×
95
            this.timeTaker = new TimeTaker.Recording();
×
96
        } else {
97
            this.timeTaker = new TimeTaker.Default();
×
98
        }
99
    }
×
100

101
    @Override
102
    public void handleException(LanguageClient languageClient, Throwable err, CompletableFuture<Object> resFut) {
103
        if (err instanceof RequestFailedException) {
×
104
            RequestFailedException rfe = (RequestFailedException) err;
×
105
            languageClient.showMessage(new MessageParams(rfe.getMessageType(), rfe.getMessage()));
×
106
            resFut.complete(new Object());
×
107
        } else {
×
108
            super.handleException(languageClient, err, resFut);
×
109
        }
110
    }
×
111

112
    protected File compileMap(File projectFolder, WurstGui gui, Optional<File> mapCopy, RunArgs runArgs, WurstModel model,
113
                              WurstProjectConfigData projectConfigData, boolean isProd) {
114
        try (@Nullable MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy)) {
×
115
            if (mpqEditor != null && !mpqEditor.canWrite()) {
×
116
                WLogger.severe("The supplied map is invalid/corrupted/protected and Wurst cannot write to it.\n" +
×
117
                    "Please supply a valid .w3x input map that can be opened in the world editor.");
118
                throw new NonWritableChannelException();
×
119
            }
120
            WurstCompilerJassImpl compiler = new WurstCompilerJassImpl(timeTaker, projectFolder, gui, mpqEditor, runArgs);
×
121
            compiler.setMapFile(mapCopy);
×
122
            purgeUnimportedFiles(model);
×
123

124
            gui.sendProgress("Check program");
×
125
            compiler.checkProg(model);
×
126

127
            if (gui.getErrorCount() > 0) {
×
128
                throw new RequestFailedException(MessageType.Warning, "Could not compile project: ", gui.getErrorList().get(0));
×
129
            }
130

131
            print("translating program ... ");
×
132
            compiler.translateProgToIm(model);
×
133

134
            if (gui.getErrorCount() > 0) {
×
135
                throw new RequestFailedException(MessageType.Error, "Could not compile project (error in translation): " + gui.getErrorList().get(0));
×
136
            }
137

138
            timeTaker.measure("Runinng Compiletime Functions", () -> compiler.runCompiletime(projectConfigData, isProd, runArgs.isCompiletimeCache()));
×
139

140
            if (runArgs.isLua()) {
×
141
                print("translating program to Lua ... ");
×
142
                Optional<LuaCompilationUnit> luaCode = Optional.ofNullable(compiler.transformProgToLua());
×
143

144
                if (!luaCode.isPresent()) {
×
145
                    print("Could not compile project\n");
×
146
                    throw new RuntimeException("Could not compile project (error in LUA translation)");
×
147
                }
148

149
                StringBuilder sb = new StringBuilder();
×
150
                luaCode.get().print(sb, 0);
×
151

152
                String compiledMapScript = sb.toString();
×
153
                File buildDir = getBuildDir();
×
154
                File outFile = new File(buildDir, "compiled.lua");
×
155
                Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile);
×
156
                return outFile;
×
157

158
            } else {
159
                print("translating program to jass ... ");
×
160
                compiler.transformProgToJass();
×
161

162
                Optional<JassProg> jassProg = Optional.ofNullable(compiler.getProg());
×
163
                if (!jassProg.isPresent()) {
×
164
                    print("Could not compile project\n");
×
165
                    throw new RuntimeException("Could not compile project (error in JASS translation)");
×
166
                }
167

168
                gui.sendProgress("Printing program");
×
169
                JassPrinter printer = new JassPrinter(!runArgs.isOptimize(), jassProg.get());
×
170
                String compiledMapScript = printer.printProg();
×
171
                File buildDir = getBuildDir();
×
172
                File outFile = new File(buildDir, "compiled.j.txt");
×
173
                Files.write(compiledMapScript.getBytes(Charsets.UTF_8), outFile);
×
174

175
                if (!runArgs.isDisablePjass()) {
×
176
                    gui.sendProgress("Running PJass");
×
177
                    Pjass.Result pJassResult = Pjass.runPjass(outFile,
×
178
                        new File(buildDir, "common.j").getAbsolutePath(),
×
179
                        new File(buildDir, "blizzard.j").getAbsolutePath());
×
180
                    WLogger.info(pJassResult.getMessage());
×
181
                    if (!pJassResult.isOk()) {
×
182
                        for (CompileError err : pJassResult.getErrors()) {
×
183
                            gui.sendError(err);
×
184
                        }
×
185
                        throw new RuntimeException("Could not compile project (PJass error)");
×
186
                    }
187
                }
188

189
                if (runArgs.isHotStartmap()) {
×
190
                    gui.sendProgress("Running JHCR");
×
191
                    return runJassHotCodeReload(outFile);
×
192
                }
193
                return outFile;
×
194
            }
195
        } catch (Exception e) {
×
196
            throw new RuntimeException(e);
×
197
        }
198
    }
199

200
    private File runJassHotCodeReload(File mapScript) throws IOException, InterruptedException {
201
        File buildDir = getBuildDir();
×
202
        File commonJ = new File(buildDir, "common.j");
×
203
        File blizzardJ = new File(buildDir, "blizzard.j");
×
204

205
        if (!commonJ.exists()) {
×
206
            throw new IOException("Could not find file " + commonJ.getAbsolutePath());
×
207
        }
208

209
        if (!blizzardJ.exists()) {
×
210
            throw new IOException("Could not find file " + blizzardJ.getAbsolutePath());
×
211
        }
212

213
        ProcessBuilder pb = new ProcessBuilder(langServer.getConfigProvider().getJhcrExe(), "init", commonJ.getName(), blizzardJ.getName(), mapScript.getName());
×
214
        pb.directory(buildDir);
×
215
        Utils.exec(pb, Duration.ofSeconds(30), System.err::println);
×
216
        return new File(buildDir, "jhcr_war3map.j");
×
217
    }
218

219
    /**
220
     * removes everything compilation unit which is neither
221
     * - inside a wurst folder
222
     * - a jass file
223
     * - imported by a file in a wurst folder
224
     */
225
    private void purgeUnimportedFiles(WurstModel model) {
226

227
        Set<CompilationUnit> imported = model.stream()
×
228
            .filter(cu -> isInWurstFolder(cu.getCuInfo().getFile()) || cu.getCuInfo().getFile().endsWith(".j")).collect(Collectors.toSet());
×
229
        addImports(imported, imported);
×
230

231
        model.removeIf(cu -> !imported.contains(cu));
×
232
    }
×
233

234
    private boolean isInWurstFolder(String file) {
235
        Path p = Paths.get(file);
×
236
        Path w;
237
        try {
238
            w = workspaceRoot.getPath();
×
239
        } catch (FileNotFoundException e) {
×
240
            return false;
×
241
        }
×
242
        return p.startsWith(w)
×
243
            && java.nio.file.Files.exists(p)
×
244
            && Utils.isWurstFile(file);
×
245
    }
246

247
    protected File getBuildDir() {
248
        File buildDir;
249
        try {
250
            buildDir = new File(workspaceRoot.getFile(), "_build");
×
251
        } catch (FileNotFoundException e) {
×
252
            throw new RuntimeException("Cannot get build dir", e);
×
253
        }
×
254
        if (!buildDir.exists()) {
×
255
            UtilsIO.mkdirs(buildDir);
×
256
        }
257
        return buildDir;
×
258
    }
259

260
    private void addImports(Set<CompilationUnit> result, Set<CompilationUnit> toAdd) {
261
        Set<CompilationUnit> imported =
×
262
            toAdd.stream()
×
263
                .flatMap((CompilationUnit cu) -> cu.getPackages().stream())
×
264
                .flatMap((WPackage p) -> p.getImports().stream())
×
265
                .map(WImport::attrImportedPackage)
×
266
                .filter(Objects::nonNull)
×
267
                .map(WPackage::attrCompilationUnit)
×
268
                .collect(Collectors.toSet());
×
269
        boolean changed = result.addAll(imported);
×
270
        if (changed) {
×
271
            // recursive call terminates, as there are only finitely many compilation units
272
            addImports(result, imported);
×
273
        }
274
    }
×
275

276
    protected void print(String s) {
277
        WLogger.info(s);
×
278
    }
×
279

280
    protected void println(String s) {
281
        WLogger.info(s);
×
282
    }
×
283

284

285
    protected File compileScript(WurstGui gui, ModelManager modelManager, List<String> compileArgs, Optional<File> mapCopy,
286
                                 WurstProjectConfigData projectConfigData, boolean isProd, File scriptFile) throws Exception {
287
        RunArgs runArgs = new RunArgs(compileArgs);
×
288
        gui.sendProgress("Compiling Script");
×
289
        print("Compile Script : ");
×
290
        for (File dep : modelManager.getDependencyWurstFiles()) {
×
291
            WLogger.info("dep: " + dep.getPath());
×
292
        }
×
293
        print("Dependencies done.");
×
294
        if (safeCompilation != RunMap.SafetyLevel.QuickAndDirty) {
×
295
            // it is safer to rebuild the project, instead of taking the current editor state
296
            gui.sendProgress("Cleaning project");
×
297
            modelManager.clean();
×
298
            gui.sendProgress("Building project");
×
299
            modelManager.buildProject();
×
300
        }
301

302
        if (modelManager.hasErrors()) {
×
303
            for (CompileError compileError : modelManager.getParseErrors()) {
×
304
                gui.sendError(compileError);
×
305
            }
×
306
            throw new RequestFailedException(MessageType.Warning, "Cannot run code with syntax errors.");
×
307
        }
308

309
        WurstModel model = modelManager.getModel();
×
310
        if (safeCompilation != RunMap.SafetyLevel.QuickAndDirty) {
×
311
            // compilation will alter the model (e.g. remove unused imports),
312
            // so it is safer to create a copy
313
            model = ModelManager.copy(model);
×
314
        }
315

316
        return compileMap(modelManager.getProjectPath(), gui, mapCopy, runArgs, model, projectConfigData, isProd);
×
317
    }
318

319

320
    protected CompilationResult compileScript(ModelManager modelManager, WurstGui gui, Optional<File> testMap, WurstProjectConfigData projectConfigData, File buildDir, boolean isProd) throws Exception {
321
        if (testMap.isPresent() && testMap.get().exists()) {
×
322
            boolean deleteOk = testMap.get().delete();
×
323
            if (!deleteOk) {
×
324
                throw new RequestFailedException(MessageType.Error, "Could not delete old mapfile: " + testMap);
×
325
            }
326
        }
327
        if (map.isPresent() && testMap.isPresent()) {
×
328
            Files.copy(map.get(), testMap.get());
×
329
        }
330

331
        CompilationResult result;
332

333
        if (runArgs.isHotReload()) {
×
334
            // For hot reload use cached war3map if it exists
335
            result = new CompilationResult();
×
336
            result.script = new File(buildDir, "war3mapj_with_config.j.txt");
×
337
            if (!result.script.exists()) {
×
338
                result.script = new File(new File(workspaceRoot.getFile(), "wurst"), "war3map.j");
×
339
            }
340
            if (!result.script.exists()) {
×
341
                throw new RequestFailedException(MessageType.Error, "Could not find war3map.j file");
×
342
            }
343
        } else {
344
            timeTaker.beginPhase("load map script");
×
345
            File scriptFile = loadMapScript(testMap, modelManager, gui);
×
346
            timeTaker.endPhase();
×
347
            result = applyProjectConfig(gui, testMap, buildDir, projectConfigData, scriptFile);
×
348
        }
349

350

351
        // first compile the script:
352
        result.script = compileScript(gui, modelManager, compileArgs, testMap, projectConfigData, isProd, result.script);
×
353

354
        Optional<WurstModel> model = Optional.ofNullable(modelManager.getModel());
×
355
        if (!model.isPresent()
×
356
            || model
357
            .get()
×
358
            .stream()
×
359
            .noneMatch((CompilationUnit cu) -> cu.getCuInfo().getFile().endsWith("war3map.j"))) {
×
360
            println("No 'war3map.j' file could be found inside the map nor inside the wurst folder");
×
361
            println("If you compile the map with WurstPack once, this file should be in your wurst-folder. ");
×
362
            println("We will try to start the map now, but it will probably fail. ");
×
363
        }
364
        return result;
×
365
    }
366

367
    private static Long lastMapModified = 0L;
×
368

369
    private File loadMapScript(Optional<File> mapCopy, ModelManager modelManager, WurstGui gui) throws Exception {
370
        File scriptFile = new File(new File(workspaceRoot.getFile(), "wurst"), "war3map.j");
×
371
        // If runargs are no extract, either use existing or throw error
372
        // Otherwise try loading from map, if map was saved with wurst, try existing script, otherwise error
373
        if (!mapCopy.isPresent() || runArgs.isNoExtractMapScript()) {
×
374
            if (scriptFile.exists()) {
×
375
                modelManager.syncCompilationUnit(WFile.create(scriptFile));
×
376
                return scriptFile;
×
377
            } else {
378
                throw new CompileError(new WPos("", new LineOffsets(), 0, 0),
×
379
                    "RunArg noExtractMapScript is set but no mapscript is provided inside the wurst folder");
380
            }
381
        }
382
        long mapLastModified = mapCopy.get().lastModified();
×
383
        if (mapLastModified > lastMapModified) {
×
384
            lastMapModified = mapLastModified;
×
385
            WLogger.info("extracting mapscript");
×
386
            byte[] extractedScript = null;
×
387
            try (@Nullable MpqEditor mpqEditor = MpqEditorFactory.getEditor(mapCopy, true)) {
×
388
                if (mpqEditor.hasFile("war3map.j")) {
×
389
                    extractedScript = mpqEditor.extractFile("war3map.j");
×
390
                }
391
            }
392
            if (extractedScript == null) {
×
393
                if (scriptFile.exists()) {
×
394
                    String msg = "No war3map.j in map file, using old extracted file";
×
395
                    WLogger.info(msg);
×
396
                } else {
×
397
                    CompileError err = new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0),
×
398
                        "No war3map.j found in map file.");
399
                    gui.showInfoMessage(err.getMessage());
×
400
                    WLogger.severe(err);
×
401
                }
×
402
            } else if (new String(extractedScript, StandardCharsets.UTF_8).startsWith(JassPrinter.WURST_COMMENT_RAW)) {
×
403
                WLogger.info("map has already been compiled with wurst");
×
404
                // file generated by wurst, do not use
405
                if (scriptFile.exists()) {
×
406
                    String msg = "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Using war3map.j from Wurst directory instead.";
×
407
                    WLogger.info(msg);
×
408
                } else {
×
409
                    CompileError err = new CompileError(new WPos(mapCopy.toString(), new LineOffsets(), 0, 0),
×
410
                        "Cannot use war3map.j from map file, because it already was compiled with wurst. " + "Please add war3map.j to the wurst directory.");
411
                    gui.showInfoMessage(err.getMessage());
×
412
                    WLogger.severe(err);
×
413
                }
×
414
            } else {
415
                WLogger.info("new map, use extracted");
×
416
                // write mapfile from map to workspace
417
                Files.write(extractedScript, scriptFile);
×
418
            }
419
        } else {
×
420
            System.out.println("Map not modified, not extracting script");
×
421
        }
422

423

424
        return scriptFile;
×
425
    }
426

427
    private CompilationResult applyProjectConfig(WurstGui gui, Optional<File> testMap, File buildDir, WurstProjectConfigData projectConfig, File scriptFile) throws FileNotFoundException {
428
        AtomicReference<CompilationResult> result = new AtomicReference<>();
×
429
        gui.sendProgress("Applying Map Config...");
×
430
        timeTaker.measure("Applying Map Config", () -> {
×
431
            try {
432
                result.set(ProjectConfigBuilder.apply(projectConfig, testMap.get(), scriptFile, buildDir, runArgs, w3data));
×
433
            } catch (IOException e) {
×
434
                throw new RuntimeException(e);
×
435
            }
×
436
        });
×
437
        return result.get();
×
438
    }
439

440
    private W3InstallationData getBestW3InstallationData() throws RequestFailedException {
441
        if (Orient.isLinuxSystem()) {
×
442
            // no Warcraft installation supported on Linux
443
            return new W3InstallationData(Optional.empty(), Optional.empty());
×
444
        }
445
        if (wc3Path.isPresent() && StringUtils.isNotBlank(wc3Path.get())) {
×
446
            W3InstallationData w3data = new W3InstallationData(langServer, new File(wc3Path.get()));
×
447
            if (w3data.getWc3PatchVersion().isEmpty()) {
×
448
                throw new RequestFailedException(MessageType.Error, "Could not find Warcraft III installation at specified path: " + wc3Path);
×
449
            }
450

451
            return w3data;
×
452
        } else {
453
            return new W3InstallationData(langServer);
×
454
        }
455
    }
456

457
    protected void injectMapData(WurstGui gui, Optional<File> testMap, CompilationResult result) throws Exception {
458
        gui.sendProgress("Injecting map data");
×
459
        try (MpqEditor mpqEditor = MpqEditorFactory.getEditor(testMap)) {
×
460
            String mapScriptName;
461
            if (runArgs.isLua()) {
×
462
                mapScriptName = "war3map.lua";
×
463
            } else {
464
                mapScriptName = "war3map.j";
×
465
            }
466
            // delete both original mapscripts, just to be sure:
467
            mpqEditor.deleteFile("war3map.j");
×
468
            mpqEditor.deleteFile("war3map.lua");
×
469
            if (result.w3i != null) {
×
470
                mpqEditor.deleteFile(W3I.GAME_PATH.getName());
×
471
                mpqEditor.insertFile(W3I.GAME_PATH.getName(), result.w3i);
×
472
            }
473
            mpqEditor.insertFile(mapScriptName, result.script);
×
474
        }
475
    }
×
476
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc