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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 3x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 4x 4x 40x 40x 2x 4x 4x 12x 9x 9x 9x 1x 4x 7x 7x 7x 7x 6x 2x 2x 6x 7x 7x 7x 3x 3x 3x 3x 4x 1x 7x 13x 13x 13x 10x 10x 10x 4x 4x 6x 1x 3x 13x | import * as fs from 'fs/promises';
import * as path from 'path';
import dotenv from 'dotenv';
// Load environment variables
dotenv.config();
const DEFAULT_CONTEXT_DIR = './lamplighter_context';
const SUMMARY_FILE_NAME = 'codebase_summary.md';
// Tech stack detection patterns
const TECH_PATTERNS = {
nodejs: ['package.json', 'node_modules'],
typescript: ['tsconfig.json', '.ts', '.tsx'],
python: ['requirements.txt', 'setup.py', '.py'],
java: ['pom.xml', 'build.gradle', '.java'],
rust: ['Cargo.toml', '.rs'],
go: ['go.mod', '.go'],
docker: ['Dockerfile', 'docker-compose.yml'],
git: ['.git', '.gitignore'],
} as const;
// Directories to ignore
const IGNORE_DIRS = new Set([
'node_modules',
'dist',
'build',
'target',
'.git',
'__pycache__',
'venv',
'.env'
]);
export class CodebaseAnalyzer {
private contextDir: string;
private summaryPath: string;
constructor() {
this.contextDir = process.env.LAMPLIGHTER_CONTEXT_DIR || DEFAULT_CONTEXT_DIR;
this.summaryPath = path.join(this.contextDir, SUMMARY_FILE_NAME);
}
/**
* Analyzes the project structure and generates a summary
*/
async analyze(projectRoot: string): Promise<void> {
const content: string[] = [];
content.push('# Codebase Summary\n');
content.push(`*Generated at: ${new Date().toISOString()}*\n`);
try {
// Ensure context directory exists
await fs.mkdir(this.contextDir, { recursive: true });
// Detect tech stack
const techStack = await this.detectTechStack(projectRoot);
content.push('## Tech Stack\n');
if (techStack.length > 0) {
for (const tech of techStack) {
content.push(tech);
}
} else {
content.push('_(No specific technologies detected)_\n');
}
content.push('\n');
// Analyze directory structure
content.push('## Directory Structure\n');
content.push('```');
const dirStructure = await this.analyzeDirectory(projectRoot, 0);
content.push(dirStructure || '_(Empty or unreadable)_');
content.push('```\n');
// Write the summary to file
await fs.writeFile(this.summaryPath, content.join('\n'), 'utf-8');
console.log(`[CodebaseAnalyzer] Summary written to ${this.summaryPath}`);
} catch (error) {
console.error('[CodebaseAnalyzer] Error during analysis:', error);
// Attempt to write an error state to the summary file
content.push('\n## Analysis Error\n');
content.push('```');
content.push(`An error occurred during analysis: ${error instanceof Error ? error.message : String(error)}`);
content.push('```');
try {
await fs.writeFile(this.summaryPath, content.join('\n'), 'utf-8');
console.warn(`[CodebaseAnalyzer] Wrote error state to summary file: ${this.summaryPath}`);
} catch (writeError) {
console.error(`[CodebaseAnalyzer] Failed to write error state to summary file:`, writeError);
}
// Do not re-throw; allow the process to continue if possible,
// but the summary file will indicate the failure.
}
}
/**
* Detects the primary technologies used in the project.
*/
private async detectTechStack(projectRoot: string): Promise<string[]> {
const tech: Set<string> = new Set(); // Use a Set to prevent duplicates inherently
const techReasons: Record<string, string> = {}; // Store reason for first detection
const addTech = (name: string, reason: string) => {
if (!tech.has(name)) {
tech.add(name);
techReasons[name] = reason;
}
};
const checks = [
{ name: 'nodejs', file: 'package.json' },
{ name: 'typescript', file: 'tsconfig.json' },
{ name: 'python', file: 'requirements.txt' },
{ name: 'python', file: 'setup.py' },
{ name: 'java', file: 'pom.xml' },
{ name: 'java', file: 'build.gradle' },
{ name: 'rust', file: 'Cargo.toml' },
{ name: 'golang', file: 'go.mod' },
{ name: 'git', file: '.git' }, // Check for .git directory
{ name: 'git', file: '.gitignore' },
];
for (const check of checks) {
try {
await fs.access(path.join(projectRoot, check.file));
addTech(check.name, check.file);
} catch (error) { /* ignore */ }
}
// Fallback: Check for file extensions ONLY if the tech hasn't been added by primary file
const fileExtensionChecks = [
{ name: 'typescript', ext: '.ts' },
{ name: 'typescript', ext: '.tsx' },
{ name: 'python', ext: '.py' },
// Add more extension checks if needed
];
for (const extCheck of fileExtensionChecks) {
if (!tech.has(extCheck.name)) { // Only check if tech not already detected
try {
const files = await this.findFilesByExtension(projectRoot, extCheck.ext);
if (files.length > 0) {
addTech(extCheck.name, `${extCheck.ext} files`);
}
} catch (error) {
// Log this error as it might indicate deeper issues than just missing tech
console.error(`[CodebaseAnalyzer] Error during fallback extension check for ${extCheck.ext}:`, error);
}
}
}
// Format output
return Array.from(tech).map(name => `- **${name}** (detected from: ${techReasons[name]})`);
}
/**
* Recursively analyzes directory structure
*/
private async analyzeDirectory(dir: string, depth: number): Promise<string> {
const indent = ' '.repeat(depth);
const result: string[] = [];
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
const sortedEntries = entries.sort((a, b) => {
// Directories first, then files
Iif (a.isDirectory() && !b.isDirectory()) return -1;
if (!a.isDirectory() && b.isDirectory()) return 1;
return a.name.localeCompare(b.name);
});
for (const entry of sortedEntries) {
const fullPath = path.join(dir, entry.name);
// Skip ignored directories
Iif (entry.isDirectory() && IGNORE_DIRS.has(entry.name)) {
continue;
}
if (entry.isDirectory()) {
result.push(`${indent}📁 ${entry.name}/`);
const subDirContent = await this.analyzeDirectory(fullPath, depth + 1);
if (subDirContent) {
result.push(subDirContent);
}
} else {
result.push(`${indent}📄 ${entry.name}`);
}
}
} catch (error) {
console.error(`[CodebaseAnalyzer] Error analyzing directory ${dir}:`, error);
}
return result.join('\n');
}
/**
* Helper to find files with specific extension
*/
private async findFilesByExtension(dir: string, ext: string): Promise<string[]> {
const result: string[] = [];
try {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory() && !IGNORE_DIRS.has(entry.name)) {
const subDirFiles = await this.findFilesByExtension(fullPath, ext);
result.push(...subDirFiles);
} else if (entry.isFile() && entry.name.endsWith(ext)) {
result.push(fullPath);
}
}
} catch (error) {
console.error(`[CodebaseAnalyzer] Error finding files with extension ${ext}:`, error);
}
return result;
}
}
|