-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcheckVersion.ts
More file actions
179 lines (156 loc) · 5.3 KB
/
Copy pathcheckVersion.ts
File metadata and controls
179 lines (156 loc) · 5.3 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
import { spawnSync } from "node:child_process";
import * as console from "node:console";
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import process from "node:process";
import boxen from "boxen";
import chalk from "chalk";
import semver from "semver";
import pkg from "../package.json" with { type: "json" };
import { handleUpgrade } from "./lib/upgrade.ts";
const CACHE_FILE = join(homedir(), ".sfcompute", "version-cache");
const CACHE_TTL = 1 * 60 * 60 * 1000; // 1 hour in milliseconds
interface VersionCache {
version: string;
timestamp: number;
}
async function checkCacheExists(): Promise<boolean> {
try {
await stat(CACHE_FILE);
return true;
} catch {
return false;
}
}
async function readCache(): Promise<VersionCache | null> {
try {
const cacheData = await readFile(CACHE_FILE, "utf-8");
const cache = JSON.parse(cacheData);
if (typeof cache === "object" && cache !== null) {
return cache as VersionCache;
}
return null;
} catch {
return null;
}
}
async function writeCache(version: string): Promise<void> {
const cacheDir = join(homedir(), ".sfcompute");
const cacheData = JSON.stringify({
version,
timestamp: Date.now(),
});
try {
await mkdir(cacheDir, { recursive: true });
await writeFile(CACHE_FILE, cacheData);
} catch {
// Ignore cache write failures
}
}
async function checkProductionCLIVersion() {
// Check cache first
const exists = await checkCacheExists();
if (exists) {
const cache = await readCache();
if (cache) {
const now = Date.now();
if (now - cache.timestamp < CACHE_TTL) {
return cache.version;
}
}
}
// Fetch from network
try {
const response = await fetch(
"https://raw.githubusercontent.com/sfcompute/cli/refs/heads/main/package.json",
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = (await response.json()) as { version: string };
// If current version is stable and latest is prerelease, ignore the prerelease
const currentIsStable = !semver.prerelease(pkg.version);
const latestIsPrerelease = semver.prerelease(data.version);
if (currentIsStable && latestIsPrerelease) {
return pkg.version; // Return current version to prevent upgrade notification
}
await writeCache(data.version);
return data.version;
} catch (error) {
console.error("failed to check latest CLI version:", error);
return null;
}
}
/**
* Returns true if an upgrade banner was shown (or an auto-upgrade was
* performed), false otherwise. Callers can use this to decide whether to
* show a different banner instead.
*/
export async function checkVersion(): Promise<boolean> {
// Disable auto-upgrade if env var is set
if (process.env.SF_CLI_DISABLE_AUTO_UPGRADE) {
return false;
}
// Skip version check if running upgrade command
const args = process.argv.slice(2);
if (args[0] === "upgrade") return false;
const version = pkg.version;
const latestVersion = await checkProductionCLIVersion();
if (!latestVersion) return false;
if (version === latestVersion) return false;
// Don't upgrade from stable to prerelease
const currentIsStable = !semver.prerelease(version);
const latestIsPrerelease = semver.prerelease(latestVersion);
if (currentIsStable && latestIsPrerelease) return false;
const isOutdated = semver.lt(version, latestVersion);
if (!isOutdated) return false;
// Only auto-upgrade for patch changes and when not going to a prerelease
const isPatchUpdate = semver.diff(version, latestVersion) === "patch";
if (isPatchUpdate && !latestIsPrerelease) {
console.log(
chalk.cyan(`Automatically upgrading ${version} → ${latestVersion}`),
);
try {
const success = await handleUpgrade(version, latestVersion);
if (!success) throw new Error("Upgrade failed");
console.log(chalk.gray("\n☁️☁️☁️\n"));
// Re-run the original command with the newly installed binary.
// process.execPath is the binary's own path in a pkg build; the
// upgrade just replaced that file on disk, so re-invoking it runs
// the new version. We use `env -u PKG_EXECPATH` because pkg's
// patched child_process re-adds PKG_EXECPATH even if we delete it
// from the env object, causing the bootstrap to treat argv[1] as a
// script path. spawnSync with an argv array avoids shell injection.
const reRun = spawnSync(
"env",
["-u", "PKG_EXECPATH", process.execPath, ...process.argv.slice(2)],
{
stdio: "inherit",
env: { ...process.env, SF_CLI_DISABLE_AUTO_UPGRADE: "1" },
},
);
process.exit(reRun.status ?? 0);
} catch {
// Silent error, just run the command the user wanted to run
}
return true;
} else if (!latestIsPrerelease) {
// Only show update message for non-prerelease versions
const message = `
Please update your CLI.
Your version: ${version}
Latest version: ${latestVersion}
Run 'sf upgrade' to update to the latest version
`;
console.log(
boxen(chalk.yellow(message), {
padding: 1,
borderColor: "yellow",
borderStyle: "round",
}),
);
return true;
}
return false;
}