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.
@@ -0,0 +1,185 @@
1
+ import * as crypto from 'crypto';
2
+ import { promises as fs } from 'fs';
3
+ import { formatSize } from './utils';
4
+ import { DuplicateFileGroup, LargeFile, ProgressCallback, EmptyFile } from './types';
5
+
6
+ export class DuplicateDetector {
7
+ private fileHashes = new Map<string, string[]>();
8
+ private processedFiles = 0;
9
+ private totalFiles = 0;
10
+
11
+ async detectDuplicates(
12
+ filePaths: string[],
13
+ progressCallback?: ProgressCallback
14
+ ): Promise<DuplicateFileGroup[]> {
15
+ this.fileHashes.clear();
16
+ this.processedFiles = 0;
17
+ this.totalFiles = filePaths.length;
18
+
19
+ if (progressCallback) {
20
+ progressCallback(0, this.totalFiles, 'Starting duplicate detection...');
21
+ }
22
+
23
+ // Process files in batches to avoid memory issues
24
+ const batchSize = 50;
25
+ for (let i = 0; i < filePaths.length; i += batchSize) {
26
+ const batch = filePaths.slice(i, i + batchSize);
27
+ await Promise.all(batch.map(filePath => this.processFile(filePath, progressCallback)));
28
+ }
29
+
30
+ return this.generateDuplicateGroups();
31
+ }
32
+
33
+ private async processFile(filePath: string, progressCallback?: ProgressCallback): Promise<void> {
34
+ try {
35
+ const hash = await this.calculateFileHash(filePath);
36
+
37
+ if (!this.fileHashes.has(hash)) {
38
+ this.fileHashes.set(hash, []);
39
+ }
40
+ this.fileHashes.get(hash)!.push(filePath);
41
+
42
+ this.processedFiles++;
43
+
44
+ if (progressCallback) {
45
+ progressCallback(this.processedFiles, this.totalFiles, filePath);
46
+ }
47
+ } catch (error) {
48
+ // Skip files that can't be processed
49
+ this.processedFiles++;
50
+ if (progressCallback) {
51
+ progressCallback(this.processedFiles, this.totalFiles);
52
+ }
53
+ }
54
+ }
55
+
56
+ private async calculateFileHash(filePath: string): Promise<string> {
57
+ const hash = crypto.createHash('md5');
58
+ const stream = await fs.readFile(filePath);
59
+ hash.update(stream);
60
+ return hash.digest('hex');
61
+ }
62
+
63
+ private async generateDuplicateGroups(): Promise<DuplicateFileGroup[]> {
64
+ const groups: DuplicateFileGroup[] = [];
65
+
66
+ for (const [hash, files] of this.fileHashes) {
67
+ if (files.length > 1) {
68
+ try {
69
+ const stats = await fs.stat(files[0]);
70
+ const size = stats.size;
71
+ const totalWastedSpace = size * (files.length - 1);
72
+
73
+ groups.push({
74
+ hash,
75
+ size,
76
+ sizeFormatted: formatSize(size),
77
+ files: [...files],
78
+ totalWastedSpace,
79
+ totalWastedSpaceFormatted: formatSize(totalWastedSpace)
80
+ });
81
+ } catch (error) {
82
+ // Skip if we can't get file stats
83
+ }
84
+ }
85
+ }
86
+
87
+ return groups.sort((a, b) => b.totalWastedSpace - a.totalWastedSpace);
88
+ }
89
+ }
90
+
91
+ export class LargeFileDetector {
92
+ static detectLargeFiles(
93
+ files: Array<{ path: string; size: number }>,
94
+ threshold: number
95
+ ): LargeFile[] {
96
+ return files
97
+ .filter(file => file.size >= threshold)
98
+ .sort((a, b) => b.size - a.size)
99
+ .map(file => ({
100
+ path: file.path,
101
+ size: file.size,
102
+ sizeFormatted: formatSize(file.size)
103
+ }));
104
+ }
105
+
106
+ static getTopLargestFiles(
107
+ files: Array<{ path: string; size: number }>,
108
+ count: number
109
+ ): LargeFile[] {
110
+ return files
111
+ .sort((a, b) => b.size - a.size)
112
+ .slice(0, count)
113
+ .map(file => ({
114
+ path: file.path,
115
+ size: file.size,
116
+ sizeFormatted: formatSize(file.size)
117
+ }));
118
+ }
119
+ }
120
+
121
+ export class EmptyFileDetector {
122
+ static async detectEmptyFiles(
123
+ files: Array<{ path: string; size: number }>
124
+ ): Promise<EmptyFile[]> {
125
+ const emptyFiles: EmptyFile[] = [];
126
+
127
+ for (const file of files) {
128
+ if (file.size === 0) {
129
+ try {
130
+ const stats = await fs.stat(file.path);
131
+ emptyFiles.push({
132
+ path: file.path,
133
+ modifiedDate: stats.mtime
134
+ });
135
+ } catch (error) {
136
+ // Skip files that can't be accessed
137
+ }
138
+ }
139
+ }
140
+
141
+ return emptyFiles.sort((a, b) =>
142
+ b.modifiedDate.getTime() - a.modifiedDate.getTime()
143
+ );
144
+ }
145
+ }
146
+
147
+ export class FileFilter {
148
+ static filterBySize(
149
+ files: Array<{ path: string; size: number }>,
150
+ minSize?: number,
151
+ maxSize?: number
152
+ ): Array<{ path: string; size: number }> {
153
+ return files.filter(file => {
154
+ if (minSize !== undefined && file.size < minSize) return false;
155
+ if (maxSize !== undefined && file.size > maxSize) return false;
156
+ return true;
157
+ });
158
+ }
159
+
160
+ static async filterByDate(
161
+ files: Array<{ path: string; size: number }>,
162
+ dateFrom?: Date,
163
+ dateTo?: Date
164
+ ): Promise<Array<{ path: string; size: number }>> {
165
+ if (!dateFrom && !dateTo) return files;
166
+
167
+ const filteredFiles: Array<{ path: string; size: number }> = [];
168
+
169
+ for (const file of files) {
170
+ try {
171
+ const stats = await fs.stat(file.path);
172
+ const modifiedDate = stats.mtime;
173
+
174
+ if (dateFrom && modifiedDate < dateFrom) continue;
175
+ if (dateTo && modifiedDate > dateTo) continue;
176
+
177
+ filteredFiles.push(file);
178
+ } catch (error) {
179
+ // Skip files that can't be accessed
180
+ }
181
+ }
182
+
183
+ return filteredFiles;
184
+ }
185
+ }
@@ -0,0 +1,278 @@
1
+ import { promises as fs } from 'fs';
2
+ import * as path from 'path';
3
+ import { FileClassifier, FileTypeClassification } from './classifier';
4
+ import { shouldExcludeDirectory, shouldExcludeFile, formatSizeInMB } from './utils';
5
+ import { DuplicateDetector, LargeFileDetector, EmptyFileDetector, FileFilter } from './advanced-analysis';
6
+ import { ProgressCallback, LargeFile, DuplicateFileGroup, EmptyFile } from './types';
7
+ import { TreeViewGenerator } from './tree-view';
8
+ import { ExtendedAnalysisResult } from './export';
9
+
10
+ export interface AnalysisOptions {
11
+ path: string;
12
+ recursive: boolean;
13
+ excludePatterns: string[];
14
+ largeSizeThreshold?: number;
15
+ enableDuplicateDetection?: boolean;
16
+ progressCallback?: ProgressCallback;
17
+ maxDepth?: number;
18
+ // Phase 1 new options
19
+ minSize?: number;
20
+ maxSize?: number;
21
+ dateFrom?: Date;
22
+ dateTo?: Date;
23
+ topN?: number;
24
+ showEmptyFiles?: boolean;
25
+ }
26
+
27
+ export interface AnalysisResult {
28
+ path: string;
29
+ totalSizeBytes: number; totalSizeMB: number;
30
+ folders: number;
31
+ files: number;
32
+ types: FileTypeClassification;
33
+ }
34
+
35
+ export class DirectoryAnalyzer {
36
+ private classifier: FileClassifier;
37
+ private totalSize: number = 0;
38
+ private folderCount: number = 0;
39
+ private fileCount: number = 0;
40
+ private allFiles: Array<{ path: string; size: number }> = [];
41
+ private processedFiles: number = 0;
42
+ private currentDepth: number = 0;
43
+
44
+ constructor() {
45
+ this.classifier = new FileClassifier();
46
+ }
47
+
48
+ async analyze(options: AnalysisOptions): Promise<ExtendedAnalysisResult> {
49
+ // Reset counters
50
+ this.totalSize = 0;
51
+ this.folderCount = 0;
52
+ this.fileCount = 0;
53
+ this.allFiles = [];
54
+ this.processedFiles = 0;
55
+ this.currentDepth = 0;
56
+ this.classifier.reset();
57
+
58
+ // Validate path exists
59
+ try {
60
+ const stats = await fs.stat(options.path);
61
+ if (!stats.isDirectory()) {
62
+ throw new Error(`Path '${options.path}' is not a directory`);
63
+ }
64
+ } catch (error) {
65
+ throw new Error(`Unable to access path '${options.path}': ${error}`);
66
+ }
67
+
68
+ if (options.progressCallback) {
69
+ options.progressCallback(0, 1, 'Scanning directories...');
70
+ }
71
+
72
+ // First pass: count total files for progress tracking
73
+ const totalFiles = await this.countFiles(options.path, options.recursive, options.excludePatterns, options.maxDepth || -1);
74
+
75
+ // Second pass: analyze directory
76
+ await this.analyzeDirectory(
77
+ options.path,
78
+ options.recursive,
79
+ options.excludePatterns,
80
+ options.progressCallback,
81
+ totalFiles,
82
+ options.maxDepth || -1,
83
+ 0
84
+ );
85
+
86
+ const basicResult: AnalysisResult = {
87
+ path: options.path,
88
+ totalSizeBytes: this.totalSize,
89
+ totalSizeMB: formatSizeInMB(this.totalSize),
90
+ folders: this.folderCount,
91
+ files: this.fileCount,
92
+ types: this.classifier.getClassification()
93
+ };
94
+
95
+ const extendedResult: ExtendedAnalysisResult = { ...basicResult };
96
+
97
+ // Large file detection
98
+ if (options.largeSizeThreshold) {
99
+ extendedResult.largeFiles = LargeFileDetector.detectLargeFiles(
100
+ this.allFiles,
101
+ options.largeSizeThreshold
102
+ );
103
+ }
104
+
105
+ // Duplicate detection
106
+ if (options.enableDuplicateDetection) {
107
+ const duplicateDetector = new DuplicateDetector();
108
+ const filePaths = this.allFiles.map(f => f.path);
109
+
110
+ if (options.progressCallback) {
111
+ options.progressCallback(0, filePaths.length, 'Detecting duplicates...');
112
+ }
113
+
114
+ extendedResult.duplicateGroups = await duplicateDetector.detectDuplicates(
115
+ filePaths,
116
+ options.progressCallback
117
+ );
118
+
119
+ if (extendedResult.duplicateGroups.length > 0) {
120
+ const totalWastedSpace = extendedResult.duplicateGroups.reduce(
121
+ (sum, group) => sum + group.totalWastedSpace,
122
+ 0
123
+ ); extendedResult.duplicateStats = {
124
+ totalGroups: extendedResult.duplicateGroups.length,
125
+ totalWastedSpace,
126
+ totalWastedSpaceFormatted: require('./utils').formatSize(totalWastedSpace)
127
+ };
128
+ }
129
+ }
130
+
131
+ // Phase 1 new features
132
+ // Apply file filters
133
+ let filteredFiles = this.allFiles;
134
+
135
+ // Apply size filters
136
+ if (options.minSize !== undefined || options.maxSize !== undefined) {
137
+ filteredFiles = FileFilter.filterBySize(filteredFiles, options.minSize, options.maxSize);
138
+ }
139
+
140
+ // Apply date filters
141
+ if (options.dateFrom || options.dateTo) {
142
+ filteredFiles = await FileFilter.filterByDate(filteredFiles, options.dateFrom, options.dateTo);
143
+ }
144
+
145
+ // Top N largest files
146
+ if (options.topN) {
147
+ extendedResult.topLargestFiles = LargeFileDetector.getTopLargestFiles(
148
+ filteredFiles,
149
+ options.topN
150
+ );
151
+ }
152
+
153
+ // Empty file detection
154
+ if (options.showEmptyFiles) {
155
+ extendedResult.emptyFiles = await EmptyFileDetector.detectEmptyFiles(this.allFiles);
156
+ }
157
+
158
+ // Tree view generation (only for smaller datasets to avoid performance issues)
159
+ if (filteredFiles.length <= 1000) {
160
+ extendedResult.treeView = TreeViewGenerator.generateCompactTreeView(
161
+ filteredFiles,
162
+ options.path,
163
+ 50
164
+ );
165
+ }
166
+
167
+ return extendedResult;
168
+ }
169
+
170
+ private async countFiles(
171
+ dirPath: string,
172
+ recursive: boolean,
173
+ excludePatterns: string[],
174
+ maxDepth: number,
175
+ currentDepth: number = 0
176
+ ): Promise<number> {
177
+ if (maxDepth >= 0 && currentDepth > maxDepth) {
178
+ return 0;
179
+ }
180
+
181
+ try {
182
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
183
+ let count = 0;
184
+
185
+ for (const entry of entries) {
186
+ if (entry.isDirectory()) {
187
+ if (shouldExcludeDirectory(entry.name, excludePatterns)) {
188
+ continue;
189
+ }
190
+ if (recursive) {
191
+ const fullPath = path.join(dirPath, entry.name);
192
+ count += await this.countFiles(fullPath, recursive, excludePatterns, maxDepth, currentDepth + 1);
193
+ }
194
+ } else if (entry.isFile()) {
195
+ if (!shouldExcludeFile(entry.name, excludePatterns)) {
196
+ count++;
197
+ }
198
+ }
199
+ }
200
+
201
+ return count;
202
+ } catch (error) {
203
+ return 0;
204
+ }
205
+ }
206
+
207
+ private async analyzeDirectory(
208
+ dirPath: string,
209
+ recursive: boolean,
210
+ excludePatterns: string[],
211
+ progressCallback?: ProgressCallback,
212
+ totalFiles?: number,
213
+ maxDepth: number = -1,
214
+ currentDepth: number = 0
215
+ ): Promise<void> {
216
+ if (maxDepth >= 0 && currentDepth > maxDepth) {
217
+ return;
218
+ }
219
+
220
+ try {
221
+ const entries = await fs.readdir(dirPath, { withFileTypes: true });
222
+
223
+ for (const entry of entries) {
224
+ const fullPath = path.join(dirPath, entry.name);
225
+
226
+ if (entry.isDirectory()) {
227
+ // Check if directory should be excluded
228
+ if (shouldExcludeDirectory(entry.name, excludePatterns)) {
229
+ continue;
230
+ }
231
+
232
+ this.folderCount++;
233
+
234
+ if (recursive) {
235
+ await this.analyzeDirectory(
236
+ fullPath,
237
+ recursive,
238
+ excludePatterns,
239
+ progressCallback,
240
+ totalFiles,
241
+ maxDepth,
242
+ currentDepth + 1
243
+ );
244
+ }
245
+ } else if (entry.isFile()) {
246
+ // Check if file should be excluded
247
+ if (shouldExcludeFile(entry.name, excludePatterns)) {
248
+ continue;
249
+ }
250
+
251
+ try {
252
+ const stats = await fs.stat(fullPath);
253
+ this.totalSize += stats.size;
254
+ this.fileCount++;
255
+ this.classifier.classifyFile(entry.name);
256
+
257
+ // Store file info for advanced analysis
258
+ this.allFiles.push({
259
+ path: fullPath,
260
+ size: stats.size
261
+ });
262
+
263
+ this.processedFiles++;
264
+
265
+ if (progressCallback && totalFiles) {
266
+ progressCallback(this.processedFiles, totalFiles, fullPath);
267
+ }
268
+ } catch (error) {
269
+ // Skip files that can't be accessed
270
+ console.warn(`Warning: Unable to access file '${fullPath}': ${error}`);
271
+ }
272
+ }
273
+ }
274
+ } catch (error) {
275
+ console.warn(`Warning: Unable to read directory '${dirPath}': ${error}`);
276
+ }
277
+ }
278
+ }
@@ -0,0 +1,83 @@
1
+ export interface FileTypeClassification {
2
+ images: number;
3
+ videos: number;
4
+ documents: number;
5
+ audio: number;
6
+ code: number;
7
+ archives: number;
8
+ other: number;
9
+ }
10
+
11
+ export interface FileTypeExtensions {
12
+ images: string[];
13
+ videos: string[];
14
+ documents: string[];
15
+ audio: string[];
16
+ code: string[];
17
+ archives: string[];
18
+ }
19
+
20
+ export const FILE_TYPE_EXTENSIONS: FileTypeExtensions = {
21
+ images: ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp', '.tiff', '.ico'],
22
+ videos: ['.mp4', '.mkv', '.avi', '.mov', '.webm', '.flv', '.wmv', '.m4v'],
23
+ documents: ['.pdf', '.docx', '.xlsx', '.pptx', '.txt', '.doc', '.xls', '.ppt', '.rtf', '.odt', '.ods', '.odp'],
24
+ audio: ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a'],
25
+ code: [
26
+ '.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.cpp', '.c', '.h', '.hpp',
27
+ '.cs', '.php', '.rb', '.go', '.rs', '.swift', '.kt', '.scala', '.clj',
28
+ '.sh', '.bat', '.ps1', '.sql', '.html', '.css', '.scss', '.sass', '.less',
29
+ '.json', '.xml', '.yaml', '.yml', '.toml', '.ini', '.cfg', '.conf'
30
+ ],
31
+ archives: ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.tar.gz', '.tar.bz2']
32
+ };
33
+
34
+ export class FileClassifier {
35
+ private classification: FileTypeClassification = {
36
+ images: 0,
37
+ videos: 0,
38
+ documents: 0,
39
+ audio: 0,
40
+ code: 0,
41
+ archives: 0,
42
+ other: 0
43
+ };
44
+
45
+ classifyFile(filename: string): void {
46
+ const extension = this.getFileExtension(filename);
47
+ const fileType = this.getFileType(extension);
48
+ this.classification[fileType]++;
49
+ }
50
+
51
+ private getFileExtension(filename: string): string {
52
+ const lastDotIndex = filename.lastIndexOf('.');
53
+ if (lastDotIndex === -1 || lastDotIndex === filename.length - 1) {
54
+ return '';
55
+ }
56
+ return filename.substring(lastDotIndex).toLowerCase();
57
+ }
58
+
59
+ private getFileType(extension: string): keyof FileTypeClassification {
60
+ for (const [type, extensions] of Object.entries(FILE_TYPE_EXTENSIONS)) {
61
+ if (extensions.includes(extension)) {
62
+ return type as keyof FileTypeClassification;
63
+ }
64
+ }
65
+ return 'other';
66
+ }
67
+
68
+ getClassification(): FileTypeClassification {
69
+ return { ...this.classification };
70
+ }
71
+
72
+ reset(): void {
73
+ this.classification = {
74
+ images: 0,
75
+ videos: 0,
76
+ documents: 0,
77
+ audio: 0,
78
+ code: 0,
79
+ archives: 0,
80
+ other: 0
81
+ };
82
+ }
83
+ }