Compare commits
20 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67ca9cbb76 | ||
|
|
6c8b82940a | ||
|
|
aebfa26308 | ||
|
|
328b24d5a6 | ||
|
|
ced074a3a0 | ||
|
|
44b4737a20 | ||
|
|
ea2ca08efd | ||
|
|
173a9799d0 | ||
|
|
bb758580d7 | ||
|
|
b1586c5e25 | ||
|
|
cabf6400e7 | ||
|
|
f3cd2274a6 | ||
|
|
9afe49c378 | ||
|
|
0589dd0396 | ||
|
|
3e0c7f69bf | ||
|
|
12977e1a77 | ||
|
|
c064e3aab1 | ||
|
|
283bb7c772 | ||
|
|
e794f241ba | ||
|
|
1f001dc306 |
7 changed files with 205 additions and 56 deletions
|
|
@ -21,6 +21,11 @@ linux:
|
||||||
target:
|
target:
|
||||||
- AppImage
|
- AppImage
|
||||||
- deb
|
- deb
|
||||||
|
# tar.gz is what the in-app updater installs (pickAsset looks for a
|
||||||
|
# linux x86_64/amd64 tarball); arch must be x64 so the asset name ends
|
||||||
|
# in -linux-x86_64 like every published release.
|
||||||
|
- target: tar.gz
|
||||||
|
arch: x64
|
||||||
|
|
||||||
# OS file associations: double-click / "Open with Folio" on Markdown and
|
# OS file associations: double-click / "Open with Folio" on Markdown and
|
||||||
# plain-text files imports them as books (see folio:openPathOrImport and
|
# plain-text files imports them as books (see folio:openPathOrImport and
|
||||||
|
|
|
||||||
4
package-lock.json
generated
4
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "folio",
|
"name": "folio",
|
||||||
"version": "0.1.6",
|
"version": "0.1.17",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "folio",
|
"name": "folio",
|
||||||
"version": "0.1.6",
|
"version": "0.1.17",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tiptap/core": "^2.27.2",
|
"@tiptap/core": "^2.27.2",
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "folio",
|
"name": "folio",
|
||||||
"version": "0.1.6",
|
"version": "0.1.17",
|
||||||
"description": "A simple, local, open-source desktop writing app.",
|
"description": "A simple, local, open-source desktop writing app.",
|
||||||
"productName": "Folio",
|
"productName": "Folio",
|
||||||
"author": "Folio Contributors",
|
"author": "Folio Contributors",
|
||||||
|
|
@ -15,6 +15,7 @@
|
||||||
"dev": "concurrently -k \"npm run build:watch\" \"wait-on dist/main.js && npm run electron\"",
|
"dev": "concurrently -k \"npm run build:watch\" \"wait-on dist/main.js && npm run electron\"",
|
||||||
"start": "npm run build && npm run electron",
|
"start": "npm run build && npm run electron",
|
||||||
"lint": "tsc --noEmit",
|
"lint": "tsc --noEmit",
|
||||||
|
"prepackage": "npm run build",
|
||||||
"test": "node tests/run-project-test.mjs && node tests/run-chapters-test.mjs && node tests/run-wikilinks-test.mjs && node tests/run-office-export-test.mjs && node tests/run-migration-test.mjs && node tests/run-editor-test.mjs && node tests/run-fullbook-test.mjs && node tests/run-print-test.mjs && node tests/run-update-import-test.mjs && node tests/run-update-installer-test.mjs && node tests/run-snapshots-test.mjs && node tests/run-search-test.mjs",
|
"test": "node tests/run-project-test.mjs && node tests/run-chapters-test.mjs && node tests/run-wikilinks-test.mjs && node tests/run-office-export-test.mjs && node tests/run-migration-test.mjs && node tests/run-editor-test.mjs && node tests/run-fullbook-test.mjs && node tests/run-print-test.mjs && node tests/run-update-import-test.mjs && node tests/run-update-installer-test.mjs && node tests/run-snapshots-test.mjs && node tests/run-search-test.mjs",
|
||||||
"package": "electron-builder"
|
"package": "electron-builder"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -246,13 +246,30 @@ async function openBookAt(p: string): Promise<BookResult | ErrResult> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a new book as a dedicated folder <name>/ inside the user's Documents
|
// Create a new book as a dedicated folder <name>/ inside the user's chosen
|
||||||
// directory, then open it. The folder name is the sanitized book title; if a
|
// storage folder (Settings → Folder), falling back to Documents when none is
|
||||||
// folder with that name already exists we append a numeric suffix.
|
// set or the stored one no longer exists, then open it. The folder name is
|
||||||
|
// the sanitized book title; if a folder with that name already exists we
|
||||||
|
// append a numeric suffix.
|
||||||
|
function getBooksDir(): string {
|
||||||
|
// One storage folder drives everything (snapshots, recovery, new books).
|
||||||
|
// snapshotLocation is the one the Settings modal writes; backupLocation is
|
||||||
|
// the older key — honor both so an existing choice keeps working.
|
||||||
|
for (const key of ["snapshotLocation", "backupLocation"]) {
|
||||||
|
const v = String(getSetting<string>(key, "") || "").trim();
|
||||||
|
try {
|
||||||
|
if (v && fs.statSync(v).isDirectory()) return v;
|
||||||
|
} catch {
|
||||||
|
// stale or unreadable path — fall through to the next candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return app.getPath("documents");
|
||||||
|
}
|
||||||
|
|
||||||
handleIpc("folio:newBookNamed", async (_e, name: string) => {
|
handleIpc("folio:newBookNamed", async (_e, name: string) => {
|
||||||
const title = (name || "").trim();
|
const title = (name || "").trim();
|
||||||
if (!title) return { error: "Please provide a book name." };
|
if (!title) return { error: "Please provide a book name." };
|
||||||
const base = app.getPath("documents");
|
const base = getBooksDir();
|
||||||
const folder = sanitizeBookFolderName(title) || "Untitled";
|
const folder = sanitizeBookFolderName(title) || "Untitled";
|
||||||
let target = path.join(base, folder);
|
let target = path.join(base, folder);
|
||||||
let n = 2;
|
let n = 2;
|
||||||
|
|
@ -591,7 +608,7 @@ function exportDefaultPath(filename: string): string {
|
||||||
const dir =
|
const dir =
|
||||||
last && fs.existsSync(last) && fs.statSync(last).isDirectory()
|
last && fs.existsSync(last) && fs.statSync(last).isDirectory()
|
||||||
? last
|
? last
|
||||||
: app.getPath("documents");
|
: getBooksDir();
|
||||||
return path.join(dir, filename);
|
return path.join(dir, filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -972,6 +989,7 @@ function snapshotSettingsSnapshot() {
|
||||||
keep: clampInt(getSetting("snapshotKeep", SNAPSHOT_DEFAULTS.keep), SNAPSHOT_DEFAULTS.keep, 0, 200),
|
keep: clampInt(getSetting("snapshotKeep", SNAPSHOT_DEFAULTS.keep), SNAPSHOT_DEFAULTS.keep, 0, 200),
|
||||||
location,
|
location,
|
||||||
resolvedRoot: resolved,
|
resolvedRoot: resolved,
|
||||||
|
booksDir: getBooksDir(),
|
||||||
snapshotCount: snaps.length,
|
snapshotCount: snaps.length,
|
||||||
lastSnapshot: snaps.length ? snaps[snaps.length - 1] : null,
|
lastSnapshot: snaps.length ? snaps[snaps.length - 1] : null,
|
||||||
};
|
};
|
||||||
|
|
@ -1008,7 +1026,7 @@ handleIpc("folio:setSnapshotSettings", (_e, patch: unknown) => {
|
||||||
handleIpc("folio:pickSnapshotFolder", async () => {
|
handleIpc("folio:pickSnapshotFolder", async () => {
|
||||||
const { canceled, filePaths } = await showOpenDialog({
|
const { canceled, filePaths } = await showOpenDialog({
|
||||||
properties: ["openDirectory"],
|
properties: ["openDirectory"],
|
||||||
title: "Choose snapshot folder",
|
title: "Choose storage folder (new books + snapshots)",
|
||||||
});
|
});
|
||||||
return { canceled, filePaths };
|
return { canceled, filePaths };
|
||||||
});
|
});
|
||||||
|
|
@ -1089,14 +1107,14 @@ handleIpc("folio:importMarkdown", async () => {
|
||||||
filters: [{ name: "Markdown and text", extensions: ["md", "markdown", "txt"] }],
|
filters: [{ name: "Markdown and text", extensions: ["md", "markdown", "txt"] }],
|
||||||
});
|
});
|
||||||
if (canceled || !filePaths.length) return { canceled: true } as const;
|
if (canceled || !filePaths.length) return { canceled: true } as const;
|
||||||
return importMarkdownFiles(filePaths, app.getPath("documents"));
|
return importMarkdownFiles(filePaths, getBooksDir());
|
||||||
});
|
});
|
||||||
|
|
||||||
// Open a path that may be either a Folio book directory or a Markdown file
|
// Open a path that may be either a Folio book directory or a Markdown file
|
||||||
// (the desktop launcher can be handed either via file associations).
|
// (the desktop launcher can be handed either via file associations).
|
||||||
handleIpc("folio:openPathOrImport", async (_e, p: string) => {
|
handleIpc("folio:openPathOrImport", async (_e, p: string) => {
|
||||||
if (p && isImportableMarkdown(p)) {
|
if (p && isImportableMarkdown(p)) {
|
||||||
const results = importMarkdownFiles([p], app.getPath("documents"));
|
const results = importMarkdownFiles([p], getBooksDir());
|
||||||
const r = results[0];
|
const r = results[0];
|
||||||
if (!r.ok) return { error: r.error };
|
if (!r.ok) return { error: r.error };
|
||||||
return openBookAt(r.bookPath as string);
|
return openBookAt(r.bookPath as string);
|
||||||
|
|
@ -1202,46 +1220,100 @@ handleIpc("folio:performUpdate", async () => {
|
||||||
app.getPath("temp"),
|
app.getPath("temp"),
|
||||||
`folio-update-${Date.now()}.tar.gz`
|
`folio-update-${Date.now()}.tar.gz`
|
||||||
);
|
);
|
||||||
// Downloads of the ~100MB asset have twice truncated near the end while
|
// Downloads go through curl, not Chromium's network stack: on flaky Wi-Fi
|
||||||
// the server copy stayed intact. The old 2-byte magic check could not
|
// the Electron net stack restarts requests mid-stream, producing a
|
||||||
// see that, so the detached installer failed after the app had quit and
|
// right-sized but corrupt gzip ("100% three times, then failed"). curl
|
||||||
// the update silently no-oped. Now: retry the download up to 3 times,
|
// resumes with HTTP Range (-C -) so a dropped connection continues where
|
||||||
// require the advertised byte count, and gunzip the whole file before
|
// it left off instead of restarting, and retries internally. We still
|
||||||
// handing off. A corrupt file is deleted and the user gets a real error.
|
// verify the exact byte count and gunzip the whole file before handoff.
|
||||||
const { Readable } = await import("stream");
|
|
||||||
const { createWriteStream } = await import("fs");
|
|
||||||
const { pipeline } = await import("stream/promises");
|
|
||||||
const total = Number(asset.size) || 0;
|
const total = Number(asset.size) || 0;
|
||||||
let lastError = "";
|
let lastError = "";
|
||||||
let downloaded = false;
|
let downloaded = false;
|
||||||
for (let attempt = 1; attempt <= 3 && !downloaded; attempt++) {
|
const { spawn } = await import("child_process");
|
||||||
try {
|
const haveCurl = await new Promise<boolean>((resolve) => {
|
||||||
const res = await fetch(asset.browser_download_url, {
|
const p = spawn("curl", ["--version"], { stdio: "ignore" });
|
||||||
redirect: "follow",
|
p.on("error", () => resolve(false));
|
||||||
signal: AbortSignal.timeout(10 * 60 * 1000),
|
p.on("close", (code) => resolve(code === 0));
|
||||||
|
});
|
||||||
|
if (haveCurl) {
|
||||||
|
for (let attempt = 1; attempt <= 3 && !downloaded; attempt++) {
|
||||||
|
const code = await new Promise<number>((resolve) => {
|
||||||
|
const c = spawn(
|
||||||
|
"curl",
|
||||||
|
[
|
||||||
|
"-fsSL",
|
||||||
|
"-C", "-", // resume a partial file
|
||||||
|
"--max-time", "900",
|
||||||
|
"--retry", "5", "--retry-delay", "2", "--retry-all-errors",
|
||||||
|
"--connect-timeout", "15",
|
||||||
|
"-o", tarball,
|
||||||
|
asset.browser_download_url,
|
||||||
|
],
|
||||||
|
{ stdio: "ignore" }
|
||||||
|
);
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
try {
|
||||||
|
getWindow()?.webContents.send("folio:update-progress", {
|
||||||
|
received: fs.statSync(tarball).size,
|
||||||
|
total,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
/* file not created yet */
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
c.on("error", () => { clearInterval(timer); resolve(-1); });
|
||||||
|
c.on("close", (rc) => { clearInterval(timer); resolve(rc ?? -1); });
|
||||||
});
|
});
|
||||||
if (!res.ok || !res.body) {
|
if (code !== 0) {
|
||||||
lastError = `Download failed (HTTP ${res.status}).`;
|
lastError = `Download failed (curl exit ${code}).`;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let received = 0;
|
const size = fs.existsSync(tarball) ? fs.statSync(tarball).size : 0;
|
||||||
const source = Readable.fromWeb(res.body as never);
|
if (looksTruncated(size, total)) {
|
||||||
source.on("data", (chunk: Buffer) => {
|
lastError = `Download truncated (${size}/${total} bytes).`;
|
||||||
received += chunk.length;
|
|
||||||
getWindow()?.webContents.send("folio:update-progress", { received, total });
|
|
||||||
});
|
|
||||||
await pipeline(source, createWriteStream(tarball));
|
|
||||||
if (looksTruncated(received, total)) {
|
|
||||||
lastError = `Download truncated (${received}/${total} bytes).`;
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!(await verifyArchiveGzip(tarball))) {
|
if (!(await verifyArchiveGzip(tarball))) {
|
||||||
lastError = "Downloaded archive is corrupt (gzip stream incomplete).";
|
lastError = "Downloaded archive is corrupt (gzip stream incomplete).";
|
||||||
|
fs.rmSync(tarball, { force: true }); // corrupted resume file must not poison the next attempt
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
downloaded = true;
|
downloaded = true;
|
||||||
} catch (e) {
|
}
|
||||||
lastError = `Download failed: ${(e as Error).message}`;
|
} else {
|
||||||
|
// No curl on PATH: fall back to the in-process fetch pipeline.
|
||||||
|
const { Readable } = await import("stream");
|
||||||
|
const { createWriteStream } = await import("fs");
|
||||||
|
const { pipeline } = await import("stream/promises");
|
||||||
|
for (let attempt = 1; attempt <= 3 && !downloaded; attempt++) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(asset.browser_download_url, {
|
||||||
|
redirect: "follow",
|
||||||
|
signal: AbortSignal.timeout(10 * 60 * 1000),
|
||||||
|
});
|
||||||
|
if (!res.ok || !res.body) {
|
||||||
|
lastError = `Download failed (HTTP ${res.status}).`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let received = 0;
|
||||||
|
const source = Readable.fromWeb(res.body as never);
|
||||||
|
source.on("data", (chunk: Buffer) => {
|
||||||
|
received += chunk.length;
|
||||||
|
getWindow()?.webContents.send("folio:update-progress", { received, total });
|
||||||
|
});
|
||||||
|
await pipeline(source, createWriteStream(tarball));
|
||||||
|
if (looksTruncated(received, total)) {
|
||||||
|
lastError = `Download truncated (${received}/${total} bytes).`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!(await verifyArchiveGzip(tarball))) {
|
||||||
|
lastError = "Downloaded archive is corrupt (gzip stream incomplete).";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
downloaded = true;
|
||||||
|
} catch (e) {
|
||||||
|
lastError = `Download failed: ${(e as Error).message}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!downloaded) {
|
if (!downloaded) {
|
||||||
|
|
@ -1254,6 +1326,9 @@ handleIpc("folio:performUpdate", async () => {
|
||||||
app.getPath("temp"),
|
app.getPath("temp"),
|
||||||
`folio-update-${process.pid}.sh`
|
`folio-update-${process.pid}.sh`
|
||||||
);
|
);
|
||||||
|
// Persistent, append-only handoff log: survives the swap and tells us
|
||||||
|
// exactly where a failed update stopped (temp files can vanish).
|
||||||
|
const updateLog = path.join(app.getPath("userData"), "update.log");
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(
|
||||||
script,
|
script,
|
||||||
buildInstallerScript({
|
buildInstallerScript({
|
||||||
|
|
@ -1261,15 +1336,48 @@ handleIpc("folio:performUpdate", async () => {
|
||||||
tarball,
|
tarball,
|
||||||
installDir: cfg.installDir,
|
installDir: cfg.installDir,
|
||||||
relaunch: cfg.launcher,
|
relaunch: cfg.launcher,
|
||||||
|
log: updateLog,
|
||||||
}),
|
}),
|
||||||
{ mode: 0o700 }
|
{ mode: 0o700 }
|
||||||
);
|
);
|
||||||
const { spawn } = await import("child_process");
|
// IMPORTANT: on systemd desktops (Hyprland/uwsm) the app runs inside a
|
||||||
const child = spawn("/bin/sh", [script], { detached: true, stdio: "ignore" });
|
// systemd scope cgroup, and a plain detached child stays in that cgroup —
|
||||||
child.on("error", (err) => {
|
// when the app quits, systemd sweeps the scope and kills the swap script
|
||||||
console.error("[folio] updater spawn failed:", err.message);
|
// mid-run (root cause of the "update failed" reports: the handoff died
|
||||||
});
|
// before swapping, and the app was relaunched from the old tree).
|
||||||
child.unref();
|
// systemd-run puts the script in its own transient unit that outlives us;
|
||||||
|
// verified to survive on this machine. Fall back to a detached spawn for
|
||||||
|
// non-systemd sessions.
|
||||||
|
let handedOff = false;
|
||||||
|
try {
|
||||||
|
const { execFileSync } = await import("child_process");
|
||||||
|
execFileSync("systemd-run", [
|
||||||
|
"--user", "--quiet", "--collect",
|
||||||
|
`--description=Folio updater handoff`,
|
||||||
|
// Default KillMode=control-group means the unit's cgroup is swept
|
||||||
|
// when the script exits — that killed the backgrounded relaunch
|
||||||
|
// before Electron got to start (v0.1.15 update: swap OK, app died).
|
||||||
|
// KillMode=process lets the script exit while its child app lives.
|
||||||
|
"--property=KillMode=process",
|
||||||
|
"/bin/sh", script,
|
||||||
|
], { timeout: 10_000, stdio: "ignore" });
|
||||||
|
handedOff = true;
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
const child = spawn("/bin/sh", [script], { detached: true, stdio: "ignore" });
|
||||||
|
child.on("error", (err) => {
|
||||||
|
console.error("[folio] updater spawn failed:", err.message);
|
||||||
|
});
|
||||||
|
child.unref();
|
||||||
|
handedOff = true;
|
||||||
|
} catch (e) {
|
||||||
|
void e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!handedOff) {
|
||||||
|
try { fs.appendFileSync(updateLog, new Date().toISOString() + " FAIL: could not start swap script\n"); } catch { /* ignore */ }
|
||||||
|
return { error: "Could not start the installer. Your current version is unchanged." };
|
||||||
|
}
|
||||||
// Quit so the swap script can replace the app directory.
|
// Quit so the swap script can replace the app directory.
|
||||||
setTimeout(() => app.quit(), 300);
|
setTimeout(() => app.quit(), 300);
|
||||||
return { ok: true, version: rel.version };
|
return { ok: true, version: rel.version };
|
||||||
|
|
@ -1296,7 +1404,7 @@ function fileArgFrom(argv: string[]): string | null {
|
||||||
|
|
||||||
function openFromArg(p: string): void {
|
function openFromArg(p: string): void {
|
||||||
if (isImportableMarkdown(p)) {
|
if (isImportableMarkdown(p)) {
|
||||||
const results = importMarkdownFiles([p], app.getPath("documents"));
|
const results = importMarkdownFiles([p], getBooksDir());
|
||||||
const r = results[0];
|
const r = results[0];
|
||||||
if (r.ok) {
|
if (r.ok) {
|
||||||
openBookAt(r.bookPath as string);
|
openBookAt(r.bookPath as string);
|
||||||
|
|
@ -1320,4 +1428,8 @@ if (app.requestSingleInstanceLock()) {
|
||||||
}
|
}
|
||||||
if (f) openFromArg(f);
|
if (f) openFromArg(f);
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
// Lost the lock: another Folio is already running. Without this quit the
|
||||||
|
// second process falls through to whenReady() and opens a duplicate window.
|
||||||
|
app.quit();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -163,6 +163,8 @@ export interface InstallerSpec {
|
||||||
tarball: string;
|
tarball: string;
|
||||||
installDir: string;
|
installDir: string;
|
||||||
relaunch: string;
|
relaunch: string;
|
||||||
|
/** Optional append-only log; the script narrates every step into it. */
|
||||||
|
log?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The handoff script. Deliberately forgiving (no set -e): on any failure it
|
// The handoff script. Deliberately forgiving (no set -e): on any failure it
|
||||||
|
|
@ -170,7 +172,10 @@ export interface InstallerSpec {
|
||||||
// user without an app. The old tree is kept as .old.<pid> and pruned only
|
// user without an app. The old tree is kept as .old.<pid> and pruned only
|
||||||
// after a successful swap.
|
// after a successful swap.
|
||||||
export function buildInstallerScript(spec: InstallerSpec): string {
|
export function buildInstallerScript(spec: InstallerSpec): string {
|
||||||
const { pid, tarball, installDir, relaunch } = spec;
|
const { pid, tarball, installDir, relaunch, log } = spec;
|
||||||
|
const logLine = log
|
||||||
|
? `say() { echo "$(date '+%F %T') $*" >> ${shQuote(log)} 2>/dev/null; }`
|
||||||
|
: "say() { :; }";
|
||||||
return [
|
return [
|
||||||
"#!/bin/sh",
|
"#!/bin/sh",
|
||||||
"# Folio updater — waits for the app to exit, swaps in the new version,",
|
"# Folio updater — waits for the app to exit, swaps in the new version,",
|
||||||
|
|
@ -181,30 +186,52 @@ export function buildInstallerScript(spec: InstallerSpec): string {
|
||||||
`RELAUNCH=${shQuote(relaunch)}`,
|
`RELAUNCH=${shQuote(relaunch)}`,
|
||||||
`NEW="$INSTALL.update-new.$$"`,
|
`NEW="$INSTALL.update-new.$$"`,
|
||||||
`OLD="$INSTALL.old.$$"`,
|
`OLD="$INSTALL.old.$$"`,
|
||||||
|
logLine,
|
||||||
|
'say "handoff start pid=$PID tarball=$TARBALL"',
|
||||||
"# Wait (bounded to ~2 minutes) for the app process to exit.",
|
"# Wait (bounded to ~2 minutes) for the app process to exit.",
|
||||||
"i=0",
|
"i=0",
|
||||||
'while [ "$PID" -gt 0 ] 2>/dev/null && kill -0 "$PID" 2>/dev/null && [ "$i" -lt 400 ]; do sleep 0.3; i=$((i+1)); done',
|
'while [ "$PID" -gt 0 ] 2>/dev/null && kill -0 "$PID" 2>/dev/null && [ "$i" -lt 400 ]; do sleep 0.3; i=$((i+1)); done',
|
||||||
|
'kill -0 "$PID" 2>/dev/null && say "WARN: app still alive after wait window" || say "app exited after ${i} polls"',
|
||||||
'rm -rf "$NEW"',
|
'rm -rf "$NEW"',
|
||||||
'mkdir -p "$NEW"',
|
'mkdir -p "$NEW" || { say "FAIL: mkdir $NEW"; "$RELAUNCH" >/dev/null 2>&1 & exit 1; }',
|
||||||
'if tar -xzf "$TARBALL" -C "$NEW"; then',
|
'if tar -xzf "$TARBALL" -C "$NEW"; then',
|
||||||
' # electron-builder nests everything under a top-level dir; flatten it.',
|
' say "extracted ok"',
|
||||||
|
' # electron-builder nests everything under a top-level dir; flatten it',
|
||||||
|
" # by adopting the nested dir itself (mv of the dir, not a glob — globs",
|
||||||
|
" # miss dotfiles and a partial mv leaves a broken tree).",
|
||||||
' if [ ! -e "$NEW/folio" ]; then',
|
' if [ ! -e "$NEW/folio" ]; then',
|
||||||
' ONLY=$(find "$NEW" -mindepth 1 -maxdepth 1 -type d | head -n 1)',
|
' ONLY=$(find "$NEW" -mindepth 1 -maxdepth 1 -type d | head -n 1)',
|
||||||
' [ -n "$ONLY" ] && mv "$ONLY"/* "$NEW"/ 2>/dev/null',
|
' REST=$(find "$NEW" -mindepth 1 -maxdepth 1 | wc -l)',
|
||||||
|
' if [ -n "$ONLY" ] && [ "$REST" -eq 1 ]; then',
|
||||||
|
' mv "$ONLY" "$NEW.new" && rm -rf "$NEW" && mv "$NEW.new" "$NEW" && say "flattened nested dir"',
|
||||||
|
" fi",
|
||||||
" fi",
|
" fi",
|
||||||
|
"else",
|
||||||
|
' say "FAIL: tar extract failed"',
|
||||||
"fi",
|
"fi",
|
||||||
'if [ -x "$NEW/folio" ]; then',
|
'if [ -x "$NEW/folio" ]; then',
|
||||||
' [ -e "$INSTALL" ] && mv "$INSTALL" "$OLD"',
|
' [ -e "$INSTALL" ] && mv "$INSTALL" "$OLD" && say "moved old install aside"',
|
||||||
' if mv "$NEW" "$INSTALL"; then',
|
' if mv "$NEW" "$INSTALL"; then',
|
||||||
|
' say "SWAP OK — new version installed"',
|
||||||
' rm -rf "$OLD" "$INSTALL.update-new".* "$INSTALL.old".* 2>/dev/null',
|
' rm -rf "$OLD" "$INSTALL.update-new".* "$INSTALL.old".* 2>/dev/null',
|
||||||
' rm -f "$TARBALL"',
|
' rm -f "$TARBALL"',
|
||||||
" else",
|
" else",
|
||||||
|
' say "FAIL: mv NEW->INSTALL; restoring old"',
|
||||||
' [ -e "$OLD" ] && mv "$OLD" "$INSTALL"',
|
' [ -e "$OLD" ] && mv "$OLD" "$INSTALL"',
|
||||||
" fi",
|
" fi",
|
||||||
"else",
|
"else",
|
||||||
|
' say "FAIL: no executable at $NEW/folio; keeping old install"',
|
||||||
' rm -rf "$NEW"',
|
' rm -rf "$NEW"',
|
||||||
"fi",
|
"fi",
|
||||||
'"$RELAUNCH" >/dev/null 2>&1 &',
|
'say "relaunching"',
|
||||||
|
// Detach fully: setsid moves the relaunch into its own session so it
|
||||||
|
// survives this script's exit and any cgroup sweep of the transient
|
||||||
|
// unit (systemd KillMode). Fallback chain for missing setsid.
|
||||||
|
'if command -v setsid >/dev/null 2>&1; then',
|
||||||
|
' setsid "$RELAUNCH" >/dev/null 2>&1 < /dev/null &',
|
||||||
|
'else',
|
||||||
|
' nohup "$RELAUNCH" >/dev/null 2>&1 < /dev/null &',
|
||||||
|
"fi",
|
||||||
"",
|
"",
|
||||||
].join("\n");
|
].join("\n");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,8 @@ interface SnapshotSettings {
|
||||||
keep: number;
|
keep: number;
|
||||||
location: string;
|
location: string;
|
||||||
resolvedRoot: string;
|
resolvedRoot: string;
|
||||||
|
/** Where new books are saved (Settings → Storage folder). */
|
||||||
|
booksDir?: string;
|
||||||
snapshotCount: number;
|
snapshotCount: number;
|
||||||
lastSnapshot: string | null;
|
lastSnapshot: string | null;
|
||||||
}
|
}
|
||||||
|
|
@ -59,8 +61,10 @@ export function createSettingsFeature(ctx: BookCtx): SettingsFeature {
|
||||||
intervalInput.value = String(s.intervalMin ?? 5);
|
intervalInput.value = String(s.intervalMin ?? 5);
|
||||||
keepInput.value = String(s.keep ?? 20);
|
keepInput.value = String(s.keep ?? 20);
|
||||||
locationInput.value = s.location || "";
|
locationInput.value = s.location || "";
|
||||||
locationInput.placeholder = "Default: <book>/Folio-Backups";
|
locationInput.placeholder = "Default: Documents (books) · <book>/Folio-Backups (snapshots)";
|
||||||
resolvedEl.textContent = `Saving to: ${shortPath(s.resolvedRoot || "—")}`;
|
resolvedEl.textContent = s.booksDir
|
||||||
|
? `New books save to: ${shortPath(s.booksDir)}`
|
||||||
|
: `Saving to: ${shortPath(s.resolvedRoot || "—")}`;
|
||||||
lastSnapEl.textContent = s.lastSnapshot
|
lastSnapEl.textContent = s.lastSnapshot
|
||||||
? `${s.snapshotCount} snapshot${s.snapshotCount === 1 ? "" : "s"} · latest ${s.lastSnapshot.split("/").pop()}`
|
? `${s.snapshotCount} snapshot${s.snapshotCount === 1 ? "" : "s"} · latest ${s.lastSnapshot.split("/").pop()}`
|
||||||
: "No snapshots yet.";
|
: "No snapshots yet.";
|
||||||
|
|
|
||||||
|
|
@ -343,9 +343,9 @@
|
||||||
<label>Keep last <input type="number" id="settingKeep" class="modal-input setting-num" min="0" max="200" value="20" /></label>
|
<label>Keep last <input type="number" id="settingKeep" class="modal-input setting-num" min="0" max="200" value="20" /></label>
|
||||||
</div>
|
</div>
|
||||||
<div class="backup-control">
|
<div class="backup-control">
|
||||||
<span class="backup-label">Folder</span>
|
<span class="backup-label">Storage folder</span>
|
||||||
<input type="text" id="settingLocation" class="backup-input" readonly placeholder="Default: <book>/Folio-Backups" title="Snapshot folder (empty = default)" />
|
<input type="text" id="settingLocation" class="backup-input" readonly placeholder="Default: Documents" title="Where new books and snapshots are saved (empty = Documents / <book>/Folio-Backups)" />
|
||||||
<button type="button" class="button button-ghost backup-browse" id="settingBrowse" title="Choose snapshot folder">…</button>
|
<button type="button" class="button button-ghost backup-browse" id="settingBrowse" title="Choose storage folder">…</button>
|
||||||
<button type="button" class="button button-ghost" id="settingResetLoc" title="Back to the default folder">Reset</button>
|
<button type="button" class="button button-ghost" id="settingResetLoc" title="Back to the default folder">Reset</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="setting-meta" id="settingResolved"></p>
|
<p class="setting-meta" id="settingResolved"></p>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue