dir-analysis-tool 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.ts ADDED
@@ -0,0 +1,431 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import { DirectoryAnalyzer, AnalysisOptions } from './analyzer';
6
+ import { formatSize, EMOJIS } from './utils';
7
+ import { ConfigManager } from './config';
8
+ import { ProgressBar } from './progress';
9
+ import { CSVExporter, ExtendedAnalysisResult } from './export';
10
+ import { InteractiveMode } from './interactive';
11
+ import { HTMLReportGenerator } from './html-report';
12
+ import chokidar from 'chokidar';
13
+
14
+ const program = new Command();
15
+
16
+ program
17
+ .name('dir-analyzer')
18
+ .description('Analyze directory contents and classify files by type with advanced features')
19
+ .version('1.0.0');
20
+
21
+ program
22
+ .option('-p, --path <path>', 'Target directory to analyze', '.')
23
+ .option('-r, --recursive', 'Recursively analyze nested directories', true)
24
+ .option('--no-recursive', 'Disable recursive analysis')
25
+ .option('-j, --json', 'Output results in JSON format')
26
+ .option('-t, --types', 'Show file type classification summary', true)
27
+ .option('--no-types', 'Hide file type classification')
28
+ .option('-e, --exclude <patterns...>', 'Exclude file patterns or directories')
29
+ .option('-l, --large-files [threshold]', 'Detect large files (default: 100MB)', '104857600')
30
+ .option('-d, --duplicates', 'Enable duplicate file detection')
31
+ .option('--csv [filename]', 'Export results to CSV file')
32
+ .option('--csv-large [filename]', 'Export large files to CSV')
33
+ .option('--csv-duplicates [filename]', 'Export duplicates to CSV')
34
+ .option('--progress', 'Show progress bar during analysis', true)
35
+ .option('--no-progress', 'Disable progress bar')
36
+ .option('--max-depth <depth>', 'Maximum directory depth to scan', parseInt)
37
+ .option('-c, --config [path]', 'Load configuration from file')
38
+ // Phase 1 new options
39
+ .option('--min-size <size>', 'Filter files by minimum size (bytes)', parseInt)
40
+ .option('--max-size <size>', 'Filter files by maximum size (bytes)', parseInt)
41
+ .option('--date-from <date>', 'Filter files modified after this date (YYYY-MM-DD)')
42
+ .option('--date-to <date>', 'Filter files modified before this date (YYYY-MM-DD)')
43
+ .option('--tree', 'Display results in tree view format')
44
+ .option('--top-n <number>', 'Show top N largest files (default: 10)', parseInt)
45
+ .option('--empty-files', 'Detect and show empty files')
46
+ // Phase 2 new options
47
+ .option('-i, --interactive', 'Start interactive mode')
48
+ .option('-w, --watch', 'Watch mode - monitor directory changes')
49
+ .option('--html [filename]', 'Generate HTML report with charts').argument('[directory]', 'Directory to analyze (alternative to --path)')
50
+ .action(async (directory, options) => {
51
+ try {
52
+ // Handle interactive mode
53
+ if (options.interactive) {
54
+ const interactive = new InteractiveMode();
55
+ await interactive.start();
56
+ return;
57
+ }
58
+
59
+ // Handle watch mode
60
+ if (options.watch) {
61
+ await startWatchMode(options);
62
+ return;
63
+ }
64
+
65
+ // Determine target path - use directory argument if provided, otherwise use --path option
66
+ const targetPath = directory || options.path || '.';
67
+
68
+ // Load configuration
69
+ const configManager = new ConfigManager();
70
+ let config = await configManager.loadConfig(options.config || process.cwd());
71
+ config = configManager.mergeWithCliOptions(options);
72
+
73
+ // Parse large file threshold
74
+ const largeSizeThreshold = options.largeFiles
75
+ ? (typeof options.largeFiles === 'string' ? parseInt(options.largeFiles) : 104857600)
76
+ : undefined;
77
+
78
+ // Parse date filters
79
+ const dateFrom = options.dateFrom ? new Date(options.dateFrom) : undefined;
80
+ const dateTo = options.dateTo ? new Date(options.dateTo) : undefined;
81
+
82
+ // Validate dates
83
+ if (dateFrom && isNaN(dateFrom.getTime())) {
84
+ throw new Error('Invalid date-from format. Use YYYY-MM-DD');
85
+ }
86
+ if (dateTo && isNaN(dateTo.getTime())) {
87
+ throw new Error('Invalid date-to format. Use YYYY-MM-DD');
88
+ }
89
+
90
+ // Setup progress callback
91
+ const progressCallback = options.progress
92
+ ? ProgressBar.createCallback(true)
93
+ : undefined; const analyzer = new DirectoryAnalyzer();
94
+
95
+ const analysisOptions: AnalysisOptions = {
96
+ path: targetPath,
97
+ recursive: options.recursive,
98
+ excludePatterns: options.exclude || config.excludePatterns || [],
99
+ largeSizeThreshold: largeSizeThreshold || config.largeSizeThreshold,
100
+ enableDuplicateDetection: options.duplicates || config.enableDuplicateDetection || false,
101
+ progressCallback,
102
+ maxDepth: options.maxDepth || config.maxDepth || -1,
103
+ // Phase 1 new options
104
+ minSize: options.minSize || config.minSize,
105
+ maxSize: options.maxSize || config.maxSize,
106
+ dateFrom: dateFrom || config.dateFrom,
107
+ dateTo: dateTo || config.dateTo,
108
+ topN: options.topN || config.topN || 10,
109
+ showEmptyFiles: options.emptyFiles || config.showEmptyFiles || false
110
+ };
111
+
112
+ if (progressCallback) {
113
+ console.log(chalk.blue('🔍 Starting directory analysis...'));
114
+ }
115
+
116
+ const result = await analyzer.analyze(analysisOptions);
117
+
118
+ if (progressCallback) {
119
+ console.log(chalk.green('✅ Analysis complete!\n'));
120
+ } // Handle CSV exports
121
+ if (options.csv || options.csvLarge || options.csvDuplicates) {
122
+ await handleCsvExports(result, options);
123
+ }
124
+
125
+ // Handle HTML report
126
+ if (options.html) {
127
+ await handleHtmlReport(result, options);
128
+ }// Display results
129
+ if (options.json) {
130
+ console.log(JSON.stringify(result, null, 2));
131
+ } else if (options.tree) {
132
+ printTreeView(result);
133
+ } else {
134
+ printFormattedOutput(result, options.types);
135
+ }
136
+ } catch (error) {
137
+ console.error(chalk.red('Error:', error instanceof Error ? error.message : String(error)));
138
+ process.exit(1);
139
+ }
140
+ });
141
+
142
+ async function handleCsvExports(result: ExtendedAnalysisResult, options: any): Promise<void> {
143
+ // Export general CSV
144
+ if (options.csv) {
145
+ const filename = typeof options.csv === 'string' ? options.csv : 'directory-analysis.csv';
146
+ const csvContent = CSVExporter.exportAnalysis(result);
147
+ await fs.promises.writeFile(filename, csvContent);
148
+ console.log(chalk.green(`📄 Analysis exported to: ${filename}`));
149
+ }
150
+
151
+ // Export large files CSV
152
+ if (options.csvLarge && result.largeFiles && result.largeFiles.length > 0) {
153
+ const filename = typeof options.csvLarge === 'string' ? options.csvLarge : 'large-files.csv';
154
+ const csvContent = CSVExporter.exportLargeFiles(result.largeFiles);
155
+ await fs.promises.writeFile(filename, csvContent);
156
+ console.log(chalk.green(`📄 Large files exported to: ${filename}`));
157
+ }
158
+
159
+ // Export duplicates CSV
160
+ if (options.csvDuplicates && result.duplicateGroups && result.duplicateGroups.length > 0) {
161
+ const filename = typeof options.csvDuplicates === 'string' ? options.csvDuplicates : 'duplicates.csv';
162
+ const csvContent = CSVExporter.exportDuplicates(result.duplicateGroups);
163
+ await fs.promises.writeFile(filename, csvContent);
164
+ console.log(chalk.green(`📄 Duplicates exported to: ${filename}`));
165
+ }
166
+ }
167
+
168
+ async function handleHtmlReport(result: ExtendedAnalysisResult, options: any): Promise<void> {
169
+ try {
170
+ const filename = typeof options.html === 'string' ? options.html : undefined;
171
+ const outputFile = await HTMLReportGenerator.generateReport(result, filename);
172
+ console.log(chalk.green(`📊 HTML report generated: ${outputFile}`));
173
+ } catch (error) {
174
+ console.error(chalk.red('HTML report generation failed:'), error instanceof Error ? error.message : String(error));
175
+ }
176
+ }
177
+
178
+ function printFormattedOutput(result: ExtendedAnalysisResult, showTypes: boolean): void {
179
+ console.log(chalk.blue(`${EMOJIS.folder} Directory: ${result.path}`));
180
+ console.log(chalk.green(`${EMOJIS.package} Total Size: ${formatSize(result.totalSizeBytes)}`));
181
+ console.log(chalk.yellow(`${EMOJIS.folderIcon} Folders: ${result.folders}`));
182
+ console.log(chalk.cyan(`${EMOJIS.fileIcon} Files: ${result.files}`));
183
+
184
+ if (showTypes) {
185
+ console.log(chalk.magenta(`\n${EMOJIS.types} File Types:`));
186
+
187
+ const typeEntries = [
188
+ { key: 'images', emoji: EMOJIS.images, label: 'Images' },
189
+ { key: 'videos', emoji: EMOJIS.videos, label: 'Videos' },
190
+ { key: 'documents', emoji: EMOJIS.documents, label: 'Documents' },
191
+ { key: 'audio', emoji: EMOJIS.audio, label: 'Audio' },
192
+ { key: 'code', emoji: EMOJIS.code, label: 'Code' },
193
+ { key: 'archives', emoji: EMOJIS.archives, label: 'Archives' },
194
+ { key: 'other', emoji: EMOJIS.other, label: 'Other' }
195
+ ]; typeEntries.forEach(({ key, emoji, label }) => {
196
+ const count = (result.types as any)[key];
197
+ if (count > 0) {
198
+ console.log(` ${emoji} ${label}: ${count}`);
199
+ }
200
+ });
201
+ }
202
+
203
+ // Display large files if found
204
+ if (result.largeFiles && result.largeFiles.length > 0) {
205
+ console.log(chalk.red(`\n🚨 Large Files (Top ${Math.min(5, result.largeFiles.length)}):`));
206
+ result.largeFiles.slice(0, 5).forEach(file => {
207
+ const relativePath = path.relative(result.path, file.path);
208
+ console.log(` 📁 ${relativePath} - ${chalk.yellow(file.sizeFormatted)}`);
209
+ });
210
+
211
+ if (result.largeFiles.length > 5) {
212
+ console.log(chalk.gray(` ... and ${result.largeFiles.length - 5} more large files`));
213
+ }
214
+ }
215
+
216
+ // Display duplicate statistics if found
217
+ if (result.duplicateStats && result.duplicateStats.totalGroups > 0) {
218
+ console.log(chalk.yellow(`\n🔄 Duplicate Files:`));
219
+ console.log(` 📊 Groups: ${result.duplicateStats.totalGroups}`);
220
+ console.log(` 💾 Wasted Space: ${chalk.red(result.duplicateStats.totalWastedSpaceFormatted)}`);
221
+
222
+ if (result.duplicateGroups && result.duplicateGroups.length > 0) {
223
+ console.log(chalk.gray(`\n Top duplicate groups:`));
224
+ result.duplicateGroups.slice(0, 3).forEach((group, index) => {
225
+ console.log(` ${index + 1}. ${group.sizeFormatted} each × ${group.files.length} files`);
226
+ group.files.slice(0, 2).forEach(file => {
227
+ const relativePath = path.relative(result.path, file);
228
+ console.log(` 📄 ${relativePath}`);
229
+ });
230
+ if (group.files.length > 2) {
231
+ console.log(chalk.gray(` ... and ${group.files.length - 2} more`));
232
+ }
233
+ });
234
+ }
235
+ }
236
+
237
+ // Show top largest files if available
238
+ if (result.topLargestFiles && result.topLargestFiles.length > 0) {
239
+ printTopLargestFiles(result);
240
+ }
241
+
242
+ // Show empty files if detected
243
+ if (result.emptyFiles && result.emptyFiles.length > 0) {
244
+ printEmptyFiles(result);
245
+ }
246
+ }
247
+
248
+ function printTreeView(result: ExtendedAnalysisResult): void {
249
+ console.log(chalk.blue(`${EMOJIS.folder} Directory Tree: ${result.path}`));
250
+ console.log(chalk.green(`${EMOJIS.package} Total Size: ${formatSize(result.totalSizeBytes)}`));
251
+ console.log(chalk.yellow(`${EMOJIS.folderIcon} Folders: ${result.folders}`));
252
+ console.log(chalk.cyan(`${EMOJIS.fileIcon} Files: ${result.files}\n`));
253
+
254
+ if (result.treeView) {
255
+ console.log(result.treeView);
256
+ } else {
257
+ console.log(chalk.yellow('Tree view not available for large datasets (>1000 files)'));
258
+ console.log('Use --top-n option to see largest files instead.\n');
259
+ }
260
+
261
+ // Show top largest files if available
262
+ if (result.topLargestFiles && result.topLargestFiles.length > 0) {
263
+ printTopLargestFiles(result);
264
+ }
265
+
266
+ // Show empty files if detected
267
+ if (result.emptyFiles && result.emptyFiles.length > 0) {
268
+ printEmptyFiles(result);
269
+ }
270
+ }
271
+
272
+ function printTopLargestFiles(result: ExtendedAnalysisResult): void {
273
+ if (!result.topLargestFiles || result.topLargestFiles.length === 0) return;
274
+
275
+ console.log(chalk.red(`\n${EMOJIS.largeFile} Top ${result.topLargestFiles.length} Largest Files:`));
276
+ result.topLargestFiles.forEach((file, index) => {
277
+ const relativePath = path.relative(result.path, file.path);
278
+ const ranking = chalk.gray(`${index + 1}.`);
279
+ console.log(` ${ranking} ${relativePath} - ${chalk.yellow(file.sizeFormatted)}`);
280
+ });
281
+ }
282
+
283
+ function printEmptyFiles(result: ExtendedAnalysisResult): void {
284
+ if (!result.emptyFiles || result.emptyFiles.length === 0) return;
285
+
286
+ console.log(chalk.yellow(`\n📭 Empty Files (${result.emptyFiles.length}):`));
287
+ const displayCount = Math.min(10, result.emptyFiles.length);
288
+
289
+ result.emptyFiles.slice(0, displayCount).forEach(file => {
290
+ const relativePath = path.relative(result.path, file.path);
291
+ const date = file.modifiedDate.toLocaleDateString();
292
+ console.log(` 📄 ${relativePath} ${chalk.gray(`(modified: ${date})`)}`);
293
+ });
294
+
295
+ if (result.emptyFiles.length > displayCount) {
296
+ console.log(chalk.gray(` ... and ${result.emptyFiles.length - displayCount} more empty files`));
297
+ }
298
+ }
299
+
300
+ // Watch mode functionality
301
+ async function startWatchMode(options: any): Promise<void> {
302
+ const watchPath = options.path || '.';
303
+ console.log(chalk.blue(`👀 Starting watch mode for: ${path.resolve(watchPath)}`));
304
+ console.log(chalk.gray('Press Ctrl+C to stop watching...\n'));
305
+
306
+ const analyzer = new DirectoryAnalyzer();
307
+ let lastAnalysis: ExtendedAnalysisResult | null = null;
308
+ let analysisTimeout: NodeJS.Timeout | null = null;
309
+
310
+ // Perform initial analysis
311
+ await performAnalysis();
312
+
313
+ // Set up file watcher
314
+ const watcher = chokidar.watch(watchPath, {
315
+ ignored: /(^|[\/\\])\../, // ignore dotfiles
316
+ persistent: true,
317
+ ignoreInitial: true,
318
+ depth: options.maxDepth || undefined
319
+ });
320
+
321
+ watcher
322
+ .on('add', (filePath) => {
323
+ console.log(chalk.green(`📄 File added: ${path.relative(watchPath, filePath)}`));
324
+ scheduleAnalysis();
325
+ })
326
+ .on('change', (filePath) => {
327
+ console.log(chalk.yellow(`📝 File changed: ${path.relative(watchPath, filePath)}`));
328
+ scheduleAnalysis();
329
+ })
330
+ .on('unlink', (filePath) => {
331
+ console.log(chalk.red(`🗑️ File removed: ${path.relative(watchPath, filePath)}`));
332
+ scheduleAnalysis();
333
+ })
334
+ .on('addDir', (dirPath) => {
335
+ console.log(chalk.blue(`📁 Directory added: ${path.relative(watchPath, dirPath)}`));
336
+ scheduleAnalysis();
337
+ })
338
+ .on('unlinkDir', (dirPath) => {
339
+ console.log(chalk.red(`📁❌ Directory removed: ${path.relative(watchPath, dirPath)}`));
340
+ scheduleAnalysis();
341
+ });
342
+
343
+ // Handle graceful shutdown
344
+ process.on('SIGINT', () => {
345
+ console.log(chalk.blue('\n👋 Stopping watch mode...'));
346
+ watcher.close();
347
+ process.exit(0);
348
+ });
349
+
350
+ async function performAnalysis(): Promise<void> {
351
+ try {
352
+ const analysisOptions: AnalysisOptions = {
353
+ path: watchPath,
354
+ recursive: options.recursive !== false,
355
+ excludePatterns: options.exclude || [],
356
+ largeSizeThreshold: options.largeFiles ?
357
+ (typeof options.largeFiles === 'string' ? parseInt(options.largeFiles) : 104857600) : undefined,
358
+ enableDuplicateDetection: options.duplicates || false,
359
+ maxDepth: options.maxDepth || -1,
360
+ topN: options.topN || 10,
361
+ showEmptyFiles: options.emptyFiles || false
362
+ };
363
+
364
+ const result = await analyzer.analyze(analysisOptions);
365
+ displayWatchResults(result, lastAnalysis);
366
+ lastAnalysis = result;
367
+ } catch (error) {
368
+ console.error(chalk.red('Analysis error:'), error instanceof Error ? error.message : String(error));
369
+ }
370
+ }
371
+
372
+ function scheduleAnalysis(): void {
373
+ if (analysisTimeout) {
374
+ clearTimeout(analysisTimeout);
375
+ }
376
+
377
+ // Debounce analysis to avoid too frequent updates
378
+ analysisTimeout = setTimeout(() => {
379
+ console.log(chalk.gray('🔄 Updating analysis...\n'));
380
+ performAnalysis();
381
+ }, 2000); // Wait 2 seconds after last change
382
+ }
383
+ }
384
+
385
+ function displayWatchResults(current: ExtendedAnalysisResult, previous: ExtendedAnalysisResult | null): void {
386
+ console.log(chalk.cyan('\n📊 Current Status:'));
387
+ console.log(` 📦 Total Size: ${formatSize(current.totalSizeBytes)}`);
388
+ console.log(` 📁 Folders: ${current.folders}`);
389
+ console.log(` 📄 Files: ${current.files}`);
390
+
391
+ if (previous) {
392
+ console.log(chalk.yellow('\n📈 Changes since last scan:'));
393
+ const sizeDiff = current.totalSizeBytes - previous.totalSizeBytes;
394
+ const filesDiff = current.files - previous.files;
395
+ const foldersDiff = current.folders - previous.folders;
396
+
397
+ if (sizeDiff !== 0) {
398
+ const color = sizeDiff > 0 ? chalk.green : chalk.red;
399
+ const symbol = sizeDiff > 0 ? '+' : '';
400
+ console.log(` 📦 Size: ${color(`${symbol}${formatSize(Math.abs(sizeDiff))}`)}`);
401
+ }
402
+
403
+ if (filesDiff !== 0) {
404
+ const color = filesDiff > 0 ? chalk.green : chalk.red;
405
+ const symbol = filesDiff > 0 ? '+' : '';
406
+ console.log(` 📄 Files: ${color(`${symbol}${filesDiff}`)}`);
407
+ }
408
+
409
+ if (foldersDiff !== 0) {
410
+ const color = foldersDiff > 0 ? chalk.green : chalk.red;
411
+ const symbol = foldersDiff > 0 ? '+' : '';
412
+ console.log(` 📁 Folders: ${color(`${symbol}${foldersDiff}`)}`);
413
+ }
414
+
415
+ if (sizeDiff === 0 && filesDiff === 0 && foldersDiff === 0) {
416
+ console.log(` ${chalk.gray('No changes detected')}`);
417
+ }
418
+ }
419
+
420
+ console.log(chalk.gray(`\n⏰ Last updated: ${new Date().toLocaleTimeString()}`));
421
+ console.log(chalk.gray('═'.repeat(50)));
422
+ }
423
+
424
+ // Handle unhandled promise rejections
425
+ process.on('unhandledRejection', (reason, promise) => {
426
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
427
+ process.exit(1);
428
+ });
429
+
430
+ // Parse command line arguments
431
+ program.parse();
package/src/config.ts ADDED
@@ -0,0 +1,66 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { ConfigOptions } from './types';
4
+
5
+ const CONFIG_FILE_NAMES = ['.dir-analyzer.json', 'dir-analyzer.config.json'];
6
+
7
+ export class ConfigManager {
8
+ private config: ConfigOptions = {};
9
+
10
+ async loadConfig(searchPath: string = process.cwd()): Promise<ConfigOptions> {
11
+ const configPath = await this.findConfigFile(searchPath);
12
+ if (configPath) {
13
+ try {
14
+ const configContent = await fs.promises.readFile(configPath, 'utf-8');
15
+ this.config = JSON.parse(configContent);
16
+ console.log(`Loaded configuration from: ${configPath}`);
17
+ } catch (error) {
18
+ console.warn(`Warning: Failed to load config file '${configPath}': ${error}`);
19
+ }
20
+ }
21
+ return this.config;
22
+ }
23
+
24
+ private async findConfigFile(searchPath: string): Promise<string | null> {
25
+ let currentPath = searchPath;
26
+
27
+ while (currentPath !== path.dirname(currentPath)) {
28
+ for (const configName of CONFIG_FILE_NAMES) {
29
+ const configPath = path.join(currentPath, configName);
30
+ try {
31
+ await fs.promises.access(configPath, fs.constants.F_OK);
32
+ return configPath;
33
+ } catch {
34
+ // File doesn't exist, continue searching
35
+ }
36
+ }
37
+ currentPath = path.dirname(currentPath);
38
+ }
39
+
40
+ return null;
41
+ }
42
+
43
+ getConfig(): ConfigOptions {
44
+ return this.config;
45
+ }
46
+
47
+ mergeWithCliOptions(cliOptions: any): ConfigOptions {
48
+ return {
49
+ ...this.config,
50
+ ...Object.fromEntries(
51
+ Object.entries(cliOptions).filter(([_, value]) => value !== undefined)
52
+ )
53
+ };
54
+ }
55
+
56
+ static getDefaultConfig(): ConfigOptions {
57
+ return {
58
+ excludePatterns: [],
59
+ largeSizeThreshold: 100 * 1024 * 1024, // 100MB
60
+ enableDuplicateDetection: false,
61
+ enableProgressBar: true,
62
+ outputFormat: 'table',
63
+ maxDepth: -1 // No limit
64
+ };
65
+ }
66
+ }
package/src/export.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { AnalysisResult } from './analyzer';
2
+ import { DuplicateFileGroup, LargeFile, EmptyFile } from './types';
3
+
4
+ export interface ExtendedAnalysisResult extends AnalysisResult {
5
+ largeFiles?: LargeFile[];
6
+ duplicateGroups?: DuplicateFileGroup[];
7
+ duplicateStats?: {
8
+ totalGroups: number;
9
+ totalWastedSpace: number;
10
+ totalWastedSpaceFormatted: string;
11
+ };
12
+ // Phase 1 new properties
13
+ emptyFiles?: EmptyFile[];
14
+ topLargestFiles?: LargeFile[];
15
+ treeView?: string;
16
+ }
17
+
18
+ export class CSVExporter {
19
+ static exportAnalysis(result: ExtendedAnalysisResult): string {
20
+ const lines: string[] = [];
21
+
22
+ // Header
23
+ lines.push('Type,Path,Size (Bytes),Size (Formatted),Count,Details');
24
+
25
+ // Summary
26
+ lines.push(`Summary,${result.path},${result.totalSizeBytes},${result.totalSizeMB}MB,${result.files},Folders: ${result.folders}`);
27
+
28
+ // File types
29
+ Object.entries(result.types).forEach(([type, count]) => {
30
+ if (count > 0) {
31
+ lines.push(`FileType,${type},-,-,${count},-`);
32
+ }
33
+ });
34
+
35
+ // Large files
36
+ if (result.largeFiles && result.largeFiles.length > 0) {
37
+ result.largeFiles.forEach(file => {
38
+ lines.push(`LargeFile,"${file.path}",${file.size},"${file.sizeFormatted}",1,-`);
39
+ });
40
+ }
41
+
42
+ // Duplicate groups
43
+ if (result.duplicateGroups && result.duplicateGroups.length > 0) {
44
+ result.duplicateGroups.forEach((group, index) => {
45
+ group.files.forEach((file, fileIndex) => {
46
+ const details = fileIndex === 0
47
+ ? `Group ${index + 1}, Total files: ${group.files.length}, Wasted space: ${group.totalWastedSpaceFormatted}`
48
+ : `Group ${index + 1} (duplicate)`;
49
+ lines.push(`Duplicate,"${file}",${group.size},"${group.sizeFormatted}",1,"${details}"`);
50
+ });
51
+ });
52
+ }
53
+
54
+ return lines.join('\n');
55
+ }
56
+
57
+ static exportLargeFiles(largeFiles: LargeFile[]): string {
58
+ const lines: string[] = [];
59
+ lines.push('Path,Size (Bytes),Size (Formatted)');
60
+
61
+ largeFiles.forEach(file => {
62
+ lines.push(`"${file.path}",${file.size},"${file.sizeFormatted}"`);
63
+ });
64
+
65
+ return lines.join('\n');
66
+ }
67
+
68
+ static exportDuplicates(duplicateGroups: DuplicateFileGroup[]): string {
69
+ const lines: string[] = [];
70
+ lines.push('Group,Path,Size (Bytes),Size (Formatted),Files in Group,Wasted Space');
71
+
72
+ duplicateGroups.forEach((group, index) => {
73
+ group.files.forEach(file => {
74
+ lines.push(`${index + 1},"${file}",${group.size},"${group.sizeFormatted}",${group.files.length},"${group.totalWastedSpaceFormatted}"`);
75
+ });
76
+ });
77
+
78
+ return lines.join('\n');
79
+ }
80
+ }