Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | 2x 2x 2x 2x 1x 1x 1x 217x 1x 1x 1x 1x 1x 1x 1x 1x 1x 316x 316x 316x 316x 102x 102x 102x 102x 337x 337x 337x 22x 315x 315x 315x 315x 102x 100x 316x 1x 1x 316x 316x 315x 216x 216x 216x 216x 5116x 216x 173x 1x 1x 532x 532x 6544x 532x 7095x 7095x 12x 7083x 1x 1x 173x 173x 173x 173x 1x 1x 1x 173x 173x 173x 173x 1x 173x 173x 173x 173x 173x 173x 173x 173x 122065x 173x 1x 1x 1x 1x 1x 1x 1x 1x 1x 173x 173x 173x 173x 173x 173x 172x 172x 1x 1x 1x 173x 173x 1x 173x 1x 1x 173x 173x 173x 1729x 173x 1556x 98x 1556x 1x 1x 1x 1x 99x 99x 99x 271x 271x 271x 271x 98x 98x 99x 1x 1x 66x 66x 66x 66x 214x 66x 281x 281x 281x 220x 215x 66x 214x 214x 214x 214x 214x 214x 126x 214x 214x 65x 149x 75x 23x 18x 41x 41x 41x 18x 9x 5x 66x 1x 1x 1x 1x 1x 1x 1x 1x 2x | const fs = require('fs-extra');
const path = require('path');
const dirTree = require('directory-tree');
const IgnoreManager = require('../ignore/ignore-manager');
/**
* Scanner để duyệt và nối file mã nguồn
*/
class FileScanner {
constructor(projectPath, options = {}) {
this.projectPath = projectPath;
this.options = {
maxFileSize: options.maxFileSize || 1024 * 1024, // 1MB default
extensions: options.extensions || this.getDefaultExtensions(),
includeHidden: options.includeHidden || false,
maxDepth: options.maxDepth || 10,
...options
};
this.ignoreManager = new IgnoreManager(projectPath);
}
/**
* Lấy danh sách extensions mặc định
*/
getDefaultExtensions() {
return [
// Web Frontend
'.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte',
'.html', '.htm', '.css', '.scss', '.sass', '.less',
// Backend
'.java', '.kt', '.scala', '.groovy',
'.py', '.rb', '.php', '.go', '.rs',
'.cs', '.vb', '.fs',
'.cpp', '.c', '.h', '.hpp',
// Config files
'.json', '.yaml', '.yml', '.toml', '.ini', '.conf',
'.xml', '.properties',
// Build files
'.gradle', '.maven', '.sbt',
// Scripts
'.sh', '.bat', '.ps1', '.cmd',
// Documentation
'.md', '.txt', '.rst',
// SQL
'.sql', '.ddl', '.dml'
];
}
/**
* Scan toàn bộ project và trả về cấu trúc file
*/
async scanProject() {
const startTime = Date.now();
try {
// Lấy cấu trúc thư mục
const tree = await this.buildFileTree();
// Lấy danh sách files
const files = await this.extractFiles(tree);
// Lọc files theo ignore rules
const filteredFiles = await this.filterFiles(files);
// Đọc nội dung files
const filesWithContent = await this.readFilesContent(filteredFiles);
const endTime = Date.now();
return {
tree,
files: filesWithContent,
stats: {
totalFiles: files.length,
filteredFiles: filteredFiles.length,
processedFiles: filesWithContent.length,
scanTime: endTime - startTime,
projectPath: this.projectPath
}
};
} catch (error) {
throw new Error(`Failed to scan project: ${error.message}`);
}
}
/**
* Xây dựng cây thư mục
*/
async buildFileTree() {
// Use manual scanning instead of directory-tree to ensure all Java files are found
return await this.scanDirectoryManually(this.projectPath);
}
/**
* Manually scan directory to ensure all files are found
*/
async scanDirectoryManually(dirPath, relativePath = '') {
const stats = await fs.stat(dirPath);
const name = path.basename(dirPath);
const node = {
path: dirPath,
name: name,
size: stats.size,
type: stats.isDirectory() ? 'directory' : 'file',
extension: stats.isFile() ? path.extname(name) : undefined
};
if (stats.isDirectory()) {
try {
const entries = await fs.readdir(dirPath);
const children = [];
for (const entry of entries) {
const entryPath = path.join(dirPath, entry);
const entryRelativePath = path.join(relativePath, entry);
// Skip ignored directories
if (this.shouldIgnoreDirectoryName(entry)) {
continue;
}
try {
const childNode = await this.scanDirectoryManually(entryPath, entryRelativePath);
Eif (childNode) {
children.push(childNode);
}
} catch (error) {
// Skip files/directories that can't be accessed
continue;
}
}
if (children.length > 0) {
node.children = children;
}
} catch (error) {
// Skip directories that can't be read
}
}
return node;
}
/**
* Get regex for build directories and hidden files to ignore
*/
getBuildIgnoreRegex() {
// Create regex pattern for directories to ignore
const ignorePatterns = [
// Hidden directories (starting with .)
'^\\..*',
// Build directories
'^build$',
'^target$',
'^dist$',
'^out$',
'^bin$',
// Dependencies
'^node_modules$',
'^vendor$',
// Temporary files
'^tmp$',
'^temp$',
// Logs
'^logs$',
'^log$',
// Coverage reports
'^coverage$'
];
// Combine all patterns into one regex
const combinedPattern = ignorePatterns.join('|');
return new RegExp(`(${combinedPattern})`);
}
/**
* Trích xuất danh sách files từ tree
*/
async extractFiles(tree) {
const files = [];
const traverse = (node, currentPath = '') => {
// Skip ignored directories
Iif (this.shouldIgnorePath(node.path || node.name)) {
return;
}
// Nếu node có children thì là directory
if (node.children) {
node.children.forEach(child => traverse(child, currentPath));
} else {
// Nếu không có children thì là file
const relativePath = path.relative(this.projectPath, node.path);
// Skip files in ignored directories
Eif (!this.shouldIgnorePath(relativePath)) {
// Filter by extension
const extensions = this.options.extensions || this.getDefaultExtensions();
const hasValidExtension = extensions.some(ext =>
node.name.toLowerCase().endsWith(ext.toLowerCase())
);
if (hasValidExtension) {
files.push({
path: node.path,
relativePath: relativePath,
name: node.name,
extension: node.extension,
size: node.size
});
}
}
}
};
traverse(tree);
return files;
}
/**
* Check if path should be ignored
*/
shouldIgnorePath(filePath) {
const pathParts = filePath.split(path.sep);
// Check each part of the path
for (const part of pathParts) {
Iif (this.shouldIgnoreDirectoryName(part)) {
return true;
}
}
return false;
}
/**
* Check if directory/file should be ignored
*/
shouldIgnoreDirectoryName(name) {
// List of directories/files to ignore
const ignoreList = [
// Hidden directories (starting with .)
'.git', '.svn', '.hg',
'.gradle', '.maven', '.cache', '.npm',
'.idea', '.vscode', '.eclipse',
'.DS_Store', '.tmp',
// Build directories
'build', 'target', 'dist', 'out', 'bin',
// Dependencies
'node_modules', 'vendor',
// Temporary files
'tmp', 'temp',
// Logs
'logs', 'log',
// Coverage reports
'coverage', '.nyc_output'
];
// Check if name starts with . (hidden files/dirs)
if (name.startsWith('.')) {
return true;
}
// Check if name is in ignore list
return ignoreList.includes(name);
}
/**
* Lọc files theo ignore rules
*/
async filterFiles(files) {
const filtered = [];
for (const file of files) {
// Kiểm tra size
Iif (file.size > this.options.maxFileSize) {
continue;
}
// Kiểm tra ignore rules
const shouldIgnore = await this.ignoreManager.shouldIgnore(file.relativePath);
Eif (!shouldIgnore) {
filtered.push(file);
}
}
return filtered;
}
/**
* Đọc nội dung files
*/
async readFilesContent(files) {
const filesWithContent = [];
for (const file of files) {
try {
const content = await this.readFileContent(file.path);
Eif (content !== null) {
filesWithContent.push({
...file,
content,
lines: content.split('\n').length,
encoding: 'utf8'
});
}
} catch (error) {
// Log error but continue with other files
console.warn(`Warning: Could not read file ${file.relativePath}: ${error.message}`);
}
}
return filesWithContent;
}
/**
* Đọc nội dung một file
*/
async readFileContent(filePath) {
try {
// Kiểm tra xem file có phải binary không
Iif (await this.isBinaryFile(filePath)) {
return null;
}
const content = await fs.readFile(filePath, 'utf8');
return content;
} catch (error) {
if (error.code === 'ENOENT') {
return null;
}
throw error;
}
}
/**
* Kiểm tra xem file có phải binary không
*/
async isBinaryFile(filePath) {
try {
const buffer = await fs.readFile(filePath);
// Kiểm tra 1024 bytes đầu
const chunk = buffer.slice(0, 1024);
// Nếu có null bytes thì có thể là binary
for (let i = 0; i < chunk.length; i++) {
Iif (chunk[i] === 0) {
return true;
}
}
return false;
} catch (error) {
return true; // Assume binary if can't read
}
}
/**
* Tạo nội dung kết hợp từ tất cả files
*/
async createCombinedContent(files, options = {}) {
const {
includeStats = true,
includeTree = true,
headerTemplate = this.getDefaultHeaderTemplate(),
separatorTemplate = this.getDefaultSeparatorTemplate()
} = options;
let content = '';
// Header với thông tin project
Eif (includeStats) {
content += this.generateProjectHeader(files);
content += '\n\n';
}
// Cấu trúc thư mục
Eif (includeTree) {
content += this.generateTreeStructure(files);
content += '\n\n';
}
// Nội dung từng file
for (let i = 0; i < files.length; i++) {
const file = files[i];
// Header cho file
content += headerTemplate
.replace('{path}', file.relativePath)
.replace('{name}', file.name)
.replace('{extension}', file.extension || '')
.replace('{size}', file.size)
.replace('{lines}', file.lines);
content += '\n';
content += file.content;
content += '\n';
// Separator giữa các files
if (i < files.length - 1) {
content += separatorTemplate;
content += '\n';
}
}
return content;
}
/**
* Template header mặc định cho file
*/
getDefaultHeaderTemplate() {
return `
================================================================================
File: {path}
Size: {size} bytes | Lines: {lines}
================================================================================`;
}
/**
* Template separator mặc định
*/
getDefaultSeparatorTemplate() {
return '\n\n';
}
/**
* Tạo header thông tin project
*/
generateProjectHeader(files) {
const totalSize = files.reduce((sum, file) => sum + file.size, 0);
const totalLines = files.reduce((sum, file) => sum + file.lines, 0);
return `
# Project Analysis Report
Generated: ${new Date().toISOString()}
Project Path: ${this.projectPath}
## Statistics
- Total Files: ${files.length}
- Total Size: ${this.formatBytes(totalSize)}
- Total Lines: ${totalLines.toLocaleString()}
- Extensions: ${[...new Set(files.map(f => f.extension))].filter(Boolean).join(', ')}
`;
}
/**
* Tạo cấu trúc thư mục
*/
generateTreeStructure(files) {
const tree = {};
// Build tree structure
files.forEach(file => {
const parts = file.relativePath.split(path.sep);
let current = tree;
parts.forEach((part, index) => {
if (index === parts.length - 1) {
// File
current[part] = file;
} else {
// Directory
if (!current[part]) {
current[part] = {};
}
current = current[part];
}
});
});
// Generate tree string
let treeStr = '\n## Project Structure\n```\n';
treeStr += this.renderTree(tree, '', true);
treeStr += '```\n';
return treeStr;
}
/**
* Render tree structure
*/
renderTree(node, prefix = '', isLast = true) {
let result = '';
const entries = Object.entries(node);
entries.forEach(([name, value], index) => {
const isLastEntry = index === entries.length - 1;
const connector = isLastEntry ? '└── ' : '├── ';
result += prefix + connector + name + '\n';
if (typeof value === 'object' && !value.relativePath) {
// Directory
const newPrefix = prefix + (isLastEntry ? ' ' : '│ ');
result += this.renderTree(value, newPrefix, isLastEntry);
}
});
return result;
}
/**
* Render project tree structure
*/
renderProjectTree(tree, maxDepth = 10) {
Iif (!tree) return 'No tree structure available';
const renderNode = (node, prefix = '', depth = 0) => {
Iif (depth > maxDepth) return '';
let result = '';
Eif (node.children && node.children.length > 0) {
// Filter out ignored directories
const filteredChildren = node.children.filter(child =>
!this.shouldIgnoreDirectoryName(child.name)
);
// Sort children: directories first, then files
filteredChildren.sort((a, b) => {
const aIsDir = a.children && a.children.length > 0;
const bIsDir = b.children && b.children.length > 0;
if (aIsDir && !bIsDir) return -1;
if (!aIsDir && bIsDir) return 1;
return a.name.localeCompare(b.name);
});
filteredChildren.forEach((child, index) => {
const isLast = index === filteredChildren.length - 1;
const connector = isLast ? '└── ' : '├── ';
const nextPrefix = prefix + (isLast ? ' ' : '│ ');
const isDirectory = child.children !== undefined;
result += `${prefix}${connector}${child.name}`;
if (!isDirectory) {
// It's a file, show extension
result += ` (${child.extension || 'file'})`;
}
result += '\n';
if (isDirectory && depth < maxDepth) {
result += renderNode(child, nextPrefix, depth + 1);
} else if (isDirectory && depth >= maxDepth) {
// Show some files even at max depth for Java packages
const files = child.children ? child.children.filter(c => !c.children && c.extension === '.java') : [];
if (files.length > 0) {
files.slice(0, 3).forEach((file, fileIndex) => {
const fileIsLast = fileIndex === Math.min(files.length, 3) - 1 && files.length <= 3;
const fileConnector = fileIsLast ? '└── ' : '├── ';
result += `${nextPrefix}${fileConnector}${file.name} (${file.extension || 'file'})\n`;
});
if (files.length > 3) {
result += `${nextPrefix}└── ... and ${files.length - 3} more Java files\n`;
}
} else {
result += `${nextPrefix}...\n`;
}
}
});
}
return result;
};
let result = `${tree.name}/\n`;
result += renderNode(tree);
return result;
}
/**
* Format bytes to human readable
*/
formatBytes(bytes) {
Iif (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
}
module.exports = FileScanner;
|