forked from lessweb/deepcode-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdateCheck.ts
More file actions
296 lines (265 loc) · 8.2 KB
/
updateCheck.ts
File metadata and controls
296 lines (265 loc) · 8.2 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
import { spawn } from "child_process";
import React from "react";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { render, type Instance } from "ink";
import chalk from "chalk";
import { UpdatePrompt, type UpdatePromptChoice } from "./ui";
export type PackageInfo = {
name: string;
version: string;
};
type UpdateState = {
pending?: {
currentVersion: string;
latestVersion: string;
packageName: string;
checkedAt: string;
} | null;
ignoredVersions?: string[];
};
const UPDATE_STATE_FILE = "update-check.json";
const NPM_VIEW_TIMEOUT_MS = 5000;
const MAX_NPM_VIEW_OUTPUT_CHARS = 64 * 1024;
const TENCENT_MIRROR_REGISTRY = "https://mirrors.cloud.tencent.com/npm/";
export async function promptForPendingUpdate(packageInfo: PackageInfo): Promise<{ installed: boolean }> {
const state = readUpdateState();
const pending = state.pending;
if (!pending) {
return { installed: false };
}
if (compareVersions(packageInfo.version, pending.latestVersion) >= 0) {
writeUpdateState({ ...state, pending: null });
return { installed: false };
}
if (state.ignoredVersions?.includes(pending.latestVersion)) {
writeUpdateState({ ...state, pending: null });
return { installed: false };
}
const installSpec = `${pending.packageName}@${pending.latestVersion}`;
const installCommand = `npm install -g ${installSpec}`;
const choice = await promptUpdateChoice({
currentVersion: packageInfo.version,
latestVersion: pending.latestVersion,
installCommand,
});
if (choice === "install") {
const ok = await runNpmInstallGlobal(installSpec);
if (ok) {
writeUpdateState({ ...state, pending: null });
process.stdout.write(
`\n${chalk.red("Deep Code has been updated. Please restart the CLI to use the new version.")}\n\n`
);
}
return { installed: ok };
}
if (choice === "ignore-version") {
const ignoredVersions = Array.from(new Set([...(state.ignoredVersions ?? []), pending.latestVersion]));
writeUpdateState({ ...state, pending: null, ignoredVersions });
return { installed: false };
}
writeUpdateState({ ...state, pending: null });
return { installed: false };
}
export async function checkForNpmUpdate(packageInfo: PackageInfo): Promise<void> {
if (!packageInfo.name || !packageInfo.version) {
return;
}
try {
const latestVersion = await fetchLatestNpmVersion(packageInfo.name);
if (!latestVersion || compareVersions(latestVersion, packageInfo.version) <= 0) {
clearPendingUpdate();
return;
}
const state = readUpdateState();
if (state.ignoredVersions?.includes(latestVersion)) {
clearPendingUpdate(state);
return;
}
writeUpdateState({
...state,
pending: {
currentVersion: packageInfo.version,
latestVersion,
packageName: packageInfo.name,
checkedAt: new Date().toISOString(),
},
});
} catch {
// Update checks must never affect CLI startup or normal operation.
}
}
export function compareVersions(a: string, b: string): number {
const left = parseVersion(a);
const right = parseVersion(b);
const width = Math.max(left.length, right.length);
for (let index = 0; index < width; index += 1) {
const leftPart = left[index] ?? 0;
const rightPart = right[index] ?? 0;
if (leftPart > rightPart) {
return 1;
}
if (leftPart < rightPart) {
return -1;
}
}
return 0;
}
export function getUpdateStatePath(): string {
return path.join(os.homedir(), ".deepcode", UPDATE_STATE_FILE);
}
async function promptUpdateChoice({
currentVersion,
latestVersion,
installCommand,
}: {
currentVersion: string;
latestVersion: string;
installCommand: string;
}): Promise<"install" | "ignore-once" | "ignore-version"> {
return new Promise<UpdatePromptChoice>((resolve) => {
let selected = false;
let instance: Instance | null = null;
const handleSelect = (choice: UpdatePromptChoice): void => {
if (selected) {
return;
}
selected = true;
resolve(choice);
instance?.unmount();
};
instance = render(
React.createElement(UpdatePrompt, {
currentVersion,
latestVersion,
installCommand,
onSelect: handleSelect,
}),
{ exitOnCtrlC: false }
);
});
}
async function runNpmInstallGlobal(installSpec: string): Promise<boolean> {
return new Promise((resolve) => {
const child = spawn("npm", ["install", "-g", installSpec], {
stdio: "inherit",
shell: process.platform === "win32",
});
child.on("error", (error) => {
process.stderr.write(`Failed to start npm install: ${error.message}\n`);
resolve(false);
});
child.on("close", (code) => {
if (code === 0) {
resolve(true);
return;
}
process.stderr.write(`npm install exited with code ${code ?? "unknown"}.\n`);
resolve(false);
});
});
}
async function fetchLatestNpmVersion(packageName: string): Promise<string | null> {
// Try Tencent mirror first for faster access in mainland China.
const mirrorResult = await runNpmViewLatestVersion(packageName, TENCENT_MIRROR_REGISTRY, NPM_VIEW_TIMEOUT_MS);
if (mirrorResult.ok) {
return parseNpmViewVersion(mirrorResult.stdout);
}
// Fall back to the official npm registry.
const result = await runNpmViewLatestVersion(packageName, undefined, NPM_VIEW_TIMEOUT_MS);
if (!result.ok) {
return null;
}
return parseNpmViewVersion(result.stdout);
}
function runNpmViewLatestVersion(
packageName: string,
registry: string | undefined,
timeoutMs: number
): Promise<{ ok: true; stdout: string } | { ok: false }> {
return new Promise((resolve) => {
const args = ["view", packageName, "dist-tags.latest", "--json"];
if (registry) {
args.push("--registry", registry);
}
const child = spawn("npm", args, {
stdio: ["ignore", "pipe", "pipe"],
shell: process.platform === "win32",
});
let stdout = "";
let settled = false;
const finish = (result: { ok: true; stdout: string } | { ok: false }): void => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
resolve(result);
};
const timer = setTimeout(() => {
child.kill();
finish({ ok: false });
}, timeoutMs);
child.stdout?.on("data", (chunk: string | Buffer) => {
if (stdout.length >= MAX_NPM_VIEW_OUTPUT_CHARS) {
return;
}
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
stdout += text.slice(0, MAX_NPM_VIEW_OUTPUT_CHARS - stdout.length);
});
child.on("error", () => finish({ ok: false }));
child.on("close", (code) => {
finish(code === 0 ? { ok: true, stdout } : { ok: false });
});
});
}
export function parseNpmViewVersion(output: string): string | null {
const trimmed = output.trim();
if (!trimmed) {
return null;
}
try {
const parsed = JSON.parse(trimmed) as unknown;
return typeof parsed === "string" && parsed.trim() ? parsed.trim() : null;
} catch {
return trimmed.split(/\r?\n/)[0]?.trim() || null;
}
}
function readUpdateState(): UpdateState {
const statePath = getUpdateStatePath();
if (!fs.existsSync(statePath)) {
return {};
}
try {
const parsed = JSON.parse(fs.readFileSync(statePath, "utf8")) as UpdateState;
return {
pending: parsed.pending ?? null,
ignoredVersions: Array.isArray(parsed.ignoredVersions)
? parsed.ignoredVersions.filter(
(value): value is string => typeof value === "string" && value.trim().length > 0
)
: [],
};
} catch {
return {};
}
}
function writeUpdateState(state: UpdateState): void {
const statePath = getUpdateStatePath();
fs.mkdirSync(path.dirname(statePath), { recursive: true });
fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
}
function clearPendingUpdate(state = readUpdateState()): void {
if (!state.pending) {
return;
}
writeUpdateState({ ...state, pending: null });
}
function parseVersion(value: string): number[] {
return value
.split("-", 1)[0]
.split(".")
.map((part) => Number.parseInt(part, 10))
.map((part) => (Number.isFinite(part) ? part : 0));
}