-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.ts
More file actions
246 lines (215 loc) · 9.44 KB
/
build.ts
File metadata and controls
246 lines (215 loc) · 9.44 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
#!/usr/bin/env bun
/**
* Build script – compiles github-code-search.ts into a standalone binary.
*
* Usage:
* bun run build.ts # current platform
* bun run build.ts --target=bun-linux-x64 # cross-compile
*
* Supported targets (Bun executables):
* bun-linux-x64 bun-linux-x64-baseline bun-linux-arm64
* bun-darwin-x64 bun-darwin-arm64
* bun-windows-x64 bun-windows-x64-baseline bun-windows-x64-modern
* bun-windows-arm64
*/
import { version, description, author, license } from "./package.json" with { type: "json" };
// ─── Pure helpers (exported for unit tests) ───────────────────────────────────
export type ParsedTarget = {
os: string;
arch: string;
};
/**
* Derive a canonical { os, arch } pair from a Bun target string such as
* "bun-windows-x64-modern" or "bun-linux-arm64".
* Returns { os: process.platform, arch: process.arch } when `t` is null/undefined.
*/
export function parseTarget(t: string | null | undefined): ParsedTarget {
if (!t)
return {
// Normalize Node's "win32" platform name to the canonical "windows" used
// throughout this build script so isWindowsTarget() / getOutfile() work
// correctly when building natively on Windows without a --target flag.
os: process.platform === "win32" ? "windows" : process.platform,
arch: process.arch === "x64" ? "x64" : process.arch,
};
const s = t.replace(/^bun-/, "");
if (s.startsWith("linux-x64-baseline")) return { os: "linux", arch: "x64-baseline" };
if (s.startsWith("linux-x64")) return { os: "linux", arch: "x64" };
if (s.startsWith("linux-arm64-musl")) return { os: "linux", arch: "arm64-musl" };
if (s.startsWith("linux-arm64")) return { os: "linux", arch: "arm64" };
if (s.startsWith("darwin-x64")) return { os: "darwin", arch: "x64" };
if (s.startsWith("darwin-arm64")) return { os: "darwin", arch: "arm64" };
if (s.startsWith("windows-x64-baseline")) return { os: "windows", arch: "x64-baseline" };
if (s.startsWith("windows-x64-modern")) return { os: "windows", arch: "x64-modern" };
if (s.startsWith("windows-x64")) return { os: "windows", arch: "x64" };
if (s.startsWith("windows-arm64")) return { os: "windows", arch: "arm64" };
// Fix: normalize win32 → windows for unrecognised target strings (e.g. future targets).
return { os: process.platform === "win32" ? "windows" : process.platform, arch: process.arch };
}
/**
* Returns true when the given os value targets Windows.
*/
export function isWindowsTarget(targetOs: string): boolean {
return targetOs === "windows";
}
/**
* Compute the output filename for the binary.
*
* target=bun-linux-x64 → dist/github-code-search-linux-x64
* target=bun-windows-x64 → dist/github-code-search-windows-x64.exe
* target=bun-windows-x64-modern → dist/github-code-search-windows-x64-modern.exe
* target=null (native) → dist/github-code-search
*/
export function getOutfile(targetOs: string, target: string | null): string {
const ext = isWindowsTarget(targetOs) ? ".exe" : "";
const suffix = target ? `-${target.replace(/^bun-/, "")}` : "";
return `./dist/github-code-search${suffix}${ext}`;
}
export type WindowsMeta = {
iconPath?: string;
title?: string;
publisher?: string;
appVersion?: string;
description?: string;
copyright?: string;
};
/**
* Build the `compile` options forwarded to Bun.build().
* Windows binaries receive metadata-enriching flags so the resulting .exe
* is not misidentified as "bun" by the OS and shows correct file properties.
* See: https://bun.sh/docs/bundler/executables#windows-specific-flags
*
* @param meta.iconPath Absolute path to .ico — must be absolute so Bun
* resolves it correctly regardless of the caller's CWD.
*/
export function getBuildCompileOptions(
targetOs: string,
outfile: string,
meta: WindowsMeta = {},
): NonNullable<Parameters<typeof Bun.build>[0]["compile"]> {
if (isWindowsTarget(targetOs)) {
return {
outfile,
windows: {
// iconPath must be absolute — relative paths are resolved from the
// process CWD which may differ from the script location.
icon: meta.iconPath,
// hideConsole: true — prevents Windows from spawning a detached console
// window when the binary is launched from a GUI context (e.g. Explorer).
// The binary still runs correctly in any terminal emulator / cmd / pwsh.
hideConsole: true,
title: meta.title,
publisher: meta.publisher,
version: meta.appVersion,
description: meta.description,
copyright: meta.copyright,
},
};
}
return { outfile };
}
/**
* Extract the --target=<value> argument from a process argv array.
* Pure function — extracted so it can be unit-tested without touching process.argv.
*/
export function parseTargetArg(argv: string[]): string | null {
return argv.find((a) => a.startsWith("--target="))?.slice("--target=".length) ?? null;
}
/**
* Format the human-readable version label printed during the build.
* Pure function — extracted so it can be unit-tested.
*/
export function buildLabel(ver: string, commit: string, os: string, arch: string): string {
return `${ver} (${commit} · ${os}/${arch})`;
}
/**
* Format the copyright string embedded in Windows EXE metadata.
* Pure function — extracted so it can be unit-tested.
*/
export function buildCopyrightLine(year: number, authorName: string, lic: string): string {
return `Copyright © ${year} ${authorName} — ${lic}`;
}
// ─── CLI args ─────────────────────────────────────────────────────────────────
// Fix: guard with import.meta.main so this block does not run when build.ts is
// imported by unit tests — see issue #108.
if (import.meta.main) {
const target = parseTargetArg(process.argv);
// ─── Derive OS / arch from target ────────────────────────────────────────
const { os: targetOs, arch: targetArch } = parseTarget(target);
// ─── Output path ─────────────────────────────────────────────────────────
const outfile = getOutfile(targetOs, target);
// ─── Git commit hash ─────────────────────────────────────────────────────
let commit = "dev";
try {
const proc = Bun.spawn(["git", "rev-parse", "--short", "HEAD"], {
stdout: "pipe",
stderr: "pipe",
});
await proc.exited;
commit = (await new Response(proc.stdout).text()).trim() || "dev";
} catch {
// Not a git repo or git not available
}
// ─── Build ───────────────────────────────────────────────────────────────
const label = buildLabel(version, commit, targetOs, targetArch);
console.log(`Building github-code-search v${label}… outfile=${outfile}`);
if (target) console.log(` Target: ${target}`);
// Absolute path to the Windows icon — must be absolute so Bun resolves it
// correctly when the script is invoked from any working directory.
const icoPath = `${import.meta.dir}/docs/public/icons/favicon.ico`;
const currentYear = new Date().getFullYear();
const authorName = typeof author === "string" ? author : author.name;
await Bun.$`mkdir -p dist`;
await Bun.build({
entrypoints: ["./github-code-search.ts"],
minify: true,
// Fix: bytecode: true causes the binary to fail on Windows — removed.
compile: getBuildCompileOptions(targetOs, outfile, {
iconPath: icoPath,
title: "github-code-search",
publisher: authorName,
appVersion: version,
description,
copyright: buildCopyrightLine(currentYear, authorName, license),
}),
define: {
BUILD_VERSION: JSON.stringify(version),
BUILD_COMMIT: JSON.stringify(commit),
BUILD_TARGET_OS: JSON.stringify(targetOs),
BUILD_TARGET_ARCH: JSON.stringify(targetArch),
},
target: target ? (target as Parameters<typeof Bun.build>[0]["target"]) : undefined,
});
console.log(` Built ${outfile}`);
// ─── Ad-hoc codesign (macOS only) ────────────────────────────────────────
if (targetOs === "darwin" && process.platform === "darwin") {
const sign = Bun.spawn(
[
"codesign",
"--deep",
"--force",
"--sign",
"-",
"--entitlements",
`${import.meta.dir}/entitlements.plist`,
outfile,
],
{ stdout: "inherit", stderr: "inherit" },
);
const signCode = await sign.exited;
if (signCode !== 0) {
console.error(`codesign failed (exit ${signCode})`);
process.exit(signCode);
}
console.log(` Codesigned ${outfile}`);
const verify = Bun.spawn(["codesign", "--verify", "--verbose", outfile], {
stdout: "inherit",
stderr: "inherit",
});
const verifyCode = await verify.exited;
if (verifyCode !== 0) {
console.error(`codesign verification failed (exit ${verifyCode})`);
process.exit(verifyCode);
}
}
}