forked from nommiin/builder
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbuild.js
295 lines (289 loc) · 12.9 KB
/
build.js
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
Builder = Object.assign(Builder, {
Extension: (Builder.Platform.includes("Windows") == true ? "win" : "ios"),
Command: require("child_process"),
Compiler: undefined,
ErrorMet: false,
Runner: [],
Errors: [],
Outpath: "",
Runtime: "",
Cache: "",
Drive: "",
Drives: [],
Run: function(fork) {
return BuilderCompile.run(fork);
},
Stop: function() {
// Make sure a GMS2 project is open!
if (Builder.ProjectVersion($gmedit["gml.Project"].current) != 2) return;
// Display errors and kill processes!
if (Builder.ErrorMet == true) Builder.Display();
if (Builder.Compiler != undefined) {
Builder.Compiler.kill();
Builder.Compiler = undefined;
}
if (Builder.Runner.length > 0) {
Builder.Runner.forEach((e) => {
e.kill();
});
}
},
Fork: function() {
// Make sure a GMS2 project is open!
if (Builder.ProjectVersion($gmedit["gml.Project"].current) != 2) return;
// Fork runner and add it to process list!
Builder.Runner.push(Builder.Spawn(Builder.Runtime, Builder.Outpath, Builder.Name, true));
},
CleanRuntime: function() {
// you can run the game again
for (let item of Builder.MenuItems.list) {
item.enabled = item.id.includes("-run") || item.id.includes("-clean");
}
BuilderDrives.removeCurrent();
Builder.Runner = [];
},
CleanCache: function(_then) {
const cacheDir = Builder.Cache;
if (!cacheDir) return 1;
if (!Electron_FS.existsSync(cacheDir)) return 2;
Electron_FS.rmdir(cacheDir, { recursive: true }, (err) => {
if (err) {
console.error(`Couldn't clean cache directory ${cacheDir}: `, err);
} else {
console.log(`Cleaned up cache directory ${cacheDir}`);
}
if (_then) _then(err);
});
return 0;
},
CleanGUI: function() {
console.log("clean?")
let result = Builder.CleanCache((err) => {
if (err) {
Electron_Dialog.showErrorBox({
type: "error",
title: "Builder",
message: "Couldn't clean cache in\n" + Builder.Cache + "\n" + err
});
} else {
Electron_Dialog.showMessageBox({
type: "info",
title: "Builder",
message: "Successfully cleaned cache in\n" + Builder.Cache
});
}
});
switch (result) {
case 1: Electron_Dialog.showMessageBox({
type: "error",
title: "Builder",
message: "No idea where the cache is - run the game first"
}); break;
case 2: Electron_Dialog.showMessageBox({
type: "info",
title: "Builder",
message: "Builder-specific cache directory doesn't exist - no action needed"
}); break;
}
},
Parse: function(string, type) {
// Parse error output!
let Contents = (string.toString()).split("\n");
for(let i = 0; i < Contents.length; i++) {
let Message = Contents[i];
switch (type) {
case 0: { // GMAssetCompiler.exe
if (Message.slice(0, 8) == "Error : ") {
Builder.Errors.push(Message.slice(8).trim());
Builder.ErrorMet = true;
} else if (Message.startsWith("Final Compile") == true && Builder.ErrorMet == true) {
return 1;
}
break;
}
case 1: { // Runner.exe
if (BuilderPreferences.current.displayLine == true && (Message.startsWith("ERROR!!! :: ") == true && Contents[i + 1].startsWith("FATAL ERROR") == true)) {
for(let j = i + 1; j < Contents.length; j++) {
if (Contents[j].startsWith("stack frame is") == true) {
let Stack = Builder.ParseDescriptor(Contents[++j]);
if ($gmedit["ui.OpenDeclaration"].openLocal(Stack.Asset, Stack.Line) == true) {
setTimeout(() => {
let Offset = 0;
if (Stack.Type == "Object") {
for(let Event = Builder.GetEvent(Stack.Event), k = 0; k < aceEditor.session.getLength(); k++) {
if (aceEditor.session.getLine(k).startsWith("#event " + Event) == true) {
Offset = ++k;
break;
}
}
}
aceEditor.gotoLine(Stack.Line + Offset);
}, 10);
}
break;
}
}
}
break;
}
}
}
return 0;
},
ParseDescriptor: function(string) {
// Parse error descriptor and return object about it!
let Descriptor = {};
if (string.startsWith("gml_")) string = string.slice(4);
Descriptor.Type = string.slice(0, string.indexOf("_"));
string = string.slice(Descriptor.Type.length + 1);
Descriptor.Line = parseInt(string.slice(string.lastIndexOf("(") + 1, string.lastIndexOf(")")).replace("line", ""));
string = string.slice(0, string.lastIndexOf("(")).trim();
if (Descriptor.Type == "Object") {
Descriptor.Event = string.slice(string.lastIndexOf("_", string.lastIndexOf("_") - 1) + 1);
string = string.slice(0, (Descriptor.Event.length * -1) - 1);
}
Descriptor.Asset = string;
return Descriptor;
},
GetEvent: function(event) {
// Turn descriptor event into GMEdit event name!
let SubEvent = event.slice(event.lastIndexOf("_") + 1), GmlEvent = $gmedit["parsers.GmlEvent"];
event = event.slice(0, event.lastIndexOf("_"));
for(let i = 0; i < GmlEvent.t2sc.length; i++) {
if (GmlEvent.t2sc[i] == event) {
return GmlEvent.i2s[i][SubEvent];
}
}
return "";
},
Display: function() {
// Display errors in new tab!
let project = $gmedit["gml.Project"].current;
let GmlFile = $gmedit["gml.file.GmlFile"];
let output = new GmlFile(`Compilation Errors`, null, $gmedit["file.kind.gml.KGmlSearchResults"].inst, `// Compile failed with ${Builder.Errors.length} error${(Builder.Errors.length == 1 ? "" : "s")}\n\n`);
output.Write = (e) => {output.editor.session.setValue(output.editor.session.getValue() + "\n" + e); }
for (let error of Builder.Errors) {
let colonPos = error.indexOf(":");
let descriptor = Builder.ParseDescriptor(error.slice(0, colonPos).trim());
let errorText = error.slice(colonPos + 1).trim();
let errorLine = "";
grabErrorLine: {
let resourceGUID = project.yyResourceGUIDs[descriptor.Asset];
if (resourceGUID == null) break grabErrorLine;
let resource = project.yyResources[resourceGUID];
if (resource == null) break grabErrorLine;
let resourcePath;
if (resource.Value) {
resourcePath = resource.Value.resourcePath;
} else if (resource.id) {
resourcePath = resource.id.path;
} else break grabErrorLine;
let path = resourcePath.slice(0, -(3 + descriptor.Asset.length));
switch (descriptor.Type) {
case "Object": path += descriptor.Event; break;
default: path += descriptor.Asset; break;
}
try {
errorLine = project.readTextFileSync(path + ".gml").split("\n")[descriptor.Line].trim();
} catch (_) {}
};
output.Write(`// Error in ${descriptor.Type[0].toLowerCase() + descriptor.Type.slice(1)} at @[${descriptor.Asset}${(descriptor.Type == "Object" ? `(${Builder.GetEvent(descriptor.Event)})` : "")}:${descriptor.Line + 1}]:\n// ${errorText}\n${errorLine}\n`)
}
GmlFile.openTab(output);
},
Spawn: function(runtime, outputPath, name, isFork, callback) {
// Spawn an instance of the runner!
let runnerPath = Builder.RunnerPath;
runnerPath ??= (Builder.Platform == "win"
? `${runtime}/windows/Runner.exe`
: `${runtime}/mac/YoYo Runner.app/Contents/MacOS/Mac_Runner`
);
let builderSettings = $gmedit["gml.Project"].current.properties.builderSettings;
let args = [
"-game", `${outputPath}/${name}.${Builder.Extension}`
];
const parseArgs = (str) => {
if (str == null) return [];
str = str.trim();
if (str == "") return [];
if (str.startsWith("[")) try {
return JSON.parse(str);
} catch (e) {
console.log('Error parsing', str, e);
return [];
}
let result = [];
let start = 0, acc = "";
let pos = 0, len = str.length;
let isInQuotes = false
const flush = (till) => {
if (!(till > start || acc != "")) return;
result.push(acc + str.substring(start, till));
acc = "";
};
while (pos < len) {
let c = str.charAt(pos++);
if (c == ' ') {
if (isInQuotes) {
//
} else {
flush(pos - 1);
start = pos;
}
} else if (c == '"') {
if (pos < len && str.charAt(pos) == '"') {
acc += str.substring(start, pos);
start = ++pos;
} else {
flush(pos - 1);
start = pos;
isInQuotes = !isInQuotes;
}
}
}
flush(pos);
return result;
};
if (builderSettings?.steamAppID != null) {
if (builderSettings?.steamAppID != 0) args.push("-debug_steamapi");
} else if (Electron_FS.existsSync(`${outputPath}/steam_appid.txt`)) {
args.push("-debug_steamapi");
}
{
let extraArguments = builderSettings?.extraArguments;
args = args.concat(parseArgs(extraArguments));
}
if (isFork) {
let forkArguments = builderSettings?.forkArguments ?? BuilderPreferences.current.forkArguments;
args = args.concat(parseArgs(forkArguments));
}
let output = BuilderOutput.open(isFork);
output.write(`Running ${[runnerPath].concat(args).join(" ")}...\n`);
let runner = Builder.Command.spawn(runnerPath, args, {
cwd: outputPath
});
runner.stdout.on("data", (e) => {
let text = e.toString();
switch (Builder.Parse(text, 1)) {
default: output.write(text, false);
}
});
runner.addListener("close", function(code) {
let runners = Builder.Runner;
let i = runners.indexOf(this);
if (i >= 0) runners.splice(i, 1);
if (code != 0 && code != null) output.write(`Runner exited with non-zero status (0x${code.toString(16)} = ${code})`)
if (callback) callback(code);
Builder.CleanRuntime();
if (runners.length == 0 && BuilderPreferences.current.cleanAfterRun) Builder.CleanCache();
});
return runner;
},
Sanitize: (value) => { return value.replace(/ /g, "_"); },
Random: () => { return Math.round(Math.random() * 4294967295).toString(16).padStart(8, "0").toUpperCase(); },
GetTime: (t) => {
if (t == null) t = new Date();
return `${t.getHours().toString().padStart(2, "0")}:${t.getMinutes().toString().padStart(2, "0")}:${t.getSeconds().toString().padStart(2, "0")}`
},
SessionsFile: new $gmedit["electron.ConfigFile"]("session", "builder-projects"),
});