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
package/dist/cli.js
ADDED
|
@@ -0,0 +1,882 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { A as formatBytes, F as parsePointInTime, I as AbortError, L as DatError, N as VERSION, R as errorCode, S as joinRelative, a as renderComparisonMarkdown, c as formatCount, g as compare, i as renderAnalysisMarkdown, j as parseSize, k as parseBudget, l as createStyle, n as renderAnalysisCsv, o as renderAnalysis, p as loadConfig, r as renderComparisonCsv, s as renderComparison, t as renderAnalysisHtml, u as supportsColor, w as Excluder, x as listDirectories, y as analyze, z as errorMessage } from "./shared-Cmryy0SH.js";
|
|
3
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { existsSync, watch } from "node:fs";
|
|
6
|
+
import { Command, CommanderError, InvalidArgumentError, Option } from "commander";
|
|
7
|
+
//#region src/cli/io.ts
|
|
8
|
+
function processIO(signal) {
|
|
9
|
+
return {
|
|
10
|
+
stdout: process.stdout,
|
|
11
|
+
stderr: process.stderr,
|
|
12
|
+
stdinIsTTY: process.stdin.isTTY,
|
|
13
|
+
env: process.env,
|
|
14
|
+
cwd: process.cwd(),
|
|
15
|
+
signal
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Exit codes, documented in the README. */
|
|
19
|
+
const ExitCode = {
|
|
20
|
+
Ok: 0,
|
|
21
|
+
Error: 1,
|
|
22
|
+
BudgetFailed: 2,
|
|
23
|
+
Interrupted: 130
|
|
24
|
+
};
|
|
25
|
+
/** Writes to a stream and waits until the data is flushed (important for large piped output). */
|
|
26
|
+
function write(stream, text) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
stream.write(text, (error) => error ? reject(error) : resolve());
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function terminalWidth(io) {
|
|
32
|
+
const fromEnv = Number(io.env["COLUMNS"]);
|
|
33
|
+
return io.stdout.columns ?? (Number.isInteger(fromEnv) && fromEnv > 0 ? fromEnv : 100);
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/cli/argv.ts
|
|
37
|
+
/**
|
|
38
|
+
* Options whose value is optional. Commander would treat the next argument
|
|
39
|
+
* as their value, so `dat -l ./photos` would read "./photos" as a size. For
|
|
40
|
+
* these flags the next argument is only taken when it is a valid value;
|
|
41
|
+
* otherwise the flag is used with its default and the argument stays
|
|
42
|
+
* positional.
|
|
43
|
+
*/
|
|
44
|
+
const OPTIONAL_VALUE_FLAGS = [
|
|
45
|
+
{
|
|
46
|
+
names: ["-l", "--large-files"],
|
|
47
|
+
long: "--large-files",
|
|
48
|
+
accepts: isSize
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
names: ["--stale"],
|
|
52
|
+
long: "--stale",
|
|
53
|
+
accepts: isPointInTime
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
names: ["--html"],
|
|
57
|
+
long: "--html",
|
|
58
|
+
accepts: (v) => /\.html?$/i.test(v)
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
names: ["--csv"],
|
|
62
|
+
long: "--csv",
|
|
63
|
+
accepts: (v) => /\.csv$/i.test(v)
|
|
64
|
+
}
|
|
65
|
+
];
|
|
66
|
+
function normalizeArgv(argv) {
|
|
67
|
+
const out = [];
|
|
68
|
+
for (let i = 0; i < argv.length; i++) {
|
|
69
|
+
const token = argv[i];
|
|
70
|
+
if (token === "--") {
|
|
71
|
+
out.push(...argv.slice(i));
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
const flag = OPTIONAL_VALUE_FLAGS.find((f) => f.names.includes(token));
|
|
75
|
+
const next = argv[i + 1];
|
|
76
|
+
if (flag && next !== void 0 && !next.startsWith("-") && !flag.accepts(next)) {
|
|
77
|
+
out.push(`${flag.long}=`);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
out.push(token);
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
function isSize(value) {
|
|
85
|
+
try {
|
|
86
|
+
parseSize(value);
|
|
87
|
+
return true;
|
|
88
|
+
} catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function isPointInTime(value) {
|
|
93
|
+
try {
|
|
94
|
+
parsePointInTime(value);
|
|
95
|
+
return true;
|
|
96
|
+
} catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region src/reporters/index.ts
|
|
102
|
+
const FORMATS = [
|
|
103
|
+
"pretty",
|
|
104
|
+
"json",
|
|
105
|
+
"markdown",
|
|
106
|
+
"csv",
|
|
107
|
+
"html"
|
|
108
|
+
];
|
|
109
|
+
function renderAnalysisAs(format, result, options) {
|
|
110
|
+
switch (format) {
|
|
111
|
+
case "pretty": return renderAnalysis(result, options);
|
|
112
|
+
case "json": return `${JSON.stringify(result, null, 2)}\n`;
|
|
113
|
+
case "markdown": return renderAnalysisMarkdown(result, options);
|
|
114
|
+
case "csv": return renderAnalysisCsv(result);
|
|
115
|
+
case "html": return renderAnalysisHtml(result, { units: options.units });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function renderComparisonAs(format, result, options) {
|
|
119
|
+
switch (format) {
|
|
120
|
+
case "pretty": return renderComparison(result, options);
|
|
121
|
+
case "json": return `${JSON.stringify(result, null, 2)}\n`;
|
|
122
|
+
case "markdown": return renderComparisonMarkdown(result, options);
|
|
123
|
+
case "csv": return renderComparisonCsv(result);
|
|
124
|
+
case "html": throw new RangeError("HTML output is not available for compare; use pretty, json, markdown, or csv.");
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/cli/options.ts
|
|
129
|
+
const SCAN_GROUP = "Scan options:";
|
|
130
|
+
const REPORT_GROUP = "Report options:";
|
|
131
|
+
const OUTPUT_GROUP = "Output options:";
|
|
132
|
+
/** Commander parser for whole numbers of at least `min`. */
|
|
133
|
+
function integer(min) {
|
|
134
|
+
return (value) => {
|
|
135
|
+
const parsed = Number(value);
|
|
136
|
+
if (!/^\s*-?\d+\s*$/.test(value) || !Number.isSafeInteger(parsed) || parsed < min) throw new InvalidArgumentError(`Expected a whole number of at least ${min}.`);
|
|
137
|
+
return parsed;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function validated(check) {
|
|
141
|
+
return (value) => {
|
|
142
|
+
if (value === "") return value;
|
|
143
|
+
try {
|
|
144
|
+
check(value);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
throw new InvalidArgumentError(errorMessage(error));
|
|
147
|
+
}
|
|
148
|
+
return value;
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function collect(validate) {
|
|
152
|
+
return (value, previous) => {
|
|
153
|
+
if (validate) validated(validate)(value);
|
|
154
|
+
return [...previous ?? [], value];
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const size = validated(parseSize);
|
|
158
|
+
const pointInTime = validated((v) => parsePointInTime(v));
|
|
159
|
+
function option(flags, description, group) {
|
|
160
|
+
return new Option(flags, description).helpGroup(group);
|
|
161
|
+
}
|
|
162
|
+
/** Options that control which files are scanned. Shared by every command. */
|
|
163
|
+
function addScanOptions(command) {
|
|
164
|
+
return command.addOption(option("-e, --exclude <pattern>", "skip paths matching a gitignore-style pattern (repeatable)", SCAN_GROUP).argParser(collect())).addOption(option("-a, --all", "include .git, .hg, .svn, and node_modules (skipped by default)", SCAN_GROUP)).addOption(option("--no-default-excludes", "same as --all", SCAN_GROUP).hideHelp()).addOption(option("--default-excludes", "skip .git, .hg, .svn, and node_modules", SCAN_GROUP).hideHelp()).addOption(option("-g, --gitignore", "honor .gitignore files", SCAN_GROUP)).addOption(option("--no-gitignore", "ignore .gitignore files", SCAN_GROUP).hideHelp()).addOption(option("--max-depth <n>", "descend at most n levels (0 = only top-level files)", SCAN_GROUP).argParser(integer(0))).addOption(option("--no-recursive", "same as --max-depth 0", SCAN_GROUP).hideHelp()).addOption(option("-L, --follow-symlinks", "follow symbolic links (cycles are detected)", SCAN_GROUP)).addOption(option("--count-hardlinks", "count every hard link instead of shared data once", SCAN_GROUP)).addOption(option("--min-size <size>", "only files at least this large (e.g. 10k, 5MiB, 1GB)", SCAN_GROUP).argParser(size)).addOption(option("--max-size <size>", "only files at most this large", SCAN_GROUP).argParser(size)).addOption(option("--newer-than <when>", "only files modified after an age (30d) or date (2024-01-31)", SCAN_GROUP).argParser(pointInTime)).addOption(option("--older-than <when>", "only files modified before an age or date (inclusive)", SCAN_GROUP).argParser(pointInTime)).addOption(option("--date-from <date>", "alias of --newer-than", SCAN_GROUP).argParser(pointInTime).hideHelp()).addOption(option("--date-to <date>", "alias of --older-than", SCAN_GROUP).argParser(pointInTime).hideHelp()).addOption(option("-c, --config <file>", "use this config file instead of discovering one", SCAN_GROUP)).addOption(option("--no-config", "ignore config files", SCAN_GROUP));
|
|
165
|
+
}
|
|
166
|
+
/** Options that turn reports on or off. */
|
|
167
|
+
function addReportOptions(command) {
|
|
168
|
+
return command.addOption(option("-n, --top <n>", "length of the largest files and folders lists (default: 10)", REPORT_GROUP).argParser(integer(0))).addOption(option("--top-n <n>", "alias of --top", REPORT_GROUP).argParser(integer(0)).hideHelp()).addOption(option("-l, --large-files [size]", "list files at least this large (default: 100MiB)", REPORT_GROUP).argParser(size)).addOption(option("-d, --duplicates", "find files with identical contents", REPORT_GROUP)).addOption(option("--no-duplicates", "turn off duplicate detection from a config file", REPORT_GROUP).hideHelp()).addOption(option("--min-duplicate-size <size>", "ignore smaller files when finding duplicates", REPORT_GROUP).argParser(size)).addOption(option("--empty", "list empty files and folders", REPORT_GROUP)).addOption(option("--empty-files", "alias of --empty", REPORT_GROUP).hideHelp()).addOption(option("--no-empty", "turn off the empty report", REPORT_GROUP).hideHelp()).addOption(option("--stale [when]", "list files not modified since an age or date (default: 1y)", REPORT_GROUP).argParser(pointInTime)).addOption(option("-x, --extensions", "show the breakdown by file extension", REPORT_GROUP)).addOption(option("--no-extensions", "hide the extension breakdown", REPORT_GROUP).hideHelp()).addOption(option("--no-types", "hide the breakdown by file type", REPORT_GROUP)).addOption(option("-t, --tree", "show a size tree", REPORT_GROUP)).addOption(option("--no-tree", "hide the size tree", REPORT_GROUP).hideHelp()).addOption(option("--tree-depth <n>", "levels shown by --tree (default: 3)", REPORT_GROUP).argParser(integer(1))).addOption(option("-b, --budget <rule>", "fail with exit code 2 unless a rule holds, e.g. \"size<=500MB\" (repeatable)", REPORT_GROUP).argParser(collect(parseBudget)));
|
|
169
|
+
}
|
|
170
|
+
/** Options that control how results are printed. */
|
|
171
|
+
function addOutputOptions(command, formats = FORMATS) {
|
|
172
|
+
return command.addOption(option("-f, --format <format>", "output format", OUTPUT_GROUP).choices(formats)).addOption(option("-j, --json", "same as --format json", OUTPUT_GROUP)).addOption(option("-o, --output <file>", "write the report to a file instead of stdout", OUTPUT_GROUP)).addOption(option("--si", "use decimal units (kB, MB) instead of binary (KiB, MiB)", OUTPUT_GROUP)).addOption(option("--color", "force colors", OUTPUT_GROUP)).addOption(option("--no-color", "disable colors (also honors NO_COLOR)", OUTPUT_GROUP)).addOption(option("--no-progress", "hide the progress line", OUTPUT_GROUP)).addOption(option("-q, --quiet", "print only the report and errors", OUTPUT_GROUP));
|
|
173
|
+
}
|
|
174
|
+
/** Legacy file outputs kept from v2: they write a file in addition to the normal output. */
|
|
175
|
+
function addFileReportOptions(command) {
|
|
176
|
+
return command.addOption(option("--html [file]", "also write a self-contained HTML report", OUTPUT_GROUP)).addOption(option("--csv [file]", "also write a CSV export", OUTPUT_GROUP));
|
|
177
|
+
}
|
|
178
|
+
/** Option values the user actually typed, so config values are only overridden explicitly. */
|
|
179
|
+
function explicitOptions(command) {
|
|
180
|
+
const values = {};
|
|
181
|
+
for (const [key, value] of Object.entries(command.opts())) {
|
|
182
|
+
const source = command.getOptionValueSource(key);
|
|
183
|
+
if (source === "cli" || source === "env" || source === "implied") values[key] = value;
|
|
184
|
+
}
|
|
185
|
+
return values;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* v2 read `--large-files 100` as 100 MB. A threshold of a few bytes is never
|
|
189
|
+
* what anyone means, so a bare number keeps that meaning (in MiB), with a hint.
|
|
190
|
+
*/
|
|
191
|
+
function applyLegacyLargeFiles(cli, warn) {
|
|
192
|
+
const value = cli["largeFiles"];
|
|
193
|
+
if (typeof value !== "string" || !/^\d+(\.\d+)?$/.test(value)) return;
|
|
194
|
+
cli["largeFiles"] = `${value}MiB`;
|
|
195
|
+
warn(`--large-files ${value} is read as ${value} MiB, as in v2. Add a unit to be explicit, for example --large-files ${value}MB.`);
|
|
196
|
+
}
|
|
197
|
+
/** Typed readers for loosely typed commander values. */
|
|
198
|
+
const read = {
|
|
199
|
+
string: (value) => typeof value === "string" ? value : void 0,
|
|
200
|
+
number: (value) => typeof value === "number" ? value : void 0,
|
|
201
|
+
boolean: (value) => typeof value === "boolean" ? value : void 0,
|
|
202
|
+
strings: (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [],
|
|
203
|
+
/** `--flag` alone (or an empty value) means true; otherwise the given string. */
|
|
204
|
+
flag: (value) => value === true || value === "" ? true : typeof value === "string" ? value : void 0
|
|
205
|
+
};
|
|
206
|
+
/** Merges config values with explicit CLI flags (flags win) into scan settings. */
|
|
207
|
+
function resolveScanSettings(cli, config) {
|
|
208
|
+
let defaultExcludes = config.defaultExcludes;
|
|
209
|
+
if (cli["all"] === true) defaultExcludes = false;
|
|
210
|
+
else defaultExcludes = read.boolean(cli["defaultExcludes"]) ?? defaultExcludes;
|
|
211
|
+
let maxDepth = config.maxDepth;
|
|
212
|
+
if (cli["recursive"] === false) maxDepth = 0;
|
|
213
|
+
maxDepth = read.number(cli["maxDepth"]) ?? maxDepth;
|
|
214
|
+
return {
|
|
215
|
+
exclude: [...config.exclude ?? [], ...read.strings(cli["exclude"])],
|
|
216
|
+
defaultExcludes,
|
|
217
|
+
gitignore: read.boolean(cli["gitignore"]) ?? config.gitignore,
|
|
218
|
+
maxDepth,
|
|
219
|
+
followSymlinks: read.boolean(cli["followSymlinks"]) ?? config.followSymlinks,
|
|
220
|
+
countHardlinks: read.boolean(cli["countHardlinks"]) ?? config.countHardlinks,
|
|
221
|
+
minSize: read.string(cli["minSize"]) ?? config.minSize,
|
|
222
|
+
maxSize: read.string(cli["maxSize"]) ?? config.maxSize,
|
|
223
|
+
modifiedAfter: read.string(cli["newerThan"]) ?? read.string(cli["dateFrom"]) ?? config.newerThan,
|
|
224
|
+
modifiedBefore: read.string(cli["olderThan"]) ?? read.string(cli["dateTo"]) ?? config.olderThan
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/** Merges config values with explicit CLI flags into full analysis options. */
|
|
228
|
+
function resolveAnalyzeOptions(cli, config) {
|
|
229
|
+
const emptyFlag = read.boolean(cli["empty"]) ?? (cli["emptyFiles"] === true ? true : void 0);
|
|
230
|
+
const treeDepth = read.number(cli["treeDepth"]) ?? config.treeDepth;
|
|
231
|
+
const tree = read.boolean(cli["tree"]) ?? config.tree ?? (cli["treeDepth"] === void 0 ? void 0 : true);
|
|
232
|
+
return {
|
|
233
|
+
...resolveScanSettings(cli, config),
|
|
234
|
+
top: read.number(cli["top"]) ?? read.number(cli["topN"]) ?? config.top,
|
|
235
|
+
largeFiles: read.flag(cli["largeFiles"]) ?? config.largeFiles,
|
|
236
|
+
duplicates: read.boolean(cli["duplicates"]) ?? config.duplicates,
|
|
237
|
+
minDuplicateSize: read.string(cli["minDuplicateSize"]) ?? config.minDuplicateSize,
|
|
238
|
+
empty: emptyFlag ?? config.empty,
|
|
239
|
+
stale: read.flag(cli["stale"]) ?? config.stale,
|
|
240
|
+
tree: tree === true ? { depth: treeDepth } : false,
|
|
241
|
+
budgets: [...config.budgets ?? [], ...read.strings(cli["budget"])]
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
function resolveDisplay(cli, config) {
|
|
245
|
+
return {
|
|
246
|
+
format: cli["json"] === true ? "json" : FORMATS.find((f) => f === cli["format"]) ?? "pretty",
|
|
247
|
+
output: read.string(cli["output"]),
|
|
248
|
+
units: cli["si"] === true ? "si" : config.units ?? "iec",
|
|
249
|
+
color: read.boolean(cli["color"]),
|
|
250
|
+
progress: cli["progress"] !== false && cli["quiet"] !== true,
|
|
251
|
+
quiet: cli["quiet"] === true,
|
|
252
|
+
types: cli["types"] !== false,
|
|
253
|
+
extensions: read.boolean(cli["extensions"]) ?? config.extensions ?? false,
|
|
254
|
+
html: read.flag(cli["html"]),
|
|
255
|
+
csv: read.flag(cli["csv"])
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/cli/progress.ts
|
|
260
|
+
const FRAMES = [
|
|
261
|
+
"⠋",
|
|
262
|
+
"⠙",
|
|
263
|
+
"⠹",
|
|
264
|
+
"⠸",
|
|
265
|
+
"⠼",
|
|
266
|
+
"⠴",
|
|
267
|
+
"⠦",
|
|
268
|
+
"⠧",
|
|
269
|
+
"⠇",
|
|
270
|
+
"⠏"
|
|
271
|
+
];
|
|
272
|
+
const CLEAR_LINE = "\r\x1B[2K";
|
|
273
|
+
/** A single, self-overwriting status line on stderr. A no-op unless enabled. */
|
|
274
|
+
var ProgressLine = class {
|
|
275
|
+
#stream;
|
|
276
|
+
#enabled;
|
|
277
|
+
#style;
|
|
278
|
+
#units;
|
|
279
|
+
#frame = 0;
|
|
280
|
+
#visible = false;
|
|
281
|
+
constructor(stream, enabled, style, units) {
|
|
282
|
+
this.#stream = stream;
|
|
283
|
+
this.#enabled = enabled;
|
|
284
|
+
this.#style = style;
|
|
285
|
+
this.#units = units;
|
|
286
|
+
}
|
|
287
|
+
get enabled() {
|
|
288
|
+
return this.#enabled;
|
|
289
|
+
}
|
|
290
|
+
update(text) {
|
|
291
|
+
if (!this.#enabled) return;
|
|
292
|
+
const frame = FRAMES[this.#frame++ % FRAMES.length];
|
|
293
|
+
const width = (this.#stream.columns ?? 80) - 1;
|
|
294
|
+
const line = `${frame} ${text}`;
|
|
295
|
+
this.#stream.write(`${CLEAR_LINE}${this.#style.cyan(line.length > width ? `${line.slice(0, width - 1)}…` : line)}`);
|
|
296
|
+
this.#visible = true;
|
|
297
|
+
}
|
|
298
|
+
analysis(progress) {
|
|
299
|
+
if (progress.phase === "scan") this.update(`Scanning · ${formatCount(progress.files)} files · ${formatCount(progress.directories)} folders · ${formatBytes(progress.bytes, this.#units)}`);
|
|
300
|
+
else {
|
|
301
|
+
const label = progress.stage === "sample" ? "Comparing samples" : "Hashing";
|
|
302
|
+
this.update(`${label} · ${formatCount(progress.done)} of ${formatCount(progress.total)} candidate files`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
clear() {
|
|
306
|
+
if (this.#visible) this.#stream.write(CLEAR_LINE);
|
|
307
|
+
this.#visible = false;
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
//#endregion
|
|
311
|
+
//#region src/cli/commands/analyze.ts
|
|
312
|
+
const EXAMPLES$2 = `
|
|
313
|
+
Examples:
|
|
314
|
+
$ dat analyze the current directory
|
|
315
|
+
$ dat ~/Downloads -l 500MB list files of 500 MB or more
|
|
316
|
+
$ dat . -d find duplicate files and reclaimable space
|
|
317
|
+
$ dat . --stale 2y --top 20 files untouched for two years
|
|
318
|
+
$ dat . -t --tree-depth 2 size tree, two levels deep
|
|
319
|
+
$ dat . -g -x honor .gitignore, show extensions
|
|
320
|
+
$ dat . -b "size<=200MB" -b "duplicates=0"
|
|
321
|
+
enforce budgets in CI (exit code 2 on failure)
|
|
322
|
+
$ dat . -f markdown >> "$GITHUB_STEP_SUMMARY"
|
|
323
|
+
$ dat . --json | jq '.largestFiles[0]'
|
|
324
|
+
$ dat . --html report.html self-contained HTML report
|
|
325
|
+
`;
|
|
326
|
+
function registerAnalyze(program, ctx) {
|
|
327
|
+
const command = program.command("analyze", { isDefault: true }).description("analyze a directory (the default command)").argument("[directory]", "directory to analyze", ".");
|
|
328
|
+
addScanOptions(command);
|
|
329
|
+
addReportOptions(command);
|
|
330
|
+
addOutputOptions(command);
|
|
331
|
+
addFileReportOptions(command);
|
|
332
|
+
command.addHelpText("after", EXAMPLES$2);
|
|
333
|
+
command.action(async (directory, _options, cmd) => {
|
|
334
|
+
const cli = explicitOptions(cmd);
|
|
335
|
+
applyLegacyLargeFiles(cli, (message) => ctx.warn(message));
|
|
336
|
+
const target = ctx.resolvePath(directory);
|
|
337
|
+
const { config } = await ctx.loadConfig(cli, target);
|
|
338
|
+
const display = resolveDisplay(cli, config);
|
|
339
|
+
const options = resolveAnalyzeOptions(cli, config);
|
|
340
|
+
const result = await runAnalysis(ctx, target, options, display);
|
|
341
|
+
await emit(ctx, result, display, listLimit(options.top));
|
|
342
|
+
reportBudgets(ctx, result, display);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
async function runAnalysis(ctx, target, options, display) {
|
|
346
|
+
const progress = new ProgressLine(ctx.io.stderr, display.progress && ctx.io.stderr.isTTY === true, ctx.err, display.units);
|
|
347
|
+
try {
|
|
348
|
+
return await analyze(target, {
|
|
349
|
+
...options,
|
|
350
|
+
signal: ctx.io.signal,
|
|
351
|
+
...progress.enabled ? { onProgress: (p) => progress.analysis(p) } : {}
|
|
352
|
+
});
|
|
353
|
+
} finally {
|
|
354
|
+
progress.clear();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
async function emit(ctx, result, display, limit) {
|
|
358
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
359
|
+
if (display.html) {
|
|
360
|
+
const file = await ctx.writeFile(display.html === true ? `directory-analysis-${today}.html` : display.html, renderAnalysisHtml(result, { units: display.units }));
|
|
361
|
+
ctx.info(`${ctx.err.green("✔")} HTML report written to ${displayPath(ctx, file)}`, display.quiet);
|
|
362
|
+
}
|
|
363
|
+
if (display.csv) {
|
|
364
|
+
const file = await ctx.writeFile(display.csv === true ? "directory-analysis.csv" : display.csv, renderAnalysisCsv(result));
|
|
365
|
+
ctx.info(`${ctx.err.green("✔")} CSV written to ${displayPath(ctx, file)}`, display.quiet);
|
|
366
|
+
}
|
|
367
|
+
let output = display.output;
|
|
368
|
+
if (!output && display.format === "html" && ctx.io.stdout.isTTY) output = `directory-analysis-${today}.html`;
|
|
369
|
+
const text = renderAnalysisAs(display.format, result, {
|
|
370
|
+
style: ctx.outputStyle(display.color, output !== void 0),
|
|
371
|
+
units: display.units,
|
|
372
|
+
width: terminalWidth(ctx.io),
|
|
373
|
+
limit,
|
|
374
|
+
types: display.types,
|
|
375
|
+
extensions: display.extensions
|
|
376
|
+
});
|
|
377
|
+
if (output) {
|
|
378
|
+
const file = await ctx.writeFile(output, text);
|
|
379
|
+
ctx.info(`${ctx.err.green("✔")} Report written to ${displayPath(ctx, file)}`, display.quiet);
|
|
380
|
+
} else await ctx.stdout(text.endsWith("\n") ? text : `${text}\n`);
|
|
381
|
+
}
|
|
382
|
+
function reportBudgets(ctx, result, display) {
|
|
383
|
+
const failed = result.budgets?.filter((b) => !b.passed) ?? [];
|
|
384
|
+
if (failed.length === 0) return;
|
|
385
|
+
ctx.exitCode = ExitCode.BudgetFailed;
|
|
386
|
+
if (display.format === "pretty" && !display.output) return;
|
|
387
|
+
for (const budget of failed) {
|
|
388
|
+
const actual = [
|
|
389
|
+
"size",
|
|
390
|
+
"disk",
|
|
391
|
+
"largest",
|
|
392
|
+
"wasted"
|
|
393
|
+
].includes(budget.metric) ? formatBytes(budget.actual, display.units) : String(budget.actual);
|
|
394
|
+
ctx.io.stderr.write(`${ctx.err.red("budget failed")} ${budget.rule} (actual ${actual})\n`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function displayPath(ctx, file) {
|
|
398
|
+
const rel = relative(ctx.io.cwd, file);
|
|
399
|
+
return rel && !rel.startsWith("..") ? rel : file;
|
|
400
|
+
}
|
|
401
|
+
/** Items printed per list: the --top value, or 10 when the top lists are turned off. */
|
|
402
|
+
function listLimit(top) {
|
|
403
|
+
return top !== void 0 && top > 0 ? top : 10;
|
|
404
|
+
}
|
|
405
|
+
//#endregion
|
|
406
|
+
//#region src/cli/commands/compare.ts
|
|
407
|
+
const EXAMPLES$1 = `
|
|
408
|
+
Examples:
|
|
409
|
+
$ dat compare dist-before dist-after what changed between two builds
|
|
410
|
+
$ dat compare ./a ./b --content also detect same-size content changes
|
|
411
|
+
$ dat compare old new -f markdown a table for a pull request comment
|
|
412
|
+
$ dat compare old new --json | jq .delta
|
|
413
|
+
`;
|
|
414
|
+
function registerCompare(program, ctx) {
|
|
415
|
+
const command = program.command("compare").description("compare two directories: added, removed, and changed files, and size changes").argument("<left>", "the baseline directory").argument("<right>", "the directory to compare against the baseline");
|
|
416
|
+
addScanOptions(command);
|
|
417
|
+
command.addOption(new Option("--content", "compare same-size files by content (SHA-256)").helpGroup("Report options:")).addOption(new Option("-n, --top <n>", "items per list (default: 10)").argParser(integer(0)).helpGroup("Report options:"));
|
|
418
|
+
addOutputOptions(command, [
|
|
419
|
+
"pretty",
|
|
420
|
+
"json",
|
|
421
|
+
"markdown",
|
|
422
|
+
"csv"
|
|
423
|
+
]);
|
|
424
|
+
command.addHelpText("after", EXAMPLES$1);
|
|
425
|
+
command.action(async (left, right, _options, cmd) => {
|
|
426
|
+
const cli = explicitOptions(cmd);
|
|
427
|
+
const { config } = await ctx.loadConfig(cli, ctx.io.cwd);
|
|
428
|
+
const display = resolveDisplay(cli, config);
|
|
429
|
+
const top = read.number(cli["top"]) ?? config.top;
|
|
430
|
+
const progress = new ProgressLine(ctx.io.stderr, display.progress && ctx.io.stderr.isTTY === true, ctx.err, display.units);
|
|
431
|
+
let result;
|
|
432
|
+
try {
|
|
433
|
+
result = await compare(ctx.resolvePath(left), ctx.resolvePath(right), {
|
|
434
|
+
...resolveScanSettings(cli, config),
|
|
435
|
+
content: cli["content"] === true,
|
|
436
|
+
top: top ?? 10,
|
|
437
|
+
signal: ctx.io.signal,
|
|
438
|
+
...progress.enabled ? { onProgress: (p) => progress.update(p.phase === "scan" ? `Scanning · ${formatCount(p.files)} files` : `Comparing contents · ${formatCount(p.files)} of ${formatCount(p.total ?? 0)}`) } : {}
|
|
439
|
+
});
|
|
440
|
+
} finally {
|
|
441
|
+
progress.clear();
|
|
442
|
+
}
|
|
443
|
+
const text = renderComparisonAs(display.format, result, {
|
|
444
|
+
style: ctx.outputStyle(display.color, display.output !== void 0),
|
|
445
|
+
units: display.units,
|
|
446
|
+
width: terminalWidth(ctx.io),
|
|
447
|
+
limit: listLimit(top),
|
|
448
|
+
types: display.types,
|
|
449
|
+
extensions: false
|
|
450
|
+
});
|
|
451
|
+
if (display.output) {
|
|
452
|
+
const file = await ctx.writeFile(display.output, text);
|
|
453
|
+
ctx.info(`${ctx.err.green("✔")} Comparison written to ${file}`, display.quiet);
|
|
454
|
+
} else await ctx.stdout(text.endsWith("\n") ? text : `${text}\n`);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
//#endregion
|
|
458
|
+
//#region src/cli/commands/init.ts
|
|
459
|
+
const SCHEMA_URL = "https://unpkg.com/dir-analysis-tool@3/schema.json";
|
|
460
|
+
function registerInit(program, ctx) {
|
|
461
|
+
program.command("init").description("create a .dir-analyzer.json config file").argument("[directory]", "where to create the file", ".").addOption(new Option("-y, --yes", "skip the questions and write a starter config")).addOption(new Option("--force", "overwrite an existing config file")).action(async (directory, options) => {
|
|
462
|
+
const path = join(ctx.resolvePath(directory), ".dir-analyzer.json");
|
|
463
|
+
const exists = existsSync(path);
|
|
464
|
+
if (exists && !options.force && (options.yes || !ctx.io.stdinIsTTY)) throw new DatError(`${path} already exists.`, { hint: "Use --force to overwrite it." });
|
|
465
|
+
let config;
|
|
466
|
+
if (options.yes) config = {
|
|
467
|
+
exclude: [],
|
|
468
|
+
gitignore: false,
|
|
469
|
+
top: 10
|
|
470
|
+
};
|
|
471
|
+
else {
|
|
472
|
+
if (!ctx.io.stdinIsTTY) throw new DatError("dat init asks questions, but this is not an interactive terminal.", { hint: "Use \"dat init --yes\" to write a starter config." });
|
|
473
|
+
config = await ask(exists && !options.force);
|
|
474
|
+
}
|
|
475
|
+
if (!config) return;
|
|
476
|
+
const file = await ctx.writeFile(path, `${JSON.stringify({
|
|
477
|
+
$schema: SCHEMA_URL,
|
|
478
|
+
...config
|
|
479
|
+
}, null, 4)}\n`);
|
|
480
|
+
ctx.info(`${ctx.err.green("✔")} Wrote ${file}`, false);
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
/** Interactive questions. Loaded lazily, so other commands never pay for the prompt library. */
|
|
484
|
+
async function ask(confirmOverwrite) {
|
|
485
|
+
const p = await import("@clack/prompts");
|
|
486
|
+
function bail(value) {
|
|
487
|
+
if (typeof value === "symbol") {
|
|
488
|
+
p.cancel("Cancelled. Nothing was written.");
|
|
489
|
+
throw new CancelledError();
|
|
490
|
+
}
|
|
491
|
+
return value;
|
|
492
|
+
}
|
|
493
|
+
try {
|
|
494
|
+
p.intro("dat init");
|
|
495
|
+
if (confirmOverwrite) {
|
|
496
|
+
if (!bail(await p.confirm({
|
|
497
|
+
message: ".dir-analyzer.json already exists. Overwrite it?",
|
|
498
|
+
initialValue: false
|
|
499
|
+
}))) {
|
|
500
|
+
p.cancel("Kept the existing file.");
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const exclude = bail(await p.text({
|
|
505
|
+
message: "Patterns to exclude (comma-separated, gitignore syntax)",
|
|
506
|
+
placeholder: "coverage/, *.log, tmp/",
|
|
507
|
+
defaultValue: ""
|
|
508
|
+
}));
|
|
509
|
+
const gitignore = bail(await p.confirm({
|
|
510
|
+
message: "Honor .gitignore files?",
|
|
511
|
+
initialValue: true
|
|
512
|
+
}));
|
|
513
|
+
const large = bail(await p.text({
|
|
514
|
+
message: "Report files at least this large (leave empty to skip)",
|
|
515
|
+
placeholder: "100MiB",
|
|
516
|
+
defaultValue: "",
|
|
517
|
+
validate: (value) => validateWith(value, parseSize)
|
|
518
|
+
}));
|
|
519
|
+
const duplicates = bail(await p.confirm({
|
|
520
|
+
message: "Look for duplicate files on every run?",
|
|
521
|
+
initialValue: false
|
|
522
|
+
}));
|
|
523
|
+
const top = bail(await p.text({
|
|
524
|
+
message: "How many of the largest files and folders to list",
|
|
525
|
+
placeholder: "10",
|
|
526
|
+
defaultValue: "10",
|
|
527
|
+
validate: (value) => !value || /^\d+$/.test(value.trim()) ? void 0 : "Enter a whole number, such as 10."
|
|
528
|
+
}));
|
|
529
|
+
const budgets = bail(await p.text({
|
|
530
|
+
message: "Budgets that must hold (comma-separated, leave empty for none)",
|
|
531
|
+
placeholder: "size<=500MB, duplicates=0",
|
|
532
|
+
defaultValue: "",
|
|
533
|
+
validate: (value) => {
|
|
534
|
+
for (const rule of splitList(value ?? "")) {
|
|
535
|
+
const problem = validateWith(rule, parseBudget);
|
|
536
|
+
if (problem) return problem;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}));
|
|
540
|
+
const config = {};
|
|
541
|
+
const patterns = splitList(exclude);
|
|
542
|
+
if (patterns.length > 0) config.exclude = patterns;
|
|
543
|
+
config.gitignore = gitignore;
|
|
544
|
+
if (large.trim()) config.largeFiles = large.trim();
|
|
545
|
+
if (duplicates) config.duplicates = true;
|
|
546
|
+
config.top = Number(top.trim() || "10");
|
|
547
|
+
const rules = splitList(budgets);
|
|
548
|
+
if (rules.length > 0) config.budgets = rules;
|
|
549
|
+
p.outro("Done. Run \"dat\" to analyze with these settings.");
|
|
550
|
+
return config;
|
|
551
|
+
} catch (error) {
|
|
552
|
+
if (error instanceof CancelledError) return null;
|
|
553
|
+
throw error;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
var CancelledError = class extends Error {};
|
|
557
|
+
function splitList(value) {
|
|
558
|
+
return value.split(",").map((item) => item.trim()).filter(Boolean);
|
|
559
|
+
}
|
|
560
|
+
function validateWith(value, parse) {
|
|
561
|
+
if (!value || !value.trim()) return void 0;
|
|
562
|
+
try {
|
|
563
|
+
parse(value.trim());
|
|
564
|
+
return;
|
|
565
|
+
} catch (error) {
|
|
566
|
+
return errorMessage(error);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
//#endregion
|
|
570
|
+
//#region src/cli/watcher.ts
|
|
571
|
+
/**
|
|
572
|
+
* Watches a directory tree with the platform's native facility.
|
|
573
|
+
*
|
|
574
|
+
* macOS and Windows support efficient recursive watching of a whole tree.
|
|
575
|
+
* On Linux, recursive watching would register every directory, including
|
|
576
|
+
* huge excluded ones like `node_modules`, so one watcher is kept per
|
|
577
|
+
* directory that the scan actually enters, re-synced after each run.
|
|
578
|
+
*/
|
|
579
|
+
var TreeWatcher = class {
|
|
580
|
+
#options;
|
|
581
|
+
#watchers = /* @__PURE__ */ new Map();
|
|
582
|
+
#recursive;
|
|
583
|
+
#closed = false;
|
|
584
|
+
constructor(options) {
|
|
585
|
+
this.#options = options;
|
|
586
|
+
this.#recursive = options.recursive ?? (process.platform === "darwin" || process.platform === "win32");
|
|
587
|
+
}
|
|
588
|
+
get recursive() {
|
|
589
|
+
return this.#recursive;
|
|
590
|
+
}
|
|
591
|
+
/** Starts or re-syncs watchers. `directories` is only used on Linux. */
|
|
592
|
+
sync(directories) {
|
|
593
|
+
if (this.#closed) return;
|
|
594
|
+
if (this.#recursive) {
|
|
595
|
+
if (this.#watchers.size === 0) this.#add("", true);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
const wanted = new Set(directories);
|
|
599
|
+
for (const [dir, watcher] of this.#watchers) if (!wanted.has(dir)) {
|
|
600
|
+
watcher.close();
|
|
601
|
+
this.#watchers.delete(dir);
|
|
602
|
+
}
|
|
603
|
+
for (const dir of wanted) if (!this.#watchers.has(dir)) this.#add(dir, false);
|
|
604
|
+
}
|
|
605
|
+
close() {
|
|
606
|
+
this.#closed = true;
|
|
607
|
+
for (const watcher of this.#watchers.values()) watcher.close();
|
|
608
|
+
this.#watchers.clear();
|
|
609
|
+
}
|
|
610
|
+
#add(dir, recursive) {
|
|
611
|
+
let watcher;
|
|
612
|
+
try {
|
|
613
|
+
watcher = watch(joinRelative(this.#options.root, dir), {
|
|
614
|
+
recursive,
|
|
615
|
+
persistent: true
|
|
616
|
+
});
|
|
617
|
+
} catch (error) {
|
|
618
|
+
this.#options.onError(error instanceof Error ? error : new Error(String(error)));
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
watcher.on("change", (_event, filename) => {
|
|
622
|
+
const name = filename === null ? "" : String(filename);
|
|
623
|
+
const native = sep === "/" ? name : name.replaceAll(sep, "/");
|
|
624
|
+
const rel = dir && native ? `${dir}/${native}` : dir || native;
|
|
625
|
+
if (rel && this.#options.isIgnored(rel)) return;
|
|
626
|
+
this.#options.onChange(rel);
|
|
627
|
+
});
|
|
628
|
+
watcher.on("error", (error) => {
|
|
629
|
+
watcher.close();
|
|
630
|
+
this.#watchers.delete(dir);
|
|
631
|
+
const code = errorCode(error);
|
|
632
|
+
if (code === "ENOENT" || code === "EPERM") this.#options.onChange(dir);
|
|
633
|
+
else this.#options.onError(error);
|
|
634
|
+
});
|
|
635
|
+
this.#watchers.set(dir, watcher);
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
//#endregion
|
|
639
|
+
//#region src/cli/commands/watch.ts
|
|
640
|
+
const CLEAR_SCREEN = "\x1B[2J\x1B[3J\x1B[H";
|
|
641
|
+
const EXAMPLES = `
|
|
642
|
+
Examples:
|
|
643
|
+
$ dat watch re-analyze the current directory on every change
|
|
644
|
+
$ dat watch ./downloads -l 1GB keep an eye on large downloads
|
|
645
|
+
$ dat watch . --json | jq -c .summary
|
|
646
|
+
one JSON document per line (NDJSON)
|
|
647
|
+
`;
|
|
648
|
+
function registerWatch(program, ctx) {
|
|
649
|
+
const command = program.command("watch").description("re-analyze a directory whenever it changes").argument("[directory]", "directory to watch", ".");
|
|
650
|
+
addScanOptions(command);
|
|
651
|
+
addReportOptions(command);
|
|
652
|
+
addOutputOptions(command, ["pretty", "json"]);
|
|
653
|
+
command.addOption(new Option("--debounce <ms>", "wait this long after the last change (default: 300)").argParser(integer(0)).helpGroup("Watch options:")).addOption(new Option("--poll <seconds>", "re-scan on an interval instead of using filesystem events").argParser(integer(1)).helpGroup("Watch options:")).addOption(new Option("--no-clear", "keep previous reports instead of clearing the screen").helpGroup("Watch options:"));
|
|
654
|
+
command.addHelpText("after", EXAMPLES);
|
|
655
|
+
command.action(async (directory, _options, cmd) => {
|
|
656
|
+
const cli = explicitOptions(cmd);
|
|
657
|
+
applyLegacyLargeFiles(cli, (message) => ctx.warn(message));
|
|
658
|
+
const target = ctx.resolvePath(directory);
|
|
659
|
+
const { config } = await ctx.loadConfig(cli, target);
|
|
660
|
+
const display = resolveDisplay(cli, config);
|
|
661
|
+
const options = resolveAnalyzeOptions(cli, config);
|
|
662
|
+
const debounce = read.number(cli["debounce"]) ?? 300;
|
|
663
|
+
const pollSeconds = read.number(cli["poll"]);
|
|
664
|
+
const clear = cli["clear"] !== false && display.format === "pretty" && ctx.io.stdout.isTTY === true;
|
|
665
|
+
const signal = ctx.io.signal;
|
|
666
|
+
let previous = null;
|
|
667
|
+
let running = false;
|
|
668
|
+
let pending = false;
|
|
669
|
+
let timer = null;
|
|
670
|
+
let changes = 0;
|
|
671
|
+
let polling = false;
|
|
672
|
+
const excluder = new Excluder({
|
|
673
|
+
patterns: options.exclude ?? [],
|
|
674
|
+
defaultExcludes: options.defaultExcludes ?? true
|
|
675
|
+
});
|
|
676
|
+
const render = async (result) => {
|
|
677
|
+
if (display.format === "json") {
|
|
678
|
+
await ctx.stdout(`${JSON.stringify(result)}\n`);
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
if (clear) await ctx.stdout(CLEAR_SCREEN);
|
|
682
|
+
await emit(ctx, result, {
|
|
683
|
+
...display,
|
|
684
|
+
html: void 0,
|
|
685
|
+
csv: void 0
|
|
686
|
+
}, listLimit(options.top));
|
|
687
|
+
const status = previous ? describeChange(previous, result, display.units) : "initial scan";
|
|
688
|
+
ctx.info(ctx.err.dim(`watching ${target} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
|
|
689
|
+
};
|
|
690
|
+
let watcher = null;
|
|
691
|
+
const run = async () => {
|
|
692
|
+
if (running) {
|
|
693
|
+
pending = true;
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
running = true;
|
|
697
|
+
try {
|
|
698
|
+
for (;;) {
|
|
699
|
+
pending = false;
|
|
700
|
+
const result = await runAnalysis(ctx, target, options, {
|
|
701
|
+
...display,
|
|
702
|
+
progress: display.progress && previous === null
|
|
703
|
+
});
|
|
704
|
+
if (!polling || !previous || changes > 0 || fingerprint(previous) !== fingerprint(result)) await render(result);
|
|
705
|
+
previous = result;
|
|
706
|
+
changes = 0;
|
|
707
|
+
if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
|
|
708
|
+
if (!pending || signal?.aborted) break;
|
|
709
|
+
}
|
|
710
|
+
} catch (error) {
|
|
711
|
+
if (error instanceof AbortError) return;
|
|
712
|
+
ctx.io.stderr.write(`${ctx.err.red("error")} ${errorMessage(error)}\n`);
|
|
713
|
+
} finally {
|
|
714
|
+
running = false;
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
const schedule = () => {
|
|
718
|
+
changes++;
|
|
719
|
+
if (timer) clearTimeout(timer);
|
|
720
|
+
timer = setTimeout(() => void run(), debounce);
|
|
721
|
+
};
|
|
722
|
+
await run();
|
|
723
|
+
if (signal?.aborted) return;
|
|
724
|
+
let poller = null;
|
|
725
|
+
const startPolling = (seconds) => {
|
|
726
|
+
polling = true;
|
|
727
|
+
poller = setInterval(() => void run(), seconds * 1e3);
|
|
728
|
+
};
|
|
729
|
+
if (pollSeconds) startPolling(pollSeconds);
|
|
730
|
+
else {
|
|
731
|
+
watcher = new TreeWatcher({
|
|
732
|
+
root: target,
|
|
733
|
+
isIgnored: (rel) => excluder.isPathExcluded(rel),
|
|
734
|
+
onChange: schedule,
|
|
735
|
+
onError: (error) => {
|
|
736
|
+
ctx.warn(`file watching failed (${error.message}); falling back to polling every 5 seconds`);
|
|
737
|
+
watcher?.close();
|
|
738
|
+
watcher = null;
|
|
739
|
+
if (!poller) startPolling(5);
|
|
740
|
+
}
|
|
741
|
+
});
|
|
742
|
+
watcher.sync(watcher.recursive ? [] : await listDirectories(target, options));
|
|
743
|
+
}
|
|
744
|
+
await new Promise((resolve) => {
|
|
745
|
+
if (!signal) return;
|
|
746
|
+
if (signal.aborted) resolve();
|
|
747
|
+
signal.addEventListener("abort", () => resolve(), { once: true });
|
|
748
|
+
});
|
|
749
|
+
if (timer) clearTimeout(timer);
|
|
750
|
+
if (poller) clearInterval(poller);
|
|
751
|
+
watcher?.close();
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
function fingerprint(result) {
|
|
755
|
+
const s = result.summary;
|
|
756
|
+
return `${s.bytes}:${s.files}:${s.directories}:${result.largestFiles.map((f) => `${f.path}@${f.modified}`).join("|")}`;
|
|
757
|
+
}
|
|
758
|
+
function describeChange(previous, current, units) {
|
|
759
|
+
const bytes = current.summary.bytes - previous.summary.bytes;
|
|
760
|
+
const files = current.summary.files - previous.summary.files;
|
|
761
|
+
if (bytes === 0 && files === 0) return "no size change";
|
|
762
|
+
const parts = [];
|
|
763
|
+
if (bytes !== 0) parts.push(`${bytes > 0 ? "+" : ""}${formatBytes(bytes, units)}`);
|
|
764
|
+
if (files !== 0) parts.push(`${files > 0 ? "+" : ""}${formatCount(files)} files`);
|
|
765
|
+
return parts.join(", ");
|
|
766
|
+
}
|
|
767
|
+
//#endregion
|
|
768
|
+
//#region src/cli/context.ts
|
|
769
|
+
/** Shared state for one CLI invocation. */
|
|
770
|
+
var Context = class {
|
|
771
|
+
io;
|
|
772
|
+
/** Styling for stderr messages. */
|
|
773
|
+
err;
|
|
774
|
+
exitCode = 0;
|
|
775
|
+
constructor(io) {
|
|
776
|
+
this.io = io;
|
|
777
|
+
this.err = createStyle(supportsColor(io.stderr, io.env));
|
|
778
|
+
}
|
|
779
|
+
resolvePath(path) {
|
|
780
|
+
return resolve(this.io.cwd, path);
|
|
781
|
+
}
|
|
782
|
+
/** Style for the main output: plain when writing to a file or when colors are off. */
|
|
783
|
+
outputStyle(color, toFile) {
|
|
784
|
+
if (toFile) return createStyle(false);
|
|
785
|
+
return createStyle(color ?? supportsColor(this.io.stdout, this.io.env));
|
|
786
|
+
}
|
|
787
|
+
info(message, quiet) {
|
|
788
|
+
if (!quiet) this.io.stderr.write(`${message}\n`);
|
|
789
|
+
}
|
|
790
|
+
warn(message) {
|
|
791
|
+
this.io.stderr.write(`${this.err.yellow("warning")} ${message}\n`);
|
|
792
|
+
}
|
|
793
|
+
async loadConfig(cli, searchFrom) {
|
|
794
|
+
if (cli["config"] === false) return {
|
|
795
|
+
config: {},
|
|
796
|
+
path: null,
|
|
797
|
+
warnings: []
|
|
798
|
+
};
|
|
799
|
+
const file = typeof cli["config"] === "string" ? this.resolvePath(cli["config"]) : void 0;
|
|
800
|
+
const loaded = await loadConfig({
|
|
801
|
+
...file ? { file } : {},
|
|
802
|
+
searchFrom
|
|
803
|
+
});
|
|
804
|
+
for (const warning of loaded.warnings) this.warn(warning);
|
|
805
|
+
return loaded;
|
|
806
|
+
}
|
|
807
|
+
async writeFile(path, content) {
|
|
808
|
+
const absolute = this.resolvePath(path);
|
|
809
|
+
await mkdir(dirname(absolute), { recursive: true });
|
|
810
|
+
await writeFile(absolute, content);
|
|
811
|
+
return absolute;
|
|
812
|
+
}
|
|
813
|
+
stdout(text) {
|
|
814
|
+
return write(this.io.stdout, text);
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
//#endregion
|
|
818
|
+
//#region src/cli/program.ts
|
|
819
|
+
function createProgram(ctx) {
|
|
820
|
+
const { io } = ctx;
|
|
821
|
+
const program = new Command("dat").description("Fast, memory-bounded directory analysis for your terminal and CI.").version(VERSION, "-v, --version", "print the version").helpOption("-h, --help", "show help").helpCommand("help [command]", "show help for a command").configureOutput({
|
|
822
|
+
writeOut: (text) => io.stdout.write(text),
|
|
823
|
+
writeErr: (text) => io.stderr.write(text),
|
|
824
|
+
outputError: (text, write) => write(ctx.err.red(text))
|
|
825
|
+
}).showHelpAfterError("(run \"dat --help\" to see all options)").showSuggestionAfterError(true).exitOverride();
|
|
826
|
+
registerAnalyze(program, ctx);
|
|
827
|
+
registerCompare(program, ctx);
|
|
828
|
+
registerWatch(program, ctx);
|
|
829
|
+
registerInit(program, ctx);
|
|
830
|
+
program.addHelpText("after", `
|
|
831
|
+
Run "dat <command> --help" for the options of a command. Exit codes: 0 success,
|
|
832
|
+
1 error, 2 a budget failed, 130 interrupted.
|
|
833
|
+
Docs: https://github.com/KhaledSaeed18/dir-analysis-tool#readme`);
|
|
834
|
+
return program;
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Runs the CLI and resolves with the process exit code. Never calls
|
|
838
|
+
* `process.exit`, so pending output is always flushed.
|
|
839
|
+
*/
|
|
840
|
+
async function run(argv, io = processIO()) {
|
|
841
|
+
const ctx = new Context(io);
|
|
842
|
+
const program = createProgram(ctx);
|
|
843
|
+
try {
|
|
844
|
+
await program.parseAsync(normalizeArgv(argv), { from: "user" });
|
|
845
|
+
return ctx.exitCode;
|
|
846
|
+
} catch (error) {
|
|
847
|
+
return handleError(error, ctx);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
function handleError(error, ctx) {
|
|
851
|
+
const { io, err } = ctx;
|
|
852
|
+
if (error instanceof CommanderError) return error.exitCode === 0 ? ExitCode.Ok : ExitCode.Error;
|
|
853
|
+
if (error instanceof AbortError || error instanceof Error && error.name === "AbortError") {
|
|
854
|
+
io.stderr.write(`${err.yellow("interrupted")}\n`);
|
|
855
|
+
return ExitCode.Interrupted;
|
|
856
|
+
}
|
|
857
|
+
if (error instanceof DatError) {
|
|
858
|
+
io.stderr.write(`${err.red("error")} ${error.message}\n`);
|
|
859
|
+
if (error.hint) io.stderr.write(`${err.dim(error.hint)}\n`);
|
|
860
|
+
return ExitCode.Error;
|
|
861
|
+
}
|
|
862
|
+
const message = errorMessage(error);
|
|
863
|
+
io.stderr.write(`${err.red("error")} ${message}\n`);
|
|
864
|
+
if (io.env["DAT_DEBUG"] && error instanceof Error && error.stack) io.stderr.write(`${err.dim(error.stack)}\n`);
|
|
865
|
+
else io.stderr.write(`${err.dim("Set DAT_DEBUG=1 for a stack trace. Please report unexpected errors: https://github.com/KhaledSaeed18/dir-analysis-tool/issues")}\n`);
|
|
866
|
+
return ExitCode.Error;
|
|
867
|
+
}
|
|
868
|
+
//#endregion
|
|
869
|
+
//#region src/cli/main.ts
|
|
870
|
+
for (const stream of [process.stdout, process.stderr]) stream.on("error", (error) => {
|
|
871
|
+
if (errorCode(error) === "EPIPE") process.exit(0);
|
|
872
|
+
throw error;
|
|
873
|
+
});
|
|
874
|
+
const controller = new AbortController();
|
|
875
|
+
process.on("SIGINT", () => {
|
|
876
|
+
if (controller.signal.aborted) process.exit(130);
|
|
877
|
+
controller.abort();
|
|
878
|
+
});
|
|
879
|
+
process.on("SIGTERM", () => controller.abort());
|
|
880
|
+
process.exitCode = await run(process.argv.slice(2), processIO(controller.signal));
|
|
881
|
+
//#endregion
|
|
882
|
+
export {};
|