{{ message }}
forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.mjs
More file actions
executable file
·299 lines (249 loc) · 8.07 KB
/
Copy pathbuild.mjs
File metadata and controls
executable file
·299 lines (249 loc) · 8.07 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
import { spawn as nodeSpawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { basename, join, relative, resolve } from "node:path";
import {
formatAnnotationToHtml,
getEnv,
isCI,
isWindows,
parseAnnotations,
parseBoolean,
printEnvironment,
reportAnnotationToBuildKite,
startGroup,
} from "./utils.mjs";
const isWindowsARM64 = isWindows && process.arch === "arm64";
if (globalThis.Bun) {
await import("./glob-sources.mjs");
}
// https://cmake.org/cmake/help/latest/manual/cmake.1.html#generate-a-project-buildsystem
const generateFlags = [
["-S", "string", "path to source directory"],
["-B", "string", "path to build directory"],
["-D", "string", "define a build option (e.g. -DCMAKE_BUILD_TYPE=Release)"],
["-G", "string", "build generator (e.g. -GNinja)"],
["-W", "string", "enable warnings (e.g. -Wno-dev)"],
["--fresh", "boolean", "force a fresh build"],
["--log-level", "string", "set the log level"],
["--debug-output", "boolean", "print debug output"],
["--toolchain", "string", "the toolchain to use"],
];
// https://cmake.org/cmake/help/latest/manual/cmake.1.html#generate-a-project-buildsystem
const buildFlags = [
["--config", "string", "build configuration (e.g. --config Release)"],
["--target", "string", "build target"],
["-t", "string", "same as --target"],
["--parallel", "number", "number of parallel jobs"],
["-j", "number", "same as --parallel"],
["--verbose", "boolean", "enable verbose output"],
["-v", "boolean", "same as --verbose"],
];
async function build(args) {
const startTime = Date.now();
if (process.platform === "win32" && !process.env["VSINSTALLDIR"]) {
const shellPath = join(import.meta.dirname, "vs-shell.ps1");
const scriptPath = import.meta.filename;
return spawn("pwsh", ["-NoProfile", "-NoLogo", "-File", shellPath, process.argv0, scriptPath, ...args]);
}
if (isCI) {
printEnvironment();
}
const env = {
...process.env,
FORCE_COLOR: "1",
CLICOLOR_FORCE: "1",
};
const generateOptions = parseOptions(args, generateFlags);
const buildOptions = parseOptions(args, buildFlags);
const ciCppBuild = isCI && !!process.env.BUN_CPP_ONLY;
const buildPath = resolve(generateOptions["-B"] || buildOptions["--build"] || "build");
generateOptions["-B"] = buildPath;
buildOptions["--build"] = buildPath;
if (!generateOptions["-S"]) {
generateOptions["-S"] = process.cwd();
}
if (!generateOptions["-DCACHE_STRATEGY"]) {
generateOptions["-DCACHE_STRATEGY"] = parseBoolean(getEnv("RELEASE", false) || "false") ? "none" : "auto";
}
const toolchain = generateOptions["--toolchain"];
if (toolchain) {
const toolchainPath = resolve(import.meta.dirname, "..", "cmake", "toolchains", `${toolchain}.cmake`);
generateOptions["--toolchain"] = toolchainPath;
}
// Windows ARM64: log detection (compiler is selected by CMake/toolchain)
if (isWindowsARM64) {
console.log("Windows ARM64 detected");
}
const generateArgs = Object.entries(generateOptions).flatMap(([flag, value]) =>
flag.startsWith("-D") ? [`${flag}=${value}`] : [flag, value],
);
try {
await Bun.file(buildPath + "/CMakeCache.txt").delete();
} catch (e) {}
await startGroup("CMake Configure", () => spawn("cmake", generateArgs, { env }));
const envPath = resolve(buildPath, ".env");
if (existsSync(envPath)) {
const envFile = readFileSync(envPath, "utf8");
for (const line of envFile.split(/\r\n|\n|\r/)) {
const [key, value] = line.split("=");
env[key] = value;
}
}
const buildArgs = Object.entries(buildOptions)
.sort(([a], [b]) => (a === "--build" ? -1 : a.localeCompare(b)))
.flatMap(([flag, value]) => [flag, value]);
await startGroup("CMake Build", () => spawn("cmake", buildArgs, { env }));
if (ciCppBuild) {
await startGroup("ccache stats", () => {
spawn("ccache", ["--show-stats"], { env });
});
}
printDuration("total", Date.now() - startTime);
}
function isBuildkite() {
return process.env.BUILDKITE === "true";
}
function parseOptions(args, flags = []) {
const options = {};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
for (const [flag, type] of flags) {
if (arg === flag) {
if (type === "boolean") {
options[arg] = undefined;
} else {
options[arg] = args[++i];
}
} else if (arg.startsWith(flag)) {
const delim = arg.indexOf("=");
if (delim === -1) {
options[flag] = arg.slice(flag.length);
} else {
options[arg.slice(0, delim)] = arg.slice(delim + 1);
}
}
}
}
return options;
}
async function spawn(command, args, options, label) {
const effectiveArgs = args.filter(Boolean);
const description = [command, ...effectiveArgs].map(arg => (arg.includes(" ") ? JSON.stringify(arg) : arg)).join(" ");
let env = options?.env;
console.log("$", description);
label ??= basename(command);
const pipe = process.env.CI === "true";
const subprocess = nodeSpawn(command, effectiveArgs, {
stdio: pipe ? "pipe" : "inherit",
...options,
env,
});
let killedManually = false;
function onKill() {
clearOnKill();
if (!subprocess.killed) {
killedManually = true;
subprocess.kill?.();
}
}
function clearOnKill() {
process.off("beforeExit", onKill);
process.off("SIGINT", onKill);
process.off("SIGTERM", onKill);
}
// Kill the entire process tree so everything gets cleaned up. On Windows, job
// control groups make this haappen automatically so we don't need to do this
// on Windows.
if (process.platform !== "win32") {
process.once("beforeExit", onKill);
process.once("SIGINT", onKill);
process.once("SIGTERM", onKill);
}
let timestamp;
subprocess.on("spawn", () => {
timestamp = Date.now();
});
let stdoutBuffer = "";
let done;
if (pipe) {
const stdout = new Promise(resolve => {
subprocess.stdout.on("end", resolve);
subprocess.stdout.on("data", data => {
stdoutBuffer += data.toString();
process.stdout.write(data);
});
});
const stderr = new Promise(resolve => {
subprocess.stderr.on("end", resolve);
subprocess.stderr.on("data", data => {
stdoutBuffer += data.toString();
process.stderr.write(data);
});
});
done = Promise.all([stdout, stderr]);
}
const { error, exitCode, signalCode } = await new Promise(resolve => {
subprocess.on("error", error => {
clearOnKill();
resolve({ error });
});
subprocess.on("exit", (exitCode, signalCode) => {
clearOnKill();
resolve({ exitCode, signalCode });
});
});
if (done) {
await done;
}
printDuration(label, Date.now() - timestamp);
if (exitCode === 0) {
return;
}
if (isBuildkite()) {
let annotated;
try {
const { annotations } = parseAnnotations(stdoutBuffer);
for (const annotation of annotations) {
const content = formatAnnotationToHtml(annotation);
reportAnnotationToBuildKite({
priority: 10,
label: annotation.title || annotation.filename,
content,
});
annotated = true;
}
} catch (error) {
console.error(`Failed to parse annotations:`, error);
}
if (!annotated) {
const content = formatAnnotationToHtml({
filename: relative(process.cwd(), import.meta.filename),
title: "build failed",
content: stdoutBuffer,
source: "build",
level: "error",
});
reportAnnotationToBuildKite({
priority: 10,
label: "build failed",
content,
});
}
}
if (signalCode) {
if (!killedManually) {
console.error(`Command killed: ${signalCode}`);
}
} else {
console.error(`Command exited: code ${exitCode}`);
}
process.exit(exitCode ?? 1);
}
function printDuration(label, duration) {
if (duration > 60000) {
console.log(`${label} took ${(duration / 60000).toFixed(2)} minutes`);
} else {
console.log(`${label} took ${(duration / 1000).toFixed(2)} seconds`);
}
}
build(process.argv.slice(2));
You can’t perform that action at this time.
