dir-analysis-tool 1.0.5 → 2.0.6

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.
Files changed (56) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +195 -278
  3. package/dist/index.js +1310 -0
  4. package/package.json +42 -25
  5. package/bin/advanced-analysis.d.ts +0 -43
  6. package/bin/advanced-analysis.d.ts.map +0 -1
  7. package/bin/advanced-analysis.js +0 -185
  8. package/bin/advanced-analysis.js.map +0 -1
  9. package/bin/analyzer.d.ts +0 -40
  10. package/bin/analyzer.d.ts.map +0 -1
  11. package/bin/analyzer.js +0 -199
  12. package/bin/analyzer.js.map +0 -1
  13. package/bin/classifier.d.ts +0 -27
  14. package/bin/classifier.d.ts.map +0 -1
  15. package/bin/classifier.js +0 -63
  16. package/bin/classifier.js.map +0 -1
  17. package/bin/cli.d.ts +0 -2
  18. package/bin/cli.d.ts.map +0 -1
  19. package/bin/cli.js +0 -395
  20. package/bin/cli.js.map +0 -1
  21. package/bin/config.d.ts +0 -10
  22. package/bin/config.d.ts.map +0 -1
  23. package/bin/config.js +0 -94
  24. package/bin/config.js.map +0 -1
  25. package/bin/export.d.ts +0 -20
  26. package/bin/export.d.ts.map +0 -1
  27. package/bin/export.js +0 -51
  28. package/bin/export.js.map +0 -1
  29. package/bin/html-report.d.ts +0 -12
  30. package/bin/html-report.d.ts.map +0 -1
  31. package/bin/html-report.js +0 -691
  32. package/bin/html-report.js.map +0 -1
  33. package/bin/index.d.ts +0 -3
  34. package/bin/index.d.ts.map +0 -1
  35. package/bin/index.js +0 -5
  36. package/bin/index.js.map +0 -1
  37. package/bin/interactive.d.ts +0 -27
  38. package/bin/interactive.d.ts.map +0 -1
  39. package/bin/interactive.js +0 -635
  40. package/bin/interactive.js.map +0 -1
  41. package/bin/progress.d.ts +0 -9
  42. package/bin/progress.d.ts.map +0 -1
  43. package/bin/progress.js +0 -42
  44. package/bin/progress.js.map +0 -1
  45. package/bin/tree-view.d.ts +0 -21
  46. package/bin/tree-view.d.ts.map +0 -1
  47. package/bin/tree-view.js +0 -132
  48. package/bin/tree-view.js.map +0 -1
  49. package/bin/types.d.ts +0 -43
  50. package/bin/types.d.ts.map +0 -1
  51. package/bin/types.js +0 -3
  52. package/bin/types.js.map +0 -1
  53. package/bin/utils.d.ts +0 -24
  54. package/bin/utils.d.ts.map +0 -1
  55. package/bin/utils.js +0 -57
  56. package/bin/utils.js.map +0 -1
package/dist/index.js ADDED
@@ -0,0 +1,1310 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command as Command5 } from "commander";
5
+
6
+ // src/commands/analyze.ts
7
+ import { Command } from "commander";
8
+ import { resolve } from "path";
9
+ import chalk2 from "chalk";
10
+
11
+ // src/core/analyzer.ts
12
+ import { stat as stat3 } from "fs/promises";
13
+ import { relative, basename, sep } from "path";
14
+ import prettyBytes2 from "pretty-bytes";
15
+
16
+ // src/core/walker.ts
17
+ import { opendir, stat } from "fs/promises";
18
+ import { join } from "path";
19
+ var DEFAULT_EXCLUDE_DIRS = /* @__PURE__ */ new Set([
20
+ "node_modules",
21
+ ".git",
22
+ ".svn",
23
+ ".hg",
24
+ "dist",
25
+ "build",
26
+ ".cache"
27
+ ]);
28
+ function matchPattern(name, pattern) {
29
+ if (pattern.includes("*")) {
30
+ const regex = new RegExp("^" + pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
31
+ return regex.test(name);
32
+ }
33
+ return name === pattern || name.endsWith(pattern);
34
+ }
35
+ function shouldExcludeDir(name, userExcludes, clearDefaults) {
36
+ if (!clearDefaults && DEFAULT_EXCLUDE_DIRS.has(name)) return true;
37
+ return userExcludes.some((p) => matchPattern(name, p));
38
+ }
39
+ function shouldExcludeFile(name, userExcludes) {
40
+ return userExcludes.some((p) => matchPattern(name, p));
41
+ }
42
+ async function* walk(root, opts = {}, depth = 0) {
43
+ const {
44
+ maxDepth = -1,
45
+ excludeDirs = [],
46
+ excludeFiles = [],
47
+ recursive = true,
48
+ clearDefaultExclusions = false
49
+ } = opts;
50
+ if (maxDepth >= 0 && depth > maxDepth) return;
51
+ let dir;
52
+ try {
53
+ dir = await opendir(root);
54
+ } catch {
55
+ return;
56
+ }
57
+ for await (const entry of dir) {
58
+ const fullPath = join(root, entry.name);
59
+ if (entry.isDirectory()) {
60
+ if (!recursive) continue;
61
+ if (shouldExcludeDir(entry.name, excludeDirs, clearDefaultExclusions)) continue;
62
+ yield { kind: "dir", path: fullPath, name: entry.name };
63
+ yield* walk(fullPath, opts, depth + 1);
64
+ } else if (entry.isFile()) {
65
+ if (shouldExcludeFile(entry.name, excludeFiles)) continue;
66
+ try {
67
+ const s = await stat(fullPath);
68
+ yield {
69
+ kind: "file",
70
+ path: fullPath,
71
+ name: entry.name,
72
+ size: s.size,
73
+ mtime: s.mtime,
74
+ ctime: s.birthtime
75
+ };
76
+ } catch {
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+ // src/core/classifier.ts
83
+ var FILE_TYPE_EXTENSIONS = {
84
+ images: [".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp", ".tiff", ".ico", ".avif", ".heic"],
85
+ videos: [".mp4", ".mkv", ".avi", ".mov", ".webm", ".flv", ".wmv", ".m4v", ".3gp", ".ogv"],
86
+ documents: [
87
+ ".pdf",
88
+ ".docx",
89
+ ".xlsx",
90
+ ".pptx",
91
+ ".txt",
92
+ ".doc",
93
+ ".xls",
94
+ ".ppt",
95
+ ".rtf",
96
+ ".odt",
97
+ ".ods",
98
+ ".odp",
99
+ ".md",
100
+ ".rst",
101
+ ".tex",
102
+ ".epub"
103
+ ],
104
+ audio: [".mp3", ".wav", ".flac", ".aac", ".ogg", ".wma", ".m4a", ".opus", ".aiff"],
105
+ code: [
106
+ ".js",
107
+ ".ts",
108
+ ".jsx",
109
+ ".tsx",
110
+ ".mjs",
111
+ ".cjs",
112
+ ".py",
113
+ ".java",
114
+ ".cpp",
115
+ ".c",
116
+ ".h",
117
+ ".hpp",
118
+ ".cs",
119
+ ".php",
120
+ ".rb",
121
+ ".go",
122
+ ".rs",
123
+ ".swift",
124
+ ".kt",
125
+ ".scala",
126
+ ".clj",
127
+ ".dart",
128
+ ".sh",
129
+ ".bash",
130
+ ".zsh",
131
+ ".bat",
132
+ ".ps1",
133
+ ".sql",
134
+ ".html",
135
+ ".css",
136
+ ".scss",
137
+ ".sass",
138
+ ".less",
139
+ ".json",
140
+ ".xml",
141
+ ".yaml",
142
+ ".yml",
143
+ ".toml",
144
+ ".ini",
145
+ ".cfg",
146
+ ".conf",
147
+ ".env",
148
+ ".vue",
149
+ ".svelte",
150
+ ".astro",
151
+ ".graphql",
152
+ ".proto",
153
+ ".dockerfile"
154
+ ],
155
+ archives: [".zip", ".rar", ".7z", ".tar", ".gz", ".bz2", ".xz", ".zst", ".lz4"]
156
+ };
157
+ var EXTENSION_MAP = /* @__PURE__ */ new Map();
158
+ for (const [type, exts] of Object.entries(FILE_TYPE_EXTENSIONS)) {
159
+ for (const ext of exts) {
160
+ EXTENSION_MAP.set(ext, type);
161
+ }
162
+ }
163
+ var FileClassifier = class {
164
+ counts = {
165
+ images: 0,
166
+ videos: 0,
167
+ documents: 0,
168
+ audio: 0,
169
+ code: 0,
170
+ archives: 0,
171
+ other: 0
172
+ };
173
+ classifyFile(filename) {
174
+ const dot = filename.lastIndexOf(".");
175
+ const ext = dot === -1 || dot === filename.length - 1 ? "" : filename.slice(dot).toLowerCase();
176
+ const type = EXTENSION_MAP.get(ext) ?? "other";
177
+ this.counts[type]++;
178
+ }
179
+ getClassification() {
180
+ return { ...this.counts };
181
+ }
182
+ reset() {
183
+ this.counts = { images: 0, videos: 0, documents: 0, audio: 0, code: 0, archives: 0, other: 0 };
184
+ }
185
+ };
186
+
187
+ // src/core/detectors.ts
188
+ import { stat as stat2 } from "fs/promises";
189
+ import prettyBytes from "pretty-bytes";
190
+
191
+ // src/core/hasher.ts
192
+ import { createHash } from "crypto";
193
+ import { createReadStream } from "fs";
194
+ async function hashFile(filePath) {
195
+ const hash = createHash("md5");
196
+ await new Promise((resolve4, reject) => {
197
+ const stream = createReadStream(filePath);
198
+ stream.on("data", (chunk) => hash.update(chunk));
199
+ stream.on("end", resolve4);
200
+ stream.on("error", reject);
201
+ });
202
+ return hash.digest("hex");
203
+ }
204
+
205
+ // src/core/detectors.ts
206
+ var HASH_BATCH_SIZE = 20;
207
+ async function detectDuplicates(filePaths, onProgress) {
208
+ const hashMap = /* @__PURE__ */ new Map();
209
+ const total = filePaths.length;
210
+ let done = 0;
211
+ for (let i = 0; i < filePaths.length; i += HASH_BATCH_SIZE) {
212
+ const batch = filePaths.slice(i, i + HASH_BATCH_SIZE);
213
+ await Promise.all(
214
+ batch.map(async (filePath) => {
215
+ try {
216
+ const hash = await hashFile(filePath);
217
+ const existing = hashMap.get(hash) ?? [];
218
+ existing.push(filePath);
219
+ hashMap.set(hash, existing);
220
+ } catch {
221
+ } finally {
222
+ done++;
223
+ onProgress?.(done, total);
224
+ }
225
+ })
226
+ );
227
+ }
228
+ const groups = [];
229
+ for (const [hash, files] of hashMap) {
230
+ if (files.length < 2) continue;
231
+ try {
232
+ const { size } = await stat2(files[0]);
233
+ const wastedSpace = size * (files.length - 1);
234
+ groups.push({
235
+ hash,
236
+ size,
237
+ sizeFormatted: prettyBytes(size),
238
+ files,
239
+ wastedSpace,
240
+ wastedSpaceFormatted: prettyBytes(wastedSpace)
241
+ });
242
+ } catch {
243
+ }
244
+ }
245
+ return groups.sort((a, b) => b.wastedSpace - a.wastedSpace);
246
+ }
247
+ function detectLargeFiles(files, thresholdBytes) {
248
+ return files.filter((f) => f.size >= thresholdBytes).sort((a, b) => b.size - a.size).map((f) => ({ path: f.path, size: f.size, sizeFormatted: prettyBytes(f.size) }));
249
+ }
250
+ function getTopLargestFiles(files, n) {
251
+ return [...files].sort((a, b) => b.size - a.size).slice(0, n).map((f) => ({ path: f.path, size: f.size, sizeFormatted: prettyBytes(f.size) }));
252
+ }
253
+ function detectEmptyFiles(files) {
254
+ return files.filter((f) => f.size === 0).sort((a, b) => b.mtime.getTime() - a.mtime.getTime()).map((f) => ({ path: f.path, mtime: f.mtime }));
255
+ }
256
+
257
+ // src/core/analyzer.ts
258
+ async function analyze(options) {
259
+ const s = await stat3(options.path).catch(() => {
260
+ throw new Error(`Cannot access path: ${options.path}`);
261
+ });
262
+ if (!s.isDirectory()) {
263
+ throw new Error(`Not a directory: ${options.path}`);
264
+ }
265
+ const classifier = new FileClassifier();
266
+ let totalSize = 0;
267
+ let fileCount = 0;
268
+ let folderCount = 0;
269
+ const allFiles = [];
270
+ for await (const entry of walk(options.path, {
271
+ recursive: options.recursive ?? true,
272
+ maxDepth: options.maxDepth,
273
+ excludeDirs: options.excludePatterns ?? [],
274
+ clearDefaultExclusions: options.clearDefaultExclusions ?? false
275
+ })) {
276
+ if (entry.kind === "dir") {
277
+ folderCount++;
278
+ continue;
279
+ }
280
+ if (options.minSize !== void 0 && entry.size < options.minSize) continue;
281
+ if (options.maxSize !== void 0 && entry.size > options.maxSize) continue;
282
+ if (options.dateFrom && entry.mtime < options.dateFrom) continue;
283
+ if (options.dateTo && entry.mtime > options.dateTo) continue;
284
+ totalSize += entry.size;
285
+ fileCount++;
286
+ classifier.classifyFile(entry.name);
287
+ allFiles.push({ path: entry.path, name: entry.name, size: entry.size, mtime: entry.mtime });
288
+ options.onProgress?.(fileCount, entry.path);
289
+ }
290
+ const result = {
291
+ path: options.path,
292
+ totalSizeBytes: totalSize,
293
+ totalSizeFormatted: prettyBytes2(totalSize),
294
+ totalSizeMB: Math.round(totalSize / (1024 * 1024) * 10) / 10,
295
+ folders: folderCount,
296
+ files: fileCount,
297
+ types: classifier.getClassification()
298
+ };
299
+ const thresholdBytes = options.largeSizeThresholdMB !== void 0 ? options.largeSizeThresholdMB * 1024 * 1024 : void 0;
300
+ if (thresholdBytes !== void 0) {
301
+ result.largeFiles = detectLargeFiles(allFiles, thresholdBytes);
302
+ }
303
+ if (options.enableDuplicateDetection && allFiles.length > 0) {
304
+ result.duplicateGroups = await detectDuplicates(
305
+ allFiles.map((f) => f.path),
306
+ options.onHashProgress
307
+ );
308
+ if (result.duplicateGroups.length > 0) {
309
+ const wastedSpace = result.duplicateGroups.reduce((sum, g) => sum + g.wastedSpace, 0);
310
+ result.duplicateStats = {
311
+ totalGroups: result.duplicateGroups.length,
312
+ wastedSpace,
313
+ wastedSpaceFormatted: prettyBytes2(wastedSpace)
314
+ };
315
+ }
316
+ }
317
+ if (options.topN && options.topN > 0) {
318
+ result.topLargestFiles = getTopLargestFiles(allFiles, options.topN);
319
+ }
320
+ if (options.showEmptyFiles) {
321
+ result.emptyFiles = detectEmptyFiles(allFiles);
322
+ }
323
+ if (allFiles.length <= 1e3) {
324
+ result.treeView = buildTreeView(allFiles, options.path);
325
+ }
326
+ return result;
327
+ }
328
+ function buildTreeView(files, root) {
329
+ const rootNode = { name: basename(root) || root, isDir: true, size: 0, children: /* @__PURE__ */ new Map() };
330
+ for (const file of files) {
331
+ const rel = relative(root, file.path);
332
+ if (!rel || rel === ".") continue;
333
+ const parts = rel.split(sep);
334
+ let node = rootNode;
335
+ for (let i = 0; i < parts.length - 1; i++) {
336
+ const part = parts[i];
337
+ if (!node.children.has(part)) {
338
+ node.children.set(part, { name: part, isDir: true, size: 0, children: /* @__PURE__ */ new Map() });
339
+ }
340
+ node = node.children.get(part);
341
+ }
342
+ const fileName = parts[parts.length - 1];
343
+ node.children.set(fileName, {
344
+ name: fileName,
345
+ isDir: false,
346
+ size: file.size,
347
+ children: /* @__PURE__ */ new Map()
348
+ });
349
+ }
350
+ const lines = [];
351
+ renderNode(rootNode, "", true, lines, 0);
352
+ return lines.join("\n");
353
+ }
354
+ function renderNode(node, prefix, isLast, lines, depth) {
355
+ if (depth > 10) return;
356
+ const connector = depth === 0 ? "" : isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
357
+ const icon = node.isDir ? "\u{1F4C1}" : "\u{1F4C4}";
358
+ const size = node.isDir ? "" : ` (${prettyBytes2(node.size)})`;
359
+ lines.push(`${prefix}${connector}${icon} ${node.name}${size}`);
360
+ const children = [...node.children.values()].sort((a, b) => {
361
+ if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
362
+ return a.name.localeCompare(b.name);
363
+ });
364
+ const newPrefix = depth === 0 ? "" : prefix + (isLast ? " " : "\u2502 ");
365
+ for (let i = 0; i < children.length; i++) {
366
+ renderNode(children[i], newPrefix, i === children.length - 1, lines, depth + 1);
367
+ }
368
+ }
369
+
370
+ // src/config.ts
371
+ import { readFileSync } from "fs";
372
+ import { access, constants } from "fs/promises";
373
+ import { join as join2, dirname } from "path";
374
+ import { z } from "zod";
375
+ var CONFIG_FILE_NAMES = [".dir-analyzer.json", "dir-analyzer.config.json"];
376
+ var ConfigSchema = z.object({
377
+ excludePatterns: z.array(z.string()).optional(),
378
+ clearDefaultExclusions: z.boolean().optional(),
379
+ largeSizeThresholdMB: z.number().optional(),
380
+ enableDuplicateDetection: z.boolean().optional(),
381
+ maxDepth: z.number().int().optional(),
382
+ topN: z.number().int().optional(),
383
+ showEmptyFiles: z.boolean().optional()
384
+ });
385
+ async function findConfigFile(startPath) {
386
+ let current = startPath;
387
+ while (true) {
388
+ for (const name of CONFIG_FILE_NAMES) {
389
+ const candidate = join2(current, name);
390
+ try {
391
+ await access(candidate, constants.F_OK);
392
+ return candidate;
393
+ } catch {
394
+ }
395
+ }
396
+ const parent = dirname(current);
397
+ if (parent === current) break;
398
+ current = parent;
399
+ }
400
+ return null;
401
+ }
402
+ async function loadConfig(searchPath) {
403
+ const configPath = await findConfigFile(searchPath ?? process.cwd());
404
+ if (!configPath) return {};
405
+ try {
406
+ const raw = JSON.parse(readFileSync(configPath, "utf-8"));
407
+ const parsed = ConfigSchema.safeParse(raw);
408
+ if (!parsed.success) {
409
+ console.warn(`Warning: invalid config at ${configPath} \u2014 using defaults`);
410
+ return {};
411
+ }
412
+ return parsed.data;
413
+ } catch {
414
+ console.warn(`Warning: could not read config at ${configPath}`);
415
+ return {};
416
+ }
417
+ }
418
+ function mergeConfig(fileConfig, cliOptions) {
419
+ const merged = { ...fileConfig };
420
+ for (const [key, value] of Object.entries(cliOptions)) {
421
+ if (value !== void 0 && value !== null) {
422
+ merged[key] = value;
423
+ }
424
+ }
425
+ return merged;
426
+ }
427
+
428
+ // src/reporters/console.ts
429
+ import { relative as relative2 } from "path";
430
+ import chalk from "chalk";
431
+ import prettyBytes3 from "pretty-bytes";
432
+ var ICONS = {
433
+ folder: "\u{1F4C2}",
434
+ package: "\u{1F4E6}",
435
+ folderIcon: "\u{1F4C1}",
436
+ fileIcon: "\u{1F4C4}",
437
+ types: "\u{1F5C2}",
438
+ images: "\u{1F4F7}",
439
+ videos: "\u{1F3AC}",
440
+ documents: "\u{1F4C4}",
441
+ audio: "\u{1F3B5}",
442
+ code: "\u{1F9D1}\u200D\u{1F4BB}",
443
+ archives: "\u{1F5C3}\uFE0F",
444
+ other: "\u2753",
445
+ largeFile: "\u{1F6A8}",
446
+ duplicates: "\u{1F504}",
447
+ empty: "\u{1F4ED}"
448
+ };
449
+ function printResult(result, opts = {}) {
450
+ if (opts.treeView) {
451
+ printTreeOutput(result);
452
+ } else {
453
+ printSummary(result, opts.showTypes ?? true);
454
+ }
455
+ }
456
+ function printSummary(result, showTypes) {
457
+ console.log(chalk.blue(`${ICONS.folder} Directory: ${result.path}`));
458
+ console.log(chalk.green(`${ICONS.package} Total Size: ${result.totalSizeFormatted}`));
459
+ console.log(chalk.yellow(`${ICONS.folderIcon} Folders: ${result.folders.toLocaleString()}`));
460
+ console.log(chalk.cyan(`${ICONS.fileIcon} Files: ${result.files.toLocaleString()}`));
461
+ if (showTypes) {
462
+ const entries = [
463
+ { key: "images", icon: ICONS.images, label: "Images" },
464
+ { key: "videos", icon: ICONS.videos, label: "Videos" },
465
+ { key: "documents", icon: ICONS.documents, label: "Documents" },
466
+ { key: "audio", icon: ICONS.audio, label: "Audio" },
467
+ { key: "code", icon: ICONS.code, label: "Code" },
468
+ { key: "archives", icon: ICONS.archives, label: "Archives" },
469
+ { key: "other", icon: ICONS.other, label: "Other" }
470
+ ];
471
+ const hasTypes = entries.some(({ key }) => result.types[key] > 0);
472
+ if (hasTypes) {
473
+ console.log(chalk.magenta(`
474
+ ${ICONS.types} File Types:`));
475
+ for (const { key, icon, label } of entries) {
476
+ const count = result.types[key];
477
+ if (count > 0) {
478
+ console.log(` ${icon} ${label}: ${count.toLocaleString()}`);
479
+ }
480
+ }
481
+ }
482
+ }
483
+ printLargeFiles(result);
484
+ printDuplicates(result);
485
+ printTopLargest(result);
486
+ printEmptyFiles(result);
487
+ }
488
+ function printTreeOutput(result) {
489
+ console.log(chalk.blue(`${ICONS.folder} Directory Tree: ${result.path}`));
490
+ console.log(chalk.green(`${ICONS.package} Total Size: ${result.totalSizeFormatted}`));
491
+ console.log(chalk.yellow(`${ICONS.folderIcon} Folders: ${result.folders.toLocaleString()}`));
492
+ console.log(chalk.cyan(`${ICONS.fileIcon} Files: ${result.files.toLocaleString()}
493
+ `));
494
+ if (result.treeView) {
495
+ console.log(result.treeView);
496
+ } else {
497
+ console.log(chalk.yellow("Tree view not available for large datasets (>1000 files)."));
498
+ console.log("Use --top-n to see the largest files instead.\n");
499
+ }
500
+ printTopLargest(result);
501
+ printEmptyFiles(result);
502
+ }
503
+ function printLargeFiles(result) {
504
+ if (!result.largeFiles || result.largeFiles.length === 0) return;
505
+ const shown = Math.min(5, result.largeFiles.length);
506
+ console.log(chalk.red(`
507
+ ${ICONS.largeFile} Large Files (showing ${shown} of ${result.largeFiles.length}):`));
508
+ for (const file of result.largeFiles.slice(0, 5)) {
509
+ const rel = relative2(result.path, file.path);
510
+ console.log(` \u{1F4C1} ${rel} \u2014 ${chalk.yellow(file.sizeFormatted)}`);
511
+ }
512
+ if (result.largeFiles.length > 5) {
513
+ console.log(chalk.gray(` \u2026 and ${result.largeFiles.length - 5} more. Use --html to see all.`));
514
+ }
515
+ }
516
+ function printDuplicates(result) {
517
+ if (!result.duplicateStats || result.duplicateStats.totalGroups === 0) return;
518
+ console.log(chalk.yellow(`
519
+ ${ICONS.duplicates} Duplicate Files:`));
520
+ console.log(` Groups: ${result.duplicateStats.totalGroups}`);
521
+ console.log(` Wasted Space: ${chalk.red(result.duplicateStats.wastedSpaceFormatted)}`);
522
+ if (result.duplicateGroups && result.duplicateGroups.length > 0) {
523
+ console.log(chalk.gray("\n Top duplicate groups:"));
524
+ for (const [i, group] of result.duplicateGroups.slice(0, 3).entries()) {
525
+ console.log(` ${i + 1}. ${group.sizeFormatted} each \xD7 ${group.files.length} copies`);
526
+ for (const file of group.files.slice(0, 2)) {
527
+ console.log(` \u{1F4C4} ${relative2(result.path, file)}`);
528
+ }
529
+ if (group.files.length > 2) {
530
+ console.log(chalk.gray(` \u2026 and ${group.files.length - 2} more`));
531
+ }
532
+ }
533
+ }
534
+ }
535
+ function printTopLargest(result) {
536
+ if (!result.topLargestFiles || result.topLargestFiles.length === 0) return;
537
+ console.log(chalk.red(`
538
+ ${ICONS.largeFile} Top ${result.topLargestFiles.length} Largest Files:`));
539
+ for (const [i, file] of result.topLargestFiles.entries()) {
540
+ const rel = relative2(result.path, file.path);
541
+ console.log(` ${chalk.gray(`${i + 1}.`)} ${rel} \u2014 ${chalk.yellow(file.sizeFormatted)}`);
542
+ }
543
+ }
544
+ function printEmptyFiles(result) {
545
+ if (!result.emptyFiles || result.emptyFiles.length === 0) return;
546
+ const shown = Math.min(10, result.emptyFiles.length);
547
+ console.log(chalk.yellow(`
548
+ ${ICONS.empty} Empty Files (${result.emptyFiles.length}):`));
549
+ for (const file of result.emptyFiles.slice(0, shown)) {
550
+ const rel = relative2(result.path, file.path);
551
+ const date = file.mtime.toLocaleDateString();
552
+ console.log(` \u{1F4C4} ${rel} ${chalk.gray(`(modified: ${date})`)}`);
553
+ }
554
+ if (result.emptyFiles.length > shown) {
555
+ console.log(chalk.gray(` \u2026 and ${result.emptyFiles.length - shown} more`));
556
+ }
557
+ }
558
+ function printComparison(a, b) {
559
+ const col = 28;
560
+ const header = (label) => chalk.bold.blue(label.padEnd(col));
561
+ const val = (v) => String(v).padStart(16);
562
+ console.log(`
563
+ ${chalk.bold("Directory Comparison")}`);
564
+ console.log(chalk.gray("\u2500".repeat(80)));
565
+ const pathA = a.path.length > col - 2 ? "\u2026" + a.path.slice(-(col - 3)) : a.path;
566
+ const pathB = b.path.length > col - 2 ? "\u2026" + b.path.slice(-(col - 3)) : b.path;
567
+ console.log(`${header("Path")}${val(pathA)} ${val(pathB)}`);
568
+ console.log(chalk.gray("\u2500".repeat(80)));
569
+ const row = (label, va, vb) => {
570
+ console.log(`${label.padEnd(col)}${val(va)} ${val(vb)}`);
571
+ };
572
+ row("Total Size", a.totalSizeFormatted, b.totalSizeFormatted);
573
+ row("Files", a.files.toLocaleString(), b.files.toLocaleString());
574
+ row("Folders", a.folders.toLocaleString(), b.folders.toLocaleString());
575
+ row("Images", a.types.images, b.types.images);
576
+ row("Videos", a.types.videos, b.types.videos);
577
+ row("Documents", a.types.documents, b.types.documents);
578
+ row("Audio", a.types.audio, b.types.audio);
579
+ row("Code", a.types.code, b.types.code);
580
+ row("Archives", a.types.archives, b.types.archives);
581
+ row("Other", a.types.other, b.types.other);
582
+ console.log(chalk.gray("\u2500".repeat(80)));
583
+ const sizeDiff = a.totalSizeBytes - b.totalSizeBytes;
584
+ const fileDiff = a.files - b.files;
585
+ const sign = (n) => n > 0 ? "+" : "";
586
+ if (sizeDiff !== 0) {
587
+ const color = sizeDiff > 0 ? chalk.red : chalk.green;
588
+ console.log(`Size difference: ${color(`${sign(sizeDiff)}${prettyBytes3(Math.abs(sizeDiff))}`)}`);
589
+ }
590
+ if (fileDiff !== 0) {
591
+ const color = fileDiff > 0 ? chalk.red : chalk.green;
592
+ console.log(`File difference: ${color(`${sign(fileDiff)}${fileDiff}`)}`);
593
+ }
594
+ }
595
+
596
+ // src/reporters/csv.ts
597
+ import { writeFile } from "fs/promises";
598
+ function escape(value) {
599
+ const str = String(value);
600
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
601
+ return `"${str.replace(/"/g, '""')}"`;
602
+ }
603
+ return str;
604
+ }
605
+ function buildAnalysisCsv(result) {
606
+ const lines = ["Type,Path,Size (Bytes),Size (Formatted),Count,Details"];
607
+ lines.push(
608
+ [
609
+ "Summary",
610
+ escape(result.path),
611
+ result.totalSizeBytes,
612
+ escape(`${result.totalSizeMB}MB`),
613
+ result.files,
614
+ escape(`Folders: ${result.folders}`)
615
+ ].join(",")
616
+ );
617
+ for (const [type, count] of Object.entries(result.types)) {
618
+ if (count > 0) {
619
+ lines.push(["FileType", escape(type), "-", "-", count, "-"].join(","));
620
+ }
621
+ }
622
+ for (const file of result.largeFiles ?? []) {
623
+ lines.push(["LargeFile", escape(file.path), file.size, escape(file.sizeFormatted), 1, "-"].join(","));
624
+ }
625
+ for (const [i, group] of (result.duplicateGroups ?? []).entries()) {
626
+ for (const [j, file] of group.files.entries()) {
627
+ const details = j === 0 ? escape(`Group ${i + 1}, files: ${group.files.length}, wasted: ${group.wastedSpaceFormatted}`) : escape(`Group ${i + 1} (duplicate)`);
628
+ lines.push(["Duplicate", escape(file), group.size, escape(group.sizeFormatted), 1, details].join(","));
629
+ }
630
+ }
631
+ return lines.join("\n");
632
+ }
633
+ function buildLargeFilesCsv(result) {
634
+ const lines = ["Path,Size (Bytes),Size (Formatted)"];
635
+ for (const file of result.largeFiles ?? []) {
636
+ lines.push([escape(file.path), file.size, escape(file.sizeFormatted)].join(","));
637
+ }
638
+ return lines.join("\n");
639
+ }
640
+ function buildDuplicatesCsv(result) {
641
+ const lines = ["Group,Path,Size (Bytes),Size (Formatted),Files in Group,Wasted Space"];
642
+ for (const [i, group] of (result.duplicateGroups ?? []).entries()) {
643
+ for (const file of group.files) {
644
+ lines.push(
645
+ [
646
+ i + 1,
647
+ escape(file),
648
+ group.size,
649
+ escape(group.sizeFormatted),
650
+ group.files.length,
651
+ escape(group.wastedSpaceFormatted)
652
+ ].join(",")
653
+ );
654
+ }
655
+ }
656
+ return lines.join("\n");
657
+ }
658
+ async function writeCsvFiles(result, opts) {
659
+ if (opts.csv) {
660
+ const filename = typeof opts.csv === "string" ? opts.csv : "directory-analysis.csv";
661
+ await writeFile(filename, buildAnalysisCsv(result));
662
+ console.log(`\u{1F4C4} Analysis exported to: ${filename}`);
663
+ }
664
+ if (opts.csvLarge && result.largeFiles && result.largeFiles.length > 0) {
665
+ const filename = typeof opts.csvLarge === "string" ? opts.csvLarge : "large-files.csv";
666
+ await writeFile(filename, buildLargeFilesCsv(result));
667
+ console.log(`\u{1F4C4} Large files exported to: ${filename}`);
668
+ }
669
+ if (opts.csvDuplicates && result.duplicateGroups && result.duplicateGroups.length > 0) {
670
+ const filename = typeof opts.csvDuplicates === "string" ? opts.csvDuplicates : "duplicates.csv";
671
+ await writeFile(filename, buildDuplicatesCsv(result));
672
+ console.log(`\u{1F4C4} Duplicates exported to: ${filename}`);
673
+ }
674
+ }
675
+
676
+ // src/reporters/html.ts
677
+ import { writeFile as writeFile2, stat as stat4 } from "fs/promises";
678
+ import { join as join3 } from "path";
679
+ function escape2(text2) {
680
+ return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
681
+ }
682
+ function countNonZeroTypes(types) {
683
+ return Object.values(types).filter((v) => v > 0).length;
684
+ }
685
+ function typeChartData(types) {
686
+ const mapping = {
687
+ code: "\u{1F9D1}\u200D\u{1F4BB} Code",
688
+ images: "\u{1F4F7} Images",
689
+ documents: "\u{1F4C4} Documents",
690
+ videos: "\u{1F3AC} Videos",
691
+ audio: "\u{1F3B5} Audio",
692
+ archives: "\u{1F5C3}\uFE0F Archives",
693
+ other: "\u2753 Other"
694
+ };
695
+ const labels = [];
696
+ const data = [];
697
+ for (const [k, v] of Object.entries(types)) {
698
+ if (v > 0) {
699
+ labels.push(mapping[k]);
700
+ data.push(v);
701
+ }
702
+ }
703
+ return { labels, data };
704
+ }
705
+ function largestFilesChartData(files) {
706
+ if (!files?.length) return { labels: [], data: [] };
707
+ return {
708
+ labels: files.map((f) => {
709
+ const name = f.path.split(/[/\\]/).pop() ?? f.path;
710
+ return name.length > 20 ? name.slice(0, 17) + "\u2026" : name;
711
+ }),
712
+ data: files.map((f) => f.size)
713
+ };
714
+ }
715
+ function generateHTML(result) {
716
+ const typeData = typeChartData(result.types);
717
+ const largestData = largestFilesChartData(result.topLargestFiles);
718
+ const version = true ? "2.0.6" : "2.0.0";
719
+ return `<!DOCTYPE html>
720
+ <html lang="en">
721
+ <head>
722
+ <meta charset="UTF-8">
723
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
724
+ <title>Directory Analysis \u2014 ${escape2(result.path)}</title>
725
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
726
+ <style>
727
+ * { margin: 0; padding: 0; box-sizing: border-box; }
728
+ body { font-family: 'Fira Code', 'Consolas', 'Monaco', monospace; color: #00ff00; background: #0a0a0a;
729
+ background-image: linear-gradient(90deg, rgba(0,255,0,.03) 1px, transparent 1px),
730
+ linear-gradient(rgba(0,255,0,.03) 1px, transparent 1px);
731
+ background-size: 20px 20px; }
732
+ .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
733
+ .header { background: #1a1a1a; padding: 30px; border: 2px solid #00ff00;
734
+ border-radius: 8px; box-shadow: 0 0 20px rgba(0,255,0,.3); margin-bottom: 30px; text-align: center; position: relative; }
735
+ .header::before { content: '> '; position: absolute; left: 15px; top: 15px; color: #00ff00; font-weight: bold; }
736
+ .header h1 { font-size: 2.5em; margin-bottom: 10px; color: #00ff00; text-shadow: 0 0 10px rgba(0,255,0,.5); }
737
+ .path { font-size: 1.1em; color: #00cccc; margin-bottom: 4px; word-break: break-all; }
738
+ .timestamp { color: #666; font-size: 0.9em; }
739
+ .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 30px; }
740
+ .card { background: #1a1a1a; padding: 25px; border: 1px solid #333; border-radius: 8px;
741
+ box-shadow: 0 0 15px rgba(0,255,0,.1); display: flex; align-items: center;
742
+ transition: all .3s; position: relative; }
743
+ .card::before { content: '$ '; position: absolute; left: 10px; top: 10px; color: #00ff00; font-size: .9em; }
744
+ .card:hover { border-color: #00ff00; box-shadow: 0 0 25px rgba(0,255,0,.3); transform: translateY(-2px); }
745
+ .card-icon { font-size: 2.5em; margin-right: 15px; filter: grayscale(1) brightness(1.5); }
746
+ .card-label { color: #00cccc; font-size: .85em; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; }
747
+ .card-value { font-size: 1.8em; font-weight: bold; color: #00ff00; text-shadow: 0 0 5px rgba(0,255,0,.5); }
748
+ .charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); gap: 30px; margin-bottom: 30px; }
749
+ .section { background: #1a1a1a; padding: 25px; border: 1px solid #333; border-radius: 8px;
750
+ box-shadow: 0 0 15px rgba(0,255,0,.1); margin-bottom: 30px; position: relative; }
751
+ .section::before { content: '>> '; position: absolute; left: 10px; top: 10px; color: #00ff00; font-size: .9em; }
752
+ .section h2 { margin-bottom: 20px; color: #00ff00; border-bottom: 2px solid #00ff00;
753
+ padding-bottom: 10px; text-transform: uppercase; letter-spacing: 1px; }
754
+ .chart-wrap { position: relative; height: 300px; }
755
+ table { width: 100%; border-collapse: collapse; margin-top: 10px; }
756
+ th, td { padding: 12px; text-align: left; border-bottom: 1px solid #333; }
757
+ th { background: #0d0d0d; color: #00cccc; text-transform: uppercase; letter-spacing: 1px; font-size: .85em; }
758
+ tr:hover { background: #2a2a2a; }
759
+ .mono { font-family: 'Fira Code', monospace; font-size: .9em; color: #00ff00; word-break: break-all; }
760
+ .size { color: #ff6b6b; font-weight: bold; }
761
+ .date { color: #666; }
762
+ .dup-group { border: 1px solid #333; border-radius: 4px; margin-bottom: 15px; padding: 15px; background: #0d0d0d; }
763
+ .dup-group h4 { color: #00cccc; margin-bottom: 8px; }
764
+ .dup-list { list-style: none; }
765
+ .dup-list li { padding: 3px 0; font-size: .9em; color: #00ff00; }
766
+ .dup-list li::before { content: ' \u2013 '; color: #666; }
767
+ .more { color: #666; font-style: italic; }
768
+ footer { text-align: center; padding: 20px; color: #666; font-size: .9em; border-top: 1px solid #333; margin-top: 30px; }
769
+ footer::before { content: '~$ '; color: #00ff00; }
770
+ @media (max-width: 768px) {
771
+ .container { padding: 10px; }
772
+ .header h1 { font-size: 1.8em; }
773
+ .summary-grid, .charts { grid-template-columns: 1fr; }
774
+ .card { flex-direction: column; text-align: center; }
775
+ .card-icon { margin-right: 0; margin-bottom: 10px; }
776
+ }
777
+ </style>
778
+ </head>
779
+ <body>
780
+ <div class="container">
781
+ <header class="header">
782
+ <h1>\u{1F4C2} Directory Analysis Report</h1>
783
+ <p class="path">\u{1F4CD} ${escape2(result.path)}</p>
784
+ <p class="timestamp">\u{1F4C5} Generated ${(/* @__PURE__ */ new Date()).toLocaleString()}</p>
785
+ </header>
786
+
787
+ <div class="summary-grid">
788
+ <div class="card">
789
+ <div class="card-icon">\u{1F4E6}</div>
790
+ <div><div class="card-label">Total Size</div><div class="card-value">${escape2(result.totalSizeFormatted)}</div></div>
791
+ </div>
792
+ <div class="card">
793
+ <div class="card-icon">\u{1F4C4}</div>
794
+ <div><div class="card-label">Files</div><div class="card-value">${result.files.toLocaleString()}</div></div>
795
+ </div>
796
+ <div class="card">
797
+ <div class="card-icon">\u{1F4C1}</div>
798
+ <div><div class="card-label">Folders</div><div class="card-value">${result.folders.toLocaleString()}</div></div>
799
+ </div>
800
+ <div class="card">
801
+ <div class="card-icon">\u{1F5C2}\uFE0F</div>
802
+ <div><div class="card-label">File Types</div><div class="card-value">${countNonZeroTypes(result.types)}</div></div>
803
+ </div>
804
+ </div>
805
+
806
+ <div class="charts">
807
+ <div class="section">
808
+ <h2>\u{1F4CA} File Type Distribution</h2>
809
+ <div class="chart-wrap"><canvas id="typeChart"></canvas></div>
810
+ </div>
811
+ ${result.topLargestFiles?.length ? `
812
+ <div class="section">
813
+ <h2>\u{1F4C8} Largest Files</h2>
814
+ <div class="chart-wrap"><canvas id="largestChart"></canvas></div>
815
+ </div>` : ""}
816
+ </div>
817
+
818
+ ${result.largeFiles?.length ? `
819
+ <div class="section">
820
+ <h2>\u{1F6A8} Large Files</h2>
821
+ <div style="overflow-x:auto">
822
+ <table>
823
+ <thead><tr><th>File Path</th><th>Size</th></tr></thead>
824
+ <tbody>
825
+ ${result.largeFiles.slice(0, 50).map((f) => `
826
+ <tr>
827
+ <td class="mono">${escape2(f.path)}</td>
828
+ <td class="size">${escape2(f.sizeFormatted)}</td>
829
+ </tr>`).join("")}
830
+ </tbody>
831
+ </table>
832
+ </div>
833
+ </div>` : ""}
834
+
835
+ ${result.duplicateGroups?.length ? `
836
+ <div class="section">
837
+ <h2>\u{1F504} Duplicate Files</h2>
838
+ <p style="margin-bottom:15px">
839
+ Groups: <strong>${result.duplicateGroups.length}</strong>
840
+ ${result.duplicateStats ? ` &nbsp;|&nbsp; Wasted: <strong style="color:#ff6b6b">${escape2(result.duplicateStats.wastedSpaceFormatted)}</strong>` : ""}
841
+ </p>
842
+ ${result.duplicateGroups.slice(0, 10).map((group, i) => `
843
+ <div class="dup-group">
844
+ <h4>Group ${i + 1} \u2014 ${escape2(group.sizeFormatted)} each \xD7 ${group.files.length} files</h4>
845
+ <ul class="dup-list">
846
+ ${group.files.slice(0, 5).map((f) => `<li class="mono">${escape2(f)}</li>`).join("")}
847
+ ${group.files.length > 5 ? `<li class="more">\u2026 and ${group.files.length - 5} more</li>` : ""}
848
+ </ul>
849
+ </div>`).join("")}
850
+ </div>` : ""}
851
+
852
+ ${result.emptyFiles?.length ? `
853
+ <div class="section">
854
+ <h2>\u{1F4ED} Empty Files</h2>
855
+ <div style="overflow-x:auto">
856
+ <table>
857
+ <thead><tr><th>File Path</th><th>Modified</th></tr></thead>
858
+ <tbody>
859
+ ${result.emptyFiles.slice(0, 50).map((f) => `
860
+ <tr>
861
+ <td class="mono">${escape2(f.path)}</td>
862
+ <td class="date">${f.mtime.toLocaleDateString()}</td>
863
+ </tr>`).join("")}
864
+ </tbody>
865
+ </table>
866
+ </div>
867
+ </div>` : ""}
868
+
869
+ <footer>Generated by dir-analysis-tool v${escape2(version)}</footer>
870
+ </div>
871
+
872
+ <script>
873
+ (function() {
874
+ const COLORS = ['#00ff00','#00cccc','#ffff00','#ff6b6b','#9966ff','#ff9900','#66ff66','#ff3366'];
875
+ const CHART_DEFAULTS = {
876
+ responsive: true,
877
+ maintainAspectRatio: false,
878
+ plugins: {
879
+ legend: { labels: { color: '#00ff00', font: { family: 'Fira Code, monospace', size: 12 } } },
880
+ tooltip: {
881
+ backgroundColor: '#1a1a1a', titleColor: '#00ff00', bodyColor: '#00cccc',
882
+ borderColor: '#333', borderWidth: 1,
883
+ titleFont: { family: 'Fira Code, monospace' }, bodyFont: { family: 'Fira Code, monospace' },
884
+ }
885
+ }
886
+ };
887
+
888
+ const typeCtx = document.getElementById('typeChart');
889
+ if (typeCtx) {
890
+ new Chart(typeCtx, {
891
+ type: 'doughnut',
892
+ data: {
893
+ labels: ${JSON.stringify(typeData.labels)},
894
+ datasets: [{ data: ${JSON.stringify(typeData.data)}, backgroundColor: COLORS, borderColor: '#0a0a0a', borderWidth: 2 }]
895
+ },
896
+ options: { ...CHART_DEFAULTS, plugins: { ...CHART_DEFAULTS.plugins, legend: { ...CHART_DEFAULTS.plugins.legend, position: 'bottom' } } }
897
+ });
898
+ }
899
+
900
+ ${largestData.labels.length ? `
901
+ const largestCtx = document.getElementById('largestChart');
902
+ if (largestCtx) {
903
+ new Chart(largestCtx, {
904
+ type: 'bar',
905
+ data: {
906
+ labels: ${JSON.stringify(largestData.labels)},
907
+ datasets: [{ label: 'File Size', data: ${JSON.stringify(largestData.data)}, backgroundColor: '#00ff00', borderColor: '#00cccc', borderWidth: 1 }]
908
+ },
909
+ options: {
910
+ ...CHART_DEFAULTS,
911
+ plugins: { ...CHART_DEFAULTS.plugins, legend: { display: false } },
912
+ scales: {
913
+ y: { beginAtZero: true, ticks: { color: '#00ff00', callback: formatBytes }, grid: { color: '#333' } },
914
+ x: { ticks: { color: '#00ff00', maxRotation: 45 }, grid: { color: '#333' } }
915
+ }
916
+ }
917
+ });
918
+ }` : ""}
919
+
920
+ function formatBytes(v) {
921
+ if (!v) return '0 B';
922
+ const k = 1024, s = ['B','KB','MB','GB'];
923
+ const i = Math.floor(Math.log(v) / Math.log(k));
924
+ return (v / Math.pow(k, i)).toFixed(1) + ' ' + s[i];
925
+ }
926
+ })();
927
+ </script>
928
+ </body>
929
+ </html>`;
930
+ }
931
+ async function generateHtmlReport(result, filename) {
932
+ let outputFile = filename ?? `directory-analysis-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.html`;
933
+ if (filename) {
934
+ const s = await stat4(filename).catch(() => null);
935
+ if (s?.isDirectory()) {
936
+ outputFile = join3(filename, `directory-analysis-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.html`);
937
+ }
938
+ }
939
+ await writeFile2(outputFile, generateHTML(result));
940
+ return outputFile;
941
+ }
942
+
943
+ // src/progress.ts
944
+ var BAR_LENGTH = 40;
945
+ var UPDATE_INTERVAL_MS = 100;
946
+ var ProgressBar = class _ProgressBar {
947
+ lastUpdate = 0;
948
+ static isTTY() {
949
+ return process.stdout.isTTY === true;
950
+ }
951
+ show(current, total, label) {
952
+ if (!_ProgressBar.isTTY()) return;
953
+ const now = Date.now();
954
+ if (now - this.lastUpdate < UPDATE_INTERVAL_MS && current !== total) return;
955
+ this.lastUpdate = now;
956
+ const pct = Math.min(100, Math.round(current / total * 100));
957
+ const filled = Math.round(current / total * BAR_LENGTH);
958
+ const bar = "\u2588".repeat(filled) + "\u2591".repeat(BAR_LENGTH - filled);
959
+ const progressText = `[${bar}] ${pct}% (${current}/${total})`;
960
+ let output = `\r${progressText}`;
961
+ if (label) {
962
+ const cols = process.stdout.columns ?? 80;
963
+ const maxLen = cols - progressText.length - 2;
964
+ const display = label.length > maxLen ? "..." + label.slice(-(maxLen - 3)) : label;
965
+ output += ` ${display}`;
966
+ }
967
+ process.stdout.write(output);
968
+ if (current === total) process.stdout.write("\n");
969
+ }
970
+ static createHashCallback(bar) {
971
+ return (done, total) => bar.show(done, total, "hashing files");
972
+ }
973
+ };
974
+ var ScanCounter = class {
975
+ count = 0;
976
+ timer = null;
977
+ start(label) {
978
+ if (!ProgressBar.isTTY()) return;
979
+ this.timer = setInterval(() => {
980
+ process.stdout.write(`\r${label}: ${this.count.toLocaleString()} files scanned...`);
981
+ }, 150);
982
+ }
983
+ increment() {
984
+ this.count++;
985
+ }
986
+ stop() {
987
+ if (this.timer) {
988
+ clearInterval(this.timer);
989
+ this.timer = null;
990
+ }
991
+ if (ProgressBar.isTTY()) process.stdout.write("\r\x1B[K");
992
+ }
993
+ };
994
+
995
+ // src/commands/analyze.ts
996
+ var analyzeCommand = new Command("analyze").description("Analyze a directory (default command when no subcommand is given)").argument("[directory]", "Directory to analyze (defaults to current working directory)").option("--no-recursive", "Disable recursive analysis").option("-j, --json", "Output results as JSON (pipe-safe; suppresses progress bar)").option("--tree", "Display a directory tree view").option("--no-types", "Hide file type breakdown").option("-e, --exclude <patterns...>", "Exclude directory or file patterns").option(
997
+ "-l, --large-files [mb]",
998
+ "Detect large files; optionally specify threshold in MB (default: 100)",
999
+ false
1000
+ ).option("-d, --duplicates", "Enable duplicate file detection (uses streaming MD5)").option("--empty-files", "Detect and show empty (zero-byte) files").option("--top-n <n>", "Show top N largest files", parseInt).option("--max-depth <depth>", "Maximum directory depth to scan", parseInt).option("--min-size <bytes>", "Filter: include only files at least this size", parseInt).option("--max-size <bytes>", "Filter: include only files at most this size", parseInt).option("--date-from <date>", "Filter: include only files modified after (YYYY-MM-DD)").option("--date-to <date>", "Filter: include only files modified before (YYYY-MM-DD)").option("--csv [filename]", "Export full analysis to CSV").option("--csv-large [filename]", "Export large-file list to CSV").option("--csv-duplicates [filename]", "Export duplicate groups to CSV").option("--html [filename]", "Generate HTML report with charts").option("-c, --config [path]", "Path to config file (auto-detected by default)").action(async (directory, options) => {
1001
+ try {
1002
+ const targetPath = resolve(directory ?? process.cwd());
1003
+ const fileConfig = await loadConfig(
1004
+ typeof options.config === "string" ? options.config : void 0
1005
+ );
1006
+ const cliConfig = {
1007
+ excludePatterns: options.exclude,
1008
+ largeSizeThresholdMB: options.largeFiles === true ? 100 : options.largeFiles ? parseFloat(String(options.largeFiles)) : void 0,
1009
+ enableDuplicateDetection: options.duplicates || void 0,
1010
+ maxDepth: options.maxDepth,
1011
+ topN: options.topN,
1012
+ showEmptyFiles: options.emptyFiles || void 0
1013
+ };
1014
+ const config = mergeConfig(fileConfig, cliConfig);
1015
+ const dateFrom = options.dateFrom ? new Date(options.dateFrom) : void 0;
1016
+ const dateTo = options.dateTo ? new Date(options.dateTo) : void 0;
1017
+ if (dateFrom && isNaN(dateFrom.getTime())) {
1018
+ throw new Error("Invalid --date-from format. Use YYYY-MM-DD.");
1019
+ }
1020
+ if (dateTo && isNaN(dateTo.getTime())) {
1021
+ throw new Error("Invalid --date-to format. Use YYYY-MM-DD.");
1022
+ }
1023
+ const isJson = !!options.json;
1024
+ const counter = new ScanCounter();
1025
+ const hashBar = new ProgressBar();
1026
+ if (!isJson) {
1027
+ counter.start(`Scanning ${targetPath}`);
1028
+ }
1029
+ const analysisOptions = {
1030
+ path: targetPath,
1031
+ recursive: options.recursive !== false,
1032
+ excludePatterns: config.excludePatterns,
1033
+ clearDefaultExclusions: config.clearDefaultExclusions,
1034
+ largeSizeThresholdMB: config.largeSizeThresholdMB,
1035
+ enableDuplicateDetection: config.enableDuplicateDetection,
1036
+ maxDepth: config.maxDepth ?? options.maxDepth,
1037
+ minSize: options.minSize,
1038
+ maxSize: options.maxSize,
1039
+ dateFrom,
1040
+ dateTo,
1041
+ topN: config.topN ?? options.topN,
1042
+ showEmptyFiles: config.showEmptyFiles,
1043
+ onProgress: isJson ? void 0 : (_n) => counter.increment(),
1044
+ onHashProgress: isJson ? void 0 : ProgressBar.createHashCallback(hashBar)
1045
+ };
1046
+ const result = await analyze(analysisOptions);
1047
+ counter.stop();
1048
+ if (options.csv || options.csvLarge || options.csvDuplicates) {
1049
+ await writeCsvFiles(result, {
1050
+ csv: options.csv,
1051
+ csvLarge: options.csvLarge,
1052
+ csvDuplicates: options.csvDuplicates
1053
+ });
1054
+ }
1055
+ if (options.html) {
1056
+ const outFile = await generateHtmlReport(
1057
+ result,
1058
+ typeof options.html === "string" ? options.html : void 0
1059
+ );
1060
+ if (!isJson) console.log(chalk2.green(`\u{1F4CA} HTML report: ${outFile}`));
1061
+ }
1062
+ if (isJson) {
1063
+ console.log(JSON.stringify(result, null, 2));
1064
+ } else {
1065
+ printResult(result, {
1066
+ showTypes: options.types !== false,
1067
+ treeView: !!options.tree
1068
+ });
1069
+ }
1070
+ } catch (err) {
1071
+ console.error(chalk2.red("Error:", err instanceof Error ? err.message : String(err)));
1072
+ process.exit(1);
1073
+ }
1074
+ });
1075
+
1076
+ // src/commands/watch.ts
1077
+ import { Command as Command2 } from "commander";
1078
+ import { resolve as resolve2, relative as relative3 } from "path";
1079
+ import chalk3 from "chalk";
1080
+ import prettyBytes4 from "pretty-bytes";
1081
+ import { watch as chokidarWatch } from "chokidar";
1082
+ var watchCommand = new Command2("watch").description("Watch a directory for changes and re-analyze automatically").argument("[directory]", "Directory to watch (defaults to current working directory)").option("--no-recursive", "Disable recursive watching").option("-e, --exclude <patterns...>", "Exclude patterns").option("--max-depth <depth>", "Maximum depth to watch", parseInt).option("-l, --large-files [mb]", "Detect large files (threshold in MB, default: 100)", false).option("-d, --duplicates", "Enable duplicate detection on each re-analysis").option("--top-n <n>", "Top N largest files", parseInt).action(async (directory, options) => {
1083
+ const targetPath = resolve2(directory ?? process.cwd());
1084
+ console.log(chalk3.blue(`\u{1F440} Watching: ${targetPath}`));
1085
+ console.log(chalk3.gray("Press Ctrl+C to stop.\n"));
1086
+ let lastResult = null;
1087
+ let debounceTimer = null;
1088
+ async function runAnalysis() {
1089
+ try {
1090
+ const result = await analyze({
1091
+ path: targetPath,
1092
+ recursive: options.recursive !== false,
1093
+ excludePatterns: options.exclude ?? [],
1094
+ largeSizeThresholdMB: options.largeFiles === true ? 100 : options.largeFiles ? parseFloat(String(options.largeFiles)) : void 0,
1095
+ enableDuplicateDetection: !!options.duplicates,
1096
+ maxDepth: options.maxDepth,
1097
+ topN: options.topN
1098
+ });
1099
+ displayStatus(result, lastResult);
1100
+ lastResult = result;
1101
+ } catch (err) {
1102
+ console.error(chalk3.red("Analysis error:", err instanceof Error ? err.message : String(err)));
1103
+ }
1104
+ }
1105
+ function scheduleAnalysis() {
1106
+ if (debounceTimer) clearTimeout(debounceTimer);
1107
+ debounceTimer = setTimeout(() => {
1108
+ console.log(chalk3.gray("\u{1F504} Re-analyzing...\n"));
1109
+ runAnalysis();
1110
+ }, 2e3);
1111
+ }
1112
+ await runAnalysis();
1113
+ const watcher = chokidarWatch(targetPath, {
1114
+ ignored: /(^|[/\\])\../,
1115
+ persistent: true,
1116
+ ignoreInitial: true,
1117
+ depth: options.maxDepth
1118
+ });
1119
+ watcher.on("add", (p) => {
1120
+ console.log(chalk3.green(`\u{1F4C4} Added: ${relative3(targetPath, p)}`));
1121
+ scheduleAnalysis();
1122
+ }).on("change", (p) => {
1123
+ console.log(chalk3.yellow(`\u{1F4DD} Changed: ${relative3(targetPath, p)}`));
1124
+ scheduleAnalysis();
1125
+ }).on("unlink", (p) => {
1126
+ console.log(chalk3.red(`\u{1F5D1}\uFE0F Removed: ${relative3(targetPath, p)}`));
1127
+ scheduleAnalysis();
1128
+ }).on("addDir", (p) => {
1129
+ console.log(chalk3.blue(`\u{1F4C1} Dir added: ${relative3(targetPath, p)}`));
1130
+ scheduleAnalysis();
1131
+ }).on("unlinkDir", (p) => {
1132
+ console.log(chalk3.red(`\u{1F4C1}\u274C Dir removed: ${relative3(targetPath, p)}`));
1133
+ scheduleAnalysis();
1134
+ });
1135
+ process.on("SIGINT", () => {
1136
+ console.log(chalk3.blue("\n\u{1F44B} Stopping watcher\u2026"));
1137
+ watcher.close();
1138
+ process.exit(0);
1139
+ });
1140
+ });
1141
+ function displayStatus(current, previous) {
1142
+ console.log(chalk3.cyan("\n\u{1F4CA} Status:"));
1143
+ console.log(` \u{1F4E6} Size: ${current.totalSizeFormatted}`);
1144
+ console.log(` \u{1F4C1} Folders: ${current.folders.toLocaleString()}`);
1145
+ console.log(` \u{1F4C4} Files: ${current.files.toLocaleString()}`);
1146
+ if (previous) {
1147
+ const sizeDiff = current.totalSizeBytes - previous.totalSizeBytes;
1148
+ const fileDiff = current.files - previous.files;
1149
+ const folderDiff = current.folders - previous.folders;
1150
+ if (sizeDiff !== 0 || fileDiff !== 0 || folderDiff !== 0) {
1151
+ console.log(chalk3.yellow("\n\u{1F4C8} Changes:"));
1152
+ if (sizeDiff !== 0) {
1153
+ const sign = sizeDiff > 0 ? "+" : "";
1154
+ const color = sizeDiff > 0 ? chalk3.green : chalk3.red;
1155
+ console.log(` Size: ${color(`${sign}${prettyBytes4(Math.abs(sizeDiff))}`)}`);
1156
+ }
1157
+ if (fileDiff !== 0) {
1158
+ const color = fileDiff > 0 ? chalk3.green : chalk3.red;
1159
+ console.log(` Files: ${color(`${fileDiff > 0 ? "+" : ""}${fileDiff}`)}`);
1160
+ }
1161
+ if (folderDiff !== 0) {
1162
+ const color = folderDiff > 0 ? chalk3.green : chalk3.red;
1163
+ console.log(` Folders: ${color(`${folderDiff > 0 ? "+" : ""}${folderDiff}`)}`);
1164
+ }
1165
+ } else {
1166
+ console.log(chalk3.gray(" No changes."));
1167
+ }
1168
+ }
1169
+ console.log(chalk3.gray(`
1170
+ \u23F0 ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`));
1171
+ console.log(chalk3.gray("\u2500".repeat(50)));
1172
+ }
1173
+
1174
+ // src/commands/init.ts
1175
+ import { Command as Command3 } from "commander";
1176
+ import { writeFileSync, existsSync } from "fs";
1177
+ import { join as join4 } from "path";
1178
+ import { intro, outro, text, confirm, isCancel, cancel } from "@clack/prompts";
1179
+ import chalk4 from "chalk";
1180
+ var initCommand = new Command3("init").description("Create a .dir-analyzer.json configuration file interactively").option("--cwd <path>", "Directory to create the config in (default: current directory)").action(async (options) => {
1181
+ const cwd = options.cwd ?? process.cwd();
1182
+ const configPath = join4(cwd, ".dir-analyzer.json");
1183
+ if (existsSync(configPath)) {
1184
+ const overwrite = await confirm({
1185
+ message: `.dir-analyzer.json already exists. Overwrite?`,
1186
+ initialValue: false
1187
+ });
1188
+ if (isCancel(overwrite) || !overwrite) {
1189
+ cancel("Aborted.");
1190
+ process.exit(0);
1191
+ }
1192
+ }
1193
+ intro(chalk4.blue("dat init \u2014 Create .dir-analyzer.json"));
1194
+ const excludeRaw = await text({
1195
+ message: "Extra directories/patterns to exclude (comma-separated, or leave empty)",
1196
+ placeholder: "coverage,tmp,__pycache__",
1197
+ defaultValue: ""
1198
+ });
1199
+ if (isCancel(excludeRaw)) {
1200
+ cancel("Cancelled.");
1201
+ process.exit(0);
1202
+ }
1203
+ const clearDefaults = await confirm({
1204
+ message: "Clear default exclusions? (node_modules, .git, dist, build, .cache)",
1205
+ initialValue: false
1206
+ });
1207
+ if (isCancel(clearDefaults)) {
1208
+ cancel("Cancelled.");
1209
+ process.exit(0);
1210
+ }
1211
+ const largeFilesRaw = await text({
1212
+ message: "Large-file threshold in MB (leave empty to disable)",
1213
+ placeholder: "100",
1214
+ defaultValue: "",
1215
+ validate: (v) => {
1216
+ if (!v || v.trim() === "") return;
1217
+ if (isNaN(parseFloat(v)) || parseFloat(v) <= 0) return "Must be a positive number";
1218
+ }
1219
+ });
1220
+ if (isCancel(largeFilesRaw)) {
1221
+ cancel("Cancelled.");
1222
+ process.exit(0);
1223
+ }
1224
+ const enableDuplicates = await confirm({
1225
+ message: "Enable duplicate detection by default?",
1226
+ initialValue: false
1227
+ });
1228
+ if (isCancel(enableDuplicates)) {
1229
+ cancel("Cancelled.");
1230
+ process.exit(0);
1231
+ }
1232
+ const maxDepthRaw = await text({
1233
+ message: "Maximum directory depth (-1 for unlimited)",
1234
+ defaultValue: "-1",
1235
+ validate: (v) => {
1236
+ if (!v) return;
1237
+ if (isNaN(parseInt(v))) return "Must be an integer";
1238
+ }
1239
+ });
1240
+ if (isCancel(maxDepthRaw)) {
1241
+ cancel("Cancelled.");
1242
+ process.exit(0);
1243
+ }
1244
+ const topNRaw = await text({
1245
+ message: "Default number of top largest files to show (0 to disable)",
1246
+ defaultValue: "10",
1247
+ validate: (v) => {
1248
+ if (!v) return;
1249
+ if (isNaN(parseInt(v)) || parseInt(v) < 0) return "Must be a non-negative integer";
1250
+ }
1251
+ });
1252
+ if (isCancel(topNRaw)) {
1253
+ cancel("Cancelled.");
1254
+ process.exit(0);
1255
+ }
1256
+ const config = {};
1257
+ const excludeList = String(excludeRaw).split(",").map((s) => s.trim()).filter(Boolean);
1258
+ if (excludeList.length > 0) config.excludePatterns = excludeList;
1259
+ if (clearDefaults) config.clearDefaultExclusions = true;
1260
+ if (String(largeFilesRaw).trim() !== "") config.largeSizeThresholdMB = parseFloat(String(largeFilesRaw));
1261
+ if (enableDuplicates) config.enableDuplicateDetection = true;
1262
+ const depth = parseInt(String(maxDepthRaw));
1263
+ if (!isNaN(depth) && depth !== -1) config.maxDepth = depth;
1264
+ const topN = parseInt(String(topNRaw));
1265
+ if (!isNaN(topN) && topN > 0) config.topN = topN;
1266
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
1267
+ outro(chalk4.green(`\u2705 Config saved to ${configPath}`));
1268
+ });
1269
+
1270
+ // src/commands/compare.ts
1271
+ import { Command as Command4 } from "commander";
1272
+ import { resolve as resolve3 } from "path";
1273
+ import chalk5 from "chalk";
1274
+ var compareCommand = new Command4("compare").description("Compare two directories side by side").argument("<dir1>", "First directory").argument("<dir2>", "Second directory").option("--no-recursive", "Disable recursive analysis").option("-e, --exclude <patterns...>", "Exclude patterns").option("--max-depth <depth>", "Maximum directory depth", parseInt).option("-j, --json", "Output comparison as JSON").action(async (dir1, dir2, options) => {
1275
+ try {
1276
+ const path1 = resolve3(dir1);
1277
+ const path2 = resolve3(dir2);
1278
+ const sharedOpts = {
1279
+ recursive: options.recursive !== false,
1280
+ excludePatterns: options.exclude ?? [],
1281
+ maxDepth: options.maxDepth
1282
+ };
1283
+ console.log(chalk5.blue("Analyzing directories\u2026"));
1284
+ const [result1, result2] = await Promise.all([
1285
+ analyze({ path: path1, ...sharedOpts }),
1286
+ analyze({ path: path2, ...sharedOpts })
1287
+ ]);
1288
+ if (options.json) {
1289
+ console.log(JSON.stringify({ dir1: result1, dir2: result2 }, null, 2));
1290
+ } else {
1291
+ printComparison(result1, result2);
1292
+ }
1293
+ } catch (err) {
1294
+ console.error(chalk5.red("Error:", err instanceof Error ? err.message : String(err)));
1295
+ process.exit(1);
1296
+ }
1297
+ });
1298
+
1299
+ // src/index.ts
1300
+ var program = new Command5();
1301
+ program.name("dat").description("Directory Analysis Tool \u2014 fast, memory-safe directory analysis for your terminal").version(true ? "2.0.6" : "2.0.0", "-v, --version");
1302
+ program.addCommand(analyzeCommand, { isDefault: true });
1303
+ program.addCommand(watchCommand);
1304
+ program.addCommand(initCommand);
1305
+ program.addCommand(compareCommand);
1306
+ process.on("unhandledRejection", (reason) => {
1307
+ console.error("Unhandled rejection:", reason);
1308
+ process.exit(1);
1309
+ });
1310
+ program.parse();