neurastream 0.2.69 → 0.2.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -0
- package/package.json +1 -1
- package/src/adapters/omp/doctor.ts +13 -0
- package/src/cli/dispatch.ts +5 -0
- package/src/cli/init.ts +6 -0
- package/src/cli/wip.ts +91 -0
- package/src/core/config.ts +14 -0
- package/src/core/main-start.ts +8 -0
- package/src/core/wip-alerts.ts +75 -0
- package/src/core/wip-backup.ts +65 -36
- package/src/core/wip-fail.ts +82 -0
- package/src/core/wip-private.ts +93 -0
- package/src/core/wip-restore.ts +101 -0
- package/src/core/wip-roots.ts +58 -0
- package/src/core/wip-setup.ts +197 -0
- package/src/core/wip-snapshot.ts +123 -52
- package/templates/config.yml +6 -0
- package/templates/help/wip-backup.txt +3 -0
- package/templates/help/wip-snapshot.txt +2 -0
- package/templates/launchd/neurastream-wip-backup.plist +23 -0
- package/templates/launchd/neurastream-wip-snapshot.plist +18 -0
- package/templates/systemd/neurastream-wip-backup.service +6 -0
- package/templates/systemd/neurastream-wip-backup.timer +9 -0
- package/templates/systemd/neurastream-wip-snapshot.service +6 -0
- package/templates/systemd/neurastream-wip-snapshot.timer +10 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The backup target must be verifiably private before anything is pushed: a repo made public by
|
|
2
|
+
// accident would publish every saved worktree. Parsing happens first, so a hostile URL never
|
|
3
|
+
// reaches a command; the answer is "unknown" unless it is the exact word "private".
|
|
4
|
+
import { cmd, type CmdResult } from "./proc.ts";
|
|
5
|
+
|
|
6
|
+
export type Visibility = "private" | "public" | "internal" | "unknown";
|
|
7
|
+
|
|
8
|
+
/** One argv array in, one result out: tests inject this instead of running gh/glab. */
|
|
9
|
+
export type Run = (args: string[]) => CmdResult;
|
|
10
|
+
|
|
11
|
+
export interface Remote {
|
|
12
|
+
host: string;
|
|
13
|
+
segments: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const HOST_RX = /^[A-Za-z0-9.-]+$/;
|
|
17
|
+
const SEGMENT_RX = /^[A-Za-z0-9._-]+$/;
|
|
18
|
+
const SCP_RX = /^[A-Za-z0-9._-]+@([^:/@]+):(.+)$/;
|
|
19
|
+
const URL_RX = /^(?:ssh|git|https?):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/;
|
|
20
|
+
|
|
21
|
+
/** host plus path segments of a git remote, or null when the URL cannot be trusted as written. */
|
|
22
|
+
export function parseRemote(url: string): Remote | null {
|
|
23
|
+
const raw = url.trim();
|
|
24
|
+
if (raw === "") return null;
|
|
25
|
+
const scp = SCP_RX.exec(raw);
|
|
26
|
+
const scheme = scp ? null : URL_RX.exec(raw);
|
|
27
|
+
const host = scp?.[1] ?? scheme?.[1];
|
|
28
|
+
const path = scp?.[2] ?? scheme?.[2];
|
|
29
|
+
if (!host || !path || !HOST_RX.test(host)) return null;
|
|
30
|
+
// A "?" or "#" would be a query/fragment, "%" a hidden escape: the path must be plain segments.
|
|
31
|
+
const segments = path.replace(/\/+$/, "").split("/");
|
|
32
|
+
const last = segments.length - 1;
|
|
33
|
+
if (segments[last]?.endsWith(".git")) segments[last] = segments[last]!.slice(0, -4);
|
|
34
|
+
for (const segment of segments) {
|
|
35
|
+
if (!SEGMENT_RX.test(segment) || segment === "." || segment === "..") return null;
|
|
36
|
+
}
|
|
37
|
+
return { host: host.toLowerCase(), segments };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `host/owner/repo` of a remote, or null when it does not parse (P8 matches hook opt-ins on this). */
|
|
41
|
+
export function originId(url: string): { host: string; id: string; owner: string } | null {
|
|
42
|
+
const remote = parseRemote(url);
|
|
43
|
+
if (!remote) return null;
|
|
44
|
+
return {
|
|
45
|
+
host: remote.host,
|
|
46
|
+
owner: `${remote.host}/${remote.segments[0]}`,
|
|
47
|
+
id: `${remote.host}/${remote.segments.join("/")}`,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Whether a `wip.backup_hook_off` entry names this origin: it must equal the origin's `host/owner`
|
|
53
|
+
* or `host/owner/repo` exactly. A substring test would let one entry opt in every repo on a host,
|
|
54
|
+
* or even an unrelated one (`git` matching every ssh URL).
|
|
55
|
+
*/
|
|
56
|
+
export function originMatches(entry: string, url: string): boolean {
|
|
57
|
+
const parsed = originId(url);
|
|
58
|
+
return parsed !== null && (entry === parsed.owner || entry === parsed.id);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function answer(text: string): Visibility {
|
|
62
|
+
const value = text.trim();
|
|
63
|
+
return value === "private" || value === "public" || value === "internal" ? value : "unknown";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* How visible the backup repo is: "private" is the only answer that lets a push through.
|
|
68
|
+
* github and gitlab are asked through their CLIs; any other host must answer through
|
|
69
|
+
* `wip.private_check` (argv, URL last), and an empty setting is "unknown".
|
|
70
|
+
*/
|
|
71
|
+
export function backupVisibility(url: string, run: Run = (args) => cmd(args), check = ""): Visibility {
|
|
72
|
+
const remote = parseRemote(url);
|
|
73
|
+
if (!remote) return "unknown";
|
|
74
|
+
if (remote.host === "github.com") {
|
|
75
|
+
if (remote.segments.length !== 2) return "unknown";
|
|
76
|
+
const r = run(["gh", "api", `repos/${remote.segments[0]}/${remote.segments[1]}`, "--jq", ".visibility"]);
|
|
77
|
+
return r.code === 0 ? answer(r.stdout) : "unknown";
|
|
78
|
+
}
|
|
79
|
+
if (remote.host === "gitlab.com" || /(^|\.)gitlab\./.test(remote.host)) {
|
|
80
|
+
const r = run(["glab", "api", `projects/${encodeURIComponent(remote.segments.join("/"))}`]);
|
|
81
|
+
if (r.code !== 0) return "unknown";
|
|
82
|
+
try {
|
|
83
|
+
const parsed = JSON.parse(r.stdout) as { visibility?: unknown };
|
|
84
|
+
return answer(typeof parsed.visibility === "string" ? parsed.visibility : "");
|
|
85
|
+
} catch {
|
|
86
|
+
return "unknown";
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const probe = check.trim();
|
|
90
|
+
if (probe === "") return "unknown";
|
|
91
|
+
const r = run([...probe.split(/\s+/), url]);
|
|
92
|
+
return r.code === 0 && r.stdout.trim() === "private" ? "private" : "unknown";
|
|
93
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// `neurastream wip restore [<worktree>]` (plan 20261027_1130 P7): lists one worktree's hidden saves,
|
|
2
|
+
// newest first, and restores one into the worktree. A dirty worktree is snapshotted first, so the
|
|
3
|
+
// restore can never discard work done since the save; the new ref is printed.
|
|
4
|
+
|
|
5
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
6
|
+
import type { Config } from "./config.ts";
|
|
7
|
+
import { cmd } from "./proc.ts";
|
|
8
|
+
import { keyOf } from "./wip-roots.ts";
|
|
9
|
+
import { wipSnapshot } from "./wip-snapshot.ts";
|
|
10
|
+
|
|
11
|
+
/** One hidden save of a worktree, as its commit message and diff describe it. */
|
|
12
|
+
export interface WipSave {
|
|
13
|
+
/** The `YYYYMMDD-HHMM` stamp: the ref's last segment, and the order key. */
|
|
14
|
+
at: string;
|
|
15
|
+
ref: string;
|
|
16
|
+
commit: string;
|
|
17
|
+
/** The branch the worktree was on when the save ran. */
|
|
18
|
+
branch: string;
|
|
19
|
+
/** Paths the save changed against the branch head it was made on. */
|
|
20
|
+
changed: number;
|
|
21
|
+
/** New files the save refused: too big, or a secret path. */
|
|
22
|
+
skipped: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function wipSaves(wt: string, home: string): WipSave[] {
|
|
26
|
+
const key = keyOf(wt, home);
|
|
27
|
+
const r = cmd(["git", "-C", wt, "for-each-ref", "--sort=-refname", "--format=%(objectname) %(refname)", `refs/wip/${key}/`]);
|
|
28
|
+
if (r.code !== 0) return [];
|
|
29
|
+
const saves: WipSave[] = [];
|
|
30
|
+
for (const line of r.stdout.split("\n").filter(Boolean)) {
|
|
31
|
+
const [commit, ref] = line.split(" ");
|
|
32
|
+
if (!commit || !ref) continue;
|
|
33
|
+
const subject = cmd(["git", "-C", wt, "log", "-1", "--format=%s", commit]).stdout.trim();
|
|
34
|
+
const m = /\(([^)]*)\); skipped (\d+) new files/.exec(subject);
|
|
35
|
+
const diff = cmd(["git", "-C", wt, "diff", "--name-only", `${commit}^`, commit]);
|
|
36
|
+
saves.push({
|
|
37
|
+
at: ref.slice(ref.lastIndexOf("/") + 1),
|
|
38
|
+
ref,
|
|
39
|
+
commit,
|
|
40
|
+
branch: m?.[1] ?? "detached",
|
|
41
|
+
changed: diff.code === 0 ? diff.stdout.split("\n").filter(Boolean).length : 0,
|
|
42
|
+
skipped: m ? Number(m[2]) : 0,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
// The stamp is the order key; refname sort already agrees, and this keeps it true if it does not.
|
|
46
|
+
return saves.toSorted((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : 0));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* List the saves of `[<worktree>]`, or with `--pick N` restore the Nth of that newest-first list.
|
|
51
|
+
* Returns the runner's exit code: 0 listed/restored, 1 git refused, 2 bad usage.
|
|
52
|
+
*/
|
|
53
|
+
export function wipRestore(args: string[], cfg: Config, cwd: string = process.cwd()): number {
|
|
54
|
+
const pickAt = args.indexOf("--pick");
|
|
55
|
+
const pick = pickAt >= 0 ? args[pickAt + 1] : undefined;
|
|
56
|
+
if (pickAt >= 0 && pick === undefined) {
|
|
57
|
+
console.error("usage: neurastream wip restore [<worktree>] [--pick N]");
|
|
58
|
+
return 2;
|
|
59
|
+
}
|
|
60
|
+
// The value of --pick is not a worktree; with no --pick at all, -1 never matches an index.
|
|
61
|
+
const pickValueAt = pickAt >= 0 ? pickAt + 1 : -1;
|
|
62
|
+
const target = args.find((a, i) => !a.startsWith("--") && i !== pickValueAt) ?? cwd;
|
|
63
|
+
if (!existsSync(target)) {
|
|
64
|
+
console.error(`neurastream wip: ${target} does not exist`);
|
|
65
|
+
return 2;
|
|
66
|
+
}
|
|
67
|
+
const wt = realpathSync(target);
|
|
68
|
+
const saves = wipSaves(wt, cfg.paths.home);
|
|
69
|
+
if (saves.length === 0) {
|
|
70
|
+
console.log(`wip: no saves for ${wt} yet`);
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
if (pick === undefined) {
|
|
74
|
+
saves.forEach((save, i) => {
|
|
75
|
+
const skipped = save.skipped ? `, ${save.skipped} skipped big files` : "";
|
|
76
|
+
console.log(`${i + 1}. ${save.at} [${save.branch}] ${save.changed} changed paths${skipped} — ${save.ref}`);
|
|
77
|
+
});
|
|
78
|
+
console.log(`restore one: neurastream wip restore ${wt} --pick N`);
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
const n = Number(pick);
|
|
82
|
+
if (!Number.isInteger(n) || n < 1 || n > saves.length) {
|
|
83
|
+
console.error(`neurastream wip: --pick takes 1..${saves.length}`);
|
|
84
|
+
return 2;
|
|
85
|
+
}
|
|
86
|
+
const save = saves[n - 1]!;
|
|
87
|
+
// Nothing may be lost: uncommitted changes are saved — and the ref printed — before the restore.
|
|
88
|
+
if (cmd(["git", "-C", wt, "status", "--porcelain"]).stdout.trim() !== "") {
|
|
89
|
+
wipSnapshot(["--quiet"], cfg);
|
|
90
|
+
const newest = wipSaves(wt, cfg.paths.home)[0];
|
|
91
|
+
if (newest) console.log(`saved ${newest.ref} before restoring`);
|
|
92
|
+
}
|
|
93
|
+
// The commit, not the ref: a save made in this same minute reuses the stamp and moves the ref.
|
|
94
|
+
const r = cmd(["git", "-C", wt, "restore", `--source=${save.commit}`, "--worktree", "--", "."]);
|
|
95
|
+
if (r.code !== 0) {
|
|
96
|
+
console.error(`neurastream wip: git restore failed${r.stderr.trim() ? `: ${r.stderr.trim()}` : ""}`);
|
|
97
|
+
return 1;
|
|
98
|
+
}
|
|
99
|
+
console.log(`restored ${save.ref} into ${wt}`);
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
export function keyOf(path: string, home: string): string {
|
|
6
|
+
const realHome = existsSync(home) ? realpathSync(home) : home;
|
|
7
|
+
const realPath = existsSync(path) ? realpathSync(path) : path;
|
|
8
|
+
return relative(realHome, realPath).replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function walkFolder(dir: string, currentDepth: number, maxDepth: number, out: string[]): void {
|
|
12
|
+
if (currentDepth > maxDepth) return;
|
|
13
|
+
let entries: string[];
|
|
14
|
+
try {
|
|
15
|
+
entries = readdirSync(dir);
|
|
16
|
+
} catch {
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
for (const entry of entries) {
|
|
20
|
+
if (entry === "node_modules" || entry === ".git") continue;
|
|
21
|
+
const fullPath = join(dir, entry);
|
|
22
|
+
let st;
|
|
23
|
+
try {
|
|
24
|
+
st = statSync(fullPath);
|
|
25
|
+
} catch {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (!st.isDirectory()) continue;
|
|
29
|
+
|
|
30
|
+
if (existsSync(join(fullPath, ".git"))) {
|
|
31
|
+
out.push(fullPath);
|
|
32
|
+
} else {
|
|
33
|
+
walkFolder(fullPath, currentDepth + 1, maxDepth, out);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function wipRepos(cfg: Config): string[] {
|
|
39
|
+
const out: string[] = [];
|
|
40
|
+
const maxDepth = Math.max(0, cfg.wip.depth ?? 3);
|
|
41
|
+
for (const root of cfg.wip.roots) {
|
|
42
|
+
if (!existsSync(root)) continue;
|
|
43
|
+
let st;
|
|
44
|
+
try {
|
|
45
|
+
st = statSync(root);
|
|
46
|
+
} catch {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (!st.isDirectory()) continue;
|
|
50
|
+
|
|
51
|
+
if (existsSync(join(root, ".git"))) {
|
|
52
|
+
out.push(root);
|
|
53
|
+
} else {
|
|
54
|
+
walkFolder(root, 1, maxDepth, out);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return Array.from(new Set(out)).toSorted();
|
|
58
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// `neurastream wip on|off` (plan 20261027_1130 P6): installs the hourly snapshot timer and, when a
|
|
2
|
+
// backup repo is configured, the daily backup timer; off removes both. Same Runner seam as
|
|
3
|
+
// watch/pages, so tests record argv and never run systemctl or launchctl: the service manager is
|
|
4
|
+
// probed FIRST and a failed check writes nothing. Existing unit files are rewritten, never treated
|
|
5
|
+
// as "already present" — the hand-made units that failed unnoticed since 2026-10-21 are exactly
|
|
6
|
+
// what this replaces.
|
|
7
|
+
|
|
8
|
+
import { spawnSync } from "node:child_process";
|
|
9
|
+
import { accessSync, constants, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { basename, dirname, join } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { checkEdited, setConfigKeys } from "./config-edit.ts";
|
|
14
|
+
import { configFile, loadConfig, type Config } from "./config.ts";
|
|
15
|
+
import { systemRunner, type Runner } from "./pages-setup.ts";
|
|
16
|
+
import { cmd } from "./proc.ts";
|
|
17
|
+
import { readWipLast, type WipLast } from "./wip-fail.ts";
|
|
18
|
+
import { backupVisibility, type Visibility } from "./wip-private.ts";
|
|
19
|
+
|
|
20
|
+
const TEMPLATES = join(dirname(fileURLToPath(import.meta.url)), "../../templates");
|
|
21
|
+
|
|
22
|
+
/** launchctl: the macOS counterpart of systemRunner. */
|
|
23
|
+
const launchctlRunner: Runner = args => {
|
|
24
|
+
const r = spawnSync("launchctl", args, { encoding: "utf8" });
|
|
25
|
+
return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** The unit files of one job: the service and its timer (.service + .timer), or the agent plist. */
|
|
29
|
+
export interface WipUnits {
|
|
30
|
+
snapshot: string[];
|
|
31
|
+
backup: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function wipUnitPaths(home: string, platform: NodeJS.Platform = process.platform): WipUnits {
|
|
35
|
+
if (platform === "darwin") {
|
|
36
|
+
const dir = join(home, "Library/LaunchAgents");
|
|
37
|
+
return { snapshot: [join(dir, "com.neurastream.wip-snapshot.plist")], backup: [join(dir, "com.neurastream.wip-backup.plist")] };
|
|
38
|
+
}
|
|
39
|
+
const dir = join(home, ".config/systemd/user");
|
|
40
|
+
return {
|
|
41
|
+
snapshot: [join(dir, "neurastream-wip-snapshot.service"), join(dir, "neurastream-wip-snapshot.timer")],
|
|
42
|
+
backup: [join(dir, "neurastream-wip-backup.service"), join(dir, "neurastream-wip-backup.timer")],
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The templates in wipUnitPaths order, relative to templates/. */
|
|
47
|
+
function wipTemplates(platform: NodeJS.Platform): WipUnits {
|
|
48
|
+
if (platform === "darwin") return { snapshot: ["launchd/neurastream-wip-snapshot.plist"], backup: ["launchd/neurastream-wip-backup.plist"] };
|
|
49
|
+
return {
|
|
50
|
+
snapshot: ["systemd/neurastream-wip-snapshot.service", "systemd/neurastream-wip-snapshot.timer"],
|
|
51
|
+
backup: ["systemd/neurastream-wip-backup.service", "systemd/neurastream-wip-backup.timer"],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Which wip units are installed here, and how the last runs ended: the doctor line. */
|
|
56
|
+
export interface WipHealth {
|
|
57
|
+
installed: boolean;
|
|
58
|
+
backupInstalled: boolean;
|
|
59
|
+
last: WipLast;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function wipHealth(cfg: Config, platform: NodeJS.Platform = process.platform): WipHealth {
|
|
63
|
+
const paths = wipUnitPaths(cfg.paths.home, platform);
|
|
64
|
+
return {
|
|
65
|
+
installed: paths.snapshot.every(p => existsSync(p)),
|
|
66
|
+
backupInstalled: paths.backup.every(p => existsSync(p)),
|
|
67
|
+
last: readWipLast(cfg),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface WipSetupOptions {
|
|
72
|
+
/** HOME the units, the config and wip-last.json resolve against. Default: the real home. */
|
|
73
|
+
home?: string;
|
|
74
|
+
/** Defaults to process.platform; tests inject it to pick the unit set. */
|
|
75
|
+
platform?: NodeJS.Platform;
|
|
76
|
+
/** Command runner. Default: systemRunner (Linux) or launchctl. */
|
|
77
|
+
runner?: Runner;
|
|
78
|
+
/** The private-repo check; default runs `gh`/`glab`/wip.private_check for real. */
|
|
79
|
+
visibility?: (url: string) => Visibility;
|
|
80
|
+
print?: (line: string) => void;
|
|
81
|
+
error?: (line: string) => void;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function wipOn(opts: WipSetupOptions & { backupUrl?: string | null } = {}): number {
|
|
85
|
+
const home = opts.home ?? homedir();
|
|
86
|
+
const platform = opts.platform ?? process.platform;
|
|
87
|
+
const runner = opts.runner ?? (platform === "darwin" ? launchctlRunner : systemRunner);
|
|
88
|
+
const print = opts.print ?? console.log;
|
|
89
|
+
const error = opts.error ?? console.error;
|
|
90
|
+
const fail = (line: string): number => {
|
|
91
|
+
error(`neurastream wip: ${line}`);
|
|
92
|
+
return 1;
|
|
93
|
+
};
|
|
94
|
+
// Checks first (same shape as uiOn): the manager answers, roots exist, and a backup repo is
|
|
95
|
+
// private with the secret gate answering. A failed check writes nothing.
|
|
96
|
+
const probe = runner(platform === "darwin" ? ["list"] : ["--user", "show-environment"]);
|
|
97
|
+
if (probe.status !== 0) return fail(`the service manager does not answer${probe.stderr.trim() ? `: ${probe.stderr.trim()}` : ""} — nothing was written`);
|
|
98
|
+
let cfg: Config;
|
|
99
|
+
try {
|
|
100
|
+
cfg = loadConfig({ home });
|
|
101
|
+
} catch (err) {
|
|
102
|
+
return fail(err instanceof Error ? err.message : String(err));
|
|
103
|
+
}
|
|
104
|
+
if (cfg.wip.roots.length === 0) return fail("wip.roots is empty — add a folder first (`neurastream wip add <path>`), then run this again");
|
|
105
|
+
const url = (opts.backupUrl ?? cfg.wip.backup_url).trim();
|
|
106
|
+
if (url !== "") {
|
|
107
|
+
const state = (opts.visibility ?? ((u: string) => backupVisibility(u, cmd, cfg.wip.private_check)))(url);
|
|
108
|
+
if (state !== "private") {
|
|
109
|
+
const why = `${url} is ${state}`;
|
|
110
|
+
return fail(`${why} — the backup timer only runs to a repo confirmed private; nothing was written`);
|
|
111
|
+
}
|
|
112
|
+
const gate = cfg.wip.secret_gate;
|
|
113
|
+
let executable = true;
|
|
114
|
+
try {
|
|
115
|
+
accessSync(gate, constants.X_OK);
|
|
116
|
+
} catch {
|
|
117
|
+
executable = false;
|
|
118
|
+
}
|
|
119
|
+
if (!executable) return fail(`${gate} is missing — the backup refuses to upload without the secret gate; nothing was written`);
|
|
120
|
+
const scan = cmd([gate, "scan"]);
|
|
121
|
+
if (scan.code !== 0 && scan.code !== 1) {
|
|
122
|
+
return fail(`${gate} scan exited ${scan.code}${scan.stderr.trim() ? `: ${scan.stderr.trim().split("\n")[0]}` : ""} — nothing was written`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// Write the units, then enable them. Always a write: an old hand-made unit would otherwise stay.
|
|
126
|
+
const paths = wipUnitPaths(home, platform);
|
|
127
|
+
const templates = wipTemplates(platform);
|
|
128
|
+
const write = (targets: string[], sources: string[]): void => {
|
|
129
|
+
targets.forEach((file, i) => {
|
|
130
|
+
const text = readFileSync(join(TEMPLATES, sources[i]!), "utf8").replaceAll("__HOME__", home);
|
|
131
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
132
|
+
writeFileSync(file, text);
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
write(paths.snapshot, templates.snapshot);
|
|
136
|
+
if (url !== "") write(paths.backup, templates.backup);
|
|
137
|
+
const failed = (what: string, stderr: string): number =>
|
|
138
|
+
fail(`${what} failed${stderr.trim() ? `: ${stderr.trim()}` : ""} — the unit files are written; fix this and run the command again`);
|
|
139
|
+
if (platform === "darwin") {
|
|
140
|
+
for (const file of [...paths.snapshot, ...(url === "" ? [] : paths.backup)]) {
|
|
141
|
+
runner(["unload", "-w", file]); // not loaded yet is fine
|
|
142
|
+
const r = runner(["load", "-w", file]);
|
|
143
|
+
if (r.status !== 0) return failed("launchctl", r.stderr);
|
|
144
|
+
}
|
|
145
|
+
} else {
|
|
146
|
+
const reload = runner(["--user", "daemon-reload"]);
|
|
147
|
+
if (reload.status !== 0) return failed("systemctl", reload.stderr);
|
|
148
|
+
for (const timer of [paths.snapshot[1]!, ...(url === "" ? [] : [paths.backup[1]!])]) {
|
|
149
|
+
const r = runner(["--user", "enable", "--now", basename(timer)]);
|
|
150
|
+
if (r.status !== 0) return failed("systemctl", r.stderr);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// The config records the URL only once the timers are live (a failed enable leaves it alone).
|
|
154
|
+
if (opts.backupUrl && opts.backupUrl !== cfg.wip.backup_url) {
|
|
155
|
+
const file = configFile(home);
|
|
156
|
+
const edited = setConfigKeys(existsSync(file) ? readFileSync(file, "utf8") : null, { "wip.backup_url": opts.backupUrl });
|
|
157
|
+
if (!checkEdited(edited, home, error)) return 1;
|
|
158
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
159
|
+
writeFileSync(file, edited);
|
|
160
|
+
}
|
|
161
|
+
const line = url === "" ? "wip: on — snapshot hourly; no backup repo set (neurastream wip on --backup-url <url>)" : `wip: on — snapshot hourly, backup daily 23:30 to ${url}`;
|
|
162
|
+
print(line);
|
|
163
|
+
return 0;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function wipOff(opts: WipSetupOptions = {}): number {
|
|
167
|
+
const home = opts.home ?? homedir();
|
|
168
|
+
const platform = opts.platform ?? process.platform;
|
|
169
|
+
const runner = opts.runner ?? (platform === "darwin" ? launchctlRunner : systemRunner);
|
|
170
|
+
const print = opts.print ?? console.log;
|
|
171
|
+
const error = opts.error ?? console.error;
|
|
172
|
+
const paths = wipUnitPaths(home, platform);
|
|
173
|
+
const failed = (what: string, stderr: string): number => {
|
|
174
|
+
error(`neurastream wip: ${what} failed${stderr.trim() ? `: ${stderr.trim()}` : ""}`);
|
|
175
|
+
return 1;
|
|
176
|
+
};
|
|
177
|
+
if (platform === "darwin") {
|
|
178
|
+
for (const file of [...paths.snapshot, ...paths.backup]) {
|
|
179
|
+
if (!existsSync(file)) continue;
|
|
180
|
+
const r = runner(["unload", "-w", file]);
|
|
181
|
+
if (r.status !== 0) return failed("launchctl", r.stderr);
|
|
182
|
+
}
|
|
183
|
+
} else {
|
|
184
|
+
for (const timer of [paths.snapshot[1]!, paths.backup[1]!]) {
|
|
185
|
+
if (!existsSync(timer)) continue;
|
|
186
|
+
const r = runner(["--user", "disable", "--now", basename(timer)]);
|
|
187
|
+
if (r.status !== 0) return failed("systemctl", r.stderr);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
for (const file of [...paths.snapshot, ...paths.backup]) rmSync(file, { force: true });
|
|
191
|
+
if (platform !== "darwin") {
|
|
192
|
+
const reload = runner(["--user", "daemon-reload"]);
|
|
193
|
+
if (reload.status !== 0) return failed("systemctl", reload.stderr);
|
|
194
|
+
}
|
|
195
|
+
print("wip: off");
|
|
196
|
+
return 0;
|
|
197
|
+
}
|