-
Notifications
You must be signed in to change notification settings - Fork 699
Expand file tree
/
Copy pathupdate.js
More file actions
181 lines (157 loc) · 4.52 KB
/
Copy pathupdate.js
File metadata and controls
181 lines (157 loc) · 4.52 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
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const os = require("os");
const https = require("https");
const { spawnSync } = require("child_process");
const { resolveNativeBinary } = require("./platform");
const { loadPackageJson } = require("./install.js");
const stateDir = path.join(os.homedir(), ".opencodereview");
const tsFile = path.join(stateDir, "last-update-check");
const lockFile = path.join(stateDir, "update.lock");
const hintFile = path.join(stateDir, "update-available");
const DEFAULT_REGISTRY = "https://registry.npmjs.org";
function touchTimestamp() {
fs.mkdirSync(stateDir, { recursive: true });
const now = new Date();
try {
fs.utimesSync(tsFile, now, now);
} catch (_) {
fs.writeFileSync(tsFile, now.toISOString());
}
}
function acquireLock() {
fs.mkdirSync(stateDir, { recursive: true });
try {
fs.writeFileSync(lockFile, String(process.pid), { flag: "wx" });
return true;
} catch (e) {
if (e.code !== "EEXIST") return false;
try {
const pid = parseInt(fs.readFileSync(lockFile, "utf8").trim(), 10);
process.kill(pid, 0);
return false;
} catch (_) {
try {
fs.unlinkSync(lockFile);
fs.writeFileSync(lockFile, String(process.pid), { flag: "wx" });
return true;
} catch (_2) {
return false;
}
}
}
}
function releaseLock() {
try {
fs.unlinkSync(lockFile);
} catch (_) {}
}
function getInstalledVersion(binPath) {
try {
const result = spawnSync(binPath, ["version"], {
encoding: "utf8",
timeout: 3000,
});
const match = (result.stdout || "").match(/v(\d+\.\d+(?:\.\d+)?)/);
return match ? match[1] : null;
} catch (_) {
return null;
}
}
function fetchLatestVersion(pkg) {
const registry = (pkg.publishConfig && pkg.publishConfig.registry) || DEFAULT_REGISTRY;
const pkgName = pkg.name;
if (!pkgName) return Promise.resolve(null);
const encodedName = pkgName.replace(/\//g, "%2F");
const url = `${registry.replace(/\/$/, "")}/${encodedName}/latest`;
if (!url.startsWith("https://")) return Promise.resolve(null);
return new Promise((resolve) => {
const options = {
headers: { "User-Agent": "ocr-updater", Accept: "application/json" },
timeout: 15000,
};
const req = https
.get(url, options, (res) => {
if (res.statusCode !== 200) {
res.resume();
resolve(null);
return;
}
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
try {
const json = JSON.parse(data);
resolve(json.version || null);
} catch (_) {
resolve(null);
}
});
res.on("error", () => resolve(null));
})
.on("error", () => resolve(null));
req.on("timeout", () => {
req.destroy();
resolve(null);
});
});
}
const SEMVER_RE = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
function semverGt(a, b) {
const pa = a.replace(/-.*$/, "").split(".").map(Number);
const pb = b.replace(/-.*$/, "").split(".").map(Number);
for (let i = 0; i < 3; i++) {
if ((pa[i] || 0) > (pb[i] || 0)) return true;
if ((pa[i] || 0) < (pb[i] || 0)) return false;
}
const aPre = a.includes("-");
const bPre = b.includes("-");
if (bPre && !aPre) return true;
return false;
}
function writeHint(latestVersion, pkgName) {
try {
fs.writeFileSync(hintFile, JSON.stringify({ version: latestVersion, pkg: pkgName }));
} catch (_) {}
}
function removeHint() {
try {
fs.unlinkSync(hintFile);
} catch (_) {}
}
async function main() {
touchTimestamp();
if (!acquireLock()) return;
try {
const resolved = resolveNativeBinary();
if (!resolved) return;
const installedVersion = getInstalledVersion(resolved.path);
if (!installedVersion) return;
const pkg = loadPackageJson();
const latestVersion = await fetchLatestVersion(pkg);
if (!latestVersion) return;
if (!SEMVER_RE.test(latestVersion)) return;
if (!semverGt(latestVersion, installedVersion)) {
removeHint();
return;
}
const pkgName = pkg.name;
const IS_WINDOWS = process.platform === "win32";
const result = spawnSync("npm", ["i", "-g", `${pkgName}@${latestVersion}`], {
encoding: "utf8",
timeout: 120000,
shell: IS_WINDOWS,
});
if (result.status === 0) {
removeHint();
} else {
writeHint(latestVersion, pkgName);
}
} catch (_) {
} finally {
releaseLock();
}
}
main().catch(() => {});