Repository navigation
Expand file tree
/
Copy pathupdate.ts
More file actions
197 lines (185 loc) · 8.45 KB
/
Copy pathupdate.ts
File metadata and controls
197 lines (185 loc) · 8.45 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
// catpad updating itself. Releases are GitHub releases of this repository,
// tagged vX.Y.Z (scripts/release.ts makes them, .github/workflows/release.yml
// builds them). There are two ways catpad is installed, and so two ways it
// updates:
//
// app The desktop app. Electrobun's Updater reads the update manifest
// the release carries for this platform, downloads the new bundle,
// swaps it in and starts it again. The main process (src/main)
// hands this file the Updater as `globalThis.catpadUpdater`.
// source A git checkout started by run.sh. The latest release's tag is
// read from GitHub's API; updating is `git pull --ff-only`, and then
// the server exits with RESTART, which run.sh takes as "start me
// again".
//
// The update itself, as a machine:
//
// idle → checking → current | available | failed
// available → downloading → ready → applying (the app: the new version starts)
// available → applying (source: pull, then restart)
// failed → checking
//
// CATPAD_UPDATE_CHECK=0 never ask GitHub
// CATPAD_UPDATE_REPO owner/name, default tlehman/catpad
import { spawn } from "bun";
import { existsSync } from "fs";
import { join } from "path";
import { IN_APP, ROOT, VERSION } from "./paths";
import { machine } from "./web/machine.js";
export const RESTART = 75; // the exit code that asks run.sh to start the server again
const REPO = process.env.CATPAD_UPDATE_REPO || "tlehman/catpad";
const CHECK_EVERY_MS = 6 * 3600 * 1000;
// What the desktop app's main process provides.
export interface AppUpdater {
check(): Promise<{ available: boolean; version: string; error?: string
D796
}>;
download(progress: (percent: number) => void): Promise<void>;
apply(): Promise<void>;
}
export interface UpdateStatus {
mode: "app" | "source" | "off";
version: string;
state: string;
latest?: string;
url?: string;
progress?: number;
error?: string;
detail?: string; // why an update cannot be applied here, when it cannot
}
// Semver order. A pre-release (1.2.0-rc.1) comes before its release (1.2.0).
export function compareSemver(a: string, b: string): number {
const parse = (v: string) => {
const m = v.replace(/^v/, "").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/);
return m ? { n: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null } : null;
};
const x = parse(a), y = parse(b);
if (!x || !y) return 0;
for (let i = 0; i < 3; i++) if (x.n[i] !== y.n[i]) return x.n[i] - y.n[i];
if (x.pre === y.pre) return 0;
if (x.pre == null) return 1;
if (y.pre == null) return -1;
const p = x.pre.split("."), q = y.pre.split(".");
for (let i = 0; i < Math.max(p.length, q.length); i++) {
if (p[i] == null) return -1;
if (q[i] == null) return 1;
const [pn, qn] = [Number(p[i]), Number(q[i])];
const c = Number.isInteger(pn) && Number.isInteger(qn) ? pn - qn : p[i] < q[i] ? -1 : p[i] > q[i] ? 1 : 0;
if (c) return c;
}
return 0;
}
async function git(...args: string[]): Promise<{ ok: boolean; out: string }> {
try {
const p = spawn(["git", "-C", ROOT, ...args], { stdout: "pipe", stderr: "pipe" });
const out = (await new Response(p.stdout).text()) + (await new Response(p.stderr).text());
return { ok: (await p.exited) === 0, out: out.trim() };
} catch (e: any) {
return { ok: false, out: String(e?.message ?? e) };
}
}
export class Updates {
private app = (globalThis as any).catpadUpdater as AppUpdater | undefined;
readonly mode: UpdateStatus["mode"] = process.env.CATPAD_UPDATE_CHECK === "0" ? "off" : IN_APP && this.app ? "app" : IN_APP ? "off" : "source";
private latest?: string;
private url?: string;
private progress?: number;
private error?: string;
private detail?: string;
private timer?: Timer;
private m = machine("update", "idle", {
idle: { CHECK: "checking" },
checking: { CURRENT: "current", FOUND: "available", FAIL: "failed" },
current: { CHECK: "checking" },
available: { CHECK: "checking", DOWNLOAD: "downloading", APPLY: "applying" },
downloading: { READY: "ready", FAIL: "failed" },
ready: { APPLY: "applying" },
applying: { FAIL: "failed" },
failed: { CHECK: "checking" },
}, () => this.onChange(this.status()));
constructor(private onChange: (s: UpdateStatus) => void, private beforeApply: () => Promise<void>) {}
status(): UpdateStatus {
return { mode: this.mode, version: VERSION, state: this.m.state, latest: this.latest, url: this.url, progress: this.progress, error: this.error, detail: this.detail };
}
// Checks now, and then every few hours.
start() {
if (this.mode === "off") return;
setTimeout(() => void this.check(), 5000);
this.timer = setInterval(() => void this.check(), CHECK_EVERY_MS);
}
stop() { clearInterval(this.timer); }
async check(): Promise<void> {
if (this.mode === "off" || !this.m.send("CHECK")) return;
this.error = undefined;
try {
if (this.mode === "app") {
const r = await this.app!.check();
if (r.error) throw new Error(r.error);
this.latest = r.version;
this.url = `https://github.com/${REPO}/releases/tag/v${r.version}`;
// Newer, and not only different: the app in the disk image carries the
// kit and the update bundle does not, so the two are never the same build.
this.m.send(r.available && compareSemver(r.version, VERSION) > 0 ? "FOUND" : "CURRENT");
return;
}
const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
headers: { accept: "application/vnd.github+json", "user-agent": "catpad-update-check" },
signal: AbortSignal.timeout(15000),
});
if (res.status === 404) { this.m.send("CURRENT"); return; } // no release yet
if (!res.ok) throw new Error(`GitHub answered ${res.status}`);
const j: any = await res.json();
this.latest = String(j.tag_name ?? "").replace(/^v/, "");
this.url = j.html_url;
if (!this.latest || compareSemver(this.latest, VERSION) <= 0) { this.m.send("CURRENT"); return; }
this.detail = await this.whyNotPull();
this.m.send("FOUND");
} catch (e: any) {
this.error = `Could not check for updates: ${e?.message ?? e}`;
this.m.send("FAIL");
}
}
// A source checkout can update itself when git can fast-forward it without
// touching anyone's work. Returns why not, or undefined when it can.
private async whyNotPull(): Promise<string | undefined> {
if (!existsSync(join(ROOT, ".git"))) return "This copy of catpad is not a git checkout. Download the new release from its page.";
const dirty = await git("status", "--porcelain", "--untracked-files=no");
if (!dirty.ok) return "git could not read this checkout.";
if (dirty.out) return "This checkout has changes that are not committed. Commit or stash them, then update.";
const branch = await git("rev-parse", "--abbrev-ref", "HEAD");
if (branch.out !== "main") return `This checkout is on ${branch.out}, not main. Switch to main to update.`;
return undefined;
}
// Returns why not, or null when the update is under way.
async apply(): Promise<string | null> {
if (!this.m.is("available", "ready")) return this.m.is("downloading", "applying") ? "The update is already under way." : "There is no update to apply.";
if (this.mode === "source" && this.detail) return this.detail;
await this.beforeApply();
if (this.mode === "app") {
if (this.m.is("available")) {
this.m.send("DOWNLOAD");
try {
await this.app!.download((p) => { this.progress = p; this.onChange(this.status()); });
} catch (e: any) {
this.error = `The download failed: ${e?.message ?? e}`;
this.m.send("FAIL");
return this.error;
}
this.m.send("READY");
}
this.m.send("APPLY");
// The app quits here and the new version starts.
this.app!.apply().catch((e: any) => { this.error = `The update could not be applied: ${e?.message ?? e}`; this.m.send("FAIL"); });
return null;
}
this.m.send("APPLY");
const pull = await git("pull", "--ff-only", "origin", "main");
if (!pull.ok) {
this.error = `git pull failed:\n${pull.out}`;
this.m.send("FAIL");
return this.error;
}
if (process.env.CATPAD_SUPERVISED) setTimeout(() => process.exit(RESTART), 300);
else this.detail = "Updated. Restart catpad to run the new version.";
this.onChange(this.status());
return null;
}
}