dir-analysis-tool 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,15 +1,16 @@
1
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";
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-htkguqJG.js";
3
+ import { existsSync, watch } from "node:fs";
3
4
  import { mkdir, writeFile } from "node:fs/promises";
4
5
  import { dirname, join, relative, resolve, sep } from "node:path";
5
- import { existsSync, watch } from "node:fs";
6
- import { Command, CommanderError, InvalidArgumentError, Option } from "commander";
6
+ import { createInterface } from "node:readline";
7
7
  //#region src/cli/io.ts
8
8
  function processIO(signal) {
9
9
  return {
10
10
  stdout: process.stdout,
11
11
  stderr: process.stderr,
12
12
  stdinIsTTY: process.stdin.isTTY,
13
+ stdin: process.stdin,
13
14
  env: process.env,
14
15
  cwd: process.cwd(),
15
16
  signal
@@ -33,6 +34,550 @@ function terminalWidth(io) {
33
34
  return io.stdout.columns ?? (Number.isInteger(fromEnv) && fromEnv > 0 ? fromEnv : 100);
34
35
  }
35
36
  //#endregion
37
+ //#region src/cli/command.ts
38
+ /**
39
+ * A small command-line parser covering the subset of the commander API this
40
+ * CLI uses: subcommands with a default, grouped options, repeatable and
41
+ * optional-value options, negatable `--no-x` flags, help, version, and
42
+ * commander-style error messages with "did you mean" suggestions.
43
+ */
44
+ /** Thrown for help, version, and usage errors; `exitCode` 0 means a normal exit. */
45
+ var CommanderError = class extends Error {
46
+ exitCode;
47
+ code;
48
+ constructor(exitCode, code, message) {
49
+ super(message);
50
+ this.name = "CommanderError";
51
+ this.exitCode = exitCode;
52
+ this.code = code;
53
+ }
54
+ };
55
+ /** Thrown by an option's `argParser` to reject a value with a message. */
56
+ var InvalidArgumentError = class extends CommanderError {
57
+ constructor(message) {
58
+ super(1, "commander.invalidArgument", message);
59
+ this.name = "InvalidArgumentError";
60
+ }
61
+ };
62
+ var Option = class {
63
+ flags;
64
+ description;
65
+ short;
66
+ long;
67
+ /** `--no-x` style: sets `x` to false. */
68
+ negate;
69
+ /** Takes a value: `<name>` (required) or `[name]` (optional). */
70
+ required;
71
+ optional;
72
+ hidden = false;
73
+ groupTitle;
74
+ parseArg;
75
+ argChoices;
76
+ constructor(flags, description = "") {
77
+ this.flags = flags;
78
+ this.description = description;
79
+ let short;
80
+ let long;
81
+ for (const part of flags.split(/[ ,|]+/)) if (part.startsWith("--")) long = part;
82
+ else if (part.startsWith("-")) short = part;
83
+ this.short = short;
84
+ this.long = long;
85
+ this.negate = long?.startsWith("--no-") ?? false;
86
+ this.required = flags.includes("<");
87
+ this.optional = flags.includes("[");
88
+ }
89
+ /** Title of the section this option is listed under in help. */
90
+ helpGroup(title) {
91
+ this.groupTitle = title;
92
+ return this;
93
+ }
94
+ argParser(fn) {
95
+ this.parseArg = fn;
96
+ return this;
97
+ }
98
+ /** Only these values are accepted. */
99
+ choices(values) {
100
+ this.argChoices = values;
101
+ this.parseArg = (value) => {
102
+ if (!values.includes(value)) throw new InvalidArgumentError(`Allowed choices are ${values.join(", ")}.`);
103
+ return value;
104
+ };
105
+ return this;
106
+ }
107
+ hideHelp(hide = true) {
108
+ this.hidden = hide;
109
+ return this;
110
+ }
111
+ /** `--large-files` -> `largeFiles`; `--no-color` -> `color`. */
112
+ attributeName() {
113
+ return camelCase(this.name());
114
+ }
115
+ name() {
116
+ if (this.long) return this.long.replace(/^--(no-)?/, "");
117
+ return this.short?.replace(/^-/, "") ?? "";
118
+ }
119
+ is(flag) {
120
+ return this.short === flag || this.long === flag;
121
+ }
122
+ };
123
+ function camelCase(text) {
124
+ return text.replace(/-(\w)/g, (_, c) => c.toUpperCase());
125
+ }
126
+ var Command = class Command {
127
+ commands = [];
128
+ options = [];
129
+ parent = null;
130
+ #name;
131
+ #description = "";
132
+ #version;
133
+ #versionOption;
134
+ #helpOption = new Option("-h, --help", "display help for command");
135
+ #helpCommand;
136
+ #defaultCommandName;
137
+ #args = [];
138
+ #action;
139
+ #afterHelp = "";
140
+ #helpAfterError = false;
141
+ #showSuggestion = true;
142
+ #exitOverride = false;
143
+ #output;
144
+ #values = {};
145
+ #sources = {};
146
+ constructor(name = "") {
147
+ this.#name = name;
148
+ this.#output = {
149
+ writeOut: (text) => process.stdout.write(text),
150
+ writeErr: (text) => process.stderr.write(text),
151
+ outputError: (text, write) => write(text)
152
+ };
153
+ }
154
+ name() {
155
+ return this.#name;
156
+ }
157
+ description(text) {
158
+ this.#description = text;
159
+ return this;
160
+ }
161
+ version(version, flags = "-V, --version", description = "output the version number") {
162
+ this.#version = version;
163
+ this.#versionOption = new Option(flags, description);
164
+ return this;
165
+ }
166
+ helpOption(flags, description = "display help for command") {
167
+ this.#helpOption = new Option(flags, description);
168
+ return this;
169
+ }
170
+ /** `helpCommand('help [command]', 'show help for a command')`. */
171
+ helpCommand(nameAndArgs, description = "display help for command") {
172
+ const [name = "help", ...rest] = nameAndArgs.trim().split(/\s+/);
173
+ this.#helpCommand = {
174
+ name,
175
+ argument: rest.join(" "),
176
+ description
177
+ };
178
+ return this;
179
+ }
180
+ configureOutput(configuration) {
181
+ this.#output = {
182
+ ...this.#output,
183
+ ...configuration
184
+ };
185
+ return this;
186
+ }
187
+ /** Text (or `true` for the full help) printed after a usage error. */
188
+ showHelpAfterError(text = true) {
189
+ this.#helpAfterError = text;
190
+ return this;
191
+ }
192
+ showSuggestionAfterError(show = true) {
193
+ this.#showSuggestion = show;
194
+ return this;
195
+ }
196
+ /** Throw a `CommanderError` instead of calling `process.exit`. */
197
+ exitOverride() {
198
+ this.#exitOverride = true;
199
+ return this;
200
+ }
201
+ command(name, options = {}) {
202
+ const sub = new Command(name);
203
+ sub.parent = this;
204
+ sub.#output = this.#output;
205
+ sub.#helpAfterError = this.#helpAfterError;
206
+ sub.#showSuggestion = this.#showSuggestion;
207
+ sub.#exitOverride = this.#exitOverride;
208
+ if (this.#helpOption) sub.#helpOption = this.#helpOption;
209
+ this.commands.push(sub);
210
+ if (options.isDefault) this.#defaultCommandName = name;
211
+ return sub;
212
+ }
213
+ argument(spec, description = "", defaultValue) {
214
+ const required = spec.startsWith("<");
215
+ this.#args.push({
216
+ name: spec.slice(1, -1),
217
+ required,
218
+ description,
219
+ defaultValue
220
+ });
221
+ return this;
222
+ }
223
+ addOption(option) {
224
+ this.options.push(option);
225
+ if (option.negate && option.long) {
226
+ const positive = option.long.replace(/^--no-/, "--");
227
+ if (!this.options.some((o) => o.long === positive)) this.setOptionValueWithSource(option.attributeName(), true, "default");
228
+ }
229
+ return this;
230
+ }
231
+ action(fn) {
232
+ this.#action = fn;
233
+ return this;
234
+ }
235
+ addHelpText(position, text) {
236
+ if (position === "after" || position === "afterAll") this.#afterHelp += text;
237
+ return this;
238
+ }
239
+ opts() {
240
+ return { ...this.#values };
241
+ }
242
+ getOptionValue(key) {
243
+ return this.#values[key];
244
+ }
245
+ getOptionValueSource(key) {
246
+ return this.#sources[key];
247
+ }
248
+ setOptionValueWithSource(key, value, source) {
249
+ this.#values[key] = value;
250
+ this.#sources[key] = source;
251
+ return this;
252
+ }
253
+ async parseAsync(argv, options = {}) {
254
+ const args = options.from === "node" ? argv.slice(2) : [...argv];
255
+ await this.#parseCommand(args);
256
+ return this;
257
+ }
258
+ async #parseCommand(args) {
259
+ if (this.commands.length > 0 || this.#helpCommand) {
260
+ await this.#dispatch(args);
261
+ return;
262
+ }
263
+ const operands = this.#parseOptions(args);
264
+ this.#processArguments(operands);
265
+ if (this.#action) await this.#action(...this.#positionals, this.opts(), this);
266
+ }
267
+ /** Root level: route to an explicit subcommand, the help command, or the default command. */
268
+ async #dispatch(args) {
269
+ const rest = [];
270
+ let first;
271
+ let firstIndex = -1;
272
+ for (let i = 0; i < args.length; i++) {
273
+ const arg = args[i];
274
+ if (arg === "--") {
275
+ rest.push(...args.slice(i));
276
+ break;
277
+ }
278
+ if (first === void 0 && arg.startsWith("-") && arg.length > 1) {
279
+ if (this.#versionOption?.is(arg)) {
280
+ this.#output.writeOut(`${this.#version ?? ""}\n`);
281
+ this.#exit(0, "commander.version", this.#version ?? "");
282
+ }
283
+ }
284
+ if (first === void 0 && !arg.startsWith("-")) {
285
+ first = arg;
286
+ firstIndex = rest.length;
287
+ }
288
+ rest.push(arg);
289
+ }
290
+ if (first !== void 0) {
291
+ const sub = this.commands.find((c) => c.#name === first);
292
+ if (sub) {
293
+ rest.splice(firstIndex, 1);
294
+ await sub.#parseCommand(rest);
295
+ return;
296
+ }
297
+ if (this.#helpCommand && first === this.#helpCommand.name) {
298
+ const target = rest[firstIndex + 1];
299
+ if (target === void 0) this.outputHelp();
300
+ else {
301
+ const command = this.commands.find((c) => c.#name === target);
302
+ if (!command) {
303
+ this.outputHelp({ error: true });
304
+ this.#exit(1, "commander.help", "(outputHelp)");
305
+ }
306
+ command.outputHelp();
307
+ }
308
+ this.#exit(0, "commander.helpDisplayed", "(outputHelp)");
309
+ }
310
+ }
311
+ this.#outputHelpIfRequested(rest);
312
+ if (this.#defaultCommandName) {
313
+ await this.commands.find((c) => c.#name === this.#defaultCommandName).#parseCommand(rest);
314
+ return;
315
+ }
316
+ if (rest.length === 0) {
317
+ this.outputHelp({ error: true });
318
+ this.#exit(1, "commander.help", "(outputHelp)");
319
+ }
320
+ const operands = this.#parseOptions(rest);
321
+ if (operands.length > 0) this.error(`error: unknown command '${operands[0]}'`, "commander.unknownCommand");
322
+ }
323
+ #outputHelpIfRequested(args) {
324
+ if (!this.#helpOption) return;
325
+ for (const arg of args) {
326
+ if (arg === "--") return;
327
+ if (this.#helpOption.is(arg)) {
328
+ this.outputHelp();
329
+ this.#exit(0, "commander.helpDisplayed", "(outputHelp)");
330
+ }
331
+ }
332
+ }
333
+ #findOption(flag) {
334
+ return this.options.find((o) => o.is(flag));
335
+ }
336
+ /** Consumes options and returns the positional operands. */
337
+ #parseOptions(args) {
338
+ const operands = [];
339
+ const queue = [...args];
340
+ this.#outputHelpIfRequested(queue);
341
+ while (queue.length > 0) {
342
+ const arg = queue.shift();
343
+ if (arg === "--") {
344
+ operands.push(...queue);
345
+ break;
346
+ }
347
+ if (!arg.startsWith("-") || arg === "-") {
348
+ operands.push(arg);
349
+ continue;
350
+ }
351
+ if (arg.startsWith("--")) {
352
+ const eq = arg.indexOf("=");
353
+ if (eq !== -1) {
354
+ const flag = arg.slice(0, eq);
355
+ const option = this.#findOption(flag);
356
+ if (!option || !(option.required || option.optional)) this.unknownOption(arg);
357
+ this.#applyOption(option, arg.slice(eq + 1));
358
+ continue;
359
+ }
360
+ const option = this.#findOption(arg);
361
+ if (!option) this.unknownOption(arg);
362
+ this.#takeValue(option, queue);
363
+ continue;
364
+ }
365
+ const option = this.#findOption(arg.slice(0, 2));
366
+ if (!option) this.unknownOption(arg);
367
+ if (arg.length > 2) {
368
+ const attached = arg.slice(2);
369
+ if (option.required || option.optional) this.#applyOption(option, attached);
370
+ else {
371
+ this.#applyOption(option, null);
372
+ queue.unshift(`-${attached}`);
373
+ }
374
+ continue;
375
+ }
376
+ this.#takeValue(option, queue);
377
+ }
378
+ return operands;
379
+ }
380
+ #takeValue(option, queue) {
381
+ if (option.required) {
382
+ const value = queue.shift();
383
+ if (value === void 0) this.error(`error: option '${option.flags}' argument missing`, "commander.optionMissingArgument");
384
+ this.#applyOption(option, value);
385
+ } else if (option.optional) {
386
+ const next = queue[0];
387
+ if (next !== void 0 && !(next.length > 1 && next.startsWith("-"))) {
388
+ queue.shift();
389
+ this.#applyOption(option, next);
390
+ } else this.#applyOption(option, null);
391
+ } else this.#applyOption(option, null);
392
+ }
393
+ /** `value` is null when the flag was given without a value. */
394
+ #applyOption(option, value) {
395
+ const key = option.attributeName();
396
+ let result;
397
+ if (value !== null && option.parseArg) {
398
+ const previous = this.#values[key];
399
+ try {
400
+ result = option.parseArg(value, previous);
401
+ } catch (error) {
402
+ if (error instanceof InvalidArgumentError) this.error(`error: option '${option.flags}' argument '${value}' is invalid. ${error.message}`, "commander.invalidArgument");
403
+ throw error;
404
+ }
405
+ } else if (value !== null) result = value;
406
+ else if (option.negate) result = false;
407
+ else result = true;
408
+ this.setOptionValueWithSource(key, result, "cli");
409
+ }
410
+ #positionals = [];
411
+ #processArguments(operands) {
412
+ const positionals = [];
413
+ for (const [index, arg] of this.#args.entries()) {
414
+ const value = operands[index];
415
+ if (value === void 0) {
416
+ if (arg.required) this.error(`error: missing required argument '${arg.name}'`, "commander.missingArgument");
417
+ positionals.push(arg.defaultValue);
418
+ } else positionals.push(value);
419
+ }
420
+ if (operands.length > this.#args.length) {
421
+ const expected = this.#args.length;
422
+ const list = operands.length > 0 ? `: ${operands.join(", ")}` : "";
423
+ this.error(`error: too many arguments${this.parent ? ` for '${this.#name}'` : ""}. Expected ${expected} argument${expected === 1 ? "" : "s"} but got ${operands.length}${list}.`, "commander.excessArguments");
424
+ }
425
+ this.#positionals = positionals;
426
+ }
427
+ unknownOption(flag) {
428
+ let message = `error: unknown option '${flag}'`;
429
+ if (this.#showSuggestion && flag.startsWith("--")) {
430
+ const candidates = [];
431
+ for (const command of this.#ancestors()) for (const option of command.#visibleOptions()) if (option.long) candidates.push(option.long);
432
+ const suggestion = suggestSimilar(flag, candidates);
433
+ if (suggestion) message += `\n(Did you mean ${suggestion}?)`;
434
+ }
435
+ return this.error(message, "commander.unknownOption");
436
+ }
437
+ /** Prints a usage error (plus the help-after-error text) and exits with code 1. */
438
+ error(message, code = "commander.error") {
439
+ this.#output.outputError(`${message}\n`, this.#output.writeErr);
440
+ if (typeof this.#helpAfterError === "string") this.#output.writeErr(`${this.#helpAfterError}\n`);
441
+ else if (this.#helpAfterError) {
442
+ this.#output.writeErr("\n");
443
+ this.outputHelp({ error: true });
444
+ }
445
+ return this.#exit(1, code, message);
446
+ }
447
+ #exit(exitCode, code, message) {
448
+ if (this.#exitOverride) throw new CommanderError(exitCode, code, message);
449
+ process.exit(exitCode);
450
+ }
451
+ #visibleOptions() {
452
+ const visible = this.options.filter((o) => !o.hidden);
453
+ if (this.#versionOption) visible.push(this.#versionOption);
454
+ if (this.#helpOption) visible.push(this.#helpOption);
455
+ return visible;
456
+ }
457
+ /** This command and its parents, nearest first. */
458
+ #ancestors() {
459
+ return this.parent ? [this, ...this.parent.#ancestors()] : [this];
460
+ }
461
+ #fullName() {
462
+ return this.parent ? `${this.parent.#fullName()} ${this.#name}` : this.#name;
463
+ }
464
+ #argsUsage() {
465
+ return this.#args.map((a) => a.required ? `<${a.name}>` : `[${a.name}]`).join(" ");
466
+ }
467
+ #commandTerm() {
468
+ const parts = [this.#name];
469
+ if (this.options.length > 0) parts.push("[options]");
470
+ const args = this.#argsUsage();
471
+ if (args) parts.push(args);
472
+ return parts.join(" ");
473
+ }
474
+ outputHelp(options = {}) {
475
+ const write = options.error ? this.#output.writeErr : this.#output.writeOut;
476
+ const stream = options.error ? process.stderr : process.stdout;
477
+ const width = stream.isTTY ? stream.columns : void 0;
478
+ write(this.helpInformation(width));
479
+ if (this.#afterHelp) write(`${this.#afterHelp}\n`);
480
+ }
481
+ helpInformation(helpWidth = 80) {
482
+ const usage = ["[options]"];
483
+ if (this.commands.length > 0 || this.#helpCommand) usage.push("[command]");
484
+ const args = this.#argsUsage();
485
+ if (args) usage.push(args);
486
+ const lines = [`Usage: ${this.#fullName()} ${usage.join(" ")}`, ""];
487
+ if (this.#description) lines.push(this.#description, "");
488
+ const argumentItems = this.#args.map((a) => [a.name, a.description + (a.defaultValue !== void 0 ? ` (default: ${JSON.stringify(a.defaultValue)})` : "")]);
489
+ const groups = /* @__PURE__ */ new Map();
490
+ for (const option of this.#visibleOptions()) {
491
+ const title = option.groupTitle ?? "Options:";
492
+ const items = groups.get(title) ?? [];
493
+ let description = option.description;
494
+ if (option.argChoices) description += ` (choices: ${option.argChoices.map((c) => JSON.stringify(c)).join(", ")})`;
495
+ items.push([option.flags, description]);
496
+ groups.set(title, items);
497
+ }
498
+ const commandItems = this.commands.map((c) => [c.#commandTerm(), c.#description]);
499
+ if (this.#helpCommand) {
500
+ const { name, argument, description } = this.#helpCommand;
501
+ commandItems.push([argument ? `${name} ${argument}` : name, description]);
502
+ }
503
+ const all = [
504
+ ...argumentItems,
505
+ ...[...groups.values()].flat(),
506
+ ...commandItems
507
+ ];
508
+ const termWidth = Math.max(0, ...all.map(([term]) => term.length));
509
+ const section = (title, items) => {
510
+ if (items.length === 0) return;
511
+ lines.push(title);
512
+ for (const [term, description] of items) lines.push(formatItem(term, termWidth, description, helpWidth));
513
+ lines.push("");
514
+ };
515
+ section("Arguments:", argumentItems);
516
+ for (const [title, items] of groups) section(title, items);
517
+ section("Commands:", commandItems);
518
+ if (lines.at(-1) === "") lines.pop();
519
+ return `${lines.join("\n")}\n`;
520
+ }
521
+ };
522
+ function formatItem(term, termWidth, description, helpWidth) {
523
+ const indent = 2;
524
+ const spacer = 2;
525
+ if (!description) return `${" ".repeat(indent)}${term}`;
526
+ const remaining = helpWidth - termWidth - spacer - indent;
527
+ const text = remaining < 40 || description.includes("\n") ? description : wrap(description, remaining);
528
+ const continuation = `\n${" ".repeat(indent + termWidth + spacer)}`;
529
+ return `${" ".repeat(indent)}${term.padEnd(termWidth)}${" ".repeat(spacer)}${text.replaceAll("\n", continuation)}`;
530
+ }
531
+ function wrap(text, width) {
532
+ const lines = [];
533
+ let line = "";
534
+ for (const word of text.split(/\s+/)) if (line && line.length + 1 + word.length > width) {
535
+ lines.push(line);
536
+ line = word;
537
+ } else line = line ? `${line} ${word}` : word;
538
+ if (line) lines.push(line);
539
+ return lines.join("\n");
540
+ }
541
+ const MAX_DISTANCE = 3;
542
+ function editDistance(a, b) {
543
+ if (Math.abs(a.length - b.length) > MAX_DISTANCE) return Math.max(a.length, b.length);
544
+ const d = [];
545
+ for (let i = 0; i <= a.length; i++) d.push([i]);
546
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
547
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
548
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
549
+ let best = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
550
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) best = Math.min(best, d[i - 2][j - 2] + 1);
551
+ d[i][j] = best;
552
+ }
553
+ return d[a.length][b.length];
554
+ }
555
+ /** Closest candidate(s) to `word`, or '' when nothing is similar enough. */
556
+ function suggestSimilar(word, candidates) {
557
+ if (candidates.length === 0) return "";
558
+ const unique = [...new Set(candidates)];
559
+ const stripped = word.startsWith("--");
560
+ const needle = stripped ? word.slice(2) : word;
561
+ const pool = stripped ? unique.map((c) => c.slice(2)) : unique;
562
+ let similar = [];
563
+ let bestDistance = MAX_DISTANCE;
564
+ for (const candidate of pool) {
565
+ if (candidate.length <= 1) continue;
566
+ const distance = editDistance(needle, candidate);
567
+ const length = Math.max(needle.length, candidate.length);
568
+ if ((length - distance) / length > .4) {
569
+ if (distance < bestDistance) {
570
+ bestDistance = distance;
571
+ similar = [candidate];
572
+ } else if (distance === bestDistance) similar.push(candidate);
573
+ }
574
+ }
575
+ similar.sort((a, b) => a.localeCompare(b));
576
+ if (stripped) similar = similar.map((c) => `--${c}`);
577
+ if (similar.length > 1) return `one of ${similar.join(", ")}`;
578
+ return similar[0] ?? "";
579
+ }
580
+ //#endregion
36
581
  //#region src/cli/argv.ts
37
582
  /**
38
583
  * Options whose value is optional. Commander would treat the next argument
@@ -45,12 +590,14 @@ const OPTIONAL_VALUE_FLAGS = [
45
590
  {
46
591
  names: ["-l", "--large-files"],
47
592
  long: "--large-files",
48
- accepts: isSize
593
+ accepts: isSize,
594
+ looksLikeValue: /^\.?\d/
49
595
  },
50
596
  {
51
597
  names: ["--stale"],
52
598
  long: "--stale",
53
- accepts: isPointInTime
599
+ accepts: isPointInTime,
600
+ looksLikeValue: /^\d/
54
601
  },
55
602
  {
56
603
  names: ["--html"],
@@ -63,7 +610,7 @@ const OPTIONAL_VALUE_FLAGS = [
63
610
  accepts: (v) => /\.csv$/i.test(v)
64
611
  }
65
612
  ];
66
- function normalizeArgv(argv) {
613
+ function normalizeArgv(argv, cwd = process.cwd()) {
67
614
  const out = [];
68
615
  for (let i = 0; i < argv.length; i++) {
69
616
  const token = argv[i];
@@ -74,8 +621,10 @@ function normalizeArgv(argv) {
74
621
  const flag = OPTIONAL_VALUE_FLAGS.find((f) => f.names.includes(token));
75
622
  const next = argv[i + 1];
76
623
  if (flag && next !== void 0 && !next.startsWith("-") && !flag.accepts(next)) {
77
- out.push(`${flag.long}=`);
78
- continue;
624
+ if (!(flag.looksLikeValue?.test(next) && !existsSync(resolve(cwd, next)))) {
625
+ out.push(`${flag.long}=`);
626
+ continue;
627
+ }
79
628
  }
80
629
  out.push(token);
81
630
  }
@@ -385,12 +934,7 @@ function reportBudgets(ctx, result, display) {
385
934
  ctx.exitCode = ExitCode.BudgetFailed;
386
935
  if (display.format === "pretty" && !display.output) return;
387
936
  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);
937
+ const actual = formatBudgetActual(budget, display.units);
394
938
  ctx.io.stderr.write(`${ctx.err.red("budget failed")} ${budget.rule} (actual ${actual})\n`);
395
939
  }
396
940
  }
@@ -455,6 +999,136 @@ function registerCompare(program, ctx) {
455
999
  });
456
1000
  }
457
1001
  //#endregion
1002
+ //#region src/cli/prompt.ts
1003
+ /**
1004
+ * A tiny interactive prompt toolkit built on `node:readline`, so `dat init`
1005
+ * does not need a prompt library.
1006
+ *
1007
+ * Every question returns either the answer or {@link CANCEL}, which is the
1008
+ * result when the user presses Ctrl+C, stdin closes, or the CLI is aborted.
1009
+ */
1010
+ /** Returned by every prompt when the user cancelled instead of answering. */
1011
+ const CANCEL = Symbol("cancel");
1012
+ var Prompter = class {
1013
+ #io;
1014
+ #style;
1015
+ #queued = [];
1016
+ #rl = null;
1017
+ #waiting = null;
1018
+ #closed = false;
1019
+ constructor(io) {
1020
+ this.#io = io;
1021
+ this.#style = createStyle(supportsColor(io.stdout, io.env));
1022
+ }
1023
+ intro(title) {
1024
+ this.#write(`\n${this.#style.bold(title)}\n\n`);
1025
+ }
1026
+ outro(message) {
1027
+ this.#write(`\n${this.#style.green("✔")} ${message}\n`);
1028
+ }
1029
+ cancel(message) {
1030
+ this.#write(`\n${this.#style.red("■")} ${message}\n`);
1031
+ }
1032
+ async text(options) {
1033
+ const hint = options.placeholder ? ` ${this.#style.dim(`(${options.placeholder})`)}` : "";
1034
+ for (;;) {
1035
+ const line = await this.#readLine(this.#question(options.message, hint));
1036
+ if (line === CANCEL) return CANCEL;
1037
+ const value = line.trim();
1038
+ const problem = options.validate?.(value);
1039
+ if (problem) {
1040
+ this.#problem(problem);
1041
+ continue;
1042
+ }
1043
+ return value || (options.defaultValue ?? "");
1044
+ }
1045
+ }
1046
+ async confirm(options) {
1047
+ const initial = options.initialValue ?? true;
1048
+ const hint = ` ${this.#style.dim(initial ? "(Y/n)" : "(y/N)")}`;
1049
+ for (;;) {
1050
+ const line = await this.#readLine(this.#question(options.message, hint));
1051
+ if (line === CANCEL) return CANCEL;
1052
+ const value = line.trim().toLowerCase();
1053
+ if (value === "") return initial;
1054
+ if (value === "y" || value === "yes") return true;
1055
+ if (value === "n" || value === "no") return false;
1056
+ this.#problem("Please answer yes or no.");
1057
+ }
1058
+ }
1059
+ /** Releases stdin. Call when the questions are over, or the process may not exit. */
1060
+ close() {
1061
+ this.#closed = true;
1062
+ this.#rl?.close();
1063
+ this.#rl = null;
1064
+ this.#waiting?.(CANCEL);
1065
+ this.#waiting = null;
1066
+ }
1067
+ #question(message, hint) {
1068
+ return `${this.#style.cyan("?")} ${this.#style.bold(message)}${hint} ${this.#style.dim("›")} `;
1069
+ }
1070
+ #problem(message) {
1071
+ this.#write(`${this.#style.red("✖")} ${this.#style.red(message)}\n`);
1072
+ }
1073
+ #write(text) {
1074
+ this.#io.stdout.write(text);
1075
+ }
1076
+ #readLine(prompt) {
1077
+ if (this.#io.signal?.aborted) return Promise.resolve(CANCEL);
1078
+ const rl = this.#closed ? null : this.#open();
1079
+ if (!rl && this.#queued.length === 0) return Promise.resolve(CANCEL);
1080
+ if (rl && this.#terminal()) {
1081
+ rl.setPrompt(prompt);
1082
+ rl.prompt();
1083
+ } else this.#write(prompt);
1084
+ return new Promise((resolve) => {
1085
+ const queued = this.#queued.shift();
1086
+ if (queued !== void 0) {
1087
+ this.#echo(queued);
1088
+ resolve(queued);
1089
+ return;
1090
+ }
1091
+ this.#waiting = (line) => {
1092
+ this.#waiting = null;
1093
+ if (typeof line === "string") this.#echo(line);
1094
+ resolve(line);
1095
+ };
1096
+ });
1097
+ }
1098
+ /** Readline echoes typed input on a terminal; when piped, end the line ourselves. */
1099
+ #echo(_line) {
1100
+ if (!this.#terminal()) this.#write("\n");
1101
+ }
1102
+ #terminal() {
1103
+ return this.#io.stdinIsTTY && this.#io.stdout.isTTY === true;
1104
+ }
1105
+ #open() {
1106
+ if (this.#rl) return this.#rl;
1107
+ const terminal = this.#terminal();
1108
+ const rl = createInterface({
1109
+ input: this.#io.stdin ?? process.stdin,
1110
+ ...terminal ? { output: this.#io.stdout } : {},
1111
+ terminal
1112
+ });
1113
+ const cancel = () => {
1114
+ if (terminal) this.#write("\n");
1115
+ this.close();
1116
+ };
1117
+ rl.on("line", (line) => {
1118
+ if (this.#waiting) this.#waiting(line);
1119
+ else this.#queued.push(line);
1120
+ });
1121
+ rl.on("SIGINT", cancel);
1122
+ rl.on("close", () => {
1123
+ if (this.#queued.length === 0) cancel();
1124
+ else this.#closed = true;
1125
+ });
1126
+ this.#io.signal?.addEventListener("abort", cancel, { once: true });
1127
+ this.#rl = rl;
1128
+ return rl;
1129
+ }
1130
+ };
1131
+ //#endregion
458
1132
  //#region src/cli/commands/init.ts
459
1133
  const SCHEMA_URL = "https://unpkg.com/dir-analysis-tool@3/schema.json";
460
1134
  function registerInit(program, ctx) {
@@ -470,7 +1144,7 @@ function registerInit(program, ctx) {
470
1144
  };
471
1145
  else {
472
1146
  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);
1147
+ config = await ask(ctx, exists && !options.force);
474
1148
  }
475
1149
  if (!config) return;
476
1150
  const file = await ctx.writeFile(path, `${JSON.stringify({
@@ -480,11 +1154,11 @@ function registerInit(program, ctx) {
480
1154
  ctx.info(`${ctx.err.green("✔")} Wrote ${file}`, false);
481
1155
  });
482
1156
  }
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");
1157
+ /** Interactive questions, asked on the CLI's own stdin/stdout. */
1158
+ async function ask(ctx, confirmOverwrite) {
1159
+ const p = new Prompter(ctx.io);
486
1160
  function bail(value) {
487
- if (typeof value === "symbol") {
1161
+ if (value === CANCEL) {
488
1162
  p.cancel("Cancelled. Nothing was written.");
489
1163
  throw new CancelledError();
490
1164
  }
@@ -503,8 +1177,7 @@ async function ask(confirmOverwrite) {
503
1177
  }
504
1178
  const exclude = bail(await p.text({
505
1179
  message: "Patterns to exclude (comma-separated, gitignore syntax)",
506
- placeholder: "coverage/, *.log, tmp/",
507
- defaultValue: ""
1180
+ placeholder: "coverage/, *.log, tmp/"
508
1181
  }));
509
1182
  const gitignore = bail(await p.confirm({
510
1183
  message: "Honor .gitignore files?",
@@ -513,7 +1186,6 @@ async function ask(confirmOverwrite) {
513
1186
  const large = bail(await p.text({
514
1187
  message: "Report files at least this large (leave empty to skip)",
515
1188
  placeholder: "100MiB",
516
- defaultValue: "",
517
1189
  validate: (value) => validateWith(value, parseSize)
518
1190
  }));
519
1191
  const duplicates = bail(await p.confirm({
@@ -529,9 +1201,8 @@ async function ask(confirmOverwrite) {
529
1201
  const budgets = bail(await p.text({
530
1202
  message: "Budgets that must hold (comma-separated, leave empty for none)",
531
1203
  placeholder: "size<=500MB, duplicates=0",
532
- defaultValue: "",
533
1204
  validate: (value) => {
534
- for (const rule of splitList(value ?? "")) {
1205
+ for (const rule of splitList(value)) {
535
1206
  const problem = validateWith(rule, parseBudget);
536
1207
  if (problem) return problem;
537
1208
  }
@@ -551,6 +1222,8 @@ async function ask(confirmOverwrite) {
551
1222
  } catch (error) {
552
1223
  if (error instanceof CancelledError) return null;
553
1224
  throw error;
1225
+ } finally {
1226
+ p.close();
554
1227
  }
555
1228
  }
556
1229
  var CancelledError = class extends Error {};
@@ -761,7 +1434,7 @@ function describeChange(previous, current, units) {
761
1434
  if (bytes === 0 && files === 0) return "no size change";
762
1435
  const parts = [];
763
1436
  if (bytes !== 0) parts.push(`${bytes > 0 ? "+" : ""}${formatBytes(bytes, units)}`);
764
- if (files !== 0) parts.push(`${files > 0 ? "+" : ""}${formatCount(files)} files`);
1437
+ if (files !== 0) parts.push(`${files > 0 ? "+" : ""}${formatCount(files)} ${Math.abs(files) === 1 ? "file" : "files"}`);
765
1438
  return parts.join(", ");
766
1439
  }
767
1440
  //#endregion
@@ -818,7 +1491,7 @@ var Context = class {
818
1491
  //#region src/cli/program.ts
819
1492
  function createProgram(ctx) {
820
1493
  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({
1494
+ const program = new Command("dat").description("Fast, zero-dependency 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
1495
  writeOut: (text) => io.stdout.write(text),
823
1496
  writeErr: (text) => io.stderr.write(text),
824
1497
  outputError: (text, write) => write(ctx.err.red(text))
@@ -841,7 +1514,7 @@ async function run(argv, io = processIO()) {
841
1514
  const ctx = new Context(io);
842
1515
  const program = createProgram(ctx);
843
1516
  try {
844
- await program.parseAsync(normalizeArgv(argv), { from: "user" });
1517
+ await program.parseAsync(normalizeArgv(argv, io.cwd), { from: "user" });
845
1518
  return ctx.exitCode;
846
1519
  } catch (error) {
847
1520
  return handleError(error, ctx);