-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupgrade.ts
More file actions
336 lines (307 loc) · 12.9 KB
/
Copy pathupgrade.ts
File metadata and controls
336 lines (307 loc) · 12.9 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { existsSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import pc from "picocolors";
import { generateCompletion, getCompletionFilePath } from "./completions.ts";
import type { Shell } from "./completions.ts";
/** Renders a hyperlink in cyan+underline when stdout is a TTY, plain otherwise. */
const upgradeLink = (url: string): string =>
process.stdout.isTTY ? pc.cyan(pc.underline(url)) : url;
// ─── Types ────────────────────────────────────────────────────────────────────
export interface ReleaseAsset {
name: string;
browser_download_url: string;
}
interface GithubRelease {
tag_name: string;
html_url: string;
assets: ReleaseAsset[];
}
// ─── Version comparison ───────────────────────────────────────────────────────
/**
* Returns true if `latest` is strictly newer than `current`.
* Both strings may be prefixed with "v" (e.g. "v1.2.3" or "1.2.3").
* When `current` is "dev" (running from source), always returns false.
*/
const parseVersion = (v: string) => v.replace(/^v/, "").split(".").map(Number);
export function isNewerVersion(current: string, latest: string): boolean {
if (current === "dev") return false;
const a = parseVersion(current);
const b = parseVersion(latest);
const len = Math.max(a.length, b.length);
for (let i = 0; i < len; i++) {
const ai = a[i] ?? 0;
const bi = b[i] ?? 0;
if (bi > ai) return true;
if (ai > bi) return false;
}
return false;
}
// ─── Asset selection ──────────────────────────────────────────────────────────
/**
* Picks the release asset matching the current platform and architecture.
* Expected asset naming convention:
* github-code-search-<platform>-<arch> (e.g. macos-arm64)
* github-code-search-<platform>-<arch>.exe (Windows)
*
* Node.js/Bun platform names are mapped to artifact names:
* darwin → macos
* win32 → windows
*
* A legacy fallback also tries the raw Node.js platform name (darwin, win32)
* so that binaries built before v1.2.1 can still upgrade themselves.
*/
export function selectAsset(
assets: ReleaseAsset[],
platform: string,
arch: string,
): ReleaseAsset | null {
const platformMap: Record<string, string> = {
darwin: "macos",
win32: "windows",
};
const artifactPlatform = platformMap[platform] ?? platform;
const suffix = artifactPlatform === "windows" ? ".exe" : "";
const name = `github-code-search-${artifactPlatform}-${arch}${suffix}`;
// Fix: fall back to legacy platform names (darwin, win32) published alongside
// the canonical names for backward-compat with pre-v1.2.1 binaries — see issue #45
const legacySuffix = platform === "win32" ? ".exe" : "";
const legacyName = `github-code-search-${platform}-${arch}${legacySuffix}`;
return assets.find((a) => a.name === name) ?? assets.find((a) => a.name === legacyName) ?? null;
}
// ─── Blog URL helper ───────────────────────────────────────────────────────────
/**
* Derives the VitePress blog post URL for a given release tag.
* Convention: vX.Y.Z → https://fulll.github.io/github-code-search/blog/release-vX-Y-Z
*/
export function blogPostUrl(tag: string): string {
// Fix: normalize to always have a v-prefix (handles both "v1.2.3" and "1.2.3")
const normalized = `v${tag.replace(/^v/, "")}`;
const slug = normalized.replace(/\./g, "-"); // v1.2.3 → v1-2-3
return `https://fulll.github.io/github-code-search/blog/release-${slug}`;
}
// ─── GitHub API ───────────────────────────────────────────────────────────────
export async function fetchLatestRelease(
token?: string,
signal?: AbortSignal,
): Promise<GithubRelease> {
const headers: Record<string, string> = {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
};
if (token) headers["Authorization"] = `Bearer ${token}`;
const res = await fetch("https://api.github.com/repos/fulll/github-code-search/releases/latest", {
headers,
signal,
});
if (!res.ok) {
const body = await res.text();
throw new Error(`GitHub API error ${res.status}: ${body}`);
}
return res.json() as Promise<GithubRelease>;
}
// ─── Download ─────────────────────────────────────────────────────────────────
/**
* Downloads a binary from `url` and atomically replaces `dest`.
* Uses a ".tmp" sibling file so the replacement is atomic on the same FS.
*/
async function downloadBinary(url: string, dest: string, debug = false): Promise<void> {
// Validate URL to prevent SSRF attacks — initial URL must come from github.com.
try {
const parsedUrl = new URL(url);
if (parsedUrl.hostname !== "github.com") {
throw new Error("Invalid host");
}
if (parsedUrl.protocol !== "https:") {
throw new Error("Invalid protocol");
}
} catch {
throw new Error("Invalid URL");
}
if (debug) process.stdout.write(`[debug] downloading from ${url}\n`);
// Follow redirects manually to validate each hop — prevents redirect-based SSRF.
// GitHub release assets redirect from github.com to *.githubusercontent.com, so both
// are allowed redirect targets; all other hosts are blocked.
let currentUrl = url;
let res!: Response;
const maxRedirects = 10;
for (let redirectCount = 0; ; redirectCount++) {
if (redirectCount > maxRedirects) throw new Error("Too many redirects");
res = await fetch(currentUrl, { redirect: "manual" });
if (res.status >= 300 && res.status < 400) {
const location = res.headers.get("location");
if (!location) break;
let nextUrl: URL;
try {
nextUrl = new URL(location, currentUrl);
} catch {
throw new Error("Redirect blocked: invalid Location header");
}
const h = nextUrl.hostname;
const isAllowedHost = h === "github.com" || h.endsWith(".githubusercontent.com");
if (!isAllowedHost || nextUrl.protocol !== "https:") {
throw new Error("Redirect blocked");
}
currentUrl = nextUrl.toString();
continue;
}
break;
}
if (debug)
process.stdout.write(
`[debug] fetch response: status=${res.status} ok=${res.ok} url=${currentUrl}\n`,
);
if (!res.ok) {
throw new Error(`Download failed (${res.status}): ${url}`);
}
// Fix: read the body explicitly as an ArrayBuffer rather than passing the
// Response object to Bun.write, which avoids edge-case issues with Response
// body streaming on certain Bun versions.
const buffer = await res.arrayBuffer();
if (debug) process.stdout.write(`[debug] downloaded ${buffer.byteLength} bytes\n`);
if (buffer.byteLength === 0) {
throw new Error(`Downloaded empty file from ${url}`);
}
const tmpPath = `${dest}.tmp`;
process.stdout.write(`Replacing ${dest}…\n`);
await Bun.write(tmpPath, buffer);
if (debug) process.stdout.write(`[debug] wrote tmp file ${tmpPath}\n`);
// Remove quarantine attribute if present (macOS only) so Gatekeeper
// does not block the replaced binary on the next run.
if (process.platform === "darwin") {
const xattr = Bun.spawnSync(["xattr", "-d", "com.apple.quarantine", tmpPath]);
const xattrStderr = xattr.stderr?.toString() ?? "";
if (debug) {
process.stdout.write(
`[debug] xattr exit=${xattr.exitCode} stderr=${JSON.stringify(xattrStderr)}\n`,
);
}
if (xattr.exitCode !== 0) {
// macOS xattr uses ENOATTR for "attribute does not exist"; the error
// message typically includes "No such xattr" or "No such attribute".
const lowerStderr = xattrStderr.toLowerCase();
const isNoSuchAttr =
lowerStderr.includes("no such xattr") || lowerStderr.includes("no such attribute");
if (!isNoSuchAttr) {
throw new Error(`xattr failed: ${xattrStderr}`);
}
}
}
// Make executable and atomically replace the binary
const chmod = Bun.spawnSync(["chmod", "+x", tmpPath]);
if (chmod.exitCode !== 0) {
throw new Error(`chmod failed: ${chmod.stderr.toString()}`);
}
if (debug) process.stdout.write(`[debug] chmod +x done\n`);
const mv = Bun.spawnSync(["mv", tmpPath, dest]);
if (mv.exitCode !== 0) {
throw new Error(`mv failed: ${mv.stderr.toString()}`);
}
if (debug) process.stdout.write(`[debug] mv done → ${dest}\n`);
}
// ─── Orchestration ────────────────────────────────────────────────────────────
/**
* Checks for a newer release and, if found, downloads and replaces `execPath`.
*/
export async function performUpgrade(
currentVersion: string,
execPath: string,
token?: string,
debug = false,
): Promise<void> {
if (currentVersion === "dev") {
process.stdout.write(
"Running from source (dev). Upgrade is only available for compiled binaries.\n",
);
return;
}
process.stdout.write("Checking for updates…\n");
const release = await fetchLatestRelease(token);
const latestVersion = release.tag_name;
if (!isNewerVersion(currentVersion, latestVersion)) {
process.stdout.write(
`Congrats! You're already on the latest version of github-code-search (${latestVersion}).\n`,
);
return;
}
const asset = selectAsset(release.assets, process.platform, process.arch);
if (debug) {
process.stdout.write(
`[debug] available assets: ${release.assets.map((a) => a.name).join(", ")}\n`,
);
process.stdout.write(`[debug] selected asset: ${asset?.name ?? "(none)"}\n`);
}
if (!asset) {
throw new Error(
`No binary found for platform ${process.platform}/${process.arch} in release ${latestVersion}.`,
);
}
process.stdout.write(`Upgrading ${currentVersion} → ${latestVersion}…\n`);
await downloadBinary(asset.browser_download_url, execPath, debug);
process.stdout.write(
[
``,
`Welcome to github-code-search ${latestVersion}!`,
``,
`What's new in ${latestVersion}:`,
` ${upgradeLink(blogPostUrl(latestVersion))}`,
``,
`Release notes:`,
` ${upgradeLink(release.html_url)}`,
``,
`Commit log:`,
` ${upgradeLink(`https://github.com/fulll/github-code-search/compare/${currentVersion.startsWith("v") ? currentVersion : `v${currentVersion}`}...${latestVersion}`)}`,
``,
`Report a bug:`,
` ${upgradeLink("https://github.com/fulll/github-code-search/issues/new")}`,
``,
`Run \`github-code-search --help\` to explore all options.`,
``,
].join("\n"),
);
}
// ─── Silent update check ──────────────────────────────────────────────────────
/**
* Returns the latest version tag if it is strictly newer than `currentVersion`, or null.
* Silently swallows any network / API error so it never breaks the main search flow.
*/
export async function checkForUpdate(
currentVersion: string,
token?: string,
signal?: AbortSignal,
): Promise<string | null> {
if (currentVersion === "dev") return null;
try {
const release = await fetchLatestRelease(token, signal);
return isNewerVersion(currentVersion, release.tag_name) ? release.tag_name : null;
} catch {
return null;
}
}
// ─── Completion refresh ────────────────────────────────────────────────────────
/**
* Installs or refreshes the shell completion file.
* Always writes the file (creates it if absent, overwrites it if present).
* Returns the written file path, or null when `shell` is null.
*/
export async function refreshCompletions(
shell: Shell | null,
homeDir?: string,
debug = false,
): Promise<string | null> {
if (!shell) return null;
const opts = homeDir ? { homeDir } : {};
const filePath = getCompletionFilePath(shell, opts);
const alreadyExists = existsSync(filePath);
if (debug) {
process.stdout.write(
alreadyExists
? `[debug] refreshing completions at ${filePath}\n`
: `[debug] installing completions at ${filePath}\n`,
);
}
const script = generateCompletion(shell);
mkdirSync(dirname(filePath), { recursive: true });
await Bun.write(filePath, script);
if (debug) process.stdout.write(`[debug] completions written at ${filePath}\n`);
return filePath;
}