@oficiallyakshay/trash-panda 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +108 -2
- package/docs/reference.md +220 -0
- package/examples/in-charge.json +7 -0
- package/examples/live.json +17 -0
- package/package.json +38 -4
- package/scripts/claude-leftovers-cleanup.mjs +242 -0
- package/src/claude-leftovers.mjs +949 -0
- package/src/metrics.mjs +233 -0
- package/src/rebuildables.mjs +491 -0
- package/src/records.mjs +326 -0
- package/src/settings.mjs +205 -0
- package/src/setup.mjs +428 -0
- package/src/temp-entries.mjs +153 -0
- package/src/triggers.mjs +500 -0
- package/src/tui/format.mjs +177 -0
- package/src/tui/watch.mjs +118 -0
- package/src/update.mjs +281 -0
- package/src/worktree-git.mjs +145 -0
- package/src/worktree-liveness.mjs +87 -0
package/src/records.mjs
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/records.mjs — trash-panda's own records and what they add up to.
|
|
3
|
+
*
|
|
4
|
+
* history.jsonl one line per finished run
|
|
5
|
+
* events.jsonl one line each time free space goes under a mark or comes back
|
|
6
|
+
* errors.jsonl one line each time a command of trash-panda failed
|
|
7
|
+
*
|
|
8
|
+
* Every record stays in the trash-panda folder: nothing here reaches a network.
|
|
9
|
+
* Each file is capped: when it is full it becomes `<name>.1` (which replaces
|
|
10
|
+
* the older one) and a new file starts. Readers read both, oldest first, and
|
|
11
|
+
* skip a line they cannot read, so a line from an older version still counts.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
|
|
15
|
+
import { basename, join } from "node:path";
|
|
16
|
+
import { CLEANUP_RULES, formatSize } from "./claude-leftovers.mjs";
|
|
17
|
+
import { readSettings, settingsPath } from "./settings.mjs";
|
|
18
|
+
import { LABEL, defaultLaunchctl, wiring } from "./setup.mjs";
|
|
19
|
+
|
|
20
|
+
/** A record file this big is rotated before its next line. */
|
|
21
|
+
export const RECORD_MAX_BYTES = 1024 * 1024;
|
|
22
|
+
// Reasons kept per run, and lines shown by a summary.
|
|
23
|
+
const TOP = 10;
|
|
24
|
+
const TAIL_LINES = 20;
|
|
25
|
+
const SINCE_MS = { h: 3_600_000, d: 86_400_000, w: 7 * 86_400_000 };
|
|
26
|
+
const MARKS = ["low", "critical"];
|
|
27
|
+
// The kinds of a history line, each as the rules it adds up.
|
|
28
|
+
export const KINDS = {
|
|
29
|
+
worktrees: ["repos", "codeFolder"],
|
|
30
|
+
records: ["records"],
|
|
31
|
+
rebuildables: ["rebuild"],
|
|
32
|
+
caches: ["caches"],
|
|
33
|
+
scratch: ["scratch"],
|
|
34
|
+
tests: ["tests"],
|
|
35
|
+
chrome: ["chrome"],
|
|
36
|
+
uv: ["uv"],
|
|
37
|
+
playwright: ["playwright"],
|
|
38
|
+
temp: ["temp"],
|
|
39
|
+
};
|
|
40
|
+
const KIND_LABELS = { worktrees: "worktrees", records: "worktree records", rebuildables: "rebuildable folders", caches: "module caches", scratch: "scratch folders", tests: "test folders", chrome: "Chrome copies", uv: "uv cache", playwright: "old Playwright builds", temp: "old temp entries" };
|
|
41
|
+
// A keep reason that means a check got no answer, not that the item is in use.
|
|
42
|
+
const NO_ANSWER_RE = /unreadable|unresolvable|unavailable|unknown|failed|could not|no readable|not found/i;
|
|
43
|
+
|
|
44
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
45
|
+
const stamp = (ms) => new Date(ms).toISOString();
|
|
46
|
+
const readText = (path) => {
|
|
47
|
+
try {
|
|
48
|
+
return readFileSync(path, "utf8");
|
|
49
|
+
} catch {
|
|
50
|
+
return "";
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// ── files ───────────────────────────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
/** Add one line to the record file `name`; a full file is rotated first. */
|
|
57
|
+
export function appendRecord(dir, name, line, { maxBytes = RECORD_MAX_BYTES } = {}) {
|
|
58
|
+
const path = join(dir, name);
|
|
59
|
+
let size = 0;
|
|
60
|
+
try {
|
|
61
|
+
size = statSync(path).size;
|
|
62
|
+
} catch {
|
|
63
|
+
// the first line
|
|
64
|
+
}
|
|
65
|
+
if (size >= maxBytes) renameSync(path, `${path}.1`);
|
|
66
|
+
appendFileSync(path, `${JSON.stringify(line)}\n`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The record lines of `name` whose `timeKey` is a time, oldest first, the rotated file included. */
|
|
70
|
+
export function readRecords(dir, name, timeKey = "at") {
|
|
71
|
+
const path = join(dir, name);
|
|
72
|
+
const out = [];
|
|
73
|
+
for (const line of [...readText(`${path}.1`).split("\n"), ...readText(path).split("\n")]) {
|
|
74
|
+
let parsed;
|
|
75
|
+
try {
|
|
76
|
+
parsed = JSON.parse(line);
|
|
77
|
+
} catch {
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (isObject(parsed) && Number.isFinite(Date.parse(parsed[timeKey]))) out.push(parsed);
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Add one failure to errors.jsonl. Never throws: a record never stops a cleanup. */
|
|
86
|
+
export function recordError(dir, command, error, { now = Date.now } = {}) {
|
|
87
|
+
try {
|
|
88
|
+
mkdirSync(dir, { recursive: true });
|
|
89
|
+
appendRecord(dir, "errors.jsonl", { at: stamp(now()), command, message: String(error?.message ?? error).split("\n")[0].slice(0, 300) });
|
|
90
|
+
} catch {
|
|
91
|
+
// nothing can be written
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── one run ─────────────────────────────────────────────────────────────────
|
|
96
|
+
|
|
97
|
+
/** A keep reason without what differs per item: numbers, paths and command lines. */
|
|
98
|
+
export function plainReason(reason) {
|
|
99
|
+
return String(reason)
|
|
100
|
+
.split("\n")[0]
|
|
101
|
+
.replace(/^Command failed\b.*/, "Command failed")
|
|
102
|
+
.replace(/'\/[^']*'/g, "<path>")
|
|
103
|
+
.replace(/(^|[\s"(=])\/[^\s")]+/g, "$1<path>")
|
|
104
|
+
.replace(/\d+/g, "N")
|
|
105
|
+
.slice(0, 120);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function countReasons(items) {
|
|
109
|
+
const counts = new Map();
|
|
110
|
+
for (const [reason, count] of items) counts.set(reason, (counts.get(reason) ?? 0) + count);
|
|
111
|
+
return [...counts].map(([reason, count]) => ({ reason, count })).sort((a, b) => b.count - a.count || a.reason.localeCompare(b.reason));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The keys a history line has beyond `last`: free space, kinds, keep reasons and errors. */
|
|
115
|
+
export function runDetails(result, { before, after, deleted }) {
|
|
116
|
+
const kinds = {};
|
|
117
|
+
for (const [kind, rules] of Object.entries(KINDS)) {
|
|
118
|
+
// Temp entries are counted, never listed.
|
|
119
|
+
const items = rules.reduce((n, key) => n + (result[key].removedCount ?? result[key].removed.length), 0);
|
|
120
|
+
kinds[kind] = { items, freedBytes: deleted ? rules.reduce((n, key) => n + result[key].bytes, 0) : 0 };
|
|
121
|
+
}
|
|
122
|
+
const kept = countReasons(CLEANUP_RULES.flatMap(({ key }) => result[key].kept.map((k) => [plainReason(k.reason), 1])));
|
|
123
|
+
return {
|
|
124
|
+
freeBefore: before?.freeBytes ?? null,
|
|
125
|
+
freeAfter: after?.freeBytes ?? null,
|
|
126
|
+
kinds,
|
|
127
|
+
kept: kept.slice(0, TOP),
|
|
128
|
+
errors: CLEANUP_RULES.reduce((n, { key }) => n + result[key].errors, 0),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The rules a run left out because a check got no answer, as `{ rule, reason }`. */
|
|
133
|
+
export const skippedRules = (result) => CLEANUP_RULES.filter(({ key }) => result[key].skipped && result[key].skipped !== "not in --only").map(({ key, label }) => ({ rule: label, reason: result[key].skipped }));
|
|
134
|
+
|
|
135
|
+
// ── the session that started a run ──────────────────────────────────────────
|
|
136
|
+
|
|
137
|
+
/** The session's custom title from the hook input, else its folder's name, else null. */
|
|
138
|
+
export function sessionName(input) {
|
|
139
|
+
for (const value of [input?.session_title, typeof input?.cwd === "string" ? basename(input.cwd) : null]) {
|
|
140
|
+
const name = typeof value === "string" ? value.replace(/\p{Cc}+/gu, " ").trim().slice(0, 200) : "";
|
|
141
|
+
if (name) return name;
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The hook input as an object, or null when there is none. A terminal has none,
|
|
148
|
+
* and input that does not end within `waitMs` is not waited for.
|
|
149
|
+
*/
|
|
150
|
+
export function readHookInput(stdin = process.stdin, { waitMs = 300 } = {}) {
|
|
151
|
+
if (stdin.isTTY) return Promise.resolve(null);
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
let text = "";
|
|
154
|
+
const done = () => {
|
|
155
|
+
clearTimeout(timer);
|
|
156
|
+
stdin.destroy();
|
|
157
|
+
try {
|
|
158
|
+
resolve(JSON.parse(text));
|
|
159
|
+
} catch {
|
|
160
|
+
resolve(null);
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const timer = setTimeout(done, waitMs);
|
|
164
|
+
stdin.setEncoding("utf8");
|
|
165
|
+
stdin.on("data", (chunk) => {
|
|
166
|
+
text += chunk;
|
|
167
|
+
});
|
|
168
|
+
stdin.on("end", done);
|
|
169
|
+
stdin.on("error", done);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ── falls ───────────────────────────────────────────────────────────────────
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* One line in events.jsonl for each mark that free space crossed since the last
|
|
177
|
+
* line of that mark. The file is the memory, so any process may look. Unknown
|
|
178
|
+
* free space crosses nothing, and a failed write never stops a run.
|
|
179
|
+
*/
|
|
180
|
+
export function recordCrossings(dir, { disk, settings, now }) {
|
|
181
|
+
if (disk?.freePct == null) return;
|
|
182
|
+
try {
|
|
183
|
+
const events = readRecords(dir, "events.jsonl");
|
|
184
|
+
for (const mark of MARKS) {
|
|
185
|
+
const markPct = mark === "low" ? settings.lowMarkPct : settings.criticalMarkPct;
|
|
186
|
+
const last = events.findLast((e) => e.mark === mark);
|
|
187
|
+
const to = disk.freePct < markPct ? "under" : "back";
|
|
188
|
+
// The first look above a mark is no crossing.
|
|
189
|
+
if (to === (last?.to ?? "back")) continue;
|
|
190
|
+
const line = { at: stamp(now), mark, to, markPct, freeBytes: disk.freeBytes, freePct: disk.freePct };
|
|
191
|
+
if (to === "back") line.underSec = Math.max(0, Math.round((now - Date.parse(last.at)) / 1000));
|
|
192
|
+
appendRecord(dir, "events.jsonl", line);
|
|
193
|
+
}
|
|
194
|
+
} catch (e) {
|
|
195
|
+
recordError(dir, "events", e);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Falls under one mark in [from, to], and the seconds spent under it there. */
|
|
200
|
+
function fallsUnder(events, mark, from, to) {
|
|
201
|
+
let start = null;
|
|
202
|
+
let falls = 0;
|
|
203
|
+
let underMs = 0;
|
|
204
|
+
const add = (a, b) => {
|
|
205
|
+
underMs += Math.max(0, Math.min(b, to) - Math.max(a, from));
|
|
206
|
+
};
|
|
207
|
+
for (const e of events) {
|
|
208
|
+
const at = Date.parse(e.at);
|
|
209
|
+
if (e.mark !== mark || at > to) continue;
|
|
210
|
+
if (e.to === "under" && start === null) {
|
|
211
|
+
start = at;
|
|
212
|
+
if (at >= from) falls += 1;
|
|
213
|
+
} else if (e.to === "back" && start !== null) {
|
|
214
|
+
add(start, at);
|
|
215
|
+
start = null;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (start !== null) add(start, to);
|
|
219
|
+
return { falls, underSec: Math.round(underMs / 1000), underNow: start !== null };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ── stats ───────────────────────────────────────────────────────────────────
|
|
223
|
+
|
|
224
|
+
/** `7d`, `12h` or `2w` in ms, or null. */
|
|
225
|
+
export function parseSince(text) {
|
|
226
|
+
const m = /^([1-9]\d{0,3})([hdw])$/.exec(text);
|
|
227
|
+
return m ? Number(m[1]) * SINCE_MS[m[2]] : null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** What the records add up to over the last `sinceMs`. Reads only. */
|
|
231
|
+
export function buildStats(dir, { sinceMs, now }) {
|
|
232
|
+
const from = now - sinceMs;
|
|
233
|
+
const events = readRecords(dir, "events.jsonl");
|
|
234
|
+
const runs = readRecords(dir, "history.jsonl", "finishedAt").filter((r) => Date.parse(r.finishedAt) >= from && Date.parse(r.finishedAt) <= now);
|
|
235
|
+
const cleanups = runs.filter((r) => !r.preview);
|
|
236
|
+
const byTrigger = {};
|
|
237
|
+
for (const r of runs) byTrigger[r.by] = (byTrigger[r.by] ?? 0) + 1;
|
|
238
|
+
const kinds = {};
|
|
239
|
+
for (const kind of Object.keys(KINDS)) {
|
|
240
|
+
const rows = cleanups.map((r) => r.kinds?.[kind]).filter(isObject);
|
|
241
|
+
kinds[kind] = { items: rows.reduce((n, k) => n + (k.items ?? 0), 0), freedBytes: rows.reduce((n, k) => n + (k.freedBytes ?? 0), 0) };
|
|
242
|
+
}
|
|
243
|
+
const freed = cleanups.filter((r) => r.freedBytes > 0);
|
|
244
|
+
return {
|
|
245
|
+
format: 1,
|
|
246
|
+
since: stamp(from),
|
|
247
|
+
until: stamp(now),
|
|
248
|
+
falls: Object.fromEntries(MARKS.map((mark) => [mark, fallsUnder(events, mark, from, now)])),
|
|
249
|
+
runs: { total: runs.length, byTrigger, preview: runs.length - cleanups.length, freedNothing: cleanups.length - freed.length, withoutKinds: cleanups.filter((r) => !isObject(r.kinds)).length },
|
|
250
|
+
freedBytes: freed.reduce((n, r) => n + r.freedBytes, 0),
|
|
251
|
+
kinds,
|
|
252
|
+
kept: countReasons(runs.flatMap((r) => (Array.isArray(r.kept) ? r.kept.map((k) => [k.reason, k.count]) : []))).slice(0, TOP),
|
|
253
|
+
recoveries: freed.map((r) => ({ at: r.finishedAt, by: r.by, session: r.session ?? null, freedBytes: r.freedBytes, freeBefore: r.freeBefore ?? null, freeAfter: r.freeAfter ?? null })),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const duration = (sec) => (sec >= 3600 ? `${Math.floor(sec / 3600)} h ${Math.floor((sec % 3600) / 60)} min` : sec >= 60 ? `${Math.floor(sec / 60)} min` : `${sec} s`);
|
|
258
|
+
|
|
259
|
+
/** The lines `trash-panda stats` prints. */
|
|
260
|
+
export function statsLines(s) {
|
|
261
|
+
const lines = [`From ${s.since} to ${s.until}`];
|
|
262
|
+
for (const mark of MARKS) {
|
|
263
|
+
const f = s.falls[mark];
|
|
264
|
+
lines.push(`Falls under the ${mark} mark: ${f.falls}, ${duration(f.underSec)} under it${f.underNow ? ", under it now" : ""}`);
|
|
265
|
+
}
|
|
266
|
+
const triggers = Object.entries(s.runs.byTrigger).map(([by, n]) => `${by} ${n}`);
|
|
267
|
+
lines.push(`Runs: ${s.runs.total}${triggers.length ? ` (${triggers.join(", ")})` : ""}, ${s.runs.preview} in preview, ${s.runs.freedNothing} freed nothing`);
|
|
268
|
+
lines.push(`Recovered: ${formatSize(s.freedBytes)}`);
|
|
269
|
+
for (const [kind, k] of Object.entries(s.kinds)) if (k.items) lines.push(` ${KIND_LABELS[kind]}: ${k.items}, ${formatSize(k.freedBytes)}`);
|
|
270
|
+
if (s.runs.withoutKinds) lines.push(` ${s.runs.withoutKinds} older runs did not record their kinds`);
|
|
271
|
+
if (s.recoveries.length) lines.push("Latest runs that freed space:");
|
|
272
|
+
for (const r of s.recoveries.slice(-TOP)) {
|
|
273
|
+
const free = r.freeBefore === null || r.freeAfter === null ? "" : `, free ${formatSize(r.freeBefore)} to ${formatSize(r.freeAfter)}`;
|
|
274
|
+
lines.push(` ${r.at} ${r.by}${r.session ? ` (${r.session})` : ""}: ${formatSize(r.freedBytes)}${free}`);
|
|
275
|
+
}
|
|
276
|
+
if (s.kept.length) lines.push("Why items were kept (counted on each run):");
|
|
277
|
+
for (const k of s.kept) lines.push(` ${k.count} ${k.reason}`);
|
|
278
|
+
return lines;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ── diagnose ────────────────────────────────────────────────────────────────
|
|
282
|
+
|
|
283
|
+
/** What is wrong, from the records and the wiring. Reads only. */
|
|
284
|
+
export function buildDiagnosis({ dir, home, uid, now, launchctl = defaultLaunchctl }) {
|
|
285
|
+
let state = {};
|
|
286
|
+
try {
|
|
287
|
+
state = JSON.parse(readText(join(dir, "state.json")));
|
|
288
|
+
} catch {
|
|
289
|
+
// no run yet
|
|
290
|
+
}
|
|
291
|
+
const kept = Array.isArray(state.kept) ? state.kept.map((k) => plainReason(k.reason)).filter((r) => NO_ANSWER_RE.test(r)) : [];
|
|
292
|
+
const tick = readText(join(dir, "tick.log")).split("\n").filter(Boolean);
|
|
293
|
+
let lookedAt = null;
|
|
294
|
+
try {
|
|
295
|
+
lookedAt = JSON.parse(readText(join(dir, "live.json"))).at ?? null;
|
|
296
|
+
} catch {
|
|
297
|
+
// no look yet
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
format: 1,
|
|
301
|
+
at: stamp(now),
|
|
302
|
+
lastLookAt: lookedAt,
|
|
303
|
+
lastRunAt: state.finishedAt ?? null,
|
|
304
|
+
settingsProblems: readSettings(settingsPath(dir)).problems,
|
|
305
|
+
errors: readRecords(dir, "errors.jsonl").slice(-TOP),
|
|
306
|
+
unreadable: countReasons(kept.map((r) => [r, 1])),
|
|
307
|
+
skipped: Array.isArray(state.skipped) ? state.skipped : [],
|
|
308
|
+
...wiring({ home, uid, launchctl }),
|
|
309
|
+
tickLog: tick.slice(-TAIL_LINES),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The lines `trash-panda diagnose` prints. */
|
|
314
|
+
export function diagnosisLines(d) {
|
|
315
|
+
const list = (title, rows) => (rows.length ? [`${title}:`, ...rows.map((r) => ` ${r}`)] : [`${title}: none`]);
|
|
316
|
+
return [
|
|
317
|
+
`Last look: ${d.lastLookAt ?? "never"}. Last finished run: ${d.lastRunAt ?? "never"}.`,
|
|
318
|
+
`Job ${LABEL}: ${d.job.installed ? "installed" : "not installed"}, ${d.job.loaded ? "loaded" : "not loaded"}`,
|
|
319
|
+
`Session-start hook: ${d.hook.installed ? "installed" : "not installed"}`,
|
|
320
|
+
...list("Settings problems", d.settingsProblems),
|
|
321
|
+
...list("Last errors", d.errors.map((e) => `${e.at} ${e.command}: ${e.message}`)),
|
|
322
|
+
...list("Items the last run kept because a check got no answer", d.unreadable.map((u) => `${u.count} ${u.reason}`)),
|
|
323
|
+
...list("Rules the last run skipped", d.skipped.map((s) => `${s.rule}: ${s.reason}`)),
|
|
324
|
+
...list("Tick log, last lines", d.tickLog),
|
|
325
|
+
];
|
|
326
|
+
}
|
package/src/settings.mjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/settings.mjs — the one settings file, `~/.trash-panda/settings.json`,
|
|
3
|
+
* which only the person writes (`config`, its use by the Mac app's panel, and
|
|
4
|
+
* setup's question save the person's own answer in it). Nothing in trash-panda
|
|
5
|
+
* turns preview off by itself.
|
|
6
|
+
*
|
|
7
|
+
* Every key has a default. A missing file gives the defaults. An unknown key or
|
|
8
|
+
* a bad value is refused by name and its default stays; a file that cannot be
|
|
9
|
+
* read or parsed is a problem too, and any problem turns preview on, so a broken
|
|
10
|
+
* file never deletes anything. Nothing is listed by default, so a fresh install
|
|
11
|
+
* touches only what the built-in rules name. docs/reference.md lists every key.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { isAbsolute, join } from "node:path";
|
|
17
|
+
|
|
18
|
+
export const DEFAULTS = Object.freeze({
|
|
19
|
+
// In preview every start only reports what it would remove.
|
|
20
|
+
preview: true,
|
|
21
|
+
// Free space, in percent of the volume, below which space is low.
|
|
22
|
+
lowMarkPct: 20,
|
|
23
|
+
criticalMarkPct: 10,
|
|
24
|
+
triggers: {
|
|
25
|
+
lowDisk: { on: true },
|
|
26
|
+
schedule: { on: true, everySec: 3600 },
|
|
27
|
+
sessionStart: { on: true },
|
|
28
|
+
},
|
|
29
|
+
tickSec: 300,
|
|
30
|
+
onCritical: null,
|
|
31
|
+
onCriticalTimeoutSec: 60,
|
|
32
|
+
// Folders whose repositories are searched for worktrees, beside the ones the
|
|
33
|
+
// app's registry names. Full paths only.
|
|
34
|
+
repoRoots: [],
|
|
35
|
+
// Folders whose `<pid>-*` children are test folders. Full paths only.
|
|
36
|
+
testDirs: [],
|
|
37
|
+
// Folders whose hash-named children are shared package caches. Full paths only.
|
|
38
|
+
moduleCacheDirs: [],
|
|
39
|
+
// Starts of the names in the macOS user temp folder that old entries may have.
|
|
40
|
+
// Nothing else there is ever touched.
|
|
41
|
+
tempPrefixes: [],
|
|
42
|
+
// An entry's birth and last change must both be older than this many days.
|
|
43
|
+
tempMinAgeDays: 7,
|
|
44
|
+
// Entries in one batch, the seconds between batches and the batches in one run.
|
|
45
|
+
tempBatchSize: 2000,
|
|
46
|
+
tempBatchPauseSec: 30,
|
|
47
|
+
tempMaxBatches: 20,
|
|
48
|
+
// A pass stops when the file-event service uses more memory than this.
|
|
49
|
+
tempStopFseventsdMb: 300,
|
|
50
|
+
// Update by itself once a day. Only the person turns it on.
|
|
51
|
+
autoUpdate: false,
|
|
52
|
+
// Share anonymous metrics (src/metrics.mjs). Only the person turns it on.
|
|
53
|
+
metrics: false,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/** The trash-panda folder, read at call time so a changed HOME is honoured. */
|
|
57
|
+
export const trashPandaDir = () => join(homedir(), ".trash-panda");
|
|
58
|
+
export const settingsPath = (dir = trashPandaDir()) => join(dir, "settings.json");
|
|
59
|
+
|
|
60
|
+
const isPct = (v) => typeof v === "number" && v > 0 && v < 100;
|
|
61
|
+
const isInt = (lo, hi) => (v) => Number.isInteger(v) && v >= lo && v <= hi;
|
|
62
|
+
const isBool = (v) => typeof v === "boolean";
|
|
63
|
+
const isCommand = (v) => v === null || (Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s !== "") && isAbsolute(v[0]));
|
|
64
|
+
const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
65
|
+
|
|
66
|
+
// Each leaf key: its check and what a good value looks like, for the problem line.
|
|
67
|
+
const LEAVES = {
|
|
68
|
+
preview: [isBool, "true or false"],
|
|
69
|
+
lowMarkPct: [isPct, "a percent between 0 and 100"],
|
|
70
|
+
criticalMarkPct: [isPct, "a percent between 0 and 100, under lowMarkPct"],
|
|
71
|
+
"triggers.lowDisk.on": [isBool, "true or false"],
|
|
72
|
+
"triggers.schedule.on": [isBool, "true or false"],
|
|
73
|
+
"triggers.schedule.everySec": [isInt(60, 604800), "whole seconds from 60 to 604800"],
|
|
74
|
+
"triggers.sessionStart.on": [isBool, "true or false"],
|
|
75
|
+
tickSec: [isInt(60, 86400), "whole seconds from 60 to 86400"],
|
|
76
|
+
onCritical: [isCommand, "null or a list of strings that starts with a full path"],
|
|
77
|
+
onCriticalTimeoutSec: [isInt(1, 3600), "whole seconds from 1 to 3600"],
|
|
78
|
+
repoRoots: [(v) => isStringArray(v) && v.every((p) => isAbsolute(p)), "a list of full paths"],
|
|
79
|
+
// Each path is checked by name when a run reads it, so one bad entry is refused alone.
|
|
80
|
+
testDirs: [isStringArray, "a list of paths"],
|
|
81
|
+
moduleCacheDirs: [isStringArray, "a list of paths"],
|
|
82
|
+
// An empty prefix would match everything, and one with a slash could leave the folder.
|
|
83
|
+
tempPrefixes: [(v) => isStringArray(v) && v.every((p) => p !== "" && !p.includes("/")), "a list of name starts, none empty and none with a slash"],
|
|
84
|
+
tempMinAgeDays: [isInt(1, 3650), "whole days from 1 to 3650"],
|
|
85
|
+
tempBatchSize: [isInt(1, 100000), "a whole number from 1 to 100000"],
|
|
86
|
+
tempBatchPauseSec: [isInt(1, 3600), "whole seconds from 1 to 3600"],
|
|
87
|
+
tempMaxBatches: [isInt(1, 1000), "a whole number from 1 to 1000"],
|
|
88
|
+
tempStopFseventsdMb: [isInt(1, 100000), "whole MB from 1 to 100000"],
|
|
89
|
+
autoUpdate: [isBool, "true or false"],
|
|
90
|
+
metrics: [isBool, "true or false"],
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
94
|
+
|
|
95
|
+
/** Copy each known key of `from` into `into`, refusing unknown keys and bad values by name. */
|
|
96
|
+
function merge(from, into, prefix, problems) {
|
|
97
|
+
for (const [key, value] of Object.entries(from)) {
|
|
98
|
+
const name = prefix ? `${prefix}.${key}` : key;
|
|
99
|
+
if (LEAVES[name]) {
|
|
100
|
+
const [ok, want] = LEAVES[name];
|
|
101
|
+
if (ok(value)) into[key] = Array.isArray(value) ? [...value] : value;
|
|
102
|
+
else problems.push(`${name}: bad value ${JSON.stringify(value)}, needs ${want}`);
|
|
103
|
+
} else if (isObject(into[key])) {
|
|
104
|
+
if (isObject(value)) merge(value, into[key], name, problems);
|
|
105
|
+
else problems.push(`${name}: bad value ${JSON.stringify(value)}, needs an object`);
|
|
106
|
+
} else problems.push(`${name}: unknown key`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** `{ settings, problems }` for the settings file at `path`; a missing file is every default. */
|
|
111
|
+
export function readSettings(path = settingsPath()) {
|
|
112
|
+
const problems = [];
|
|
113
|
+
let text;
|
|
114
|
+
try {
|
|
115
|
+
text = readFileSync(path, "utf8");
|
|
116
|
+
} catch (e) {
|
|
117
|
+
if (e.code !== "ENOENT") problems.push(`settings file unreadable: ${e.code}`);
|
|
118
|
+
}
|
|
119
|
+
let parsed;
|
|
120
|
+
if (text !== undefined) {
|
|
121
|
+
try {
|
|
122
|
+
parsed = JSON.parse(text);
|
|
123
|
+
} catch {
|
|
124
|
+
problems.push("settings file is not valid JSON");
|
|
125
|
+
}
|
|
126
|
+
if (parsed !== undefined && !isObject(parsed)) problems.push("settings file must hold one JSON object");
|
|
127
|
+
}
|
|
128
|
+
return settingsFrom(isObject(parsed) ? parsed : {}, problems);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** `{ settings, problems }` for the object `raw`, after the file's own `problems`. */
|
|
132
|
+
function settingsFrom(raw, problems = []) {
|
|
133
|
+
const settings = structuredClone(DEFAULTS);
|
|
134
|
+
merge(raw, settings, "", problems);
|
|
135
|
+
if (settings.criticalMarkPct >= settings.lowMarkPct) {
|
|
136
|
+
problems.push(`criticalMarkPct: ${settings.criticalMarkPct} must be under lowMarkPct ${settings.lowMarkPct}`);
|
|
137
|
+
settings.criticalMarkPct = DEFAULTS.criticalMarkPct < settings.lowMarkPct ? DEFAULTS.criticalMarkPct : settings.lowMarkPct / 2;
|
|
138
|
+
}
|
|
139
|
+
if (problems.length) settings.preview = true;
|
|
140
|
+
return { settings, problems };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The settings object as the person wrote it, `{}` when there is none; throws when it is not one JSON object. */
|
|
144
|
+
export function rawSettings(path) {
|
|
145
|
+
let text;
|
|
146
|
+
try {
|
|
147
|
+
text = readFileSync(path, "utf8");
|
|
148
|
+
} catch (e) {
|
|
149
|
+
if (e.code === "ENOENT") return {};
|
|
150
|
+
throw new Error(`${path} cannot be read (${e.code}); left alone`);
|
|
151
|
+
}
|
|
152
|
+
let raw = null;
|
|
153
|
+
try {
|
|
154
|
+
raw = JSON.parse(text);
|
|
155
|
+
} catch {
|
|
156
|
+
// said below
|
|
157
|
+
}
|
|
158
|
+
if (!isObject(raw)) throw new Error(`${path} is not one JSON object; left alone`);
|
|
159
|
+
return raw;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The kind of a setting `config` may set by name: "boolean", "number", or undefined for a list, a command or no such key. */
|
|
163
|
+
const kindOf = (name) => (LEAVES[name] ? ["boolean", "number"].find((t) => typeof name.split(".").reduce((o, k) => o[k], DEFAULTS) === t) : undefined);
|
|
164
|
+
|
|
165
|
+
/** The value the engine uses for the setting `name`; throws when `config` cannot set it. */
|
|
166
|
+
export function getSetting(dir, name) {
|
|
167
|
+
if (!kindOf(name)) throw new Error(`${name}: not a setting config can change`);
|
|
168
|
+
return name.split(".").reduce((o, k) => o[k], readSettings(settingsPath(dir)).settings);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Save `text` (on, off, true, false or a number) as the setting `name` in
|
|
173
|
+
* settings.json, every other key kept, in one rename. Throws, and leaves the
|
|
174
|
+
* file alone, for a bad value, a value that crosses the marks, or a file that
|
|
175
|
+
* cannot be read or written. The person's command: preview is set only by it.
|
|
176
|
+
*/
|
|
177
|
+
export function setSetting(dir, name, text) {
|
|
178
|
+
const kind = kindOf(name);
|
|
179
|
+
if (!kind) throw new Error(`${name}: not a setting config can change`);
|
|
180
|
+
const value = kind === "boolean" ? { on: true, true: true, off: false, false: false }[text] : /^\d+(\.\d+)?$/.test(text) ? Number(text) : undefined;
|
|
181
|
+
if (value === undefined) throw new Error(`${name}: bad value ${JSON.stringify(text)}, needs ${kind === "boolean" ? "on or off" : "a number"}`);
|
|
182
|
+
writeSetting(dir, name, value);
|
|
183
|
+
return value;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Save `value` as the setting `name`, every other key kept; throws when it adds a problem or the file cannot be read or written. */
|
|
187
|
+
export function writeSetting(dir, name, value) {
|
|
188
|
+
const path = settingsPath(dir);
|
|
189
|
+
const raw = rawSettings(path);
|
|
190
|
+
const next = structuredClone(raw);
|
|
191
|
+
const keys = name.split(".");
|
|
192
|
+
let at = next;
|
|
193
|
+
for (const k of keys.slice(0, -1)) at = isObject(at[k]) ? at[k] : (at[k] = {});
|
|
194
|
+
at[keys.at(-1)] = value;
|
|
195
|
+
const had = new Set(settingsFrom(raw).problems);
|
|
196
|
+
const added = settingsFrom(next).problems.filter((p) => !had.has(p));
|
|
197
|
+
if (added.length) throw new Error(`${added.join("; ")}; left alone`);
|
|
198
|
+
mkdirSync(dir, { recursive: true });
|
|
199
|
+
// A linked settings file stays a link, and the file keeps its mode.
|
|
200
|
+
const real = existsSync(path) ? realpathSync(path) : path;
|
|
201
|
+
const mode = existsSync(real) ? statSync(real).mode & 0o777 : 0o644;
|
|
202
|
+
const tmp = `${real}.tmp-${process.pid}`;
|
|
203
|
+
writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode });
|
|
204
|
+
renameSync(tmp, real);
|
|
205
|
+
}
|