dir-analysis-tool 2.0.6 → 3.0.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/README.md +429 -133
- package/dist/cli.js +882 -0
- package/dist/index.d.ts +539 -0
- package/dist/index.js +1 -1310
- package/dist/shared-Cmryy0SH.js +3351 -0
- package/package.json +75 -49
- package/schema.json +176 -0
|
@@ -0,0 +1,3351 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { lstat, open, readFile, readdir, stat } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import ignore from "ignore";
|
|
7
|
+
//#region src/errors.ts
|
|
8
|
+
/**
|
|
9
|
+
* An expected, user-facing failure (bad input, missing directory, invalid
|
|
10
|
+
* config). The CLI prints its message without a stack trace.
|
|
11
|
+
*/
|
|
12
|
+
var DatError = class extends Error {
|
|
13
|
+
name = "DatError";
|
|
14
|
+
/** Optional hint printed after the message. */
|
|
15
|
+
hint;
|
|
16
|
+
constructor(message, options = {}) {
|
|
17
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
18
|
+
this.hint = options.hint;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/** Thrown when an operation is cancelled through its `AbortSignal`. */
|
|
22
|
+
var AbortError = class extends Error {
|
|
23
|
+
name = "AbortError";
|
|
24
|
+
constructor(message = "The operation was aborted") {
|
|
25
|
+
super(message);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/** The message of any thrown value. */
|
|
29
|
+
function errorMessage(error) {
|
|
30
|
+
return error instanceof Error ? error.message : String(error);
|
|
31
|
+
}
|
|
32
|
+
/** The Node.js error code (`ENOENT`, `EACCES`, …) of a thrown value, if it has one. */
|
|
33
|
+
function errorCode(error) {
|
|
34
|
+
if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "string") return error.code;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
//#region src/format/time.ts
|
|
38
|
+
/**
|
|
39
|
+
* Date, age, and duration helpers used by filters, reports, and the CLI.
|
|
40
|
+
*/
|
|
41
|
+
const MS_PER_UNIT = {
|
|
42
|
+
ms: 1,
|
|
43
|
+
s: 1e3,
|
|
44
|
+
m: 6e4,
|
|
45
|
+
min: 6e4,
|
|
46
|
+
h: 36e5,
|
|
47
|
+
d: 864e5,
|
|
48
|
+
w: 6048e5,
|
|
49
|
+
mo: 2629746e3,
|
|
50
|
+
y: 31556952e3
|
|
51
|
+
};
|
|
52
|
+
const DURATION_PATTERN = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|min|mo|m|h|d|w|y)\s*$/i;
|
|
53
|
+
const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
54
|
+
/** Parses a duration such as `90d`, `2w`, `6mo`, `1y`, `12h`, or `30min` into milliseconds. */
|
|
55
|
+
function parseDuration(input) {
|
|
56
|
+
const match = DURATION_PATTERN.exec(input);
|
|
57
|
+
if (!match) throw new RangeError(`Invalid duration "${input}". Use a number and a unit: s, min, h, d, w, mo, or y (for example 90d).`);
|
|
58
|
+
return Number(match[1]) * MS_PER_UNIT[match[2].toLowerCase()];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Resolves a point in time from either an age relative to now (`30d` means
|
|
62
|
+
* "30 days ago") or an absolute date (`2024-01-31`, or any ISO 8601 timestamp).
|
|
63
|
+
* Date-only values are interpreted in local time. Returns epoch milliseconds.
|
|
64
|
+
*/
|
|
65
|
+
function parsePointInTime(input, options = {}) {
|
|
66
|
+
const now = options.now ?? Date.now();
|
|
67
|
+
if (DURATION_PATTERN.test(input)) return now - parseDuration(input);
|
|
68
|
+
const dateOnly = DATE_ONLY_PATTERN.exec(input.trim());
|
|
69
|
+
if (dateOnly) {
|
|
70
|
+
const [, y, m, d] = dateOnly;
|
|
71
|
+
const date = new Date(Number(y), Number(m) - 1, Number(d));
|
|
72
|
+
if (date.getMonth() !== Number(m) - 1 || date.getDate() !== Number(d)) throw new RangeError(`Invalid date "${input}".`);
|
|
73
|
+
if (options.endOfDay) date.setHours(23, 59, 59, 999);
|
|
74
|
+
return date.getTime();
|
|
75
|
+
}
|
|
76
|
+
const parsed = Date.parse(input);
|
|
77
|
+
if (Number.isNaN(parsed)) throw new RangeError(`Invalid date or age "${input}". Use YYYY-MM-DD, an ISO timestamp, or an age such as 30d.`);
|
|
78
|
+
return parsed;
|
|
79
|
+
}
|
|
80
|
+
/** Formats an elapsed duration compactly: `840ms`, `3.2s`, `2m 05s`. */
|
|
81
|
+
function formatElapsed(ms) {
|
|
82
|
+
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
83
|
+
if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
|
|
84
|
+
const minutes = Math.floor(ms / 6e4);
|
|
85
|
+
const seconds = Math.round(ms % 6e4 / 1e3);
|
|
86
|
+
return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
|
87
|
+
}
|
|
88
|
+
/** Formats how long ago a timestamp was, using the largest whole unit: `3d`, `5mo`, `2y`. */
|
|
89
|
+
function formatAge(timestampMs, now = Date.now()) {
|
|
90
|
+
const diff = Math.max(0, now - timestampMs);
|
|
91
|
+
const units = [
|
|
92
|
+
["y", MS_PER_UNIT["y"]],
|
|
93
|
+
["mo", MS_PER_UNIT["mo"]],
|
|
94
|
+
["d", MS_PER_UNIT["d"]],
|
|
95
|
+
["h", MS_PER_UNIT["h"]],
|
|
96
|
+
["m", MS_PER_UNIT["m"]]
|
|
97
|
+
];
|
|
98
|
+
for (const [label, size] of units) if (diff >= size) return `${Math.floor(diff / size)}${label}`;
|
|
99
|
+
return "now";
|
|
100
|
+
}
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region src/version.ts
|
|
103
|
+
/**
|
|
104
|
+
* Read from the package manifest at runtime, so the reported version always
|
|
105
|
+
* matches the installed package, whatever step of the release built `dist/`.
|
|
106
|
+
* Works from both `src/` (development) and `dist/` (published): each sits one
|
|
107
|
+
* level below the package root.
|
|
108
|
+
*/
|
|
109
|
+
function readVersion() {
|
|
110
|
+
const manifest = createRequire(import.meta.url)("../package.json");
|
|
111
|
+
if (typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string") return manifest.version;
|
|
112
|
+
return "0.0.0";
|
|
113
|
+
}
|
|
114
|
+
const VERSION = readVersion();
|
|
115
|
+
const TOOL = {
|
|
116
|
+
name: "dir-analysis-tool",
|
|
117
|
+
version: VERSION
|
|
118
|
+
};
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/types.ts
|
|
121
|
+
const CATEGORIES = [
|
|
122
|
+
"code",
|
|
123
|
+
"documents",
|
|
124
|
+
"images",
|
|
125
|
+
"videos",
|
|
126
|
+
"audio",
|
|
127
|
+
"archives",
|
|
128
|
+
"fonts",
|
|
129
|
+
"data",
|
|
130
|
+
"other"
|
|
131
|
+
];
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/format/bytes.ts
|
|
134
|
+
const IEC_LABELS = [
|
|
135
|
+
"B",
|
|
136
|
+
"KiB",
|
|
137
|
+
"MiB",
|
|
138
|
+
"GiB",
|
|
139
|
+
"TiB",
|
|
140
|
+
"PiB",
|
|
141
|
+
"EiB"
|
|
142
|
+
];
|
|
143
|
+
const SI_LABELS = [
|
|
144
|
+
"B",
|
|
145
|
+
"kB",
|
|
146
|
+
"MB",
|
|
147
|
+
"GB",
|
|
148
|
+
"TB",
|
|
149
|
+
"PB",
|
|
150
|
+
"EB"
|
|
151
|
+
];
|
|
152
|
+
/**
|
|
153
|
+
* Formats a byte count for humans, keeping three significant digits
|
|
154
|
+
* (`1.23 MiB`, `12.3 MiB`, `123 MiB`). Negative values keep their sign,
|
|
155
|
+
* which is useful for deltas.
|
|
156
|
+
*/
|
|
157
|
+
function formatBytes(bytes, units = "iec") {
|
|
158
|
+
if (!Number.isFinite(bytes)) return String(bytes);
|
|
159
|
+
const sign = bytes < 0 ? "-" : "";
|
|
160
|
+
let value = Math.abs(bytes);
|
|
161
|
+
const base = units === "si" ? 1e3 : 1024;
|
|
162
|
+
const labels = units === "si" ? SI_LABELS : IEC_LABELS;
|
|
163
|
+
let index = 0;
|
|
164
|
+
while (value >= base && index < labels.length - 1) {
|
|
165
|
+
value /= base;
|
|
166
|
+
index++;
|
|
167
|
+
}
|
|
168
|
+
if (index === 0) return `${sign}${value} B`;
|
|
169
|
+
let digits = value >= 100 ? 0 : value >= 10 ? 1 : 2;
|
|
170
|
+
let rounded = Number(value.toFixed(digits));
|
|
171
|
+
if (rounded >= base && index < labels.length - 1) {
|
|
172
|
+
index++;
|
|
173
|
+
rounded = 1;
|
|
174
|
+
digits = 2;
|
|
175
|
+
}
|
|
176
|
+
return `${sign}${trimZeros(rounded.toFixed(digits))} ${labels[index]}`;
|
|
177
|
+
}
|
|
178
|
+
function trimZeros(text) {
|
|
179
|
+
return text.includes(".") ? text.replace(/\.?0+$/, "") : text;
|
|
180
|
+
}
|
|
181
|
+
const SIZE_PATTERN = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([a-z]*)\s*$/i;
|
|
182
|
+
const SIZE_MULTIPLIERS = {
|
|
183
|
+
"": 1,
|
|
184
|
+
b: 1,
|
|
185
|
+
k: 1024,
|
|
186
|
+
m: 1024 ** 2,
|
|
187
|
+
g: 1024 ** 3,
|
|
188
|
+
t: 1024 ** 4,
|
|
189
|
+
p: 1024 ** 5,
|
|
190
|
+
kib: 1024,
|
|
191
|
+
mib: 1024 ** 2,
|
|
192
|
+
gib: 1024 ** 3,
|
|
193
|
+
tib: 1024 ** 4,
|
|
194
|
+
pib: 1024 ** 5,
|
|
195
|
+
kb: 1e3,
|
|
196
|
+
mb: 1e3 ** 2,
|
|
197
|
+
gb: 1e3 ** 3,
|
|
198
|
+
tb: 1e3 ** 4,
|
|
199
|
+
pb: 1e3 ** 5
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* Parses a human size into bytes.
|
|
203
|
+
*
|
|
204
|
+
* - Plain numbers are bytes: `4096`.
|
|
205
|
+
* - Single letters and IEC suffixes are binary: `10k`, `1.5M`, `2GiB`.
|
|
206
|
+
* - Two-letter SI suffixes are decimal: `10kB`, `500MB`, `1GB`.
|
|
207
|
+
*
|
|
208
|
+
* Suffixes are case-insensitive. Throws a `RangeError` for anything else.
|
|
209
|
+
*/
|
|
210
|
+
function parseSize(input) {
|
|
211
|
+
if (typeof input === "number") {
|
|
212
|
+
if (Number.isFinite(input) && input >= 0) return Math.floor(input);
|
|
213
|
+
throw new RangeError(`Invalid size: ${input}`);
|
|
214
|
+
}
|
|
215
|
+
const match = SIZE_PATTERN.exec(input);
|
|
216
|
+
const multiplier = match ? SIZE_MULTIPLIERS[match[2].toLowerCase()] : void 0;
|
|
217
|
+
if (!match || multiplier === void 0) throw new RangeError(`Invalid size "${input}". Use bytes or a unit, for example 512, 10k, 25MiB, or 1GB.`);
|
|
218
|
+
return Math.floor(Number(match[1]) * multiplier);
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/core/budgets.ts
|
|
222
|
+
const BUDGET_METRICS = {
|
|
223
|
+
size: {
|
|
224
|
+
kind: "size",
|
|
225
|
+
description: "total apparent size",
|
|
226
|
+
read: (r) => r.summary.bytes
|
|
227
|
+
},
|
|
228
|
+
disk: {
|
|
229
|
+
kind: "size",
|
|
230
|
+
description: "total size on disk",
|
|
231
|
+
read: (r) => r.summary.diskBytes
|
|
232
|
+
},
|
|
233
|
+
files: {
|
|
234
|
+
kind: "count",
|
|
235
|
+
description: "number of files",
|
|
236
|
+
read: (r) => r.summary.files
|
|
237
|
+
},
|
|
238
|
+
dirs: {
|
|
239
|
+
kind: "count",
|
|
240
|
+
description: "number of directories",
|
|
241
|
+
read: (r) => r.summary.directories
|
|
242
|
+
},
|
|
243
|
+
largest: {
|
|
244
|
+
kind: "size",
|
|
245
|
+
description: "size of the largest file",
|
|
246
|
+
read: (r) => r.summary.largestFileBytes
|
|
247
|
+
},
|
|
248
|
+
large: {
|
|
249
|
+
kind: "count",
|
|
250
|
+
description: "number of large files",
|
|
251
|
+
requires: "largeFiles",
|
|
252
|
+
read: (r) => r.largeFiles?.count ?? 0
|
|
253
|
+
},
|
|
254
|
+
duplicates: {
|
|
255
|
+
kind: "count",
|
|
256
|
+
description: "number of duplicate groups",
|
|
257
|
+
requires: "duplicates",
|
|
258
|
+
read: (r) => r.duplicates?.count ?? 0
|
|
259
|
+
},
|
|
260
|
+
wasted: {
|
|
261
|
+
kind: "size",
|
|
262
|
+
description: "space wasted by duplicates",
|
|
263
|
+
requires: "duplicates",
|
|
264
|
+
read: (r) => r.duplicates?.wastedBytes ?? 0
|
|
265
|
+
},
|
|
266
|
+
empty: {
|
|
267
|
+
kind: "count",
|
|
268
|
+
description: "number of empty files",
|
|
269
|
+
requires: "empty",
|
|
270
|
+
read: (r) => r.emptyFiles?.count ?? 0
|
|
271
|
+
},
|
|
272
|
+
stale: {
|
|
273
|
+
kind: "count",
|
|
274
|
+
description: "number of stale files",
|
|
275
|
+
requires: "stale",
|
|
276
|
+
read: (r) => r.staleFiles?.count ?? 0
|
|
277
|
+
},
|
|
278
|
+
errors: {
|
|
279
|
+
kind: "count",
|
|
280
|
+
description: "number of unreadable paths",
|
|
281
|
+
read: (r) => r.summary.errors
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
const OPERATORS = {
|
|
285
|
+
"<": "<",
|
|
286
|
+
"<=": "<=",
|
|
287
|
+
">": ">",
|
|
288
|
+
">=": ">=",
|
|
289
|
+
"=": "=",
|
|
290
|
+
"==": "=",
|
|
291
|
+
"!=": "!="
|
|
292
|
+
};
|
|
293
|
+
function isBudgetMetric(value) {
|
|
294
|
+
return Object.hasOwn(BUDGET_METRICS, value);
|
|
295
|
+
}
|
|
296
|
+
const RULE_PATTERN = /^\s*([a-z]+)\s*(<=|>=|!=|==|<|>|=)\s*(\S.*?)\s*$/i;
|
|
297
|
+
/** Parses a rule such as `size<=500MB`, `duplicates=0`, or `files < 10000`. */
|
|
298
|
+
function parseBudget(rule) {
|
|
299
|
+
const match = RULE_PATTERN.exec(rule);
|
|
300
|
+
if (!match) throw new RangeError(`Invalid budget "${rule}". Expected <metric><operator><value>, for example size<=500MB.`);
|
|
301
|
+
const metric = match[1].toLowerCase();
|
|
302
|
+
if (!isBudgetMetric(metric)) throw new RangeError(`Unknown budget metric "${match[1]}" in "${rule}". Known metrics: ${Object.keys(BUDGET_METRICS).join(", ")}.`);
|
|
303
|
+
const spec = BUDGET_METRICS[metric];
|
|
304
|
+
const operator = OPERATORS[match[2]];
|
|
305
|
+
const raw = match[3];
|
|
306
|
+
let limit;
|
|
307
|
+
if (spec.kind === "size") limit = parseSize(raw);
|
|
308
|
+
else {
|
|
309
|
+
limit = Number(raw.replaceAll(/[_,]/g, ""));
|
|
310
|
+
if (!Number.isInteger(limit) || limit < 0) throw new RangeError(`Budget "${rule}": ${metric} needs a whole number (got "${raw}").`);
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
rule: rule.trim(),
|
|
314
|
+
metric,
|
|
315
|
+
operator,
|
|
316
|
+
limit
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
/** Features that must be enabled for the given budgets to be measurable. */
|
|
320
|
+
function requiredFeatures(budgets) {
|
|
321
|
+
const features = /* @__PURE__ */ new Set();
|
|
322
|
+
for (const budget of budgets) {
|
|
323
|
+
const required = BUDGET_METRICS[budget.metric].requires;
|
|
324
|
+
if (required) features.add(required);
|
|
325
|
+
}
|
|
326
|
+
return features;
|
|
327
|
+
}
|
|
328
|
+
function evaluateBudgets(budgets, result) {
|
|
329
|
+
return budgets.map((budget) => {
|
|
330
|
+
const actual = BUDGET_METRICS[budget.metric].read(result);
|
|
331
|
+
return {
|
|
332
|
+
...budget,
|
|
333
|
+
actual,
|
|
334
|
+
passed: compare$1(actual, budget.operator, budget.limit)
|
|
335
|
+
};
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
function compare$1(actual, operator, limit) {
|
|
339
|
+
switch (operator) {
|
|
340
|
+
case "<": return actual < limit;
|
|
341
|
+
case "<=": return actual <= limit;
|
|
342
|
+
case ">": return actual > limit;
|
|
343
|
+
case ">=": return actual >= limit;
|
|
344
|
+
case "=": return actual === limit;
|
|
345
|
+
case "!=": return actual !== limit;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
//#endregion
|
|
349
|
+
//#region src/core/classify.ts
|
|
350
|
+
const EXTENSIONS = {
|
|
351
|
+
code: [
|
|
352
|
+
"js",
|
|
353
|
+
"mjs",
|
|
354
|
+
"cjs",
|
|
355
|
+
"jsx",
|
|
356
|
+
"ts",
|
|
357
|
+
"mts",
|
|
358
|
+
"cts",
|
|
359
|
+
"tsx",
|
|
360
|
+
"vue",
|
|
361
|
+
"svelte",
|
|
362
|
+
"astro",
|
|
363
|
+
"c",
|
|
364
|
+
"h",
|
|
365
|
+
"cc",
|
|
366
|
+
"cpp",
|
|
367
|
+
"cxx",
|
|
368
|
+
"hpp",
|
|
369
|
+
"hh",
|
|
370
|
+
"hxx",
|
|
371
|
+
"m",
|
|
372
|
+
"mm",
|
|
373
|
+
"rs",
|
|
374
|
+
"go",
|
|
375
|
+
"zig",
|
|
376
|
+
"nim",
|
|
377
|
+
"java",
|
|
378
|
+
"kt",
|
|
379
|
+
"kts",
|
|
380
|
+
"scala",
|
|
381
|
+
"groovy",
|
|
382
|
+
"gradle",
|
|
383
|
+
"cs",
|
|
384
|
+
"fs",
|
|
385
|
+
"vb",
|
|
386
|
+
"swift",
|
|
387
|
+
"dart",
|
|
388
|
+
"py",
|
|
389
|
+
"pyi",
|
|
390
|
+
"rb",
|
|
391
|
+
"php",
|
|
392
|
+
"pl",
|
|
393
|
+
"pm",
|
|
394
|
+
"lua",
|
|
395
|
+
"r",
|
|
396
|
+
"jl",
|
|
397
|
+
"ex",
|
|
398
|
+
"exs",
|
|
399
|
+
"erl",
|
|
400
|
+
"hrl",
|
|
401
|
+
"clj",
|
|
402
|
+
"cljs",
|
|
403
|
+
"edn",
|
|
404
|
+
"hs",
|
|
405
|
+
"elm",
|
|
406
|
+
"ml",
|
|
407
|
+
"mli",
|
|
408
|
+
"sol",
|
|
409
|
+
"sh",
|
|
410
|
+
"bash",
|
|
411
|
+
"zsh",
|
|
412
|
+
"fish",
|
|
413
|
+
"ps1",
|
|
414
|
+
"psm1",
|
|
415
|
+
"bat",
|
|
416
|
+
"cmd",
|
|
417
|
+
"html",
|
|
418
|
+
"htm",
|
|
419
|
+
"css",
|
|
420
|
+
"scss",
|
|
421
|
+
"sass",
|
|
422
|
+
"less",
|
|
423
|
+
"styl",
|
|
424
|
+
"wasm",
|
|
425
|
+
"wat",
|
|
426
|
+
"json",
|
|
427
|
+
"jsonc",
|
|
428
|
+
"json5",
|
|
429
|
+
"yaml",
|
|
430
|
+
"yml",
|
|
431
|
+
"toml",
|
|
432
|
+
"ini",
|
|
433
|
+
"cfg",
|
|
434
|
+
"conf",
|
|
435
|
+
"env",
|
|
436
|
+
"xml",
|
|
437
|
+
"xsd",
|
|
438
|
+
"graphql",
|
|
439
|
+
"gql",
|
|
440
|
+
"proto",
|
|
441
|
+
"prisma",
|
|
442
|
+
"tf",
|
|
443
|
+
"hcl",
|
|
444
|
+
"nix",
|
|
445
|
+
"cmake",
|
|
446
|
+
"mk",
|
|
447
|
+
"dockerfile",
|
|
448
|
+
"lock",
|
|
449
|
+
"sql",
|
|
450
|
+
"map"
|
|
451
|
+
],
|
|
452
|
+
documents: [
|
|
453
|
+
"pdf",
|
|
454
|
+
"doc",
|
|
455
|
+
"docx",
|
|
456
|
+
"odt",
|
|
457
|
+
"rtf",
|
|
458
|
+
"txt",
|
|
459
|
+
"md",
|
|
460
|
+
"mdx",
|
|
461
|
+
"markdown",
|
|
462
|
+
"rst",
|
|
463
|
+
"adoc",
|
|
464
|
+
"tex",
|
|
465
|
+
"org",
|
|
466
|
+
"epub",
|
|
467
|
+
"mobi",
|
|
468
|
+
"xls",
|
|
469
|
+
"xlsx",
|
|
470
|
+
"ods",
|
|
471
|
+
"ppt",
|
|
472
|
+
"pptx",
|
|
473
|
+
"odp",
|
|
474
|
+
"key",
|
|
475
|
+
"pages",
|
|
476
|
+
"numbers"
|
|
477
|
+
],
|
|
478
|
+
images: [
|
|
479
|
+
"png",
|
|
480
|
+
"jpg",
|
|
481
|
+
"jpeg",
|
|
482
|
+
"gif",
|
|
483
|
+
"webp",
|
|
484
|
+
"avif",
|
|
485
|
+
"heic",
|
|
486
|
+
"heif",
|
|
487
|
+
"bmp",
|
|
488
|
+
"tif",
|
|
489
|
+
"tiff",
|
|
490
|
+
"ico",
|
|
491
|
+
"icns",
|
|
492
|
+
"svg",
|
|
493
|
+
"psd",
|
|
494
|
+
"ai",
|
|
495
|
+
"eps",
|
|
496
|
+
"raw",
|
|
497
|
+
"cr2",
|
|
498
|
+
"cr3",
|
|
499
|
+
"nef",
|
|
500
|
+
"arw",
|
|
501
|
+
"dng",
|
|
502
|
+
"xcf",
|
|
503
|
+
"sketch",
|
|
504
|
+
"fig",
|
|
505
|
+
"jxl"
|
|
506
|
+
],
|
|
507
|
+
videos: [
|
|
508
|
+
"mp4",
|
|
509
|
+
"m4v",
|
|
510
|
+
"mov",
|
|
511
|
+
"mkv",
|
|
512
|
+
"webm",
|
|
513
|
+
"avi",
|
|
514
|
+
"wmv",
|
|
515
|
+
"flv",
|
|
516
|
+
"mpg",
|
|
517
|
+
"mpeg",
|
|
518
|
+
"3gp",
|
|
519
|
+
"ogv"
|
|
520
|
+
],
|
|
521
|
+
audio: [
|
|
522
|
+
"mp3",
|
|
523
|
+
"wav",
|
|
524
|
+
"flac",
|
|
525
|
+
"aac",
|
|
526
|
+
"m4a",
|
|
527
|
+
"ogg",
|
|
528
|
+
"oga",
|
|
529
|
+
"opus",
|
|
530
|
+
"wma",
|
|
531
|
+
"aiff",
|
|
532
|
+
"aif",
|
|
533
|
+
"alac",
|
|
534
|
+
"mid",
|
|
535
|
+
"midi"
|
|
536
|
+
],
|
|
537
|
+
archives: [
|
|
538
|
+
"zip",
|
|
539
|
+
"tar",
|
|
540
|
+
"gz",
|
|
541
|
+
"tgz",
|
|
542
|
+
"bz2",
|
|
543
|
+
"tbz2",
|
|
544
|
+
"xz",
|
|
545
|
+
"txz",
|
|
546
|
+
"zst",
|
|
547
|
+
"lz4",
|
|
548
|
+
"lzma",
|
|
549
|
+
"7z",
|
|
550
|
+
"rar",
|
|
551
|
+
"jar",
|
|
552
|
+
"war",
|
|
553
|
+
"apk",
|
|
554
|
+
"aab",
|
|
555
|
+
"ipa",
|
|
556
|
+
"deb",
|
|
557
|
+
"rpm",
|
|
558
|
+
"dmg",
|
|
559
|
+
"iso",
|
|
560
|
+
"pkg",
|
|
561
|
+
"msi",
|
|
562
|
+
"cab",
|
|
563
|
+
"whl",
|
|
564
|
+
"gem",
|
|
565
|
+
"nupkg",
|
|
566
|
+
"crx",
|
|
567
|
+
"vsix"
|
|
568
|
+
],
|
|
569
|
+
fonts: [
|
|
570
|
+
"ttf",
|
|
571
|
+
"otf",
|
|
572
|
+
"woff",
|
|
573
|
+
"woff2",
|
|
574
|
+
"eot",
|
|
575
|
+
"pfb",
|
|
576
|
+
"pfm"
|
|
577
|
+
],
|
|
578
|
+
data: [
|
|
579
|
+
"csv",
|
|
580
|
+
"tsv",
|
|
581
|
+
"parquet",
|
|
582
|
+
"avro",
|
|
583
|
+
"orc",
|
|
584
|
+
"arrow",
|
|
585
|
+
"feather",
|
|
586
|
+
"db",
|
|
587
|
+
"sqlite",
|
|
588
|
+
"sqlite3",
|
|
589
|
+
"mdb",
|
|
590
|
+
"accdb",
|
|
591
|
+
"npy",
|
|
592
|
+
"npz",
|
|
593
|
+
"h5",
|
|
594
|
+
"hdf5",
|
|
595
|
+
"pkl",
|
|
596
|
+
"pickle",
|
|
597
|
+
"ndjson",
|
|
598
|
+
"jsonl",
|
|
599
|
+
"bin",
|
|
600
|
+
"dat",
|
|
601
|
+
"log",
|
|
602
|
+
"onnx",
|
|
603
|
+
"safetensors",
|
|
604
|
+
"pt",
|
|
605
|
+
"ckpt",
|
|
606
|
+
"gguf"
|
|
607
|
+
]
|
|
608
|
+
};
|
|
609
|
+
/** Well-known file names without a meaningful extension. Keys are lowercase. */
|
|
610
|
+
const FILE_NAMES = {
|
|
611
|
+
dockerfile: "code",
|
|
612
|
+
containerfile: "code",
|
|
613
|
+
makefile: "code",
|
|
614
|
+
gnumakefile: "code",
|
|
615
|
+
justfile: "code",
|
|
616
|
+
rakefile: "code",
|
|
617
|
+
gemfile: "code",
|
|
618
|
+
podfile: "code",
|
|
619
|
+
brewfile: "code",
|
|
620
|
+
procfile: "code",
|
|
621
|
+
vagrantfile: "code",
|
|
622
|
+
jenkinsfile: "code",
|
|
623
|
+
"cmakelists.txt": "code",
|
|
624
|
+
".gitignore": "code",
|
|
625
|
+
".gitattributes": "code",
|
|
626
|
+
".gitmodules": "code",
|
|
627
|
+
".dockerignore": "code",
|
|
628
|
+
".npmrc": "code",
|
|
629
|
+
".nvmrc": "code",
|
|
630
|
+
".editorconfig": "code",
|
|
631
|
+
".env": "code",
|
|
632
|
+
".prettierrc": "code",
|
|
633
|
+
".babelrc": "code",
|
|
634
|
+
license: "documents",
|
|
635
|
+
licence: "documents",
|
|
636
|
+
readme: "documents",
|
|
637
|
+
changelog: "documents",
|
|
638
|
+
authors: "documents",
|
|
639
|
+
contributors: "documents",
|
|
640
|
+
notice: "documents"
|
|
641
|
+
};
|
|
642
|
+
const EXTENSION_TO_CATEGORY = /* @__PURE__ */ new Map();
|
|
643
|
+
for (const category of CATEGORIES) {
|
|
644
|
+
if (category === "other") continue;
|
|
645
|
+
for (const extension of EXTENSIONS[category]) EXTENSION_TO_CATEGORY.set(`.${extension}`, category);
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Extracts the lowercased extension (with the dot) from a file name.
|
|
649
|
+
* Dotfiles such as `.env` have no extension; `archive.tar.gz` has `.gz`.
|
|
650
|
+
*/
|
|
651
|
+
function extensionOf(fileName) {
|
|
652
|
+
const dot = fileName.lastIndexOf(".");
|
|
653
|
+
if (dot <= 0 || dot === fileName.length - 1) return "";
|
|
654
|
+
return fileName.slice(dot).toLowerCase();
|
|
655
|
+
}
|
|
656
|
+
/** Classifies a file by its well-known name first, then by extension. */
|
|
657
|
+
function classify(fileName, extension = extensionOf(fileName)) {
|
|
658
|
+
const byExtension = EXTENSION_TO_CATEGORY.get(extension);
|
|
659
|
+
if (byExtension) return byExtension;
|
|
660
|
+
const lower = fileName.toLowerCase();
|
|
661
|
+
return FILE_NAMES[lower] ?? (lower.startsWith(".env.") ? "code" : "other");
|
|
662
|
+
}
|
|
663
|
+
/** A zeroed statistics record for every category. */
|
|
664
|
+
function emptyTypeStats() {
|
|
665
|
+
return {
|
|
666
|
+
code: {
|
|
667
|
+
files: 0,
|
|
668
|
+
bytes: 0
|
|
669
|
+
},
|
|
670
|
+
documents: {
|
|
671
|
+
files: 0,
|
|
672
|
+
bytes: 0
|
|
673
|
+
},
|
|
674
|
+
images: {
|
|
675
|
+
files: 0,
|
|
676
|
+
bytes: 0
|
|
677
|
+
},
|
|
678
|
+
videos: {
|
|
679
|
+
files: 0,
|
|
680
|
+
bytes: 0
|
|
681
|
+
},
|
|
682
|
+
audio: {
|
|
683
|
+
files: 0,
|
|
684
|
+
bytes: 0
|
|
685
|
+
},
|
|
686
|
+
archives: {
|
|
687
|
+
files: 0,
|
|
688
|
+
bytes: 0
|
|
689
|
+
},
|
|
690
|
+
fonts: {
|
|
691
|
+
files: 0,
|
|
692
|
+
bytes: 0
|
|
693
|
+
},
|
|
694
|
+
data: {
|
|
695
|
+
files: 0,
|
|
696
|
+
bytes: 0
|
|
697
|
+
},
|
|
698
|
+
other: {
|
|
699
|
+
files: 0,
|
|
700
|
+
bytes: 0
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
//#endregion
|
|
705
|
+
//#region src/core/limiter.ts
|
|
706
|
+
/**
|
|
707
|
+
* A tiny concurrency limiter for filesystem work.
|
|
708
|
+
*
|
|
709
|
+
* Tasks run at most `concurrency` at a time. Pending tasks are taken
|
|
710
|
+
* last-in-first-out, which makes a directory walk proceed depth-first and
|
|
711
|
+
* keeps the pending queue small even on very wide trees.
|
|
712
|
+
*/
|
|
713
|
+
var Limiter = class {
|
|
714
|
+
#concurrency;
|
|
715
|
+
#queue = [];
|
|
716
|
+
#active = 0;
|
|
717
|
+
#failure = void 0;
|
|
718
|
+
#failed = false;
|
|
719
|
+
#idle = null;
|
|
720
|
+
constructor(concurrency) {
|
|
721
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError(`concurrency must be a positive integer (got ${concurrency})`);
|
|
722
|
+
this.#concurrency = concurrency;
|
|
723
|
+
}
|
|
724
|
+
/** Schedules a task. Tasks are expected to handle their own errors; a thrown error aborts the run. */
|
|
725
|
+
run(task) {
|
|
726
|
+
if (this.#failed) return;
|
|
727
|
+
this.#queue.push(task);
|
|
728
|
+
this.#pump();
|
|
729
|
+
}
|
|
730
|
+
/** Resolves once every scheduled task, including tasks scheduled by tasks, has finished. */
|
|
731
|
+
idle() {
|
|
732
|
+
if (this.#failed) return Promise.reject(this.#failure);
|
|
733
|
+
if (this.#active === 0 && this.#queue.length === 0) return Promise.resolve();
|
|
734
|
+
return new Promise((resolve, reject) => {
|
|
735
|
+
this.#idle = {
|
|
736
|
+
resolve,
|
|
737
|
+
reject
|
|
738
|
+
};
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
/** Stops scheduling new work and rejects `idle()` with `reason`. */
|
|
742
|
+
abort(reason) {
|
|
743
|
+
if (this.#failed) return;
|
|
744
|
+
this.#failed = true;
|
|
745
|
+
this.#failure = reason;
|
|
746
|
+
this.#queue.length = 0;
|
|
747
|
+
this.#idle?.reject(reason);
|
|
748
|
+
this.#idle = null;
|
|
749
|
+
}
|
|
750
|
+
#pump() {
|
|
751
|
+
while (this.#active < this.#concurrency && this.#queue.length > 0) {
|
|
752
|
+
const task = this.#queue.pop();
|
|
753
|
+
this.#active++;
|
|
754
|
+
task().then(this.#onDone, this.#onError);
|
|
755
|
+
}
|
|
756
|
+
if (this.#active === 0 && this.#queue.length === 0 && this.#idle) {
|
|
757
|
+
const idle = this.#idle;
|
|
758
|
+
this.#idle = null;
|
|
759
|
+
idle.resolve();
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
#onDone = () => {
|
|
763
|
+
this.#active--;
|
|
764
|
+
this.#pump();
|
|
765
|
+
};
|
|
766
|
+
#onError = (error) => {
|
|
767
|
+
this.#active--;
|
|
768
|
+
this.abort(error);
|
|
769
|
+
};
|
|
770
|
+
};
|
|
771
|
+
//#endregion
|
|
772
|
+
//#region src/core/duplicates.ts
|
|
773
|
+
/** Files up to this size are hashed in full straight away. */
|
|
774
|
+
const SAMPLE_THRESHOLD = 262144;
|
|
775
|
+
/** Bytes read from each end of a larger file for its sample hash. */
|
|
776
|
+
const SAMPLE_BYTES = 65536;
|
|
777
|
+
const READ_BUFFER_BYTES = 1048576;
|
|
778
|
+
/**
|
|
779
|
+
* Finds files with identical contents among groups of same-sized files.
|
|
780
|
+
*
|
|
781
|
+
* Work is staged so most files are never read in full:
|
|
782
|
+
* 1. Only sizes shared by at least two distinct inodes are considered.
|
|
783
|
+
* 2. Large files are first compared by a sample hash of their first and
|
|
784
|
+
* last 64 KiB, which separates almost all non-duplicates cheaply.
|
|
785
|
+
* 3. Survivors (and small files) get a full streaming SHA-256.
|
|
786
|
+
*/
|
|
787
|
+
async function findDuplicates(sizeGroups, options) {
|
|
788
|
+
const small = [];
|
|
789
|
+
const large = [];
|
|
790
|
+
for (const group of sizeGroups) {
|
|
791
|
+
const distinct = distinctInodes(group);
|
|
792
|
+
if (distinct.length < 2) continue;
|
|
793
|
+
(distinct[0].bytes <= SAMPLE_THRESHOLD ? small : large).push(distinct);
|
|
794
|
+
}
|
|
795
|
+
const buffers = new BufferPool(options.concurrency);
|
|
796
|
+
const sampled = await hashStage(large, "sample", options, buffers);
|
|
797
|
+
return await hashStage([...small, ...sampled.map((g) => g.members)], "full", options, buffers);
|
|
798
|
+
}
|
|
799
|
+
async function hashStage(groups, stage, options, buffers) {
|
|
800
|
+
const total = groups.reduce((sum, g) => sum + g.length, 0);
|
|
801
|
+
if (total === 0) return [];
|
|
802
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
803
|
+
const limiter = new Limiter(options.concurrency);
|
|
804
|
+
const { signal } = options;
|
|
805
|
+
const onAbort = () => limiter.abort(new AbortError());
|
|
806
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
807
|
+
let done = 0;
|
|
808
|
+
options.onProgress?.({
|
|
809
|
+
stage,
|
|
810
|
+
done,
|
|
811
|
+
total
|
|
812
|
+
});
|
|
813
|
+
for (const group of groups) for (const candidate of group) limiter.run(async () => {
|
|
814
|
+
const buffer = buffers.acquire();
|
|
815
|
+
try {
|
|
816
|
+
const path = options.pathOf(candidate);
|
|
817
|
+
const hash = stage === "sample" ? await sampleHash(path, candidate.bytes, buffer) : await hashFile(path, buffer);
|
|
818
|
+
const key = `${candidate.bytes}:${hash}`;
|
|
819
|
+
let entry = byKey.get(key);
|
|
820
|
+
if (!entry) {
|
|
821
|
+
entry = {
|
|
822
|
+
hash,
|
|
823
|
+
bytes: candidate.bytes,
|
|
824
|
+
members: []
|
|
825
|
+
};
|
|
826
|
+
byKey.set(key, entry);
|
|
827
|
+
}
|
|
828
|
+
entry.members.push(candidate);
|
|
829
|
+
} catch (error) {
|
|
830
|
+
options.onError?.(candidate, error);
|
|
831
|
+
} finally {
|
|
832
|
+
buffers.release(buffer);
|
|
833
|
+
done++;
|
|
834
|
+
options.onProgress?.({
|
|
835
|
+
stage,
|
|
836
|
+
done,
|
|
837
|
+
total
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
try {
|
|
842
|
+
await limiter.idle();
|
|
843
|
+
} finally {
|
|
844
|
+
signal?.removeEventListener("abort", onAbort);
|
|
845
|
+
}
|
|
846
|
+
return [...byKey.values()].filter((g) => g.members.length > 1);
|
|
847
|
+
}
|
|
848
|
+
/** Streams a file through SHA-256 and returns the hex digest. */
|
|
849
|
+
async function hashFile(path, buffer = Buffer.allocUnsafe(READ_BUFFER_BYTES)) {
|
|
850
|
+
const hash = createHash("sha256");
|
|
851
|
+
const handle = await open(path, "r");
|
|
852
|
+
try {
|
|
853
|
+
let position = 0;
|
|
854
|
+
for (;;) {
|
|
855
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
|
|
856
|
+
if (bytesRead === 0) break;
|
|
857
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
858
|
+
position += bytesRead;
|
|
859
|
+
}
|
|
860
|
+
} finally {
|
|
861
|
+
await handle.close();
|
|
862
|
+
}
|
|
863
|
+
return hash.digest("hex");
|
|
864
|
+
}
|
|
865
|
+
async function sampleHash(path, size, buffer) {
|
|
866
|
+
const hash = createHash("sha256");
|
|
867
|
+
const handle = await open(path, "r");
|
|
868
|
+
try {
|
|
869
|
+
for (const position of [0, Math.max(0, size - SAMPLE_BYTES)]) {
|
|
870
|
+
const { bytesRead } = await handle.read(buffer, 0, SAMPLE_BYTES, position);
|
|
871
|
+
hash.update(buffer.subarray(0, bytesRead));
|
|
872
|
+
}
|
|
873
|
+
} finally {
|
|
874
|
+
await handle.close();
|
|
875
|
+
}
|
|
876
|
+
return hash.digest("hex");
|
|
877
|
+
}
|
|
878
|
+
function distinctInodes(group) {
|
|
879
|
+
if (group.length < 2) return group;
|
|
880
|
+
const seen = /* @__PURE__ */ new Set();
|
|
881
|
+
return group.filter((candidate) => {
|
|
882
|
+
if (seen.has(candidate.inode)) return false;
|
|
883
|
+
seen.add(candidate.inode);
|
|
884
|
+
return true;
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
/** Reuses read buffers so hashing allocates a fixed amount of memory. */
|
|
888
|
+
var BufferPool = class {
|
|
889
|
+
#free = [];
|
|
890
|
+
constructor(size) {
|
|
891
|
+
for (let i = 0; i < size; i++) this.#free.push(Buffer.allocUnsafe(READ_BUFFER_BYTES));
|
|
892
|
+
}
|
|
893
|
+
acquire() {
|
|
894
|
+
return this.#free.pop() ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
|
|
895
|
+
}
|
|
896
|
+
release(buffer) {
|
|
897
|
+
this.#free.push(buffer);
|
|
898
|
+
}
|
|
899
|
+
};
|
|
900
|
+
//#endregion
|
|
901
|
+
//#region src/core/exclude.ts
|
|
902
|
+
/** Directories skipped unless default excludes are turned off. */
|
|
903
|
+
const DEFAULT_EXCLUDES = [
|
|
904
|
+
".git",
|
|
905
|
+
".hg",
|
|
906
|
+
".svn",
|
|
907
|
+
"node_modules"
|
|
908
|
+
];
|
|
909
|
+
const EMPTY_CHAIN = [];
|
|
910
|
+
/**
|
|
911
|
+
* Decides which entries a scan skips. Combines the default excluded directory
|
|
912
|
+
* names, user patterns (gitignore syntax, relative to the root), and optionally
|
|
913
|
+
* the repository's own `.gitignore` files, evaluated with Git's precedence:
|
|
914
|
+
* deeper files override shallower ones, and later rules override earlier ones.
|
|
915
|
+
*/
|
|
916
|
+
var Excluder = class {
|
|
917
|
+
gitignore;
|
|
918
|
+
#defaults;
|
|
919
|
+
#user;
|
|
920
|
+
#ignoreCase;
|
|
921
|
+
constructor(options = {}) {
|
|
922
|
+
this.gitignore = options.gitignore ?? false;
|
|
923
|
+
this.#ignoreCase = options.ignoreCase ?? process.platform !== "linux";
|
|
924
|
+
this.#defaults = options.defaultExcludes ?? true ? new Set(DEFAULT_EXCLUDES) : null;
|
|
925
|
+
const patterns = (options.patterns ?? []).map((p) => p.trim()).filter(Boolean);
|
|
926
|
+
this.#user = patterns.length > 0 ? this.#createMatcher().add(patterns) : null;
|
|
927
|
+
}
|
|
928
|
+
/** True when at least one rule could exclude something. */
|
|
929
|
+
get active() {
|
|
930
|
+
return this.#defaults !== null || this.#user !== null || this.gitignore;
|
|
931
|
+
}
|
|
932
|
+
/** Whether path-based rules exist (anything beyond default directory names). */
|
|
933
|
+
get needsPaths() {
|
|
934
|
+
return this.#user !== null || this.gitignore;
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* @param relPath Root-relative path with `/` separators.
|
|
938
|
+
* @param name Entry name (the last segment of `relPath`).
|
|
939
|
+
*/
|
|
940
|
+
isExcluded(relPath, name, isDirectory, chain) {
|
|
941
|
+
if (isDirectory && this.#defaults?.has(name)) return true;
|
|
942
|
+
if (this.#user !== null && this.#user.ignores(isDirectory ? `${relPath}/` : relPath)) return true;
|
|
943
|
+
return chain.length > 0 && isGitIgnored(chain, relPath, isDirectory);
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Checks a path and each of its ancestors against the default and user
|
|
947
|
+
* rules. Used to filter filesystem events in watch mode.
|
|
948
|
+
*/
|
|
949
|
+
isPathExcluded(relPath) {
|
|
950
|
+
const segments = relPath.split("/").filter(Boolean);
|
|
951
|
+
let current = "";
|
|
952
|
+
for (let i = 0; i < segments.length; i++) {
|
|
953
|
+
const segment = segments[i];
|
|
954
|
+
current = current ? `${current}/${segment}` : segment;
|
|
955
|
+
const isLast = i === segments.length - 1;
|
|
956
|
+
if (!isLast && this.isExcluded(current, segment, true, EMPTY_CHAIN)) return true;
|
|
957
|
+
if (isLast) return this.isExcluded(current, segment, false, EMPTY_CHAIN) || (this.#defaults?.has(segment) ?? false);
|
|
958
|
+
}
|
|
959
|
+
return false;
|
|
960
|
+
}
|
|
961
|
+
/** Builds the scope for a `.gitignore` found at `rootRelativeDir` (`''` for the root). */
|
|
962
|
+
async loadScope(filePath, rootRelativeDir) {
|
|
963
|
+
const content = await readFile(filePath, "utf8").catch(() => null);
|
|
964
|
+
if (content === null || content.trim() === "") return null;
|
|
965
|
+
return {
|
|
966
|
+
matcher: this.#createMatcher().add(content),
|
|
967
|
+
prefix: "",
|
|
968
|
+
strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* When the root sits inside a Git repository, collects the `.gitignore`
|
|
973
|
+
* files of its ancestors up to the repository root, plus
|
|
974
|
+
* `.git/info/exclude`, so a sub-directory scan matches Git's view.
|
|
975
|
+
*/
|
|
976
|
+
async loadAncestorChain(root) {
|
|
977
|
+
if (!this.gitignore) return EMPTY_CHAIN;
|
|
978
|
+
const ancestors = [];
|
|
979
|
+
let repoRoot = null;
|
|
980
|
+
let current = root;
|
|
981
|
+
for (;;) {
|
|
982
|
+
if (existsSync(join(current, ".git"))) {
|
|
983
|
+
repoRoot = current;
|
|
984
|
+
break;
|
|
985
|
+
}
|
|
986
|
+
const parent = dirname(current);
|
|
987
|
+
if (parent === current) break;
|
|
988
|
+
ancestors.push(parent);
|
|
989
|
+
current = parent;
|
|
990
|
+
}
|
|
991
|
+
if (repoRoot === null) return EMPTY_CHAIN;
|
|
992
|
+
const scopes = [];
|
|
993
|
+
const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
|
|
994
|
+
const add = async (file, base) => {
|
|
995
|
+
const content = await readFile(file, "utf8").catch(() => null);
|
|
996
|
+
if (content === null || content.trim() === "") return;
|
|
997
|
+
const prefix = relative(base, root).split(sep).join("/");
|
|
998
|
+
scopes.push({
|
|
999
|
+
matcher: this.#createMatcher().add(content),
|
|
1000
|
+
prefix: prefix ? `${prefix}/` : "",
|
|
1001
|
+
strip: 0
|
|
1002
|
+
});
|
|
1003
|
+
};
|
|
1004
|
+
await add(join(repoRoot, ".git", "info", "exclude"), repoRoot);
|
|
1005
|
+
for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir);
|
|
1006
|
+
return scopes;
|
|
1007
|
+
}
|
|
1008
|
+
#createMatcher() {
|
|
1009
|
+
return ignore({
|
|
1010
|
+
ignorecase: this.#ignoreCase,
|
|
1011
|
+
allowRelativePaths: true
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
function isGitIgnored(chain, relPath, isDirectory) {
|
|
1016
|
+
let ignored = false;
|
|
1017
|
+
for (const scope of chain) {
|
|
1018
|
+
const local = scope.prefix + relPath.slice(scope.strip);
|
|
1019
|
+
if (local === "") continue;
|
|
1020
|
+
const result = scope.matcher.test(isDirectory ? `${local}/` : local);
|
|
1021
|
+
if (result.ignored) ignored = true;
|
|
1022
|
+
else if (result.unignored) ignored = false;
|
|
1023
|
+
}
|
|
1024
|
+
return ignored;
|
|
1025
|
+
}
|
|
1026
|
+
//#endregion
|
|
1027
|
+
//#region src/core/paths.ts
|
|
1028
|
+
/** Ordinal comparison, so output order never depends on the locale. */
|
|
1029
|
+
function comparePaths(a, b) {
|
|
1030
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1031
|
+
}
|
|
1032
|
+
/** Joins an absolute native directory and a `/`-separated relative path. */
|
|
1033
|
+
function joinRelative(root, relative) {
|
|
1034
|
+
if (!relative) return root;
|
|
1035
|
+
const native = sep === "/" ? relative : relative.replaceAll("/", sep);
|
|
1036
|
+
return root.endsWith(sep) ? root + native : root + sep + native;
|
|
1037
|
+
}
|
|
1038
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
1039
|
+
/**
|
|
1040
|
+
* Concurrent directory walker.
|
|
1041
|
+
*
|
|
1042
|
+
* Reads directories with `readdir({ withFileTypes })` so directory entries
|
|
1043
|
+
* never need a `stat`; regular files are `lstat`ed exactly once. All
|
|
1044
|
+
* filesystem calls go through one {@link Limiter}, so concurrency stays
|
|
1045
|
+
* bounded no matter how wide the tree is. Results are independent of
|
|
1046
|
+
* scheduling order: callers sort what they report.
|
|
1047
|
+
*/
|
|
1048
|
+
var Scanner = class {
|
|
1049
|
+
dirs = [];
|
|
1050
|
+
errors = [];
|
|
1051
|
+
counters = {
|
|
1052
|
+
files: 0,
|
|
1053
|
+
bytes: 0,
|
|
1054
|
+
diskBytes: 0,
|
|
1055
|
+
directories: 0,
|
|
1056
|
+
symlinks: 0,
|
|
1057
|
+
hardlinks: 0,
|
|
1058
|
+
excluded: 0,
|
|
1059
|
+
filtered: 0,
|
|
1060
|
+
errors: 0
|
|
1061
|
+
};
|
|
1062
|
+
#options;
|
|
1063
|
+
#visitor;
|
|
1064
|
+
#limiter;
|
|
1065
|
+
#filtersActive;
|
|
1066
|
+
/** `dev:ino` of files with several links (or of every file when following symlinks). */
|
|
1067
|
+
#seenInodes = /* @__PURE__ */ new Set();
|
|
1068
|
+
/** `dev:ino` of entered directories, tracked only when following symlinks. */
|
|
1069
|
+
#seenDirs = /* @__PURE__ */ new Set();
|
|
1070
|
+
constructor(options, visitor) {
|
|
1071
|
+
this.#options = options;
|
|
1072
|
+
this.#visitor = visitor;
|
|
1073
|
+
this.#limiter = new Limiter(options.concurrency);
|
|
1074
|
+
this.#filtersActive = options.minSize > 0 || options.maxSize < Infinity || options.modifiedAfter > -Infinity || options.modifiedBefore < Infinity;
|
|
1075
|
+
}
|
|
1076
|
+
async run() {
|
|
1077
|
+
const { root, signal, excluder } = this.#options;
|
|
1078
|
+
if (signal?.aborted) throw new AbortError();
|
|
1079
|
+
const rootStats = await stat(root);
|
|
1080
|
+
if (this.#options.followSymlinks) this.#seenDirs.add(inodeKey(rootStats));
|
|
1081
|
+
const chain = await excluder.loadAncestorChain(root);
|
|
1082
|
+
const index = this.#addDir("", -1, 0);
|
|
1083
|
+
const onAbort = () => this.#limiter.abort(new AbortError());
|
|
1084
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1085
|
+
try {
|
|
1086
|
+
this.#limiter.run(() => this.#scanDir(index, root, chain));
|
|
1087
|
+
await this.#limiter.idle();
|
|
1088
|
+
} finally {
|
|
1089
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
/** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
|
|
1093
|
+
relativePath(dirIndex, name) {
|
|
1094
|
+
const parts = name === void 0 ? [] : [name];
|
|
1095
|
+
for (let i = dirIndex; i > 0; i = this.dirs[i].parent) parts.push(this.dirs[i].name);
|
|
1096
|
+
return parts.toReversed().join("/");
|
|
1097
|
+
}
|
|
1098
|
+
absolutePath(dirIndex, name) {
|
|
1099
|
+
return joinRelative(this.#options.root, this.relativePath(dirIndex, name));
|
|
1100
|
+
}
|
|
1101
|
+
#addDir(name, parent, depth) {
|
|
1102
|
+
const node = {
|
|
1103
|
+
name,
|
|
1104
|
+
parent,
|
|
1105
|
+
depth,
|
|
1106
|
+
entries: 0,
|
|
1107
|
+
ownFiles: 0,
|
|
1108
|
+
ownBytes: 0,
|
|
1109
|
+
ownDiskBytes: 0,
|
|
1110
|
+
files: 0,
|
|
1111
|
+
bytes: 0,
|
|
1112
|
+
diskBytes: 0,
|
|
1113
|
+
largestChild: 0
|
|
1114
|
+
};
|
|
1115
|
+
const index = this.dirs.push(node) - 1;
|
|
1116
|
+
this.counters.directories++;
|
|
1117
|
+
this.#visitor.directory?.(index, node);
|
|
1118
|
+
return index;
|
|
1119
|
+
}
|
|
1120
|
+
async #scanDir(index, absPath, inherited) {
|
|
1121
|
+
const { excluder } = this.#options;
|
|
1122
|
+
let entries;
|
|
1123
|
+
try {
|
|
1124
|
+
entries = await readdir(absPath, { withFileTypes: true });
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
this.recordError(this.relativePath(index), error);
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
const node = this.dirs[index];
|
|
1130
|
+
node.entries = entries.length;
|
|
1131
|
+
if (entries.length === 0) return;
|
|
1132
|
+
const relDir = excluder.needsPaths ? this.relativePath(index) : "";
|
|
1133
|
+
let chain = inherited;
|
|
1134
|
+
if (excluder.gitignore && entries.some((e) => e.name === ".gitignore" && !e.isDirectory())) {
|
|
1135
|
+
const scope = await excluder.loadScope(joinNative(absPath, ".gitignore"), relDir);
|
|
1136
|
+
if (scope) chain = [...inherited, scope];
|
|
1137
|
+
}
|
|
1138
|
+
const base = absPath.endsWith(sep) ? absPath : absPath + sep;
|
|
1139
|
+
const checkExclusion = excluder.active;
|
|
1140
|
+
for (const entry of entries) {
|
|
1141
|
+
const name = entry.name;
|
|
1142
|
+
const isDirectory = entry.isDirectory();
|
|
1143
|
+
const isFile = !isDirectory && entry.isFile();
|
|
1144
|
+
const isSymlink = !isDirectory && !isFile && entry.isSymbolicLink();
|
|
1145
|
+
const isUnknown = !isDirectory && !isFile && !isSymlink && isUnknownType(entry);
|
|
1146
|
+
if (!isDirectory && !isFile && !isSymlink && !isUnknown) continue;
|
|
1147
|
+
if (checkExclusion) {
|
|
1148
|
+
const rel = relDir ? `${relDir}/${name}` : name;
|
|
1149
|
+
if (excluder.isExcluded(rel, name, isDirectory, chain)) {
|
|
1150
|
+
this.counters.excluded++;
|
|
1151
|
+
continue;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
const fullPath = base + name;
|
|
1155
|
+
if (this.#options.directoriesOnly && !isDirectory) continue;
|
|
1156
|
+
if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain);
|
|
1157
|
+
else if (isFile) this.#limiter.run(() => this.#statFile(index, name, fullPath));
|
|
1158
|
+
else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, isSymlink, isDirectory));
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
#enterDir(parent, name, fullPath, chain) {
|
|
1162
|
+
const depth = this.dirs[parent].depth + 1;
|
|
1163
|
+
if (depth > this.#options.maxDepth) return;
|
|
1164
|
+
const child = this.#addDir(name, parent, depth);
|
|
1165
|
+
this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
|
|
1166
|
+
}
|
|
1167
|
+
async #statFile(dirIndex, name, fullPath) {
|
|
1168
|
+
let stats;
|
|
1169
|
+
try {
|
|
1170
|
+
stats = await lstat(fullPath);
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
this.recordError(this.relativePath(dirIndex, name), error);
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
this.#acceptFile(dirIndex, name, stats);
|
|
1176
|
+
}
|
|
1177
|
+
/**
|
|
1178
|
+
* Handles symlinks, entries whose type the filesystem did not report, and
|
|
1179
|
+
* (when following symlinks) directories, which then need their identity.
|
|
1180
|
+
*/
|
|
1181
|
+
async #resolveEntry(dirIndex, name, fullPath, chain, isSymlink, checkedAsDirectory) {
|
|
1182
|
+
let stats;
|
|
1183
|
+
try {
|
|
1184
|
+
stats = await lstat(fullPath);
|
|
1185
|
+
if (stats.isSymbolicLink()) {
|
|
1186
|
+
isSymlink = true;
|
|
1187
|
+
if (!this.#options.followSymlinks) {
|
|
1188
|
+
this.counters.symlinks++;
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
stats = await stat(fullPath);
|
|
1192
|
+
}
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
const code = errorCode(error);
|
|
1195
|
+
if (isSymlink && (code === "ENOENT" || code === "ELOOP")) {
|
|
1196
|
+
this.counters.symlinks++;
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
this.recordError(this.relativePath(dirIndex, name), error);
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
if (isSymlink) this.counters.symlinks++;
|
|
1203
|
+
if (stats.isDirectory()) {
|
|
1204
|
+
const { excluder } = this.#options;
|
|
1205
|
+
if (excluder.active && !checkedAsDirectory) {
|
|
1206
|
+
const rel = this.relativePath(dirIndex, name);
|
|
1207
|
+
if (excluder.isExcluded(rel, name, true, chain)) {
|
|
1208
|
+
this.counters.excluded++;
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
const key = inodeKey(stats);
|
|
1213
|
+
if (this.#seenDirs.has(key)) return;
|
|
1214
|
+
this.#seenDirs.add(key);
|
|
1215
|
+
this.#enterDir(dirIndex, name, fullPath, chain);
|
|
1216
|
+
} else if (stats.isFile()) this.#acceptFile(dirIndex, name, stats);
|
|
1217
|
+
}
|
|
1218
|
+
#acceptFile(dirIndex, name, stats) {
|
|
1219
|
+
if (!this.#options.countHardlinks && (stats.nlink > 1 || this.#options.followSymlinks)) {
|
|
1220
|
+
const key = inodeKey(stats);
|
|
1221
|
+
if (this.#seenInodes.has(key)) {
|
|
1222
|
+
if (stats.nlink > 1) this.counters.hardlinks++;
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
this.#seenInodes.add(key);
|
|
1226
|
+
}
|
|
1227
|
+
const size = stats.size;
|
|
1228
|
+
if (this.#filtersActive) {
|
|
1229
|
+
const o = this.#options;
|
|
1230
|
+
const mtime = stats.mtimeMs;
|
|
1231
|
+
if (size < o.minSize || size > o.maxSize || mtime < o.modifiedAfter || mtime > o.modifiedBefore) {
|
|
1232
|
+
this.counters.filtered++;
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
const diskBytes = IS_WINDOWS || !(stats.blocks >= 0) ? size : stats.blocks * 512;
|
|
1237
|
+
const node = this.dirs[dirIndex];
|
|
1238
|
+
node.ownFiles++;
|
|
1239
|
+
node.ownBytes += size;
|
|
1240
|
+
node.ownDiskBytes += diskBytes;
|
|
1241
|
+
this.counters.files++;
|
|
1242
|
+
this.counters.bytes += size;
|
|
1243
|
+
this.counters.diskBytes += diskBytes;
|
|
1244
|
+
this.#visitor.file(dirIndex, name, stats, diskBytes);
|
|
1245
|
+
}
|
|
1246
|
+
/** Counts an error and keeps its details, up to {@link MAX_ERROR_DETAILS}. */
|
|
1247
|
+
recordError(path, error) {
|
|
1248
|
+
this.counters.errors++;
|
|
1249
|
+
if (this.errors.length >= 100) return;
|
|
1250
|
+
const code = errorCode(error);
|
|
1251
|
+
this.errors.push({
|
|
1252
|
+
path: path || ".",
|
|
1253
|
+
code: code ?? "UNKNOWN",
|
|
1254
|
+
message: (code && ERROR_DESCRIPTIONS[code]) ?? errorMessage(error)
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
/**
|
|
1259
|
+
* Rolls per-directory totals up the tree. Must run once, after the scan.
|
|
1260
|
+
* Relies on children always having larger indices than their parents.
|
|
1261
|
+
*/
|
|
1262
|
+
function rollUp(dirs) {
|
|
1263
|
+
for (let i = dirs.length - 1; i >= 0; i--) {
|
|
1264
|
+
const node = dirs[i];
|
|
1265
|
+
node.files += node.ownFiles;
|
|
1266
|
+
node.bytes += node.ownBytes;
|
|
1267
|
+
node.diskBytes += node.ownDiskBytes;
|
|
1268
|
+
if (node.parent >= 0) {
|
|
1269
|
+
const parent = dirs[node.parent];
|
|
1270
|
+
parent.files += node.files;
|
|
1271
|
+
parent.bytes += node.bytes;
|
|
1272
|
+
parent.diskBytes += node.diskBytes;
|
|
1273
|
+
if (node.bytes > parent.largestChild) parent.largestChild = node.bytes;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
function inodeKey(stats) {
|
|
1278
|
+
return `${stats.dev}:${stats.ino}`;
|
|
1279
|
+
}
|
|
1280
|
+
function joinNative(dir, name) {
|
|
1281
|
+
return dir.endsWith(sep) ? dir + name : dir + sep + name;
|
|
1282
|
+
}
|
|
1283
|
+
function isUnknownType(entry) {
|
|
1284
|
+
return !(entry.isBlockDevice() || entry.isCharacterDevice() || entry.isFIFO() || entry.isSocket());
|
|
1285
|
+
}
|
|
1286
|
+
const ERROR_DESCRIPTIONS = {
|
|
1287
|
+
EACCES: "permission denied",
|
|
1288
|
+
EPERM: "operation not permitted",
|
|
1289
|
+
ENOENT: "no longer exists",
|
|
1290
|
+
ELOOP: "too many levels of symbolic links",
|
|
1291
|
+
EMFILE: "too many open files",
|
|
1292
|
+
ENAMETOOLONG: "name too long",
|
|
1293
|
+
EIO: "input/output error",
|
|
1294
|
+
EBUSY: "resource busy"
|
|
1295
|
+
};
|
|
1296
|
+
//#endregion
|
|
1297
|
+
//#region src/core/options.ts
|
|
1298
|
+
/** Default number of concurrent filesystem operations. */
|
|
1299
|
+
const DEFAULT_CONCURRENCY = 16;
|
|
1300
|
+
/** Validates the root and turns user-facing settings into scanner options. */
|
|
1301
|
+
async function resolveScan(path, input, now) {
|
|
1302
|
+
const root = resolve(path);
|
|
1303
|
+
await assertDirectory(root);
|
|
1304
|
+
const maxDepth = input.maxDepth ?? null;
|
|
1305
|
+
if (maxDepth !== null && (!Number.isInteger(maxDepth) || maxDepth < 0)) throw new DatError(`maxDepth must be a non-negative integer (got ${maxDepth}).`);
|
|
1306
|
+
const concurrency = input.concurrency ?? 16;
|
|
1307
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) throw new DatError(`concurrency must be a positive integer (got ${concurrency}).`);
|
|
1308
|
+
const minSize = toBytes(input.minSize, "minSize");
|
|
1309
|
+
const maxSize = toBytes(input.maxSize, "maxSize");
|
|
1310
|
+
if (minSize !== null && maxSize !== null && minSize > maxSize) throw new DatError(`minSize (${minSize}) is larger than maxSize (${maxSize}).`);
|
|
1311
|
+
const after = toTimestamp(input.modifiedAfter, "modifiedAfter", now, false);
|
|
1312
|
+
const before = toTimestamp(input.modifiedBefore, "modifiedBefore", now, true);
|
|
1313
|
+
if (after !== null && before !== null && after > before) throw new DatError("modifiedAfter is later than modifiedBefore, so no file could match.");
|
|
1314
|
+
const exclude = [...input.exclude ?? []];
|
|
1315
|
+
const defaultExcludes = input.defaultExcludes ?? true;
|
|
1316
|
+
const gitignore = input.gitignore ?? false;
|
|
1317
|
+
const followSymlinks = input.followSymlinks ?? false;
|
|
1318
|
+
const countHardlinks = input.countHardlinks ?? false;
|
|
1319
|
+
return {
|
|
1320
|
+
options: {
|
|
1321
|
+
root,
|
|
1322
|
+
excluder: new Excluder({
|
|
1323
|
+
patterns: exclude,
|
|
1324
|
+
defaultExcludes,
|
|
1325
|
+
gitignore
|
|
1326
|
+
}),
|
|
1327
|
+
maxDepth: maxDepth ?? Infinity,
|
|
1328
|
+
followSymlinks,
|
|
1329
|
+
countHardlinks,
|
|
1330
|
+
minSize: minSize ?? 0,
|
|
1331
|
+
maxSize: maxSize ?? Infinity,
|
|
1332
|
+
modifiedAfter: after ?? -Infinity,
|
|
1333
|
+
modifiedBefore: before ?? Infinity,
|
|
1334
|
+
concurrency,
|
|
1335
|
+
signal: input.signal
|
|
1336
|
+
},
|
|
1337
|
+
settings: {
|
|
1338
|
+
exclude,
|
|
1339
|
+
defaultExcludes,
|
|
1340
|
+
gitignore,
|
|
1341
|
+
maxDepth,
|
|
1342
|
+
followSymlinks,
|
|
1343
|
+
countHardlinks,
|
|
1344
|
+
minSize,
|
|
1345
|
+
maxSize,
|
|
1346
|
+
modifiedAfter: after === null ? null : new Date(after).toISOString(),
|
|
1347
|
+
modifiedBefore: before === null ? null : new Date(before).toISOString()
|
|
1348
|
+
}
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
async function assertDirectory(path) {
|
|
1352
|
+
if (!(await stat(path).catch((error) => {
|
|
1353
|
+
const code = errorCode(error);
|
|
1354
|
+
if (code === "ENOENT") throw new DatError(`No such directory: ${path}`);
|
|
1355
|
+
if (code === "EACCES" || code === "EPERM") throw new DatError(`Permission denied: ${path}`);
|
|
1356
|
+
throw new DatError(`Cannot access ${path}: ${errorMessage(error)}`, { cause: error });
|
|
1357
|
+
})).isDirectory()) throw new DatError(`Not a directory: ${path}`);
|
|
1358
|
+
}
|
|
1359
|
+
function toBytes(value, name) {
|
|
1360
|
+
if (value === void 0 || value === null) return null;
|
|
1361
|
+
try {
|
|
1362
|
+
return parseSize(value);
|
|
1363
|
+
} catch (error) {
|
|
1364
|
+
throw new DatError(`${name}: ${errorMessage(error)}`);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
function toTimestamp(value, name, now, endOfDay) {
|
|
1368
|
+
if (value === void 0) return null;
|
|
1369
|
+
if (value instanceof Date) return value.getTime();
|
|
1370
|
+
if (typeof value === "number") return value;
|
|
1371
|
+
try {
|
|
1372
|
+
return parsePointInTime(value, {
|
|
1373
|
+
now,
|
|
1374
|
+
endOfDay
|
|
1375
|
+
});
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
throw new DatError(`${name}: ${errorMessage(error)}`);
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Lists the directories a scan with these settings would enter, as
|
|
1382
|
+
* root-relative `/` paths (the root itself is `""`). Files are not examined.
|
|
1383
|
+
*/
|
|
1384
|
+
async function listDirectories(path, settings = {}) {
|
|
1385
|
+
const { options } = await resolveScan(path, settings, Date.now());
|
|
1386
|
+
const scanner = new Scanner({
|
|
1387
|
+
...options,
|
|
1388
|
+
directoriesOnly: true
|
|
1389
|
+
}, { file() {} });
|
|
1390
|
+
await scanner.run();
|
|
1391
|
+
return scanner.dirs.map((_, index) => scanner.relativePath(index));
|
|
1392
|
+
}
|
|
1393
|
+
//#endregion
|
|
1394
|
+
//#region src/core/top.ts
|
|
1395
|
+
/**
|
|
1396
|
+
* Keeps the `limit` largest items seen, in O(limit) memory and O(log limit)
|
|
1397
|
+
* time per insertion, using a binary min-heap keyed by `score`.
|
|
1398
|
+
*
|
|
1399
|
+
* Ties are broken by `tieBreak`, so the selection is deterministic even when
|
|
1400
|
+
* items arrive in a different order between runs.
|
|
1401
|
+
*/
|
|
1402
|
+
var TopK = class {
|
|
1403
|
+
limit;
|
|
1404
|
+
#heap = [];
|
|
1405
|
+
#tieBreak;
|
|
1406
|
+
/** @param tieBreak Negative when `a` should rank above `b` among equal scores. */
|
|
1407
|
+
constructor(limit, tieBreak = () => 0) {
|
|
1408
|
+
this.limit = Math.max(0, Math.floor(limit));
|
|
1409
|
+
this.#tieBreak = tieBreak;
|
|
1410
|
+
}
|
|
1411
|
+
get size() {
|
|
1412
|
+
return this.#heap.length;
|
|
1413
|
+
}
|
|
1414
|
+
/** Cheap pre-check, so callers can skip building items that would be rejected. */
|
|
1415
|
+
accepts(score) {
|
|
1416
|
+
if (this.limit === 0) return false;
|
|
1417
|
+
if (this.#heap.length < this.limit) return true;
|
|
1418
|
+
return score >= this.#heap[0].score;
|
|
1419
|
+
}
|
|
1420
|
+
push(score, item) {
|
|
1421
|
+
if (!this.accepts(score)) return;
|
|
1422
|
+
const entry = {
|
|
1423
|
+
score,
|
|
1424
|
+
item
|
|
1425
|
+
};
|
|
1426
|
+
if (this.#heap.length < this.limit) {
|
|
1427
|
+
this.#heap.push(entry);
|
|
1428
|
+
this.#siftUp(this.#heap.length - 1);
|
|
1429
|
+
} else if (this.#ranksAbove(entry, this.#heap[0])) {
|
|
1430
|
+
this.#heap[0] = entry;
|
|
1431
|
+
this.#siftDown(0);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
/** Items from highest to lowest score. */
|
|
1435
|
+
sorted() {
|
|
1436
|
+
return [...this.#heap].sort((a, b) => this.#ranksAbove(a, b) ? -1 : this.#ranksAbove(b, a) ? 1 : 0).map((e) => e.item);
|
|
1437
|
+
}
|
|
1438
|
+
#ranksAbove(a, b) {
|
|
1439
|
+
if (a.score !== b.score) return a.score > b.score;
|
|
1440
|
+
return this.#tieBreak(a.item, b.item) < 0;
|
|
1441
|
+
}
|
|
1442
|
+
#siftUp(index) {
|
|
1443
|
+
const heap = this.#heap;
|
|
1444
|
+
while (index > 0) {
|
|
1445
|
+
const parent = index - 1 >> 1;
|
|
1446
|
+
if (!this.#ranksAbove(heap[parent], heap[index])) break;
|
|
1447
|
+
[heap[parent], heap[index]] = [heap[index], heap[parent]];
|
|
1448
|
+
index = parent;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
#siftDown(index) {
|
|
1452
|
+
const heap = this.#heap;
|
|
1453
|
+
for (;;) {
|
|
1454
|
+
const left = index * 2 + 1;
|
|
1455
|
+
const right = left + 1;
|
|
1456
|
+
let lowest = index;
|
|
1457
|
+
if (left < heap.length && this.#ranksAbove(heap[lowest], heap[left])) lowest = left;
|
|
1458
|
+
if (right < heap.length && this.#ranksAbove(heap[lowest], heap[right])) lowest = right;
|
|
1459
|
+
if (lowest === index) return;
|
|
1460
|
+
[heap[lowest], heap[index]] = [heap[index], heap[lowest]];
|
|
1461
|
+
index = lowest;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
};
|
|
1465
|
+
//#endregion
|
|
1466
|
+
//#region src/core/analyze.ts
|
|
1467
|
+
/** Default size for "large file" detection: 100 MiB. */
|
|
1468
|
+
const DEFAULT_LARGE_FILE_THRESHOLD = 104857600;
|
|
1469
|
+
/** Default age for stale-file detection. */
|
|
1470
|
+
const DEFAULT_STALE_AGE = "1y";
|
|
1471
|
+
/** A directory is folded into its largest child when that child holds this share of its size. */
|
|
1472
|
+
const PASS_THROUGH_SHARE$1 = .95;
|
|
1473
|
+
/**
|
|
1474
|
+
* Analyzes a directory tree in a single pass.
|
|
1475
|
+
*
|
|
1476
|
+
* Memory stays bounded by default: totals, type and extension statistics,
|
|
1477
|
+
* and top-N lists are computed while scanning. Opt-in reports (large, empty,
|
|
1478
|
+
* and stale files) hold only matching entries; duplicate detection holds one
|
|
1479
|
+
* small record per file that shares its size with another.
|
|
1480
|
+
*
|
|
1481
|
+
* @example
|
|
1482
|
+
* ```ts
|
|
1483
|
+
* import { analyze } from 'dir-analysis-tool';
|
|
1484
|
+
*
|
|
1485
|
+
* const result = await analyze('.', { duplicates: true, top: 5 });
|
|
1486
|
+
* console.log(result.summary.bytes, result.duplicates?.wastedBytes);
|
|
1487
|
+
* ```
|
|
1488
|
+
*/
|
|
1489
|
+
async function analyze(path, options = {}) {
|
|
1490
|
+
const startedAt = Date.now();
|
|
1491
|
+
const started = performance.now();
|
|
1492
|
+
const features = resolveFeatures(options, startedAt);
|
|
1493
|
+
const { options: scanOptions, settings } = await resolveScan(path, options, startedAt);
|
|
1494
|
+
const collector = new Collector(features);
|
|
1495
|
+
const scanner = new Scanner(scanOptions, collector);
|
|
1496
|
+
collector.attach(scanner);
|
|
1497
|
+
const report = options.onProgress;
|
|
1498
|
+
const progress = createProgressReporter(report, options.progressInterval, () => ({
|
|
1499
|
+
phase: "scan",
|
|
1500
|
+
files: scanner.counters.files,
|
|
1501
|
+
directories: scanner.counters.directories,
|
|
1502
|
+
bytes: scanner.counters.bytes,
|
|
1503
|
+
errors: scanner.counters.errors
|
|
1504
|
+
}));
|
|
1505
|
+
try {
|
|
1506
|
+
await scanner.run();
|
|
1507
|
+
progress.flush();
|
|
1508
|
+
rollUp(scanner.dirs);
|
|
1509
|
+
let duplicates;
|
|
1510
|
+
if (features.duplicates) {
|
|
1511
|
+
progress.stop();
|
|
1512
|
+
duplicates = await collector.findDuplicates(scanOptions.concurrency, scanOptions.signal, (p) => report?.({
|
|
1513
|
+
phase: "hash",
|
|
1514
|
+
files: scanner.counters.files,
|
|
1515
|
+
bytes: scanner.counters.bytes,
|
|
1516
|
+
...p
|
|
1517
|
+
}));
|
|
1518
|
+
}
|
|
1519
|
+
const result = collector.build(scanner, {
|
|
1520
|
+
root: scanOptions.root,
|
|
1521
|
+
startedAt,
|
|
1522
|
+
settings,
|
|
1523
|
+
duplicates
|
|
1524
|
+
});
|
|
1525
|
+
if (features.budgets.length > 0) result.budgets = evaluateBudgets(features.budgets, result);
|
|
1526
|
+
result.durationMs = Math.round(performance.now() - started);
|
|
1527
|
+
return result;
|
|
1528
|
+
} finally {
|
|
1529
|
+
progress.stop();
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
function resolveFeatures(options, now) {
|
|
1533
|
+
const top = options.top ?? 10;
|
|
1534
|
+
if (!Number.isInteger(top) || top < 0) throw new DatError(`top must be a non-negative integer (got ${top}).`);
|
|
1535
|
+
let budgets;
|
|
1536
|
+
try {
|
|
1537
|
+
budgets = (options.budgets ?? []).map(parseBudget);
|
|
1538
|
+
} catch (error) {
|
|
1539
|
+
throw new DatError(errorMessage(error));
|
|
1540
|
+
}
|
|
1541
|
+
const required = requiredFeatures(budgets);
|
|
1542
|
+
let largeThreshold = null;
|
|
1543
|
+
if (options.largeFiles === true || options.largeFiles === void 0 && required.has("largeFiles")) largeThreshold = DEFAULT_LARGE_FILE_THRESHOLD;
|
|
1544
|
+
else if (options.largeFiles !== void 0 && options.largeFiles !== false) largeThreshold = toBytes(options.largeFiles, "largeFiles");
|
|
1545
|
+
let staleBefore = null;
|
|
1546
|
+
const stale = options.stale ?? (required.has("stale") ? true : void 0);
|
|
1547
|
+
if (stale !== void 0 && stale !== false) {
|
|
1548
|
+
if (stale === true) staleBefore = parsePointInTime("1y", { now });
|
|
1549
|
+
else if (stale instanceof Date) staleBefore = stale.getTime();
|
|
1550
|
+
else if (typeof stale === "number") staleBefore = stale;
|
|
1551
|
+
else try {
|
|
1552
|
+
staleBefore = parsePointInTime(stale, {
|
|
1553
|
+
now,
|
|
1554
|
+
endOfDay: true
|
|
1555
|
+
});
|
|
1556
|
+
} catch (error) {
|
|
1557
|
+
throw new DatError(`stale: ${errorMessage(error)}`);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
let tree = null;
|
|
1561
|
+
if (options.tree) {
|
|
1562
|
+
const config = options.tree === true ? {} : options.tree;
|
|
1563
|
+
const depth = config.depth ?? 3;
|
|
1564
|
+
const limit = config.limit ?? Math.max(top, 10);
|
|
1565
|
+
if (!Number.isInteger(depth) || depth < 1) throw new DatError(`tree depth must be a positive integer (got ${depth}).`);
|
|
1566
|
+
if (!Number.isInteger(limit) || limit < 1) throw new DatError(`tree limit must be a positive integer (got ${limit}).`);
|
|
1567
|
+
tree = {
|
|
1568
|
+
depth,
|
|
1569
|
+
limit
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
return {
|
|
1573
|
+
top,
|
|
1574
|
+
largeThreshold,
|
|
1575
|
+
duplicates: options.duplicates === true || required.has("duplicates"),
|
|
1576
|
+
minDuplicateSize: Math.max(1, toBytes(options.minDuplicateSize, "minDuplicateSize") ?? 1),
|
|
1577
|
+
empty: options.empty === true || required.has("empty"),
|
|
1578
|
+
staleBefore,
|
|
1579
|
+
tree,
|
|
1580
|
+
budgets
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
/** Collects every statistic during the scan. One instance per analysis. */
|
|
1584
|
+
var Collector = class {
|
|
1585
|
+
#features;
|
|
1586
|
+
#scanner = null;
|
|
1587
|
+
#types = emptyTypeStats();
|
|
1588
|
+
#extensions = /* @__PURE__ */ new Map();
|
|
1589
|
+
#largestFileBytes = 0;
|
|
1590
|
+
#topFiles;
|
|
1591
|
+
#large = {
|
|
1592
|
+
refs: [],
|
|
1593
|
+
bytes: 0
|
|
1594
|
+
};
|
|
1595
|
+
#empty = [];
|
|
1596
|
+
#stale = {
|
|
1597
|
+
refs: [],
|
|
1598
|
+
bytes: 0
|
|
1599
|
+
};
|
|
1600
|
+
/** Size -> candidates; a single candidate is stored unwrapped to save memory. */
|
|
1601
|
+
#bySize = /* @__PURE__ */ new Map();
|
|
1602
|
+
/** Tree data: subdirectories and largest files of each directory shallower than the tree depth. */
|
|
1603
|
+
#treeChildren = /* @__PURE__ */ new Map();
|
|
1604
|
+
#treeFiles = /* @__PURE__ */ new Map();
|
|
1605
|
+
constructor(features) {
|
|
1606
|
+
this.#features = features;
|
|
1607
|
+
this.#topFiles = new TopK(features.top, (a, b) => this.#compareRefs(a, b));
|
|
1608
|
+
}
|
|
1609
|
+
attach(scanner) {
|
|
1610
|
+
this.#scanner = scanner;
|
|
1611
|
+
}
|
|
1612
|
+
directory(index, node) {
|
|
1613
|
+
const tree = this.#features.tree;
|
|
1614
|
+
if (tree && node.parent >= 0 && node.depth <= tree.depth) {
|
|
1615
|
+
let siblings = this.#treeChildren.get(node.parent);
|
|
1616
|
+
if (!siblings) this.#treeChildren.set(node.parent, siblings = []);
|
|
1617
|
+
siblings.push(index);
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
file(dir, name, stats) {
|
|
1621
|
+
const bytes = stats.size;
|
|
1622
|
+
const mtimeMs = stats.mtimeMs;
|
|
1623
|
+
const features = this.#features;
|
|
1624
|
+
const extension = extensionOf(name);
|
|
1625
|
+
const type = this.#types[classify(name, extension)];
|
|
1626
|
+
type.files++;
|
|
1627
|
+
type.bytes += bytes;
|
|
1628
|
+
const ext = this.#extensions.get(extension);
|
|
1629
|
+
if (ext) {
|
|
1630
|
+
ext.files++;
|
|
1631
|
+
ext.bytes += bytes;
|
|
1632
|
+
} else this.#extensions.set(extension, {
|
|
1633
|
+
files: 1,
|
|
1634
|
+
bytes
|
|
1635
|
+
});
|
|
1636
|
+
if (bytes > this.#largestFileBytes) this.#largestFileBytes = bytes;
|
|
1637
|
+
let ref;
|
|
1638
|
+
const makeRef = () => ref ??= {
|
|
1639
|
+
dir,
|
|
1640
|
+
name,
|
|
1641
|
+
bytes,
|
|
1642
|
+
mtimeMs
|
|
1643
|
+
};
|
|
1644
|
+
if (this.#topFiles.accepts(bytes)) this.#topFiles.push(bytes, makeRef());
|
|
1645
|
+
if (features.largeThreshold !== null && bytes >= features.largeThreshold) {
|
|
1646
|
+
this.#large.refs.push(makeRef());
|
|
1647
|
+
this.#large.bytes += bytes;
|
|
1648
|
+
}
|
|
1649
|
+
if (features.empty && bytes === 0) this.#empty.push(makeRef());
|
|
1650
|
+
if (features.staleBefore !== null && mtimeMs < features.staleBefore) {
|
|
1651
|
+
this.#stale.refs.push(makeRef());
|
|
1652
|
+
this.#stale.bytes += bytes;
|
|
1653
|
+
}
|
|
1654
|
+
if (features.tree) {
|
|
1655
|
+
if (this.#scanner.dirs[dir].depth < features.tree.depth) {
|
|
1656
|
+
let heap = this.#treeFiles.get(dir);
|
|
1657
|
+
if (!heap) {
|
|
1658
|
+
heap = new TopK(features.tree.limit, (a, b) => a.name.localeCompare(b.name));
|
|
1659
|
+
this.#treeFiles.set(dir, heap);
|
|
1660
|
+
}
|
|
1661
|
+
if (heap.accepts(bytes)) heap.push(bytes, makeRef());
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
if (features.duplicates && bytes >= features.minDuplicateSize) {
|
|
1665
|
+
const candidate = {
|
|
1666
|
+
dir,
|
|
1667
|
+
name,
|
|
1668
|
+
bytes,
|
|
1669
|
+
mtimeMs,
|
|
1670
|
+
inode: `${stats.dev}:${stats.ino}`
|
|
1671
|
+
};
|
|
1672
|
+
const existing = this.#bySize.get(bytes);
|
|
1673
|
+
if (existing === void 0) this.#bySize.set(bytes, candidate);
|
|
1674
|
+
else if (Array.isArray(existing)) existing.push(candidate);
|
|
1675
|
+
else this.#bySize.set(bytes, [existing, candidate]);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
async findDuplicates(concurrency, signal, onProgress) {
|
|
1679
|
+
const scanner = this.#scanner;
|
|
1680
|
+
const groups = [];
|
|
1681
|
+
for (const value of this.#bySize.values()) if (Array.isArray(value)) groups.push(value);
|
|
1682
|
+
this.#bySize.clear();
|
|
1683
|
+
const dirPaths = /* @__PURE__ */ new Map();
|
|
1684
|
+
const items = (await findDuplicates(groups, {
|
|
1685
|
+
pathOf: (c) => {
|
|
1686
|
+
let dir = dirPaths.get(c.dir);
|
|
1687
|
+
if (dir === void 0) dirPaths.set(c.dir, dir = scanner.absolutePath(c.dir));
|
|
1688
|
+
return joinRelative(dir, c.name);
|
|
1689
|
+
},
|
|
1690
|
+
concurrency: Math.min(concurrency, 8),
|
|
1691
|
+
signal,
|
|
1692
|
+
onProgress,
|
|
1693
|
+
onError: (c, error) => scanner.recordError(scanner.relativePath(c.dir, c.name), error)
|
|
1694
|
+
})).map((group) => {
|
|
1695
|
+
const files = group.members.map((m) => scanner.relativePath(m.dir, m.name)).sort(comparePaths);
|
|
1696
|
+
return {
|
|
1697
|
+
hash: group.hash,
|
|
1698
|
+
bytes: group.bytes,
|
|
1699
|
+
wastedBytes: group.bytes * (files.length - 1),
|
|
1700
|
+
files
|
|
1701
|
+
};
|
|
1702
|
+
});
|
|
1703
|
+
items.sort((a, b) => b.wastedBytes - a.wastedBytes || comparePaths(a.files[0], b.files[0]));
|
|
1704
|
+
let files = 0;
|
|
1705
|
+
let wastedBytes = 0;
|
|
1706
|
+
let bytes = 0;
|
|
1707
|
+
for (const group of items) {
|
|
1708
|
+
files += group.files.length;
|
|
1709
|
+
wastedBytes += group.wastedBytes;
|
|
1710
|
+
bytes += group.bytes * group.files.length;
|
|
1711
|
+
}
|
|
1712
|
+
return {
|
|
1713
|
+
count: items.length,
|
|
1714
|
+
files,
|
|
1715
|
+
bytes,
|
|
1716
|
+
wastedBytes,
|
|
1717
|
+
items
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
build(scanner, context) {
|
|
1721
|
+
const features = this.#features;
|
|
1722
|
+
const c = scanner.counters;
|
|
1723
|
+
const toEntry = (ref) => ({
|
|
1724
|
+
path: scanner.relativePath(ref.dir, ref.name),
|
|
1725
|
+
bytes: ref.bytes,
|
|
1726
|
+
modified: new Date(ref.mtimeMs).toISOString()
|
|
1727
|
+
});
|
|
1728
|
+
const bySizeThenPath = (a, b) => b.bytes - a.bytes || comparePaths(a.path, b.path);
|
|
1729
|
+
const result = {
|
|
1730
|
+
schemaVersion: 3,
|
|
1731
|
+
tool: TOOL,
|
|
1732
|
+
root: context.root,
|
|
1733
|
+
startedAt: new Date(context.startedAt).toISOString(),
|
|
1734
|
+
durationMs: 0,
|
|
1735
|
+
settings: context.settings,
|
|
1736
|
+
summary: {
|
|
1737
|
+
bytes: c.bytes,
|
|
1738
|
+
diskBytes: c.diskBytes,
|
|
1739
|
+
files: c.files,
|
|
1740
|
+
directories: c.directories - 1,
|
|
1741
|
+
largestFileBytes: this.#largestFileBytes,
|
|
1742
|
+
symlinks: c.symlinks,
|
|
1743
|
+
hardlinks: c.hardlinks,
|
|
1744
|
+
excluded: c.excluded,
|
|
1745
|
+
filtered: c.filtered,
|
|
1746
|
+
errors: c.errors
|
|
1747
|
+
},
|
|
1748
|
+
types: this.#types,
|
|
1749
|
+
extensions: [...this.#extensions].map(([extension, stat]) => ({
|
|
1750
|
+
extension,
|
|
1751
|
+
...stat
|
|
1752
|
+
})).sort((a, b) => b.bytes - a.bytes || b.files - a.files || a.extension.localeCompare(b.extension)),
|
|
1753
|
+
largestDirectories: this.#largestDirectories(scanner),
|
|
1754
|
+
largestFiles: this.#topFiles.sorted().map(toEntry),
|
|
1755
|
+
errors: [...scanner.errors].sort((a, b) => comparePaths(a.path, b.path))
|
|
1756
|
+
};
|
|
1757
|
+
if (features.largeThreshold !== null) result.largeFiles = {
|
|
1758
|
+
threshold: features.largeThreshold,
|
|
1759
|
+
count: this.#large.refs.length,
|
|
1760
|
+
bytes: this.#large.bytes,
|
|
1761
|
+
items: this.#large.refs.map(toEntry).sort(bySizeThenPath)
|
|
1762
|
+
};
|
|
1763
|
+
if (context.duplicates) result.duplicates = context.duplicates;
|
|
1764
|
+
if (features.empty) {
|
|
1765
|
+
result.emptyFiles = {
|
|
1766
|
+
count: this.#empty.length,
|
|
1767
|
+
bytes: 0,
|
|
1768
|
+
items: this.#empty.map(toEntry).sort((a, b) => comparePaths(a.path, b.path))
|
|
1769
|
+
};
|
|
1770
|
+
const emptyDirs = [];
|
|
1771
|
+
for (let i = 1; i < scanner.dirs.length; i++) if (scanner.dirs[i].entries === 0) emptyDirs.push(scanner.relativePath(i));
|
|
1772
|
+
result.emptyDirectories = {
|
|
1773
|
+
count: emptyDirs.length,
|
|
1774
|
+
items: emptyDirs.sort(comparePaths)
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
if (features.staleBefore !== null) result.staleFiles = {
|
|
1778
|
+
modifiedBefore: new Date(features.staleBefore).toISOString(),
|
|
1779
|
+
count: this.#stale.refs.length,
|
|
1780
|
+
bytes: this.#stale.bytes,
|
|
1781
|
+
items: this.#stale.refs.map(toEntry).sort(bySizeThenPath)
|
|
1782
|
+
};
|
|
1783
|
+
if (features.tree) result.tree = this.#buildTree(scanner, 0, features.tree.limit, toEntry);
|
|
1784
|
+
return result;
|
|
1785
|
+
}
|
|
1786
|
+
#largestDirectories(scanner) {
|
|
1787
|
+
const top = new TopK(this.#features.top, (a, b) => comparePaths(scanner.relativePath(a), scanner.relativePath(b)));
|
|
1788
|
+
const dirs = scanner.dirs;
|
|
1789
|
+
for (let i = 1; i < dirs.length; i++) {
|
|
1790
|
+
const node = dirs[i];
|
|
1791
|
+
if (node.bytes === 0) continue;
|
|
1792
|
+
if (node.largestChild >= node.bytes * PASS_THROUGH_SHARE$1) continue;
|
|
1793
|
+
if (top.accepts(node.bytes)) top.push(node.bytes, i);
|
|
1794
|
+
}
|
|
1795
|
+
return top.sorted().map((i) => ({
|
|
1796
|
+
path: scanner.relativePath(i),
|
|
1797
|
+
bytes: dirs[i].bytes,
|
|
1798
|
+
files: dirs[i].files
|
|
1799
|
+
}));
|
|
1800
|
+
}
|
|
1801
|
+
#buildTree(scanner, index, limit, toEntry) {
|
|
1802
|
+
const node = scanner.dirs[index];
|
|
1803
|
+
const result = {
|
|
1804
|
+
name: index === 0 ? "." : node.name,
|
|
1805
|
+
path: index === 0 ? "" : scanner.relativePath(index),
|
|
1806
|
+
type: "directory",
|
|
1807
|
+
bytes: node.bytes,
|
|
1808
|
+
files: node.files
|
|
1809
|
+
};
|
|
1810
|
+
const subdirs = this.#treeChildren.get(index);
|
|
1811
|
+
const files = this.#treeFiles.get(index);
|
|
1812
|
+
if (!subdirs && !files) return result;
|
|
1813
|
+
const candidates = [];
|
|
1814
|
+
for (const child of subdirs ?? []) candidates.push({
|
|
1815
|
+
bytes: scanner.dirs[child].bytes,
|
|
1816
|
+
key: scanner.dirs[child].name,
|
|
1817
|
+
build: () => this.#buildTree(scanner, child, limit, toEntry)
|
|
1818
|
+
});
|
|
1819
|
+
for (const ref of files?.sorted() ?? []) candidates.push({
|
|
1820
|
+
bytes: ref.bytes,
|
|
1821
|
+
key: ref.name,
|
|
1822
|
+
build: () => {
|
|
1823
|
+
const entry = toEntry(ref);
|
|
1824
|
+
return {
|
|
1825
|
+
name: ref.name,
|
|
1826
|
+
path: entry.path,
|
|
1827
|
+
type: "file",
|
|
1828
|
+
bytes: ref.bytes,
|
|
1829
|
+
files: 1
|
|
1830
|
+
};
|
|
1831
|
+
}
|
|
1832
|
+
});
|
|
1833
|
+
candidates.sort((a, b) => b.bytes - a.bytes || a.key.localeCompare(b.key));
|
|
1834
|
+
const shown = candidates.slice(0, limit);
|
|
1835
|
+
result.children = shown.map((c) => c.build());
|
|
1836
|
+
const omittedEntries = (subdirs?.length ?? 0) + node.ownFiles - shown.length;
|
|
1837
|
+
if (omittedEntries > 0) {
|
|
1838
|
+
let shownBytes = 0;
|
|
1839
|
+
let shownFiles = 0;
|
|
1840
|
+
for (const child of result.children) {
|
|
1841
|
+
shownBytes += child.bytes;
|
|
1842
|
+
shownFiles += child.files;
|
|
1843
|
+
}
|
|
1844
|
+
result.omitted = {
|
|
1845
|
+
entries: omittedEntries,
|
|
1846
|
+
files: node.files - shownFiles,
|
|
1847
|
+
bytes: node.bytes - shownBytes
|
|
1848
|
+
};
|
|
1849
|
+
}
|
|
1850
|
+
return result;
|
|
1851
|
+
}
|
|
1852
|
+
#compareRefs(a, b) {
|
|
1853
|
+
const scanner = this.#scanner;
|
|
1854
|
+
return comparePaths(scanner.relativePath(a.dir, a.name), scanner.relativePath(b.dir, b.name));
|
|
1855
|
+
}
|
|
1856
|
+
};
|
|
1857
|
+
function createProgressReporter(report, interval, snapshot) {
|
|
1858
|
+
if (!report) return {
|
|
1859
|
+
flush() {},
|
|
1860
|
+
stop() {}
|
|
1861
|
+
};
|
|
1862
|
+
const timer = setInterval(() => report(snapshot()), interval ?? 100);
|
|
1863
|
+
timer.unref();
|
|
1864
|
+
let stopped = false;
|
|
1865
|
+
return {
|
|
1866
|
+
flush() {
|
|
1867
|
+
if (!stopped) report(snapshot());
|
|
1868
|
+
},
|
|
1869
|
+
stop() {
|
|
1870
|
+
stopped = true;
|
|
1871
|
+
clearInterval(timer);
|
|
1872
|
+
}
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
//#endregion
|
|
1876
|
+
//#region src/core/compare.ts
|
|
1877
|
+
const PASS_THROUGH_SHARE = .95;
|
|
1878
|
+
/** Records every file by its root-relative path, for diffing. */
|
|
1879
|
+
var FileIndex = class {
|
|
1880
|
+
files = /* @__PURE__ */ new Map();
|
|
1881
|
+
types = emptyTypeStats();
|
|
1882
|
+
#dirPaths = [];
|
|
1883
|
+
directory(index, node) {
|
|
1884
|
+
const parentPath = node.parent >= 0 ? this.#dirPaths[node.parent] : "";
|
|
1885
|
+
this.#dirPaths[index] = parentPath ? `${parentPath}/${node.name}` : node.name;
|
|
1886
|
+
}
|
|
1887
|
+
file(dir, name, stats) {
|
|
1888
|
+
const dirPath = this.#dirPaths[dir];
|
|
1889
|
+
this.files.set(dirPath ? `${dirPath}/${name}` : name, {
|
|
1890
|
+
bytes: stats.size,
|
|
1891
|
+
mtimeMs: stats.mtimeMs
|
|
1892
|
+
});
|
|
1893
|
+
const type = this.types[classify(name)];
|
|
1894
|
+
type.files++;
|
|
1895
|
+
type.bytes += stats.size;
|
|
1896
|
+
}
|
|
1897
|
+
dirPath(index) {
|
|
1898
|
+
return this.#dirPaths[index];
|
|
1899
|
+
}
|
|
1900
|
+
};
|
|
1901
|
+
/**
|
|
1902
|
+
* Compares two directory trees: what was added, removed, or changed, and
|
|
1903
|
+
* which folders grew or shrank the most. Both sides use the same exclusion
|
|
1904
|
+
* rules and filters. Memory grows with the number of files in both trees.
|
|
1905
|
+
*/
|
|
1906
|
+
async function compare(left, right, options = {}) {
|
|
1907
|
+
const startedAt = Date.now();
|
|
1908
|
+
const started = performance.now();
|
|
1909
|
+
const top = options.top ?? 10;
|
|
1910
|
+
if (!Number.isInteger(top) || top < 0) throw new DatError(`top must be a non-negative integer (got ${top}).`);
|
|
1911
|
+
const [a, b] = await Promise.all([resolveScan(left, options, startedAt), resolveScan(right, options, startedAt)]);
|
|
1912
|
+
const leftIndex = new FileIndex();
|
|
1913
|
+
const rightIndex = new FileIndex();
|
|
1914
|
+
const leftScanner = new Scanner(a.options, leftIndex);
|
|
1915
|
+
const rightScanner = new Scanner(b.options, rightIndex);
|
|
1916
|
+
const progress = createProgressReporter(options.onProgress, options.progressInterval, () => ({
|
|
1917
|
+
phase: "scan",
|
|
1918
|
+
files: leftScanner.counters.files + rightScanner.counters.files
|
|
1919
|
+
}));
|
|
1920
|
+
try {
|
|
1921
|
+
await Promise.all([leftScanner.run(), rightScanner.run()]);
|
|
1922
|
+
} finally {
|
|
1923
|
+
progress.stop();
|
|
1924
|
+
}
|
|
1925
|
+
rollUp(leftScanner.dirs);
|
|
1926
|
+
rollUp(rightScanner.dirs);
|
|
1927
|
+
const added = [];
|
|
1928
|
+
const removed = [];
|
|
1929
|
+
const changed = [];
|
|
1930
|
+
const sameSize = [];
|
|
1931
|
+
let unchanged = 0;
|
|
1932
|
+
for (const [path, l] of leftIndex.files) {
|
|
1933
|
+
const r = rightIndex.files.get(path);
|
|
1934
|
+
if (!r) removed.push(toEntry(path, l));
|
|
1935
|
+
else if (l.bytes !== r.bytes) changed.push({
|
|
1936
|
+
path,
|
|
1937
|
+
leftBytes: l.bytes,
|
|
1938
|
+
rightBytes: r.bytes,
|
|
1939
|
+
delta: r.bytes - l.bytes
|
|
1940
|
+
});
|
|
1941
|
+
else if (options.content && l.bytes > 0) sameSize.push(path);
|
|
1942
|
+
else unchanged++;
|
|
1943
|
+
}
|
|
1944
|
+
for (const [path, r] of rightIndex.files) if (!leftIndex.files.has(path)) added.push(toEntry(path, r));
|
|
1945
|
+
if (sameSize.length > 0) {
|
|
1946
|
+
const differing = await findContentChanges(sameSize, a.options.root, b.options.root, options);
|
|
1947
|
+
for (const path of sameSize) if (differing.has(path)) {
|
|
1948
|
+
const bytes = leftIndex.files.get(path).bytes;
|
|
1949
|
+
changed.push({
|
|
1950
|
+
path,
|
|
1951
|
+
leftBytes: bytes,
|
|
1952
|
+
rightBytes: bytes,
|
|
1953
|
+
delta: 0
|
|
1954
|
+
});
|
|
1955
|
+
} else unchanged++;
|
|
1956
|
+
}
|
|
1957
|
+
const bySize = (x, y) => y.bytes - x.bytes || comparePaths(x.path, y.path);
|
|
1958
|
+
added.sort(bySize);
|
|
1959
|
+
removed.sort(bySize);
|
|
1960
|
+
changed.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta) || comparePaths(x.path, y.path));
|
|
1961
|
+
const leftSide = side(a.options.root, leftScanner, leftIndex);
|
|
1962
|
+
const rightSide = side(b.options.root, rightScanner, rightIndex);
|
|
1963
|
+
return {
|
|
1964
|
+
schemaVersion: 3,
|
|
1965
|
+
tool: TOOL,
|
|
1966
|
+
startedAt: new Date(startedAt).toISOString(),
|
|
1967
|
+
durationMs: Math.round(performance.now() - started),
|
|
1968
|
+
mode: options.content ? "content" : "size",
|
|
1969
|
+
left: leftSide,
|
|
1970
|
+
right: rightSide,
|
|
1971
|
+
delta: {
|
|
1972
|
+
bytes: rightSide.summary.bytes - leftSide.summary.bytes,
|
|
1973
|
+
diskBytes: rightSide.summary.diskBytes - leftSide.summary.diskBytes,
|
|
1974
|
+
files: rightSide.summary.files - leftSide.summary.files,
|
|
1975
|
+
directories: rightSide.summary.directories - leftSide.summary.directories
|
|
1976
|
+
},
|
|
1977
|
+
added: list(added),
|
|
1978
|
+
removed: list(removed),
|
|
1979
|
+
changed: {
|
|
1980
|
+
count: changed.length,
|
|
1981
|
+
delta: changed.reduce((sum, c) => sum + c.delta, 0),
|
|
1982
|
+
items: changed
|
|
1983
|
+
},
|
|
1984
|
+
unchanged,
|
|
1985
|
+
directories: directoryDeltas(leftScanner, leftIndex, rightScanner, rightIndex, top)
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
function toEntry(path, record) {
|
|
1989
|
+
return {
|
|
1990
|
+
path,
|
|
1991
|
+
bytes: record.bytes,
|
|
1992
|
+
modified: new Date(record.mtimeMs).toISOString()
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
function list(items) {
|
|
1996
|
+
return {
|
|
1997
|
+
count: items.length,
|
|
1998
|
+
bytes: items.reduce((sum, f) => sum + f.bytes, 0),
|
|
1999
|
+
items
|
|
2000
|
+
};
|
|
2001
|
+
}
|
|
2002
|
+
function side(root, scanner, index) {
|
|
2003
|
+
const c = scanner.counters;
|
|
2004
|
+
let largest = 0;
|
|
2005
|
+
for (const record of index.files.values()) if (record.bytes > largest) largest = record.bytes;
|
|
2006
|
+
return {
|
|
2007
|
+
root,
|
|
2008
|
+
summary: {
|
|
2009
|
+
bytes: c.bytes,
|
|
2010
|
+
diskBytes: c.diskBytes,
|
|
2011
|
+
files: c.files,
|
|
2012
|
+
directories: c.directories - 1,
|
|
2013
|
+
largestFileBytes: largest,
|
|
2014
|
+
symlinks: c.symlinks,
|
|
2015
|
+
hardlinks: c.hardlinks,
|
|
2016
|
+
excluded: c.excluded,
|
|
2017
|
+
filtered: c.filtered,
|
|
2018
|
+
errors: c.errors
|
|
2019
|
+
},
|
|
2020
|
+
types: index.types
|
|
2021
|
+
};
|
|
2022
|
+
}
|
|
2023
|
+
async function findContentChanges(paths, leftRoot, rightRoot, options) {
|
|
2024
|
+
const differing = /* @__PURE__ */ new Set();
|
|
2025
|
+
const limiter = new Limiter(Math.min(options.concurrency ?? 8, 8));
|
|
2026
|
+
const onAbort = () => limiter.abort(new AbortError());
|
|
2027
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
2028
|
+
let done = 0;
|
|
2029
|
+
for (const path of paths) limiter.run(async () => {
|
|
2030
|
+
try {
|
|
2031
|
+
const [l, r] = await Promise.all([hashFile(joinRelative(leftRoot, path)), hashFile(joinRelative(rightRoot, path))]);
|
|
2032
|
+
if (l !== r) differing.add(path);
|
|
2033
|
+
} catch {
|
|
2034
|
+
differing.add(path);
|
|
2035
|
+
} finally {
|
|
2036
|
+
done++;
|
|
2037
|
+
options.onProgress?.({
|
|
2038
|
+
phase: "hash",
|
|
2039
|
+
files: done,
|
|
2040
|
+
total: paths.length
|
|
2041
|
+
});
|
|
2042
|
+
}
|
|
2043
|
+
});
|
|
2044
|
+
try {
|
|
2045
|
+
await limiter.idle();
|
|
2046
|
+
} finally {
|
|
2047
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
2048
|
+
}
|
|
2049
|
+
return differing;
|
|
2050
|
+
}
|
|
2051
|
+
function directoryDeltas(leftScanner, leftIndex, rightScanner, rightIndex, top) {
|
|
2052
|
+
if (top === 0) return [];
|
|
2053
|
+
const sizes = /* @__PURE__ */ new Map();
|
|
2054
|
+
const collect = (scanner, index, key) => {
|
|
2055
|
+
for (let i = 1; i < scanner.dirs.length; i++) {
|
|
2056
|
+
const path = index.dirPath(i);
|
|
2057
|
+
const entry = sizes.get(path) ?? {
|
|
2058
|
+
left: 0,
|
|
2059
|
+
right: 0
|
|
2060
|
+
};
|
|
2061
|
+
entry[key] = scanner.dirs[i].bytes;
|
|
2062
|
+
sizes.set(path, entry);
|
|
2063
|
+
}
|
|
2064
|
+
};
|
|
2065
|
+
collect(leftScanner, leftIndex, "left");
|
|
2066
|
+
collect(rightScanner, rightIndex, "right");
|
|
2067
|
+
const largestChildDelta = /* @__PURE__ */ new Map();
|
|
2068
|
+
for (const [path, { left, right }] of sizes) {
|
|
2069
|
+
const slash = path.lastIndexOf("/");
|
|
2070
|
+
if (slash < 0) continue;
|
|
2071
|
+
const parent = path.slice(0, slash);
|
|
2072
|
+
const delta = right - left;
|
|
2073
|
+
const current = largestChildDelta.get(parent) ?? 0;
|
|
2074
|
+
if (Math.abs(delta) > Math.abs(current)) largestChildDelta.set(parent, delta);
|
|
2075
|
+
}
|
|
2076
|
+
const deltas = [];
|
|
2077
|
+
for (const [path, { left, right }] of sizes) {
|
|
2078
|
+
const delta = right - left;
|
|
2079
|
+
if (delta === 0) continue;
|
|
2080
|
+
const child = largestChildDelta.get(path) ?? 0;
|
|
2081
|
+
if (Math.sign(child) === Math.sign(delta) && Math.abs(child) >= Math.abs(delta) * PASS_THROUGH_SHARE) continue;
|
|
2082
|
+
deltas.push({
|
|
2083
|
+
path,
|
|
2084
|
+
leftBytes: left,
|
|
2085
|
+
rightBytes: right,
|
|
2086
|
+
delta
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
deltas.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta) || comparePaths(x.path, y.path));
|
|
2090
|
+
return deltas.slice(0, top);
|
|
2091
|
+
}
|
|
2092
|
+
//#endregion
|
|
2093
|
+
//#region src/config/schema.ts
|
|
2094
|
+
const SIZE_HINT = "Bytes, or a size such as \"512k\", \"25MiB\", or \"1GB\".";
|
|
2095
|
+
const TIME_HINT = "An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD).";
|
|
2096
|
+
/** Single source of truth for config validation, docs, and `schema.json`. */
|
|
2097
|
+
const CONFIG_FIELDS = {
|
|
2098
|
+
exclude: {
|
|
2099
|
+
type: { kind: "strings" },
|
|
2100
|
+
description: "Gitignore-style patterns to skip, relative to the analyzed directory.",
|
|
2101
|
+
examples: [[
|
|
2102
|
+
"*.log",
|
|
2103
|
+
"coverage/",
|
|
2104
|
+
"docs/**/*.pdf"
|
|
2105
|
+
]]
|
|
2106
|
+
},
|
|
2107
|
+
defaultExcludes: {
|
|
2108
|
+
type: { kind: "boolean" },
|
|
2109
|
+
description: "Skip .git, .hg, .svn, and node_modules. Default: true."
|
|
2110
|
+
},
|
|
2111
|
+
gitignore: {
|
|
2112
|
+
type: { kind: "boolean" },
|
|
2113
|
+
description: "Honor .gitignore files. Default: false."
|
|
2114
|
+
},
|
|
2115
|
+
maxDepth: {
|
|
2116
|
+
type: {
|
|
2117
|
+
kind: "integer",
|
|
2118
|
+
min: 0
|
|
2119
|
+
},
|
|
2120
|
+
description: "Directory levels to descend; 0 scans only the top-level files. Default: unlimited."
|
|
2121
|
+
},
|
|
2122
|
+
followSymlinks: {
|
|
2123
|
+
type: { kind: "boolean" },
|
|
2124
|
+
description: "Follow symbolic links (cycles are detected). Default: false."
|
|
2125
|
+
},
|
|
2126
|
+
countHardlinks: {
|
|
2127
|
+
type: { kind: "boolean" },
|
|
2128
|
+
description: "Count every hard link separately instead of counting shared data once. Default: false."
|
|
2129
|
+
},
|
|
2130
|
+
minSize: {
|
|
2131
|
+
type: { kind: "size" },
|
|
2132
|
+
description: `Only include files at least this large. ${SIZE_HINT}`
|
|
2133
|
+
},
|
|
2134
|
+
maxSize: {
|
|
2135
|
+
type: { kind: "size" },
|
|
2136
|
+
description: `Only include files at most this large. ${SIZE_HINT}`
|
|
2137
|
+
},
|
|
2138
|
+
newerThan: {
|
|
2139
|
+
type: { kind: "time" },
|
|
2140
|
+
description: `Only include files modified after this point. ${TIME_HINT}`
|
|
2141
|
+
},
|
|
2142
|
+
olderThan: {
|
|
2143
|
+
type: { kind: "time" },
|
|
2144
|
+
description: `Only include files modified before this point. ${TIME_HINT}`
|
|
2145
|
+
},
|
|
2146
|
+
top: {
|
|
2147
|
+
type: {
|
|
2148
|
+
kind: "integer",
|
|
2149
|
+
min: 0
|
|
2150
|
+
},
|
|
2151
|
+
description: "Length of the largest files and folders lists; 0 hides them. Default: 10."
|
|
2152
|
+
},
|
|
2153
|
+
largeFiles: {
|
|
2154
|
+
type: {
|
|
2155
|
+
kind: "size",
|
|
2156
|
+
allowBoolean: true
|
|
2157
|
+
},
|
|
2158
|
+
description: `Report files at least this large; true uses 100 MiB. ${SIZE_HINT}`,
|
|
2159
|
+
examples: ["50MB"]
|
|
2160
|
+
},
|
|
2161
|
+
duplicates: {
|
|
2162
|
+
type: { kind: "boolean" },
|
|
2163
|
+
description: "Find files with identical contents."
|
|
2164
|
+
},
|
|
2165
|
+
minDuplicateSize: {
|
|
2166
|
+
type: { kind: "size" },
|
|
2167
|
+
description: `Ignore files smaller than this when looking for duplicates. ${SIZE_HINT}`
|
|
2168
|
+
},
|
|
2169
|
+
empty: {
|
|
2170
|
+
type: { kind: "boolean" },
|
|
2171
|
+
description: "Report empty files and empty folders."
|
|
2172
|
+
},
|
|
2173
|
+
stale: {
|
|
2174
|
+
type: {
|
|
2175
|
+
kind: "time",
|
|
2176
|
+
allowBoolean: true
|
|
2177
|
+
},
|
|
2178
|
+
description: `Report files not modified since this point; true uses one year. ${TIME_HINT}`,
|
|
2179
|
+
examples: ["2y"]
|
|
2180
|
+
},
|
|
2181
|
+
extensions: {
|
|
2182
|
+
type: { kind: "boolean" },
|
|
2183
|
+
description: "Show the extension breakdown."
|
|
2184
|
+
},
|
|
2185
|
+
tree: {
|
|
2186
|
+
type: { kind: "boolean" },
|
|
2187
|
+
description: "Show a size tree."
|
|
2188
|
+
},
|
|
2189
|
+
treeDepth: {
|
|
2190
|
+
type: {
|
|
2191
|
+
kind: "integer",
|
|
2192
|
+
min: 1
|
|
2193
|
+
},
|
|
2194
|
+
description: "Levels shown by the tree. Default: 3."
|
|
2195
|
+
},
|
|
2196
|
+
units: {
|
|
2197
|
+
type: {
|
|
2198
|
+
kind: "enum",
|
|
2199
|
+
values: ["iec", "si"]
|
|
2200
|
+
},
|
|
2201
|
+
description: "Size units: \"iec\" (KiB, MiB; powers of 1024) or \"si\" (kB, MB; powers of 1000)."
|
|
2202
|
+
},
|
|
2203
|
+
budgets: {
|
|
2204
|
+
type: {
|
|
2205
|
+
kind: "strings",
|
|
2206
|
+
item: (rule) => void parseBudget(rule)
|
|
2207
|
+
},
|
|
2208
|
+
description: "Rules that must hold, or the run exits with code 2. Metrics: size, disk, files, dirs, largest, large, duplicates, wasted, empty, stale, errors.",
|
|
2209
|
+
examples: [[
|
|
2210
|
+
"size<=500MB",
|
|
2211
|
+
"duplicates=0",
|
|
2212
|
+
"largest<50MB"
|
|
2213
|
+
]]
|
|
2214
|
+
}
|
|
2215
|
+
};
|
|
2216
|
+
const FIELDS = new Map(Object.entries(CONFIG_FIELDS));
|
|
2217
|
+
/** Keys from v1 and v2 config files, mapped to their v3 equivalents. */
|
|
2218
|
+
const LEGACY_KEYS = {
|
|
2219
|
+
excludePatterns: (value, config) => {
|
|
2220
|
+
config["exclude"] = value;
|
|
2221
|
+
return "exclude";
|
|
2222
|
+
},
|
|
2223
|
+
clearDefaultExclusions: (value, config) => {
|
|
2224
|
+
if (typeof value === "boolean") config["defaultExcludes"] = !value;
|
|
2225
|
+
else config["defaultExcludes"] = value;
|
|
2226
|
+
return "defaultExcludes";
|
|
2227
|
+
},
|
|
2228
|
+
largeSizeThresholdMB: (value, config) => {
|
|
2229
|
+
config["largeFiles"] = typeof value === "number" ? `${value}MiB` : value;
|
|
2230
|
+
return "largeFiles";
|
|
2231
|
+
},
|
|
2232
|
+
largeSizeThreshold: (value, config) => {
|
|
2233
|
+
config["largeFiles"] = value;
|
|
2234
|
+
return "largeFiles";
|
|
2235
|
+
},
|
|
2236
|
+
enableDuplicateDetection: (value, config) => {
|
|
2237
|
+
config["duplicates"] = value;
|
|
2238
|
+
return "duplicates";
|
|
2239
|
+
},
|
|
2240
|
+
topN: (value, config) => {
|
|
2241
|
+
config["top"] = value;
|
|
2242
|
+
return "top";
|
|
2243
|
+
},
|
|
2244
|
+
showEmptyFiles: (value, config) => {
|
|
2245
|
+
config["empty"] = value;
|
|
2246
|
+
return "empty";
|
|
2247
|
+
}
|
|
2248
|
+
};
|
|
2249
|
+
/** v1 keys with no v3 equivalent. */
|
|
2250
|
+
const REMOVED_KEYS = {
|
|
2251
|
+
enableProgressBar: "progress is shown automatically in interactive terminals",
|
|
2252
|
+
outputFormat: "use --format on the command line"
|
|
2253
|
+
};
|
|
2254
|
+
/** Validates parsed JSON against {@link CONFIG_FIELDS}, translating legacy keys. */
|
|
2255
|
+
function validateConfig(raw) {
|
|
2256
|
+
const warnings = [];
|
|
2257
|
+
const errors = [];
|
|
2258
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {
|
|
2259
|
+
config: {},
|
|
2260
|
+
warnings,
|
|
2261
|
+
errors: ["the file must contain a JSON object"]
|
|
2262
|
+
};
|
|
2263
|
+
const input = Object.fromEntries(Object.entries(raw));
|
|
2264
|
+
delete input["$schema"];
|
|
2265
|
+
if (input["maxDepth"] === -1) delete input["maxDepth"];
|
|
2266
|
+
for (const [key, translate] of Object.entries(LEGACY_KEYS)) {
|
|
2267
|
+
if (!(key in input)) continue;
|
|
2268
|
+
const value = input[key];
|
|
2269
|
+
delete input[key];
|
|
2270
|
+
const replacement = translate(value, input);
|
|
2271
|
+
warnings.push(`"${key}" is deprecated; use "${replacement}" instead`);
|
|
2272
|
+
}
|
|
2273
|
+
for (const [key, reason] of Object.entries(REMOVED_KEYS)) {
|
|
2274
|
+
if (!(key in input)) continue;
|
|
2275
|
+
delete input[key];
|
|
2276
|
+
warnings.push(`"${key}" is no longer supported (${reason}); ignoring it`);
|
|
2277
|
+
}
|
|
2278
|
+
const config = {};
|
|
2279
|
+
for (const [key, value] of Object.entries(input)) {
|
|
2280
|
+
const field = FIELDS.get(key);
|
|
2281
|
+
if (!field) {
|
|
2282
|
+
warnings.push(`unknown key "${key}" ignored`);
|
|
2283
|
+
continue;
|
|
2284
|
+
}
|
|
2285
|
+
const problem = checkValue(field.type, value);
|
|
2286
|
+
if (problem) errors.push(`"${key}" ${problem}`);
|
|
2287
|
+
else config[key] = value;
|
|
2288
|
+
}
|
|
2289
|
+
return {
|
|
2290
|
+
config,
|
|
2291
|
+
warnings,
|
|
2292
|
+
errors
|
|
2293
|
+
};
|
|
2294
|
+
}
|
|
2295
|
+
function checkValue(type, value) {
|
|
2296
|
+
const got = `(got ${JSON.stringify(value)})`;
|
|
2297
|
+
switch (type.kind) {
|
|
2298
|
+
case "boolean": return typeof value === "boolean" ? null : `must be true or false ${got}`;
|
|
2299
|
+
case "integer": return typeof value === "number" && Number.isInteger(value) && value >= type.min ? null : `must be an integer of at least ${type.min} ${got}`;
|
|
2300
|
+
case "size":
|
|
2301
|
+
if (type.allowBoolean && typeof value === "boolean") return null;
|
|
2302
|
+
if (typeof value !== "string" && typeof value !== "number") return `must be a size such as "25MiB" ${got}`;
|
|
2303
|
+
try {
|
|
2304
|
+
parseSize(value);
|
|
2305
|
+
return null;
|
|
2306
|
+
} catch (error) {
|
|
2307
|
+
return `is invalid: ${errorMessage(error)}`;
|
|
2308
|
+
}
|
|
2309
|
+
case "time":
|
|
2310
|
+
if (type.allowBoolean && typeof value === "boolean") return null;
|
|
2311
|
+
if (typeof value !== "string") return `must be an age or a date such as "30d" ${got}`;
|
|
2312
|
+
try {
|
|
2313
|
+
parsePointInTime(value);
|
|
2314
|
+
return null;
|
|
2315
|
+
} catch (error) {
|
|
2316
|
+
return `is invalid: ${errorMessage(error)}`;
|
|
2317
|
+
}
|
|
2318
|
+
case "strings":
|
|
2319
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return `must be an array of strings ${got}`;
|
|
2320
|
+
if (type.item) for (const item of value) try {
|
|
2321
|
+
type.item(item);
|
|
2322
|
+
} catch (error) {
|
|
2323
|
+
return `is invalid: ${errorMessage(error)}`;
|
|
2324
|
+
}
|
|
2325
|
+
return null;
|
|
2326
|
+
case "enum": return typeof value === "string" && type.values.includes(value) ? null : `must be one of ${type.values.map((v) => `"${v}"`).join(", ")} ${got}`;
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
/** Builds the JSON Schema published as `dir-analysis-tool/schema.json`. */
|
|
2330
|
+
function buildJsonSchema() {
|
|
2331
|
+
const properties = { $schema: {
|
|
2332
|
+
type: "string",
|
|
2333
|
+
description: "JSON Schema reference for editor support."
|
|
2334
|
+
} };
|
|
2335
|
+
for (const [key, field] of Object.entries(CONFIG_FIELDS)) properties[key] = {
|
|
2336
|
+
...jsonType(field.type),
|
|
2337
|
+
description: field.description,
|
|
2338
|
+
...field.examples ? { examples: field.examples } : {}
|
|
2339
|
+
};
|
|
2340
|
+
return {
|
|
2341
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
2342
|
+
$id: "https://unpkg.com/dir-analysis-tool/schema.json",
|
|
2343
|
+
title: "dir-analysis-tool configuration",
|
|
2344
|
+
description: "Configuration for dir-analysis-tool (dat). Place it in .dir-analyzer.json or dir-analyzer.config.json.",
|
|
2345
|
+
type: "object",
|
|
2346
|
+
additionalProperties: false,
|
|
2347
|
+
properties
|
|
2348
|
+
};
|
|
2349
|
+
}
|
|
2350
|
+
function jsonType(type) {
|
|
2351
|
+
const size = { anyOf: [{
|
|
2352
|
+
type: "integer",
|
|
2353
|
+
minimum: 0
|
|
2354
|
+
}, {
|
|
2355
|
+
type: "string",
|
|
2356
|
+
pattern: "^\\s*(\\d+(\\.\\d+)?|\\.\\d+)\\s*([kKmMgGtTpP]([iI]?[bB])?|[bB])?\\s*$"
|
|
2357
|
+
}] };
|
|
2358
|
+
switch (type.kind) {
|
|
2359
|
+
case "boolean": return { type: "boolean" };
|
|
2360
|
+
case "integer": return {
|
|
2361
|
+
type: "integer",
|
|
2362
|
+
minimum: type.min
|
|
2363
|
+
};
|
|
2364
|
+
case "size": return type.allowBoolean ? { anyOf: [{ type: "boolean" }, ...size.anyOf] } : size;
|
|
2365
|
+
case "time": return type.allowBoolean ? { anyOf: [{ type: "boolean" }, { type: "string" }] } : { type: "string" };
|
|
2366
|
+
case "strings": return {
|
|
2367
|
+
type: "array",
|
|
2368
|
+
items: { type: "string" }
|
|
2369
|
+
};
|
|
2370
|
+
case "enum": return { enum: [...type.values] };
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
//#endregion
|
|
2374
|
+
//#region src/config/load.ts
|
|
2375
|
+
/** File names recognized during discovery, in priority order. */
|
|
2376
|
+
const CONFIG_FILE_NAMES = [".dir-analyzer.json", "dir-analyzer.config.json"];
|
|
2377
|
+
/** Finds the nearest config file at or above `startDir`. */
|
|
2378
|
+
function findConfigFile(startDir) {
|
|
2379
|
+
let current = resolve(startDir);
|
|
2380
|
+
for (;;) {
|
|
2381
|
+
for (const name of CONFIG_FILE_NAMES) {
|
|
2382
|
+
const candidate = join(current, name);
|
|
2383
|
+
if (existsSync(candidate)) return candidate;
|
|
2384
|
+
}
|
|
2385
|
+
const parent = dirname(current);
|
|
2386
|
+
if (parent === current) return null;
|
|
2387
|
+
current = parent;
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* Loads configuration from an explicit file, or discovers one by walking up
|
|
2392
|
+
* from `searchFrom`. Invalid files are an error rather than silently ignored.
|
|
2393
|
+
*/
|
|
2394
|
+
async function loadConfig(options) {
|
|
2395
|
+
const path = options.file ? resolve(options.file) : findConfigFile(options.searchFrom);
|
|
2396
|
+
if (!path) return {
|
|
2397
|
+
config: {},
|
|
2398
|
+
path: null,
|
|
2399
|
+
warnings: []
|
|
2400
|
+
};
|
|
2401
|
+
let text;
|
|
2402
|
+
try {
|
|
2403
|
+
text = await readFile(path, "utf8");
|
|
2404
|
+
} catch (error) {
|
|
2405
|
+
throw new DatError(errorCode(error) === "ENOENT" ? `Config file not found: ${path}` : `Cannot read config ${path}: ${errorMessage(error)}`);
|
|
2406
|
+
}
|
|
2407
|
+
let raw;
|
|
2408
|
+
try {
|
|
2409
|
+
raw = JSON.parse(text);
|
|
2410
|
+
} catch (error) {
|
|
2411
|
+
throw new DatError(`Invalid JSON in ${path}: ${errorMessage(error)}`);
|
|
2412
|
+
}
|
|
2413
|
+
const { config, warnings, errors } = validateConfig(raw);
|
|
2414
|
+
if (errors.length > 0) throw new DatError(`Invalid config ${path}:\n - ${errors.join("\n - ")}`, { hint: "Run \"dat init\" to generate a valid config, or see https://github.com/KhaledSaeed18/dir-analysis-tool#configuration" });
|
|
2415
|
+
return {
|
|
2416
|
+
config,
|
|
2417
|
+
path,
|
|
2418
|
+
warnings: warnings.map((w) => `${path}: ${w}`)
|
|
2419
|
+
};
|
|
2420
|
+
}
|
|
2421
|
+
//#endregion
|
|
2422
|
+
//#region src/format/style.ts
|
|
2423
|
+
function supportsColor(stream, env = process.env) {
|
|
2424
|
+
const force = env["FORCE_COLOR"];
|
|
2425
|
+
if (force !== void 0) return force !== "0" && force !== "false";
|
|
2426
|
+
if (env["NO_COLOR"]) return false;
|
|
2427
|
+
if (env["TERM"] === "dumb") return false;
|
|
2428
|
+
return stream.isTTY === true;
|
|
2429
|
+
}
|
|
2430
|
+
function wrap(enabled, open, close) {
|
|
2431
|
+
if (!enabled) return (text) => text;
|
|
2432
|
+
return (text) => `\u001B[${open}m${text}\u001B[${close}m`;
|
|
2433
|
+
}
|
|
2434
|
+
function createStyle(enabled) {
|
|
2435
|
+
return {
|
|
2436
|
+
enabled,
|
|
2437
|
+
bold: wrap(enabled, 1, 22),
|
|
2438
|
+
dim: wrap(enabled, 2, 22),
|
|
2439
|
+
red: wrap(enabled, 31, 39),
|
|
2440
|
+
green: wrap(enabled, 32, 39),
|
|
2441
|
+
yellow: wrap(enabled, 33, 39),
|
|
2442
|
+
blue: wrap(enabled, 34, 39),
|
|
2443
|
+
magenta: wrap(enabled, 35, 39),
|
|
2444
|
+
cyan: wrap(enabled, 36, 39)
|
|
2445
|
+
};
|
|
2446
|
+
}
|
|
2447
|
+
const ANSI_PATTERN = /\u001B\[[0-9;]*m/g;
|
|
2448
|
+
function stripAnsi(text) {
|
|
2449
|
+
return text.replace(ANSI_PATTERN, "");
|
|
2450
|
+
}
|
|
2451
|
+
//#endregion
|
|
2452
|
+
//#region src/format/text.ts
|
|
2453
|
+
/** Visible width of a string, ignoring ANSI escapes. */
|
|
2454
|
+
function visibleWidth(text) {
|
|
2455
|
+
return stripAnsi(text).length;
|
|
2456
|
+
}
|
|
2457
|
+
function padEndVisible(text, width) {
|
|
2458
|
+
return text + " ".repeat(Math.max(0, width - visibleWidth(text)));
|
|
2459
|
+
}
|
|
2460
|
+
function padStartVisible(text, width) {
|
|
2461
|
+
return " ".repeat(Math.max(0, width - visibleWidth(text))) + text;
|
|
2462
|
+
}
|
|
2463
|
+
/**
|
|
2464
|
+
* Shortens text to `max` characters by replacing its middle with an ellipsis.
|
|
2465
|
+
* Paths keep their most informative parts: the start and the file name.
|
|
2466
|
+
*/
|
|
2467
|
+
function truncateMiddle(text, max) {
|
|
2468
|
+
if (text.length <= max) return text;
|
|
2469
|
+
if (max <= 1) return "…".slice(0, max);
|
|
2470
|
+
const keepEnd = Math.ceil((max - 1) * .6);
|
|
2471
|
+
const keepStart = max - 1 - keepEnd;
|
|
2472
|
+
return `${text.slice(0, keepStart)}…${text.slice(text.length - keepEnd)}`;
|
|
2473
|
+
}
|
|
2474
|
+
const PARTIAL_BLOCKS = [
|
|
2475
|
+
"",
|
|
2476
|
+
"▏",
|
|
2477
|
+
"▎",
|
|
2478
|
+
"▍",
|
|
2479
|
+
"▌",
|
|
2480
|
+
"▋",
|
|
2481
|
+
"▊",
|
|
2482
|
+
"▉"
|
|
2483
|
+
];
|
|
2484
|
+
/** Renders a horizontal bar for `fraction` (0..1) using eighth-block characters. */
|
|
2485
|
+
function bar(fraction, width) {
|
|
2486
|
+
const eighths = Math.round(Math.min(1, Math.max(0, Number.isFinite(fraction) ? fraction : 0)) * width * 8);
|
|
2487
|
+
const full = Math.floor(eighths / 8);
|
|
2488
|
+
const partial = PARTIAL_BLOCKS[eighths % 8];
|
|
2489
|
+
const used = full + (partial ? 1 : 0);
|
|
2490
|
+
return "█".repeat(full) + partial + " ".repeat(Math.max(0, width - used));
|
|
2491
|
+
}
|
|
2492
|
+
function formatCount(value) {
|
|
2493
|
+
return value.toLocaleString("en-US");
|
|
2494
|
+
}
|
|
2495
|
+
function formatPercent(part, total) {
|
|
2496
|
+
if (total <= 0) return "0%";
|
|
2497
|
+
const pct = part / total * 100;
|
|
2498
|
+
if (pct > 0 && pct < 1) return "<1%";
|
|
2499
|
+
return `${Math.round(pct)}%`;
|
|
2500
|
+
}
|
|
2501
|
+
function plural(count, singular, pluralForm = `${singular}s`) {
|
|
2502
|
+
return `${formatCount(count)} ${count === 1 ? singular : pluralForm}`;
|
|
2503
|
+
}
|
|
2504
|
+
//#endregion
|
|
2505
|
+
//#region src/reporters/pretty.ts
|
|
2506
|
+
const CATEGORY_LABELS = {
|
|
2507
|
+
code: "Code",
|
|
2508
|
+
documents: "Documents",
|
|
2509
|
+
images: "Images",
|
|
2510
|
+
videos: "Videos",
|
|
2511
|
+
audio: "Audio",
|
|
2512
|
+
archives: "Archives",
|
|
2513
|
+
fonts: "Fonts",
|
|
2514
|
+
data: "Data",
|
|
2515
|
+
other: "Other"
|
|
2516
|
+
};
|
|
2517
|
+
const SIZE_WIDTH = 10;
|
|
2518
|
+
const BAR_WIDTH = 16;
|
|
2519
|
+
var Renderer = class {
|
|
2520
|
+
lines = [];
|
|
2521
|
+
s;
|
|
2522
|
+
units;
|
|
2523
|
+
width;
|
|
2524
|
+
limit;
|
|
2525
|
+
constructor(options) {
|
|
2526
|
+
this.s = options.style ?? createStyle(false);
|
|
2527
|
+
this.units = options.units ?? "iec";
|
|
2528
|
+
this.width = Math.max(60, options.width ?? 100);
|
|
2529
|
+
this.limit = Math.max(1, options.limit ?? 10);
|
|
2530
|
+
}
|
|
2531
|
+
bytes(value) {
|
|
2532
|
+
return formatBytes(value, this.units);
|
|
2533
|
+
}
|
|
2534
|
+
size(value) {
|
|
2535
|
+
return this.s.cyan(padStartVisible(this.bytes(value), SIZE_WIDTH));
|
|
2536
|
+
}
|
|
2537
|
+
heading(text, detail) {
|
|
2538
|
+
this.lines.push("");
|
|
2539
|
+
this.lines.push(` ${this.s.bold(text)}${detail ? ` ${this.s.dim(detail)}` : ""}`);
|
|
2540
|
+
}
|
|
2541
|
+
line(text = "") {
|
|
2542
|
+
this.lines.push(text);
|
|
2543
|
+
}
|
|
2544
|
+
/** Space left for a path after `used` columns. */
|
|
2545
|
+
room(used) {
|
|
2546
|
+
return Math.max(20, this.width - used);
|
|
2547
|
+
}
|
|
2548
|
+
more(shown, total, noun = "more") {
|
|
2549
|
+
if (total > shown) this.line(` ${this.s.dim(`… ${formatCount(total - shown)} ${noun}`)}`);
|
|
2550
|
+
}
|
|
2551
|
+
fileList(items, total, extra) {
|
|
2552
|
+
const shown = items.slice(0, this.limit);
|
|
2553
|
+
for (const item of shown) {
|
|
2554
|
+
const suffix = extra ? ` ${this.s.dim(extra(item))}` : "";
|
|
2555
|
+
const used = 15 + (extra ? extra(item).length + 2 : 0);
|
|
2556
|
+
this.line(` ${this.size(item.bytes)} ${truncateMiddle(item.path, this.room(used))}${suffix}`);
|
|
2557
|
+
}
|
|
2558
|
+
this.more(shown.length, total);
|
|
2559
|
+
}
|
|
2560
|
+
};
|
|
2561
|
+
/** Renders an analysis for a terminal. Colors only when `style` enables them. */
|
|
2562
|
+
function renderAnalysis(result, options = {}) {
|
|
2563
|
+
const r = new Renderer(options);
|
|
2564
|
+
const { s } = r;
|
|
2565
|
+
const now = options.now ?? Date.now();
|
|
2566
|
+
const sum = result.summary;
|
|
2567
|
+
r.line(` ${s.bold(s.blue("dat"))} ${s.bold(truncateMiddle(result.root, r.room(20)))} ${s.dim(formatElapsed(result.durationMs))}`);
|
|
2568
|
+
r.line("");
|
|
2569
|
+
const row = (label, value) => r.line(` ${padEndVisible(s.dim(label), 10)}${value}`);
|
|
2570
|
+
const disk = sum.diskBytes !== sum.bytes ? ` ${s.dim(`(${r.bytes(sum.diskBytes)} on disk)`)}` : "";
|
|
2571
|
+
row("Size", `${s.bold(s.cyan(r.bytes(sum.bytes)))}${disk}`);
|
|
2572
|
+
row("Files", formatCount(sum.files));
|
|
2573
|
+
row("Folders", formatCount(sum.directories));
|
|
2574
|
+
if (sum.symlinks > 0) row("Symlinks", `${formatCount(sum.symlinks)} ${s.dim(result.settings.followSymlinks ? "(followed)" : "(not followed)")}`);
|
|
2575
|
+
if (sum.hardlinks > 0) row("Hardlinks", `${formatCount(sum.hardlinks)} ${s.dim("extra links counted once")}`);
|
|
2576
|
+
const skipped = [];
|
|
2577
|
+
if (sum.excluded > 0) skipped.push(`${formatCount(sum.excluded)} excluded`);
|
|
2578
|
+
if (sum.filtered > 0) skipped.push(`${formatCount(sum.filtered)} filtered`);
|
|
2579
|
+
if (sum.errors > 0) skipped.push(s.yellow(`${formatCount(sum.errors)} unreadable`));
|
|
2580
|
+
if (skipped.length > 0) {
|
|
2581
|
+
const hint = sum.excluded > 0 && result.settings.defaultExcludes ? s.dim(" (--all includes .git and node_modules)") : "";
|
|
2582
|
+
row("Skipped", skipped.join(s.dim(" · ")) + hint);
|
|
2583
|
+
}
|
|
2584
|
+
if (options.types !== false && sum.files > 0) renderTypes(r, result);
|
|
2585
|
+
if (options.extensions && result.extensions.length > 0) renderExtensions(r, result);
|
|
2586
|
+
if (result.largestDirectories.length > 0) {
|
|
2587
|
+
r.heading("Largest folders");
|
|
2588
|
+
for (const dir of result.largestDirectories.slice(0, r.limit)) {
|
|
2589
|
+
const files = plural(dir.files, "file");
|
|
2590
|
+
r.line(` ${r.size(dir.bytes)} ${truncateMiddle(`${dir.path}/`, r.room(17 + files.length))} ${s.dim(files)}`);
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
if (result.largestFiles.length > 0) {
|
|
2594
|
+
r.heading("Largest files");
|
|
2595
|
+
r.fileList(result.largestFiles, result.largestFiles.length);
|
|
2596
|
+
}
|
|
2597
|
+
if (result.largeFiles) {
|
|
2598
|
+
const lf = result.largeFiles;
|
|
2599
|
+
r.heading(`Large files ≥ ${r.bytes(lf.threshold)}`, lf.count > 0 ? `${plural(lf.count, "file")} · ${r.bytes(lf.bytes)}` : "none");
|
|
2600
|
+
r.fileList(lf.items, lf.count);
|
|
2601
|
+
}
|
|
2602
|
+
if (result.duplicates) renderDuplicates(r, result.duplicates);
|
|
2603
|
+
if (result.emptyFiles) {
|
|
2604
|
+
r.heading("Empty files", result.emptyFiles.count > 0 ? plural(result.emptyFiles.count, "file") : "none");
|
|
2605
|
+
for (const file of result.emptyFiles.items.slice(0, r.limit)) r.line(` ${truncateMiddle(file.path, r.room(3))}`);
|
|
2606
|
+
r.more(Math.min(r.limit, result.emptyFiles.items.length), result.emptyFiles.count);
|
|
2607
|
+
}
|
|
2608
|
+
if (result.emptyDirectories) {
|
|
2609
|
+
const ed = result.emptyDirectories;
|
|
2610
|
+
r.heading("Empty folders", ed.count > 0 ? plural(ed.count, "folder") : "none");
|
|
2611
|
+
for (const dir of ed.items.slice(0, r.limit)) r.line(` ${truncateMiddle(`${dir}/`, r.room(3))}`);
|
|
2612
|
+
r.more(Math.min(r.limit, ed.items.length), ed.count);
|
|
2613
|
+
}
|
|
2614
|
+
if (result.staleFiles) {
|
|
2615
|
+
const sf = result.staleFiles;
|
|
2616
|
+
r.heading(`Not modified since ${sf.modifiedBefore.slice(0, 10)}`, sf.count > 0 ? `${plural(sf.count, "file")} · ${r.bytes(sf.bytes)}` : "none");
|
|
2617
|
+
r.fileList(sf.items, sf.count, (f) => `${formatAge(Date.parse(f.modified), now)} ago`);
|
|
2618
|
+
}
|
|
2619
|
+
if (result.tree) {
|
|
2620
|
+
r.heading("Tree");
|
|
2621
|
+
renderTree(r, result.tree);
|
|
2622
|
+
}
|
|
2623
|
+
if (result.errors.length > 0) {
|
|
2624
|
+
r.heading("Unreadable", plural(sum.errors, "path"));
|
|
2625
|
+
const shown = result.errors.slice(0, 5);
|
|
2626
|
+
for (const error of shown) {
|
|
2627
|
+
const used = 13 + error.message.length;
|
|
2628
|
+
r.line(` ${s.yellow(padEndVisible(error.code, 8))}${truncateMiddle(error.path, r.room(used))} ${s.dim(error.message)}`);
|
|
2629
|
+
}
|
|
2630
|
+
r.more(shown.length, sum.errors);
|
|
2631
|
+
}
|
|
2632
|
+
if (result.budgets && result.budgets.length > 0) {
|
|
2633
|
+
const failed = result.budgets.filter((b) => !b.passed).length;
|
|
2634
|
+
r.heading("Budgets", failed > 0 ? s.red(`${failed} failed`) : s.green("all passed"));
|
|
2635
|
+
for (const budget of result.budgets) {
|
|
2636
|
+
const actual = [
|
|
2637
|
+
"size",
|
|
2638
|
+
"disk",
|
|
2639
|
+
"largest",
|
|
2640
|
+
"wasted"
|
|
2641
|
+
].includes(budget.metric) ? r.bytes(budget.actual) : formatCount(budget.actual);
|
|
2642
|
+
const mark = budget.passed ? s.green("✔") : s.red("✘");
|
|
2643
|
+
r.line(` ${mark} ${padEndVisible(budget.rule, 24)} ${s.dim("actual")} ${budget.passed ? actual : s.red(actual)}`);
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
r.line("");
|
|
2647
|
+
return r.lines.join("\n");
|
|
2648
|
+
}
|
|
2649
|
+
function renderTypes(r, result) {
|
|
2650
|
+
const { s } = r;
|
|
2651
|
+
const total = result.summary.bytes;
|
|
2652
|
+
const rows = CATEGORIES.filter((c) => result.types[c].files > 0).sort((a, b) => result.types[b].bytes - result.types[a].bytes || result.types[b].files - result.types[a].files);
|
|
2653
|
+
r.heading("File types");
|
|
2654
|
+
for (const category of rows) {
|
|
2655
|
+
const stat = result.types[category];
|
|
2656
|
+
r.line(` ${padEndVisible(CATEGORY_LABELS[category], 10)} ${s.blue(bar(total > 0 ? stat.bytes / total : 0, BAR_WIDTH))} ${r.size(stat.bytes)} ${padStartVisible(formatPercent(stat.bytes, total), 5)} ${s.dim(plural(stat.files, "file"))}`);
|
|
2657
|
+
}
|
|
2658
|
+
}
|
|
2659
|
+
function renderExtensions(r, result) {
|
|
2660
|
+
const { s } = r;
|
|
2661
|
+
const total = result.summary.bytes;
|
|
2662
|
+
r.heading("Extensions", plural(result.extensions.length, "distinct extension"));
|
|
2663
|
+
const shown = result.extensions.slice(0, r.limit);
|
|
2664
|
+
for (const ext of shown) r.line(` ${padEndVisible(ext.extension || s.dim("(none)"), 12)} ${r.size(ext.bytes)} ${padStartVisible(formatPercent(ext.bytes, total), 5)} ${s.dim(plural(ext.files, "file"))}`);
|
|
2665
|
+
r.more(shown.length, result.extensions.length);
|
|
2666
|
+
}
|
|
2667
|
+
function renderDuplicates(r, duplicates) {
|
|
2668
|
+
const { s } = r;
|
|
2669
|
+
if (duplicates.count === 0) {
|
|
2670
|
+
r.heading("Duplicates", "none found");
|
|
2671
|
+
return;
|
|
2672
|
+
}
|
|
2673
|
+
r.heading("Duplicates", `${plural(duplicates.count, "group")} · ${plural(duplicates.files, "file")} · ${r.bytes(duplicates.wastedBytes)} reclaimable`);
|
|
2674
|
+
const shown = duplicates.items.slice(0, r.limit);
|
|
2675
|
+
for (const group of shown) {
|
|
2676
|
+
r.line(` ${r.size(group.wastedBytes)} ${s.dim(`${group.files.length} × ${r.bytes(group.bytes)}`)}`);
|
|
2677
|
+
const files = group.files.slice(0, 5);
|
|
2678
|
+
for (const file of files) r.line(` ${" ".repeat(SIZE_WIDTH)} ${truncateMiddle(file, r.room(15))}`);
|
|
2679
|
+
if (group.files.length > files.length) r.line(` ${" ".repeat(SIZE_WIDTH)} ${s.dim(`… ${group.files.length - files.length} more copies`)}`);
|
|
2680
|
+
}
|
|
2681
|
+
r.more(shown.length, duplicates.count, "more groups");
|
|
2682
|
+
}
|
|
2683
|
+
function renderTree(r, root) {
|
|
2684
|
+
const { s } = r;
|
|
2685
|
+
const walk = (node, prefix, isLast, isRoot) => {
|
|
2686
|
+
const connector = isRoot ? "" : isLast ? "└─ " : "├─ ";
|
|
2687
|
+
const used = 15 + prefix.length + connector.length;
|
|
2688
|
+
const name = truncateMiddle(node.type === "directory" && !isRoot ? `${node.name}/` : node.name, Math.max(12, r.width - used));
|
|
2689
|
+
r.line(` ${r.size(node.bytes)} ${s.dim(prefix + connector)}${node.type === "directory" ? s.bold(name) : name}`);
|
|
2690
|
+
const childPrefix = isRoot ? "" : prefix + (isLast ? " " : "│ ");
|
|
2691
|
+
const children = node.children ?? [];
|
|
2692
|
+
children.forEach((child, i) => walk(child, childPrefix, i === children.length - 1 && !node.omitted, false));
|
|
2693
|
+
if (node.omitted) r.line(` ${r.size(node.omitted.bytes)} ${s.dim(`${childPrefix}└─ … ${plural(node.omitted.entries, "more entry", "more entries")}`)}`);
|
|
2694
|
+
};
|
|
2695
|
+
walk(root, "", true, true);
|
|
2696
|
+
}
|
|
2697
|
+
/** Renders a directory comparison for a terminal. */
|
|
2698
|
+
function renderComparison(result, options = {}) {
|
|
2699
|
+
const r = new Renderer(options);
|
|
2700
|
+
const { s } = r;
|
|
2701
|
+
const signed = (n) => n > 0 ? s.green(`+${r.bytes(n)}`) : n < 0 ? s.red(r.bytes(n)) : s.dim("±0");
|
|
2702
|
+
const signedCount = (n) => n > 0 ? s.green(`+${formatCount(n)}`) : n < 0 ? s.red(`-${formatCount(-n)}`) : s.dim("±0");
|
|
2703
|
+
const pct = (left, right) => {
|
|
2704
|
+
if (left === 0) return "";
|
|
2705
|
+
const value = (right - left) / left * 100;
|
|
2706
|
+
return s.dim(` (${value > 0 ? "+" : ""}${Math.abs(value) < .1 && value !== 0 ? value.toFixed(2) : value.toFixed(1)}%)`);
|
|
2707
|
+
};
|
|
2708
|
+
r.line(` ${s.bold(s.blue("dat compare"))} ${s.dim(formatElapsed(result.durationMs))}`);
|
|
2709
|
+
r.line("");
|
|
2710
|
+
r.line(` ${s.dim("left ")} ${truncateMiddle(result.left.root, r.room(12))}`);
|
|
2711
|
+
r.line(` ${s.dim("right")} ${truncateMiddle(result.right.root, r.room(12))}`);
|
|
2712
|
+
const col = (text) => padStartVisible(text, 12);
|
|
2713
|
+
r.heading("Overview");
|
|
2714
|
+
r.line(` ${padEndVisible("", 10)}${col(s.dim("left"))}${col(s.dim("right"))} ${s.dim("change")}`);
|
|
2715
|
+
const L = result.left.summary;
|
|
2716
|
+
const R = result.right.summary;
|
|
2717
|
+
r.line(` ${padEndVisible("Size", 10)}${col(r.bytes(L.bytes))}${col(r.bytes(R.bytes))} ${signed(result.delta.bytes)}${pct(L.bytes, R.bytes)}`);
|
|
2718
|
+
r.line(` ${padEndVisible("On disk", 10)}${col(r.bytes(L.diskBytes))}${col(r.bytes(R.diskBytes))} ${signed(result.delta.diskBytes)}`);
|
|
2719
|
+
r.line(` ${padEndVisible("Files", 10)}${col(formatCount(L.files))}${col(formatCount(R.files))} ${signedCount(result.delta.files)}`);
|
|
2720
|
+
r.line(` ${padEndVisible("Folders", 10)}${col(formatCount(L.directories))}${col(formatCount(R.directories))} ${signedCount(result.delta.directories)}`);
|
|
2721
|
+
const changedTypes = CATEGORIES.filter((c) => result.left.types[c].bytes !== result.right.types[c].bytes || result.left.types[c].files !== result.right.types[c].files);
|
|
2722
|
+
if (changedTypes.length > 0) {
|
|
2723
|
+
r.heading("By type");
|
|
2724
|
+
for (const c of changedTypes) {
|
|
2725
|
+
const l = result.left.types[c];
|
|
2726
|
+
const rt = result.right.types[c];
|
|
2727
|
+
r.line(` ${padEndVisible(CATEGORY_LABELS[c], 10)}${col(r.bytes(l.bytes))}${col(r.bytes(rt.bytes))} ${signed(rt.bytes - l.bytes)} ${s.dim(`${signedCount(rt.files - l.files)} files`)}`);
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
const fileSection = (title, list, mark) => {
|
|
2731
|
+
if (list.count === 0) return;
|
|
2732
|
+
r.heading(title, `${plural(list.count, "file")} · ${r.bytes(list.bytes)}`);
|
|
2733
|
+
for (const f of list.items.slice(0, r.limit)) r.line(` ${mark} ${r.size(f.bytes)} ${truncateMiddle(f.path, r.room(17))}`);
|
|
2734
|
+
r.more(Math.min(r.limit, list.items.length), list.count);
|
|
2735
|
+
};
|
|
2736
|
+
fileSection("Added", result.added, s.green("+"));
|
|
2737
|
+
fileSection("Removed", result.removed, s.red("-"));
|
|
2738
|
+
if (result.changed.count > 0) {
|
|
2739
|
+
r.heading("Changed", `${plural(result.changed.count, "file")} · ${result.changed.delta > 0 ? "+" : ""}${formatBytes(result.changed.delta, r.units)} net`);
|
|
2740
|
+
for (const c of result.changed.items.slice(0, r.limit)) {
|
|
2741
|
+
const detail = c.delta === 0 ? "content" : `${r.bytes(c.leftBytes)} → ${r.bytes(c.rightBytes)}`;
|
|
2742
|
+
r.line(` ${s.yellow("~")} ${padStartVisible(signed(c.delta), SIZE_WIDTH)} ${truncateMiddle(c.path, r.room(19 + detail.length))} ${s.dim(detail)}`);
|
|
2743
|
+
}
|
|
2744
|
+
r.more(Math.min(r.limit, result.changed.items.length), result.changed.count);
|
|
2745
|
+
}
|
|
2746
|
+
if (result.directories.length > 0) {
|
|
2747
|
+
r.heading("Folders that changed most");
|
|
2748
|
+
for (const d of result.directories.slice(0, r.limit)) r.line(` ${padStartVisible(signed(d.delta), 12)} ${truncateMiddle(`${d.path}/`, r.room(17))}`);
|
|
2749
|
+
}
|
|
2750
|
+
r.line("");
|
|
2751
|
+
const identical = result.added.count + result.removed.count + result.changed.count === 0;
|
|
2752
|
+
r.line(` ${identical ? s.green("No differences.") : s.dim(`${plural(result.unchanged, "file")} unchanged`)} ${s.dim(`(compared by ${result.mode === "content" ? "size and content" : "size"})`)}`);
|
|
2753
|
+
r.line("");
|
|
2754
|
+
return r.lines.join("\n");
|
|
2755
|
+
}
|
|
2756
|
+
//#endregion
|
|
2757
|
+
//#region src/reporters/markdown.ts
|
|
2758
|
+
/** Inline code that is safe inside a GitHub table cell. */
|
|
2759
|
+
function mdCode(text) {
|
|
2760
|
+
const fence = text.includes("`") ? "``" : "`";
|
|
2761
|
+
return `${fence}${(fence === "``" ? ` ${text} ` : text).replaceAll("|", "\\|")}${fence}`;
|
|
2762
|
+
}
|
|
2763
|
+
function table(header, rows, align) {
|
|
2764
|
+
const sep = header.map((_, i) => align?.[i] === "r" ? "---:" : "---");
|
|
2765
|
+
return [
|
|
2766
|
+
`| ${header.join(" | ")} |`,
|
|
2767
|
+
`| ${sep.join(" | ")} |`,
|
|
2768
|
+
...rows.map((r) => `| ${r.join(" | ")} |`)
|
|
2769
|
+
];
|
|
2770
|
+
}
|
|
2771
|
+
function capitalize(text) {
|
|
2772
|
+
return text.charAt(0).toUpperCase() + text.slice(1);
|
|
2773
|
+
}
|
|
2774
|
+
/** Renders an analysis as GitHub-flavored Markdown, suited to PR comments and job summaries. */
|
|
2775
|
+
function renderAnalysisMarkdown(result, options = {}) {
|
|
2776
|
+
const units = options.units ?? "iec";
|
|
2777
|
+
const limit = options.limit ?? 10;
|
|
2778
|
+
const b = (n) => formatBytes(n, units);
|
|
2779
|
+
const sum = result.summary;
|
|
2780
|
+
const out = [];
|
|
2781
|
+
const more = (shown, total) => {
|
|
2782
|
+
if (total > shown) out.push("", `<sub>…and ${formatCount(total - shown)} more</sub>`);
|
|
2783
|
+
};
|
|
2784
|
+
const fileTable = (items, total) => {
|
|
2785
|
+
const shown = items.slice(0, limit);
|
|
2786
|
+
out.push(...table(["Size", "Path"], shown.map((f) => [b(f.bytes), mdCode(f.path)]), ["r", "l"]));
|
|
2787
|
+
more(shown.length, total);
|
|
2788
|
+
};
|
|
2789
|
+
out.push(`## Directory analysis: ${mdCode(result.root)}`, "");
|
|
2790
|
+
out.push(...table(["Metric", "Value"], [
|
|
2791
|
+
["Size", `**${b(sum.bytes)}**${sum.diskBytes !== sum.bytes ? ` (${b(sum.diskBytes)} on disk)` : ""}`],
|
|
2792
|
+
["Files", formatCount(sum.files)],
|
|
2793
|
+
["Folders", formatCount(sum.directories)],
|
|
2794
|
+
...sum.excluded > 0 ? [["Excluded", formatCount(sum.excluded)]] : [],
|
|
2795
|
+
...sum.errors > 0 ? [["Unreadable", formatCount(sum.errors)]] : []
|
|
2796
|
+
], ["l", "r"]));
|
|
2797
|
+
if (result.budgets && result.budgets.length > 0) {
|
|
2798
|
+
const failed = result.budgets.filter((x) => !x.passed).length;
|
|
2799
|
+
out.push("", `### Budgets ${failed > 0 ? `❌ ${failed} failed` : "✅ all passed"}`, "");
|
|
2800
|
+
out.push(...table([
|
|
2801
|
+
"",
|
|
2802
|
+
"Rule",
|
|
2803
|
+
"Actual"
|
|
2804
|
+
], result.budgets.map((x) => [
|
|
2805
|
+
x.passed ? "✅" : "❌",
|
|
2806
|
+
mdCode(x.rule),
|
|
2807
|
+
[
|
|
2808
|
+
"size",
|
|
2809
|
+
"disk",
|
|
2810
|
+
"largest",
|
|
2811
|
+
"wasted"
|
|
2812
|
+
].includes(x.metric) ? b(x.actual) : formatCount(x.actual)
|
|
2813
|
+
])));
|
|
2814
|
+
}
|
|
2815
|
+
const types = CATEGORIES.filter((c) => result.types[c].files > 0).sort((x, y) => result.types[y].bytes - result.types[x].bytes);
|
|
2816
|
+
if (types.length > 0) {
|
|
2817
|
+
out.push("", "### File types", "");
|
|
2818
|
+
out.push(...table([
|
|
2819
|
+
"Type",
|
|
2820
|
+
"Size",
|
|
2821
|
+
"Share",
|
|
2822
|
+
"Files"
|
|
2823
|
+
], types.map((c) => [
|
|
2824
|
+
capitalize(c),
|
|
2825
|
+
b(result.types[c].bytes),
|
|
2826
|
+
formatPercent(result.types[c].bytes, sum.bytes),
|
|
2827
|
+
formatCount(result.types[c].files)
|
|
2828
|
+
]), [
|
|
2829
|
+
"l",
|
|
2830
|
+
"r",
|
|
2831
|
+
"r",
|
|
2832
|
+
"r"
|
|
2833
|
+
]));
|
|
2834
|
+
}
|
|
2835
|
+
if (result.largestDirectories.length > 0) {
|
|
2836
|
+
out.push("", "### Largest folders", "");
|
|
2837
|
+
out.push(...table([
|
|
2838
|
+
"Size",
|
|
2839
|
+
"Folder",
|
|
2840
|
+
"Files"
|
|
2841
|
+
], result.largestDirectories.slice(0, limit).map((d) => [
|
|
2842
|
+
b(d.bytes),
|
|
2843
|
+
mdCode(`${d.path}/`),
|
|
2844
|
+
formatCount(d.files)
|
|
2845
|
+
]), [
|
|
2846
|
+
"r",
|
|
2847
|
+
"l",
|
|
2848
|
+
"r"
|
|
2849
|
+
]));
|
|
2850
|
+
}
|
|
2851
|
+
if (result.largestFiles.length > 0) {
|
|
2852
|
+
out.push("", "### Largest files", "");
|
|
2853
|
+
fileTable(result.largestFiles, result.largestFiles.length);
|
|
2854
|
+
}
|
|
2855
|
+
if (result.largeFiles && result.largeFiles.count > 0) {
|
|
2856
|
+
const lf = result.largeFiles;
|
|
2857
|
+
out.push("", `### Large files (≥ ${b(lf.threshold)}): ${plural(lf.count, "file")}, ${b(lf.bytes)}`, "");
|
|
2858
|
+
fileTable(lf.items, lf.count);
|
|
2859
|
+
}
|
|
2860
|
+
if (result.duplicates) {
|
|
2861
|
+
const d = result.duplicates;
|
|
2862
|
+
out.push("", `### Duplicates: ${plural(d.count, "group")}, ${b(d.wastedBytes)} reclaimable`);
|
|
2863
|
+
if (d.count > 0) {
|
|
2864
|
+
out.push("");
|
|
2865
|
+
const shown = d.items.slice(0, limit);
|
|
2866
|
+
out.push(...table([
|
|
2867
|
+
"Reclaimable",
|
|
2868
|
+
"Copies",
|
|
2869
|
+
"Files"
|
|
2870
|
+
], shown.map((g) => [
|
|
2871
|
+
b(g.wastedBytes),
|
|
2872
|
+
`${g.files.length} × ${b(g.bytes)}`,
|
|
2873
|
+
g.files.slice(0, 5).map(mdCode).join("<br>") + (g.files.length > 5 ? `<br>…${g.files.length - 5} more` : "")
|
|
2874
|
+
]), [
|
|
2875
|
+
"r",
|
|
2876
|
+
"r",
|
|
2877
|
+
"l"
|
|
2878
|
+
]));
|
|
2879
|
+
more(shown.length, d.count);
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
if (result.emptyFiles && result.emptyFiles.count > 0) {
|
|
2883
|
+
out.push("", `### Empty files: ${formatCount(result.emptyFiles.count)}`, "");
|
|
2884
|
+
for (const f of result.emptyFiles.items.slice(0, limit)) out.push(`- ${mdCode(f.path)}`);
|
|
2885
|
+
more(Math.min(limit, result.emptyFiles.items.length), result.emptyFiles.count);
|
|
2886
|
+
}
|
|
2887
|
+
if (result.emptyDirectories && result.emptyDirectories.count > 0) {
|
|
2888
|
+
out.push("", `### Empty folders: ${formatCount(result.emptyDirectories.count)}`, "");
|
|
2889
|
+
for (const d of result.emptyDirectories.items.slice(0, limit)) out.push(`- ${mdCode(`${d}/`)}`);
|
|
2890
|
+
more(Math.min(limit, result.emptyDirectories.items.length), result.emptyDirectories.count);
|
|
2891
|
+
}
|
|
2892
|
+
if (result.staleFiles && result.staleFiles.count > 0) {
|
|
2893
|
+
const sf = result.staleFiles;
|
|
2894
|
+
out.push("", `### Not modified since ${sf.modifiedBefore.slice(0, 10)}: ${plural(sf.count, "file")}, ${b(sf.bytes)}`, "");
|
|
2895
|
+
fileTable(sf.items, sf.count);
|
|
2896
|
+
}
|
|
2897
|
+
out.push("", `<sub>Generated by [dir-analysis-tool](https://github.com/KhaledSaeed18/dir-analysis-tool) v${result.tool.version}</sub>`, "");
|
|
2898
|
+
return out.join("\n");
|
|
2899
|
+
}
|
|
2900
|
+
/** Renders a directory comparison as GitHub-flavored Markdown. */
|
|
2901
|
+
function renderComparisonMarkdown(result, options = {}) {
|
|
2902
|
+
const units = options.units ?? "iec";
|
|
2903
|
+
const limit = options.limit ?? 10;
|
|
2904
|
+
const b = (n) => formatBytes(n, units);
|
|
2905
|
+
const signed = (n) => n > 0 ? `+${b(n)}` : n < 0 ? b(n) : "±0";
|
|
2906
|
+
const signedCount = (n) => n > 0 ? `+${formatCount(n)}` : formatCount(n);
|
|
2907
|
+
const L = result.left.summary;
|
|
2908
|
+
const R = result.right.summary;
|
|
2909
|
+
const out = [];
|
|
2910
|
+
out.push(`## Directory comparison`, "", `**Left:** ${mdCode(result.left.root)} `, `**Right:** ${mdCode(result.right.root)}`, "");
|
|
2911
|
+
out.push(...table([
|
|
2912
|
+
"",
|
|
2913
|
+
"Left",
|
|
2914
|
+
"Right",
|
|
2915
|
+
"Change"
|
|
2916
|
+
], [
|
|
2917
|
+
[
|
|
2918
|
+
"Size",
|
|
2919
|
+
b(L.bytes),
|
|
2920
|
+
b(R.bytes),
|
|
2921
|
+
`**${signed(result.delta.bytes)}**`
|
|
2922
|
+
],
|
|
2923
|
+
[
|
|
2924
|
+
"On disk",
|
|
2925
|
+
b(L.diskBytes),
|
|
2926
|
+
b(R.diskBytes),
|
|
2927
|
+
signed(result.delta.diskBytes)
|
|
2928
|
+
],
|
|
2929
|
+
[
|
|
2930
|
+
"Files",
|
|
2931
|
+
formatCount(L.files),
|
|
2932
|
+
formatCount(R.files),
|
|
2933
|
+
signedCount(result.delta.files)
|
|
2934
|
+
],
|
|
2935
|
+
[
|
|
2936
|
+
"Folders",
|
|
2937
|
+
formatCount(L.directories),
|
|
2938
|
+
formatCount(R.directories),
|
|
2939
|
+
signedCount(result.delta.directories)
|
|
2940
|
+
]
|
|
2941
|
+
], [
|
|
2942
|
+
"l",
|
|
2943
|
+
"r",
|
|
2944
|
+
"r",
|
|
2945
|
+
"r"
|
|
2946
|
+
]));
|
|
2947
|
+
const section = (title, list) => {
|
|
2948
|
+
if (list.count === 0) return;
|
|
2949
|
+
out.push("", `### ${title}: ${plural(list.count, "file")}, ${b(list.bytes)}`, "");
|
|
2950
|
+
out.push(...table(["Size", "Path"], list.items.slice(0, limit).map((f) => [b(f.bytes), mdCode(f.path)]), ["r", "l"]));
|
|
2951
|
+
if (list.count > limit) out.push("", `<sub>…and ${formatCount(list.count - limit)} more</sub>`);
|
|
2952
|
+
};
|
|
2953
|
+
section("Added", result.added);
|
|
2954
|
+
section("Removed", result.removed);
|
|
2955
|
+
if (result.changed.count > 0) {
|
|
2956
|
+
out.push("", `### Changed: ${plural(result.changed.count, "file")}, ${signed(result.changed.delta)} net`, "");
|
|
2957
|
+
out.push(...table([
|
|
2958
|
+
"Change",
|
|
2959
|
+
"Path",
|
|
2960
|
+
"Left",
|
|
2961
|
+
"Right"
|
|
2962
|
+
], result.changed.items.slice(0, limit).map((c) => [
|
|
2963
|
+
signed(c.delta),
|
|
2964
|
+
mdCode(c.path),
|
|
2965
|
+
b(c.leftBytes),
|
|
2966
|
+
b(c.rightBytes)
|
|
2967
|
+
]), [
|
|
2968
|
+
"r",
|
|
2969
|
+
"l",
|
|
2970
|
+
"r",
|
|
2971
|
+
"r"
|
|
2972
|
+
]));
|
|
2973
|
+
if (result.changed.count > limit) out.push("", `<sub>…and ${formatCount(result.changed.count - limit)} more</sub>`);
|
|
2974
|
+
}
|
|
2975
|
+
if (result.directories.length > 0) {
|
|
2976
|
+
out.push("", "### Folders that changed most", "");
|
|
2977
|
+
out.push(...table(["Change", "Folder"], result.directories.slice(0, limit).map((d) => [signed(d.delta), mdCode(`${d.path}/`)]), ["r", "l"]));
|
|
2978
|
+
}
|
|
2979
|
+
out.push("", `<sub>${plural(result.unchanged, "file")} unchanged, compared by ${result.mode === "content" ? "size and content" : "size"}. Generated by [dir-analysis-tool](https://github.com/KhaledSaeed18/dir-analysis-tool) v${result.tool.version}</sub>`, "");
|
|
2980
|
+
return out.join("\n");
|
|
2981
|
+
}
|
|
2982
|
+
//#endregion
|
|
2983
|
+
//#region src/reporters/csv.ts
|
|
2984
|
+
/**
|
|
2985
|
+
* Quotes a CSV cell when needed (RFC 4180) and neutralizes spreadsheet
|
|
2986
|
+
* formula injection: text starting with `=`, `+`, `-`, `@`, tab, or carriage
|
|
2987
|
+
* return is prefixed with an apostrophe so it is never evaluated.
|
|
2988
|
+
*/
|
|
2989
|
+
function csvCell(value) {
|
|
2990
|
+
if (value === null || value === void 0) return "";
|
|
2991
|
+
if (typeof value === "number") return String(value);
|
|
2992
|
+
let text = value;
|
|
2993
|
+
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
|
|
2994
|
+
return /[",\r\n]/.test(text) ? `"${text.replaceAll("\"", "\"\"")}"` : text;
|
|
2995
|
+
}
|
|
2996
|
+
function csv(header, rows) {
|
|
2997
|
+
return `${[header, ...rows].map((row) => row.map(csvCell).join(",")).join("\r\n")}\r\n`;
|
|
2998
|
+
}
|
|
2999
|
+
/**
|
|
3000
|
+
* Flattens an analysis into one table. The `section` column tells rows apart:
|
|
3001
|
+
* summary, type, extension, largest-directory, largest-file, large-file,
|
|
3002
|
+
* duplicate, empty-file, empty-directory, stale-file, and error.
|
|
3003
|
+
*/
|
|
3004
|
+
function renderAnalysisCsv(result) {
|
|
3005
|
+
const rows = [];
|
|
3006
|
+
const s = result.summary;
|
|
3007
|
+
rows.push([
|
|
3008
|
+
"summary",
|
|
3009
|
+
result.root,
|
|
3010
|
+
s.bytes,
|
|
3011
|
+
s.files,
|
|
3012
|
+
null,
|
|
3013
|
+
null
|
|
3014
|
+
]);
|
|
3015
|
+
for (const c of CATEGORIES) rows.push([
|
|
3016
|
+
"type",
|
|
3017
|
+
c,
|
|
3018
|
+
result.types[c].bytes,
|
|
3019
|
+
result.types[c].files,
|
|
3020
|
+
null,
|
|
3021
|
+
null
|
|
3022
|
+
]);
|
|
3023
|
+
for (const e of result.extensions) rows.push([
|
|
3024
|
+
"extension",
|
|
3025
|
+
e.extension,
|
|
3026
|
+
e.bytes,
|
|
3027
|
+
e.files,
|
|
3028
|
+
null,
|
|
3029
|
+
null
|
|
3030
|
+
]);
|
|
3031
|
+
for (const d of result.largestDirectories) rows.push([
|
|
3032
|
+
"largest-directory",
|
|
3033
|
+
d.path,
|
|
3034
|
+
d.bytes,
|
|
3035
|
+
d.files,
|
|
3036
|
+
null,
|
|
3037
|
+
null
|
|
3038
|
+
]);
|
|
3039
|
+
for (const f of result.largestFiles) rows.push([
|
|
3040
|
+
"largest-file",
|
|
3041
|
+
f.path,
|
|
3042
|
+
f.bytes,
|
|
3043
|
+
1,
|
|
3044
|
+
f.modified,
|
|
3045
|
+
null
|
|
3046
|
+
]);
|
|
3047
|
+
for (const f of result.largeFiles?.items ?? []) rows.push([
|
|
3048
|
+
"large-file",
|
|
3049
|
+
f.path,
|
|
3050
|
+
f.bytes,
|
|
3051
|
+
1,
|
|
3052
|
+
f.modified,
|
|
3053
|
+
null
|
|
3054
|
+
]);
|
|
3055
|
+
result.duplicates?.items.forEach((group, i) => {
|
|
3056
|
+
for (const path of group.files) rows.push([
|
|
3057
|
+
"duplicate",
|
|
3058
|
+
path,
|
|
3059
|
+
group.bytes,
|
|
3060
|
+
1,
|
|
3061
|
+
null,
|
|
3062
|
+
`${i + 1}:${group.hash}`
|
|
3063
|
+
]);
|
|
3064
|
+
});
|
|
3065
|
+
for (const f of result.emptyFiles?.items ?? []) rows.push([
|
|
3066
|
+
"empty-file",
|
|
3067
|
+
f.path,
|
|
3068
|
+
0,
|
|
3069
|
+
1,
|
|
3070
|
+
f.modified,
|
|
3071
|
+
null
|
|
3072
|
+
]);
|
|
3073
|
+
for (const d of result.emptyDirectories?.items ?? []) rows.push([
|
|
3074
|
+
"empty-directory",
|
|
3075
|
+
d,
|
|
3076
|
+
0,
|
|
3077
|
+
0,
|
|
3078
|
+
null,
|
|
3079
|
+
null
|
|
3080
|
+
]);
|
|
3081
|
+
for (const f of result.staleFiles?.items ?? []) rows.push([
|
|
3082
|
+
"stale-file",
|
|
3083
|
+
f.path,
|
|
3084
|
+
f.bytes,
|
|
3085
|
+
1,
|
|
3086
|
+
f.modified,
|
|
3087
|
+
null
|
|
3088
|
+
]);
|
|
3089
|
+
for (const e of result.errors) rows.push([
|
|
3090
|
+
"error",
|
|
3091
|
+
e.path,
|
|
3092
|
+
null,
|
|
3093
|
+
null,
|
|
3094
|
+
null,
|
|
3095
|
+
e.code
|
|
3096
|
+
]);
|
|
3097
|
+
return csv([
|
|
3098
|
+
"section",
|
|
3099
|
+
"item",
|
|
3100
|
+
"bytes",
|
|
3101
|
+
"files",
|
|
3102
|
+
"modified",
|
|
3103
|
+
"group"
|
|
3104
|
+
], rows);
|
|
3105
|
+
}
|
|
3106
|
+
/** Flattens a comparison: one row per added, removed, or changed file. */
|
|
3107
|
+
function renderComparisonCsv(result) {
|
|
3108
|
+
const rows = [];
|
|
3109
|
+
for (const f of result.added.items) rows.push([
|
|
3110
|
+
"added",
|
|
3111
|
+
f.path,
|
|
3112
|
+
null,
|
|
3113
|
+
f.bytes,
|
|
3114
|
+
f.bytes
|
|
3115
|
+
]);
|
|
3116
|
+
for (const f of result.removed.items) rows.push([
|
|
3117
|
+
"removed",
|
|
3118
|
+
f.path,
|
|
3119
|
+
f.bytes,
|
|
3120
|
+
null,
|
|
3121
|
+
-f.bytes
|
|
3122
|
+
]);
|
|
3123
|
+
for (const c of result.changed.items) rows.push([
|
|
3124
|
+
"changed",
|
|
3125
|
+
c.path,
|
|
3126
|
+
c.leftBytes,
|
|
3127
|
+
c.rightBytes,
|
|
3128
|
+
c.delta
|
|
3129
|
+
]);
|
|
3130
|
+
return csv([
|
|
3131
|
+
"change",
|
|
3132
|
+
"path",
|
|
3133
|
+
"left_bytes",
|
|
3134
|
+
"right_bytes",
|
|
3135
|
+
"delta"
|
|
3136
|
+
], rows);
|
|
3137
|
+
}
|
|
3138
|
+
//#endregion
|
|
3139
|
+
//#region src/reporters/html.ts
|
|
3140
|
+
const CATEGORY_COLORS = {
|
|
3141
|
+
code: "#6366f1",
|
|
3142
|
+
documents: "#0ea5e9",
|
|
3143
|
+
images: "#10b981",
|
|
3144
|
+
videos: "#f43f5e",
|
|
3145
|
+
audio: "#f59e0b",
|
|
3146
|
+
archives: "#8b5cf6",
|
|
3147
|
+
fonts: "#ec4899",
|
|
3148
|
+
data: "#14b8a6",
|
|
3149
|
+
other: "#94a3b8"
|
|
3150
|
+
};
|
|
3151
|
+
function escapeHtml(text) {
|
|
3152
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
3153
|
+
}
|
|
3154
|
+
const e = escapeHtml;
|
|
3155
|
+
/**
|
|
3156
|
+
* Renders a fully self-contained HTML report: no external requests, no
|
|
3157
|
+
* frameworks, charts drawn with inline SVG. A Content-Security-Policy blocks
|
|
3158
|
+
* all network access, so the file is safe to open and share offline.
|
|
3159
|
+
*/
|
|
3160
|
+
function renderAnalysisHtml(result, options = {}) {
|
|
3161
|
+
const units = options.units ?? "iec";
|
|
3162
|
+
const limit = options.limit ?? 500;
|
|
3163
|
+
const b = (n) => formatBytes(n, units);
|
|
3164
|
+
const sum = result.summary;
|
|
3165
|
+
const sections = [];
|
|
3166
|
+
const truncatedNote = (shown, total) => total > shown ? `<p class="muted">Showing ${formatCount(shown)} of ${formatCount(total)}. Use <code>--format json</code> for the full list.</p>` : "";
|
|
3167
|
+
const fileTable = (items, total, showModified = false) => {
|
|
3168
|
+
const shown = items.slice(0, limit);
|
|
3169
|
+
const max = shown[0]?.bytes ?? 0;
|
|
3170
|
+
return `<table class="filterable"><thead><tr><th class="num">Size</th><th>Path</th>${showModified ? "<th>Modified</th>" : ""}</tr></thead><tbody>${shown.map((f) => `<tr><td class="num">${e(b(f.bytes))}</td><td class="path">${meter(f.bytes, max)}<span>${e(f.path)}</span></td>${showModified ? `<td class="muted">${e(f.modified.slice(0, 10))}</td>` : ""}</tr>`).join("")}</tbody></table>${truncatedNote(shown.length, total)}`;
|
|
3171
|
+
};
|
|
3172
|
+
if (result.budgets && result.budgets.length > 0) {
|
|
3173
|
+
const failed = result.budgets.filter((x) => !x.passed).length;
|
|
3174
|
+
sections.push(section("Budgets", failed > 0 ? `${failed} failed` : "all passed", `<ul class="budgets">${result.budgets.map((x) => {
|
|
3175
|
+
const actual = [
|
|
3176
|
+
"size",
|
|
3177
|
+
"disk",
|
|
3178
|
+
"largest",
|
|
3179
|
+
"wasted"
|
|
3180
|
+
].includes(x.metric) ? b(x.actual) : formatCount(x.actual);
|
|
3181
|
+
return `<li class="${x.passed ? "pass" : "fail"}"><span>${x.passed ? "✔" : "✘"}</span><code>${e(x.rule)}</code><span class="muted">actual ${e(actual)}</span></li>`;
|
|
3182
|
+
}).join("")}</ul>`));
|
|
3183
|
+
}
|
|
3184
|
+
const types = CATEGORIES.filter((c) => result.types[c].files > 0).sort((x, y) => result.types[y].bytes - result.types[x].bytes);
|
|
3185
|
+
if (types.length > 0) sections.push(section("File types", plural(types.length, "category", "categories"), `<div class="types">${donut(types.map((c) => ({
|
|
3186
|
+
value: result.types[c].bytes,
|
|
3187
|
+
color: CATEGORY_COLORS[c]
|
|
3188
|
+
})))}<table><thead><tr><th>Type</th><th class="num">Size</th><th class="num">Share</th><th class="num">Files</th></tr></thead><tbody>${types.map((c) => `<tr><td><span class="swatch" style="background:${CATEGORY_COLORS[c]}"></span>${c.charAt(0).toUpperCase()}${c.slice(1)}</td><td class="num">${e(b(result.types[c].bytes))}</td><td class="num">${formatPercent(result.types[c].bytes, sum.bytes)}</td><td class="num">${formatCount(result.types[c].files)}</td></tr>`).join("")}</tbody></table></div>`));
|
|
3189
|
+
if (result.largestDirectories.length > 0) {
|
|
3190
|
+
const max = result.largestDirectories[0].bytes;
|
|
3191
|
+
sections.push(section("Largest folders", "", `<table class="filterable"><thead><tr><th class="num">Size</th><th>Folder</th><th class="num">Files</th></tr></thead><tbody>${result.largestDirectories.map((d) => `<tr><td class="num">${e(b(d.bytes))}</td><td class="path">${meter(d.bytes, max)}<span>${e(d.path)}/</span></td><td class="num">${formatCount(d.files)}</td></tr>`).join("")}</tbody></table>`));
|
|
3192
|
+
}
|
|
3193
|
+
if (result.largestFiles.length > 0) sections.push(section("Largest files", "", fileTable(result.largestFiles, result.largestFiles.length, true)));
|
|
3194
|
+
if (result.extensions.length > 0) {
|
|
3195
|
+
const shown = result.extensions.slice(0, 25);
|
|
3196
|
+
sections.push(section("Extensions", plural(result.extensions.length, "extension"), `<table class="filterable"><thead><tr><th>Extension</th><th class="num">Size</th><th class="num">Share</th><th class="num">Files</th></tr></thead><tbody>${shown.map((x) => `<tr><td><code>${e(x.extension || "(none)")}</code></td><td class="num">${e(b(x.bytes))}</td><td class="num">${formatPercent(x.bytes, sum.bytes)}</td><td class="num">${formatCount(x.files)}</td></tr>`).join("")}</tbody></table>${truncatedNote(shown.length, result.extensions.length)}`));
|
|
3197
|
+
}
|
|
3198
|
+
if (result.largeFiles) {
|
|
3199
|
+
const lf = result.largeFiles;
|
|
3200
|
+
sections.push(section(`Large files ≥ ${b(lf.threshold)}`, lf.count > 0 ? `${plural(lf.count, "file")} · ${b(lf.bytes)}` : "none", lf.count > 0 ? fileTable(lf.items, lf.count, true) : ""));
|
|
3201
|
+
}
|
|
3202
|
+
if (result.duplicates) {
|
|
3203
|
+
const d = result.duplicates;
|
|
3204
|
+
const groups = d.items.slice(0, limit);
|
|
3205
|
+
sections.push(section("Duplicates", d.count > 0 ? `${plural(d.count, "group")} · ${b(d.wastedBytes)} reclaimable` : "none found", groups.map((g) => `<details class="group"><summary><strong>${e(b(g.wastedBytes))}</strong> reclaimable <span class="muted">· ${g.files.length} × ${e(b(g.bytes))}</span></summary><ul>${g.files.map((f) => `<li class="path">${e(f)}</li>`).join("")}</ul><p class="muted hash">sha256 ${e(g.hash)}</p></details>`).join("") + truncatedNote(groups.length, d.count)));
|
|
3206
|
+
}
|
|
3207
|
+
if (result.emptyFiles || result.emptyDirectories) {
|
|
3208
|
+
const files = result.emptyFiles?.items ?? [];
|
|
3209
|
+
const dirs = result.emptyDirectories?.items ?? [];
|
|
3210
|
+
const list = (items) => `<ul class="plain">${items.slice(0, limit).map((p) => `<li class="path">${e(p)}</li>`).join("")}</ul>${truncatedNote(Math.min(limit, items.length), items.length)}`;
|
|
3211
|
+
sections.push(section("Empty files and folders", `${plural(files.length, "file")} · ${plural(dirs.length, "folder")}`, `${files.length > 0 ? `<h3>Files</h3>${list(files.map((f) => f.path))}` : ""}${dirs.length > 0 ? `<h3>Folders</h3>${list(dirs.map((d) => `${d}/`))}` : ""}`));
|
|
3212
|
+
}
|
|
3213
|
+
if (result.staleFiles) {
|
|
3214
|
+
const sf = result.staleFiles;
|
|
3215
|
+
sections.push(section(`Not modified since ${sf.modifiedBefore.slice(0, 10)}`, sf.count > 0 ? `${plural(sf.count, "file")} · ${b(sf.bytes)}` : "none", sf.count > 0 ? fileTable(sf.items, sf.count, true) : ""));
|
|
3216
|
+
}
|
|
3217
|
+
if (result.tree) sections.push(section("Tree", "", `<div class="tree">${treeHtml(result.tree, result.tree.bytes, b, true)}</div>`));
|
|
3218
|
+
if (result.errors.length > 0) sections.push(section("Unreadable paths", plural(sum.errors, "path"), `<table><thead><tr><th>Code</th><th>Path</th><th>Reason</th></tr></thead><tbody>${result.errors.map((x) => `<tr><td><code>${e(x.code)}</code></td><td class="path">${e(x.path)}</td><td class="muted">${e(x.message)}</td></tr>`).join("")}</tbody></table>`));
|
|
3219
|
+
const cards = [
|
|
3220
|
+
[
|
|
3221
|
+
"Size",
|
|
3222
|
+
b(sum.bytes),
|
|
3223
|
+
sum.diskBytes !== sum.bytes ? `${b(sum.diskBytes)} on disk` : void 0
|
|
3224
|
+
],
|
|
3225
|
+
["Files", formatCount(sum.files)],
|
|
3226
|
+
["Folders", formatCount(sum.directories)],
|
|
3227
|
+
["Largest file", b(sum.largestFileBytes)]
|
|
3228
|
+
];
|
|
3229
|
+
if (result.duplicates) cards.push([
|
|
3230
|
+
"Reclaimable",
|
|
3231
|
+
b(result.duplicates.wastedBytes),
|
|
3232
|
+
plural(result.duplicates.count, "duplicate group")
|
|
3233
|
+
]);
|
|
3234
|
+
const skipped = [
|
|
3235
|
+
sum.excluded > 0 ? `${formatCount(sum.excluded)} excluded` : "",
|
|
3236
|
+
sum.filtered > 0 ? `${formatCount(sum.filtered)} filtered` : "",
|
|
3237
|
+
sum.errors > 0 ? `${formatCount(sum.errors)} unreadable` : ""
|
|
3238
|
+
].filter(Boolean);
|
|
3239
|
+
return `<!doctype html>
|
|
3240
|
+
<html lang="en">
|
|
3241
|
+
<head>
|
|
3242
|
+
<meta charset="utf-8">
|
|
3243
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
3244
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:">
|
|
3245
|
+
<meta name="generator" content="dir-analysis-tool ${e(result.tool.version)}">
|
|
3246
|
+
<title>${e(baseName(result.root))} · Directory analysis</title>
|
|
3247
|
+
<style>${CSS}</style>
|
|
3248
|
+
</head>
|
|
3249
|
+
<body>
|
|
3250
|
+
<header>
|
|
3251
|
+
<p class="eyebrow">Directory analysis</p>
|
|
3252
|
+
<h1>${e(baseName(result.root))}</h1>
|
|
3253
|
+
<p class="path root">${e(result.root)}</p>
|
|
3254
|
+
<p class="muted">Generated ${e(result.startedAt.replace("T", " ").slice(0, 19))} UTC · scanned in ${e(formatElapsed(result.durationMs))}${skipped.length > 0 ? ` · ${e(skipped.join(" · "))}` : ""}</p>
|
|
3255
|
+
</header>
|
|
3256
|
+
<main>
|
|
3257
|
+
<div class="cards">${cards.map(([label, value, note]) => `<div class="card"><p class="label">${e(label)}</p><p class="value">${e(value)}</p>${note ? `<p class="muted">${e(note)}</p>` : ""}</div>`).join("")}</div>
|
|
3258
|
+
<input id="filter" type="search" placeholder="Filter paths…" aria-label="Filter paths">
|
|
3259
|
+
${sections.join("\n")}
|
|
3260
|
+
</main>
|
|
3261
|
+
<footer>Generated by <a href="https://github.com/KhaledSaeed18/dir-analysis-tool">dir-analysis-tool</a> v${e(result.tool.version)}</footer>
|
|
3262
|
+
<script>${SCRIPT}<\/script>
|
|
3263
|
+
</body>
|
|
3264
|
+
</html>
|
|
3265
|
+
`;
|
|
3266
|
+
}
|
|
3267
|
+
function section(title, detail, body) {
|
|
3268
|
+
return `<section><h2>${e(title)}${detail ? ` <span class="muted">${e(detail)}</span>` : ""}</h2>${body}</section>`;
|
|
3269
|
+
}
|
|
3270
|
+
function meter(value, max) {
|
|
3271
|
+
return `<i class="meter" style="width:${(max > 0 ? Math.max(.5, value / max * 100) : 0).toFixed(1)}%"></i>`;
|
|
3272
|
+
}
|
|
3273
|
+
function donut(segments) {
|
|
3274
|
+
const total = segments.reduce((s, x) => s + x.value, 0);
|
|
3275
|
+
if (total === 0) return "";
|
|
3276
|
+
let offset = 25;
|
|
3277
|
+
return `<svg class="donut" viewBox="0 0 42 42" role="img" aria-label="Size by file type">${segments.filter((x) => x.value > 0).map((x) => {
|
|
3278
|
+
const pct = x.value / total * 100;
|
|
3279
|
+
const circle = `<circle r="15.9155" cx="21" cy="21" fill="none" stroke="${x.color}" stroke-width="6" stroke-dasharray="${pct.toFixed(3)} ${(100 - pct).toFixed(3)}" stroke-dashoffset="${offset.toFixed(3)}"></circle>`;
|
|
3280
|
+
offset = (offset - pct + 100) % 100;
|
|
3281
|
+
return circle;
|
|
3282
|
+
}).join("")}</svg>`;
|
|
3283
|
+
}
|
|
3284
|
+
function treeHtml(node, rootBytes, b, open) {
|
|
3285
|
+
const label = `<span class="num">${e(b(node.bytes))}</span><span class="share">${formatPercent(node.bytes, rootBytes)}</span><span class="path">${e(node.type === "directory" && node.path ? `${node.name}/` : node.name)}</span>`;
|
|
3286
|
+
if (!node.children || node.children.length === 0) return `<div class="leaf">${label}</div>`;
|
|
3287
|
+
const omitted = node.omitted ? `<div class="leaf muted"><span class="num">${e(b(node.omitted.bytes))}</span><span class="share"></span><span>… ${plural(node.omitted.entries, "more entry", "more entries")}</span></div>` : "";
|
|
3288
|
+
return `<details${open ? " open" : ""}><summary>${label}</summary>${node.children.map((c) => treeHtml(c, rootBytes, b, false)).join("")}${omitted}</details>`;
|
|
3289
|
+
}
|
|
3290
|
+
function baseName(path) {
|
|
3291
|
+
return path.split(/[\\/]/).filter(Boolean).at(-1) ?? path;
|
|
3292
|
+
}
|
|
3293
|
+
const CSS = `
|
|
3294
|
+
:root{--bg:#f8fafc;--panel:#fff;--text:#0f172a;--muted:#64748b;--line:#e2e8f0;--accent:#6366f1;--meter:rgba(99,102,241,.14);--ok:#059669;--bad:#dc2626;color-scheme:light dark}
|
|
3295
|
+
@media (prefers-color-scheme:dark){:root{--bg:#0b1020;--panel:#121a2e;--text:#e2e8f0;--muted:#94a3b8;--line:#1f2a44;--accent:#818cf8;--meter:rgba(129,140,248,.18);--ok:#34d399;--bad:#f87171}}
|
|
3296
|
+
*{box-sizing:border-box}
|
|
3297
|
+
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
3298
|
+
header,main,footer{max-width:1100px;margin:0 auto;padding:0 24px}
|
|
3299
|
+
header{padding-top:40px;padding-bottom:8px}
|
|
3300
|
+
.eyebrow{margin:0;color:var(--accent);font-weight:600;text-transform:uppercase;letter-spacing:.08em;font-size:12px}
|
|
3301
|
+
h1{margin:4px 0;font-size:32px;letter-spacing:-.02em}
|
|
3302
|
+
h2{font-size:18px;margin:0 0 16px}
|
|
3303
|
+
h3{font-size:14px;margin:16px 0 8px;color:var(--muted)}
|
|
3304
|
+
.muted{color:var(--muted);font-weight:400}
|
|
3305
|
+
code,.path,.num{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px}
|
|
3306
|
+
.root{word-break:break-all;margin:0 0 4px}
|
|
3307
|
+
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:24px 0}
|
|
3308
|
+
.card,section{background:var(--panel);border:1px solid var(--line);border-radius:12px}
|
|
3309
|
+
.card{padding:16px}
|
|
3310
|
+
.card p{margin:0}
|
|
3311
|
+
.label{color:var(--muted);font-size:13px}
|
|
3312
|
+
.value{font-size:24px;font-weight:650;letter-spacing:-.01em}
|
|
3313
|
+
section{padding:20px;margin:16px 0}
|
|
3314
|
+
#filter{width:100%;padding:10px 14px;border-radius:10px;border:1px solid var(--line);background:var(--panel);color:var(--text);font:inherit}
|
|
3315
|
+
table{width:100%;border-collapse:collapse}
|
|
3316
|
+
th,td{text-align:left;padding:7px 10px;border-bottom:1px solid var(--line);vertical-align:top}
|
|
3317
|
+
th{font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);font-weight:600}
|
|
3318
|
+
tr:last-child td{border-bottom:0}
|
|
3319
|
+
.num{text-align:right;white-space:nowrap}
|
|
3320
|
+
td.path{position:relative;word-break:break-all}
|
|
3321
|
+
td.path span{position:relative}
|
|
3322
|
+
.meter{position:absolute;left:0;top:4px;bottom:4px;background:var(--meter);border-radius:4px}
|
|
3323
|
+
.types{display:grid;grid-template-columns:180px 1fr;gap:24px;align-items:center}
|
|
3324
|
+
.donut{width:180px;height:180px;transform:rotate(0)}
|
|
3325
|
+
.swatch{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:8px}
|
|
3326
|
+
.group{border:1px solid var(--line);border-radius:10px;padding:10px 14px;margin:8px 0}
|
|
3327
|
+
.group summary{cursor:pointer}
|
|
3328
|
+
.group ul,.plain{margin:8px 0 0;padding-left:18px}
|
|
3329
|
+
.hash{font-family:ui-monospace,monospace;font-size:11px;margin:6px 0 0;word-break:break-all}
|
|
3330
|
+
.budgets{list-style:none;padding:0;margin:0}
|
|
3331
|
+
.budgets li{display:flex;gap:12px;align-items:center;padding:6px 0}
|
|
3332
|
+
.pass span:first-child{color:var(--ok)}.fail span:first-child{color:var(--bad)}.fail code{color:var(--bad)}
|
|
3333
|
+
.tree details>details,.tree details>.leaf{margin-left:22px}
|
|
3334
|
+
.tree summary,.tree .leaf{display:flex;gap:12px;padding:3px 0;cursor:default}
|
|
3335
|
+
.tree summary{cursor:pointer}
|
|
3336
|
+
.tree .num{min-width:84px}.tree .share{min-width:40px;color:var(--muted);font-size:12px;text-align:right}
|
|
3337
|
+
.hidden{display:none}
|
|
3338
|
+
footer{padding:24px;color:var(--muted);font-size:13px;text-align:center}
|
|
3339
|
+
a{color:var(--accent)}
|
|
3340
|
+
@media (max-width:640px){.types{grid-template-columns:1fr}.donut{margin:0 auto}}
|
|
3341
|
+
`;
|
|
3342
|
+
const SCRIPT = `
|
|
3343
|
+
document.getElementById('filter').addEventListener('input', function (event) {
|
|
3344
|
+
var query = event.target.value.toLowerCase();
|
|
3345
|
+
document.querySelectorAll('table.filterable tbody tr, .group, .plain li').forEach(function (row) {
|
|
3346
|
+
row.classList.toggle('hidden', query !== '' && row.textContent.toLowerCase().indexOf(query) === -1);
|
|
3347
|
+
});
|
|
3348
|
+
});
|
|
3349
|
+
`;
|
|
3350
|
+
//#endregion
|
|
3351
|
+
export { formatBytes as A, DEFAULT_EXCLUDES as C, BUDGET_METRICS as D, extensionOf as E, parsePointInTime as F, AbortError as I, DatError as L, CATEGORIES as M, VERSION as N, evaluateBudgets as O, parseDuration as P, errorCode as R, joinRelative as S, classify as T, DEFAULT_LARGE_FILE_THRESHOLD as _, renderComparisonMarkdown as a, DEFAULT_CONCURRENCY as b, formatCount as c, CONFIG_FILE_NAMES as d, findConfigFile as f, compare as g, validateConfig as h, renderAnalysisMarkdown as i, parseSize as j, parseBudget as k, createStyle as l, buildJsonSchema as m, renderAnalysisCsv as n, renderAnalysis as o, loadConfig as p, renderComparisonCsv as r, renderComparison as s, renderAnalysisHtml as t, supportsColor as u, DEFAULT_STALE_AGE as v, Excluder as w, listDirectories as x, analyze as y, errorMessage as z };
|