Spaces:
Running
Running
File size: 19,397 Bytes
fd8cdf5 | 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 | import * as fs from 'node:fs';
import * as path from 'node:path';
import { execSync } from 'node:child_process';
/**
* Default directories to exclude from scanning.
*/
export const DEFAULT_IGNORE_DIRS = [
'node_modules',
'.git',
'dist',
'build',
'vendor',
'__pycache__',
'.next',
'.cache',
'.turbo',
'target',
'obj',
'.understand-anything',
];
/**
* Default file patterns to exclude from scanning (binary, generated, lock files).
*/
export const DEFAULT_IGNORE_FILE_PATTERNS = [
'*.lock',
'*.min.js',
'*.min.css',
'*.map',
'*.png',
'*.jpg',
'*.jpeg',
'*.gif',
'*.svg',
'*.ico',
'*.woff',
'*.woff2',
'*.ttf',
'*.eot',
'*.mp3',
'*.mp4',
'*.webm',
'*.zip',
'*.tar',
'*.gz',
'*.pdf',
'*.exe',
'*.dll',
'*.so',
'*.dylib',
];
/**
* Extension-to-language mapping.
*/
const EXTENSION_LANGUAGE_MAP = {
'.ts': 'typescript',
'.tsx': 'typescript',
'.js': 'javascript',
'.jsx': 'javascript',
'.mjs': 'javascript',
'.cjs': 'javascript',
'.py': 'python',
'.go': 'go',
'.rs': 'rust',
'.java': 'java',
'.rb': 'ruby',
'.php': 'php',
'.cs': 'csharp',
'.cpp': 'cpp',
'.cc': 'cpp',
'.cxx': 'cpp',
'.c': 'c',
'.h': 'c',
'.hpp': 'cpp',
'.swift': 'swift',
'.kt': 'kotlin',
'.sh': 'shell',
'.bash': 'shell',
'.sql': 'sql',
'.html': 'html',
'.htm': 'html',
'.css': 'css',
'.scss': 'css',
'.less': 'css',
'.json': 'json',
'.yaml': 'yaml',
'.yml': 'yaml',
'.md': 'markdown',
'.xml': 'xml',
'.toml': 'toml',
'.graphql': 'graphql',
'.gql': 'graphql',
'.proto': 'protobuf',
'.tf': 'terraform',
'.ps1': 'powershell',
'.bat': 'batch',
'.cmd': 'batch',
'.txt': 'text',
'.rst': 'restructuredtext',
'.adoc': 'asciidoc',
'.env': 'env',
'.ini': 'ini',
'.cfg': 'ini',
};
/**
* Extension-to-category mapping.
*/
const EXTENSION_CATEGORY_MAP = {
// code
'.ts': 'code',
'.tsx': 'code',
'.js': 'code',
'.jsx': 'code',
'.mjs': 'code',
'.cjs': 'code',
'.py': 'code',
'.go': 'code',
'.rs': 'code',
'.java': 'code',
'.rb': 'code',
'.php': 'code',
'.cs': 'code',
'.cpp': 'code',
'.cc': 'code',
'.cxx': 'code',
'.c': 'code',
'.h': 'code',
'.hpp': 'code',
'.swift': 'code',
'.kt': 'code',
// config
'.json': 'config',
'.yaml': 'config',
'.yml': 'config',
'.toml': 'config',
'.xml': 'config',
'.env': 'config',
'.ini': 'config',
'.cfg': 'config',
// docs
'.md': 'docs',
'.txt': 'docs',
'.rst': 'docs',
'.adoc': 'docs',
// infra
'.tf': 'infra',
// data
'.sql': 'data',
'.graphql': 'data',
'.gql': 'data',
'.proto': 'data',
// script
'.sh': 'script',
'.bash': 'script',
'.ps1': 'script',
'.bat': 'script',
'.cmd': 'script',
// markup
'.html': 'markup',
'.htm': 'markup',
'.css': 'markup',
'.scss': 'markup',
'.less': 'markup',
'.svg': 'markup',
};
/**
* Filenames that indicate infra category regardless of extension.
*/
const INFRA_FILENAMES = [
'dockerfile',
'docker-compose.yml',
'docker-compose.yaml',
];
/**
* Reads the .understand-anything/.understandignore file and returns patterns.
* Returns an empty array if the file doesn't exist.
*/
function readUnderstandIgnore(projectRoot) {
const ignorePath = path.join(projectRoot, '.understand-anything', '.understandignore');
try {
const content = fs.readFileSync(ignorePath, 'utf-8');
return content
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0 && !line.startsWith('#'));
}
catch {
return [];
}
}
/**
* Checks if a filename matches a glob pattern (simple glob: supports * wildcard).
*/
function matchesGlobPattern(filename, pattern) {
// Convert glob pattern to regex
const escaped = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.');
const regex = new RegExp(`^${escaped}$`, 'i');
return regex.test(filename);
}
/**
* Checks if a relative path matches a glob pattern that may include directory separators.
*/
function matchesPathPattern(relativePath, pattern) {
// Normalize separators
const normalizedPath = relativePath.replace(/\\/g, '/');
const normalizedPattern = pattern.replace(/\\/g, '/');
// If pattern contains a slash, match against the full relative path
if (normalizedPattern.includes('/')) {
const escaped = normalizedPattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*\*/g, '{{GLOBSTAR}}')
.replace(/\*/g, '[^/]*')
.replace(/\{\{GLOBSTAR\}\}/g, '.*')
.replace(/\?/g, '.');
const regex = new RegExp(`^${escaped}$`, 'i');
// Also try matching as a prefix (for directory patterns like "src/generated/**")
if (regex.test(normalizedPath)) {
return true;
}
// If pattern ends with /**, also match the directory itself
if (normalizedPattern.endsWith('/**')) {
const dirPrefix = normalizedPattern.slice(0, -3);
if (normalizedPath.startsWith(dirPrefix + '/') || normalizedPath === dirPrefix) {
return true;
}
}
return false;
}
// Otherwise match against just the filename
return matchesGlobPattern(path.basename(relativePath), normalizedPattern);
}
/**
* Determines if a file should be excluded based on ignore patterns.
*/
function shouldExcludeFile(relativePath, filename, ignorePatterns) {
// Check default file patterns
for (const pattern of DEFAULT_IGNORE_FILE_PATTERNS) {
if (matchesGlobPattern(filename, pattern)) {
return true;
}
}
// Check custom ignore patterns
for (const pattern of ignorePatterns) {
if (matchesPathPattern(relativePath, pattern)) {
return true;
}
}
return false;
}
/**
* Detects the language of a file from its extension or filename.
*/
function detectLanguage(filePath) {
const basename = path.basename(filePath).toLowerCase();
// Special filename-based detection
if (basename === 'dockerfile' || basename.startsWith('dockerfile.')) {
return 'dockerfile';
}
const ext = path.extname(filePath).toLowerCase();
return EXTENSION_LANGUAGE_MAP[ext] || 'unknown';
}
/**
* Detects the category of a file based on its extension and path.
*/
function detectCategory(filePath) {
const basename = path.basename(filePath).toLowerCase();
const ext = path.extname(filePath).toLowerCase();
// Special filename-based detection for infra
if (INFRA_FILENAMES.includes(basename)) {
return 'infra';
}
// Dockerfile without extension
if (basename === 'dockerfile' || basename.startsWith('dockerfile.')) {
return 'infra';
}
// Check path patterns for infra (e.g., .k8s, .helm directories)
const normalizedPath = filePath.replace(/\\/g, '/');
if (normalizedPath.includes('.k8s/') || normalizedPath.includes('.helm/') ||
normalizedPath.includes('k8s/') || normalizedPath.includes('helm/')) {
return 'infra';
}
return EXTENSION_CATEGORY_MAP[ext] || 'code';
}
/**
* Counts the number of lines in a file.
*/
function countLines(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf-8');
if (content.length === 0)
return 0;
return content.split('\n').length;
}
catch {
return 0;
}
}
/**
* Recursively scans a directory for files, respecting ignore patterns.
*/
function scanDirectory(dirPath, projectRoot, ignorePatterns, files) {
let entries;
try {
entries = fs.readdirSync(dirPath, { withFileTypes: true });
}
catch {
return;
}
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
const relativePath = path.relative(projectRoot, fullPath);
if (entry.isDirectory()) {
// Skip excluded directories
if (DEFAULT_IGNORE_DIRS.includes(entry.name)) {
continue;
}
// Check if directory matches any ignore pattern
const relDirPath = relativePath.replace(/\\/g, '/');
let skipDir = false;
for (const pattern of ignorePatterns) {
if (matchesPathPattern(relDirPath, pattern) || matchesPathPattern(relDirPath + '/', pattern)) {
skipDir = true;
break;
}
}
if (skipDir)
continue;
scanDirectory(fullPath, projectRoot, ignorePatterns, files);
}
else if (entry.isFile()) {
const relFilePath = relativePath.replace(/\\/g, '/');
// Check if file should be excluded
if (shouldExcludeFile(relFilePath, entry.name, ignorePatterns)) {
continue;
}
const language = detectLanguage(fullPath);
const category = detectCategory(relFilePath);
const lineCount = countLines(fullPath);
files.push({
path: fullPath,
relativePath: relFilePath,
category,
language,
lineCount,
});
}
}
}
/**
* Framework detection patterns based on config file names.
*/
const FRAMEWORK_FILE_PATTERNS = [
{ pattern: 'next.config', framework: 'Next.js' },
{ pattern: 'nuxt.config', framework: 'Nuxt' },
{ pattern: 'angular.json', framework: 'Angular' },
{ pattern: 'svelte.config', framework: 'Svelte' },
{ pattern: 'astro.config', framework: 'Astro' },
{ pattern: 'vite.config', framework: 'Vite' },
{ pattern: 'webpack.config', framework: 'Webpack' },
{ pattern: 'tailwind.config', framework: 'TailwindCSS' },
{ pattern: 'manage.py', framework: 'Django' },
];
/**
* Framework detection from package.json dependencies.
*/
const DEPENDENCY_FRAMEWORK_MAP = {
'react': 'React',
'vue': 'Vue',
'@angular/core': 'Angular',
'next': 'Next.js',
'express': 'Express',
'fastify': 'Fastify',
'@nestjs/core': 'NestJS',
'astro': 'Astro',
'svelte': 'Svelte',
'nuxt': 'Nuxt',
'vite': 'Vite',
};
/**
* Framework detection from Python dependencies.
*/
const PYTHON_FRAMEWORK_MAP = {
'django': 'Django',
'flask': 'Flask',
'fastapi': 'FastAPI',
};
/**
* Reads a file safely, returning null on failure.
*/
function readFileSafe(filePath) {
try {
return fs.readFileSync(filePath, 'utf-8');
}
catch {
return null;
}
}
/**
* Extracts a simple value from a TOML file using regex.
* Handles both quoted and unquoted values.
*/
function extractTomlValue(content, section, key) {
// Find the section
const sectionRegex = new RegExp(`\\[${section.replace('.', '\\.')}\\]`);
const sectionMatch = content.match(sectionRegex);
if (!sectionMatch || sectionMatch.index === undefined)
return '';
// Get content after section header until next section
const afterSection = content.slice(sectionMatch.index + sectionMatch[0].length);
const nextSectionIdx = afterSection.search(/^\[/m);
const sectionContent = nextSectionIdx >= 0 ? afterSection.slice(0, nextSectionIdx) : afterSection;
// Find the key
const keyRegex = new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, 'm');
const keyMatch = sectionContent.match(keyRegex);
return keyMatch ? keyMatch[1] : '';
}
/**
* Extracts dependencies list from a TOML section (pyproject.toml).
*/
function extractTomlDependencies(content) {
// Look for dependencies in [project] section
const depsRegex = /\[project\][\s\S]*?dependencies\s*=\s*\[([\s\S]*?)\]/;
const match = content.match(depsRegex);
if (!match)
return [];
// Extract package names from the array
return match[1]
.split('\n')
.map(line => line.trim().replace(/^["']/, '').replace(/["'].*$/, ''))
.filter(line => line.length > 0 && !line.startsWith('#'))
.map(dep => dep.split(/[>=<!\s]/)[0].toLowerCase());
}
/**
* Detects project metadata from manifest files and scanned file entries.
*/
export function detectMetadata(projectRoot, files) {
let name = '';
let description = '';
const detectedFrameworks = new Set();
// 1. Try package.json first (highest priority)
const packageJsonContent = readFileSafe(path.join(projectRoot, 'package.json'));
if (packageJsonContent) {
try {
const pkg = JSON.parse(packageJsonContent);
name = pkg.name || '';
description = pkg.description || '';
// Detect frameworks from dependencies
const allDeps = {
...(pkg.dependencies || {}),
...(pkg.devDependencies || {}),
};
for (const [depName, framework] of Object.entries(DEPENDENCY_FRAMEWORK_MAP)) {
if (depName in allDeps) {
detectedFrameworks.add(framework);
}
}
// Detect TypeScript from dependencies
if ('typescript' in allDeps || Object.keys(allDeps).some(d => d.startsWith('@types/'))) {
// TypeScript is detected as a language, not a framework — handled in language detection
}
}
catch {
// Invalid JSON, skip
}
}
// 2. Try pyproject.toml
if (!name) {
const pyprojectContent = readFileSafe(path.join(projectRoot, 'pyproject.toml'));
if (pyprojectContent) {
name = extractTomlValue(pyprojectContent, 'project', 'name');
description = extractTomlValue(pyprojectContent, 'project', 'description');
// Detect Python frameworks from dependencies
const deps = extractTomlDependencies(pyprojectContent);
for (const [depName, framework] of Object.entries(PYTHON_FRAMEWORK_MAP)) {
if (deps.some(d => d === depName || d.startsWith(depName + '['))) {
detectedFrameworks.add(framework);
}
}
}
}
// 3. Try Cargo.toml
if (!name) {
const cargoContent = readFileSafe(path.join(projectRoot, 'Cargo.toml'));
if (cargoContent) {
name = extractTomlValue(cargoContent, 'package', 'name');
description = extractTomlValue(cargoContent, 'package', 'description');
}
}
// 4. Try go.mod
if (!name) {
const goModContent = readFileSafe(path.join(projectRoot, 'go.mod'));
if (goModContent) {
const moduleMatch = goModContent.match(/^module\s+(.+)$/m);
if (moduleMatch) {
name = moduleMatch[1].trim();
}
}
}
// 5. Try pom.xml
if (!name) {
const pomContent = readFileSafe(path.join(projectRoot, 'pom.xml'));
if (pomContent) {
const artifactIdMatch = pomContent.match(/<artifactId>([^<]+)<\/artifactId>/);
const nameMatch = pomContent.match(/<name>([^<]+)<\/name>/);
name = nameMatch ? nameMatch[1] : (artifactIdMatch ? artifactIdMatch[1] : '');
const descMatch = pomContent.match(/<description>([^<]+)<\/description>/);
description = descMatch ? descMatch[1] : '';
}
}
// 6. Detect languages from scanned files
const languageCounts = new Map();
for (const file of files) {
if (file.language && file.language !== 'unknown') {
languageCounts.set(file.language, (languageCounts.get(file.language) || 0) + 1);
}
}
// Sort by frequency (most common first)
const languages = [...languageCounts.entries()]
.sort((a, b) => b[1] - a[1])
.map(([lang]) => lang);
// 7. Detect frameworks from file patterns
for (const file of files) {
const basename = path.basename(file.relativePath);
for (const { pattern, framework } of FRAMEWORK_FILE_PATTERNS) {
if (pattern === basename || basename.startsWith(pattern + '.') || basename.startsWith(pattern)) {
// Exact match or starts with pattern (e.g., "next.config.mjs" starts with "next.config")
if (pattern.includes('.') ? basename.startsWith(pattern) : basename === pattern) {
detectedFrameworks.add(framework);
}
}
}
}
// Check for Flask/FastAPI from app.py or wsgi.py
const hasAppPy = files.some(f => path.basename(f.relativePath) === 'app.py');
const hasWsgiPy = files.some(f => path.basename(f.relativePath) === 'wsgi.py');
if (hasAppPy || hasWsgiPy) {
// Try to read the file to check imports
const targetFile = files.find(f => path.basename(f.relativePath) === 'app.py' || path.basename(f.relativePath) === 'wsgi.py');
if (targetFile) {
const content = readFileSafe(targetFile.path);
if (content) {
if (content.includes('from flask') || content.includes('import flask')) {
detectedFrameworks.add('Flask');
}
if (content.includes('from fastapi') || content.includes('import fastapi')) {
detectedFrameworks.add('FastAPI');
}
}
}
}
// Check for Rails from Gemfile
const gemfileContent = readFileSafe(path.join(projectRoot, 'Gemfile'));
if (gemfileContent) {
if (gemfileContent.includes("'rails'") || gemfileContent.includes('"rails"')) {
detectedFrameworks.add('Ruby on Rails');
}
}
// 8. Get git commit hash
let gitCommitHash = '';
try {
gitCommitHash = execSync('git rev-parse HEAD', {
cwd: projectRoot,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
}
catch {
// Not a git repo or git not available
}
return {
name,
description,
languages,
frameworks: [...detectedFrameworks],
analyzedAt: new Date().toISOString(),
gitCommitHash,
};
}
/**
* Scans a project directory for source files, excluding common non-source
* directories and respecting ignore patterns.
*
* @param projectRoot - Absolute path to the project root directory
* @param ignorePatterns - Additional glob patterns to exclude
* @returns ScanResult with discovered files and detected project metadata
*/
export function scanProject(projectRoot, ignorePatterns = []) {
// Read .understand-anything/.understandignore patterns
const understandIgnorePatterns = readUnderstandIgnore(projectRoot);
// Combine all ignore patterns
const allIgnorePatterns = [...ignorePatterns, ...understandIgnorePatterns];
// Scan the directory tree
const files = [];
scanDirectory(projectRoot, projectRoot, allIgnorePatterns, files);
// Detect project metadata from manifest files and scanned files
const metadata = detectMetadata(projectRoot, files);
return {
files,
metadata,
};
}
|