dir-analysis-tool 2.0.7 → 3.0.1

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