All files codebaseAnalyzer.ts

83.33% Statements 70/84
69.23% Branches 18/26
87.5% Functions 7/8
84.14% Lines 69/82

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 1901x 1x 1x     1x   1x 1x     1x                       1x                     1x         4x 4x             4x   4x     4x 4x 4x     4x 4x 4x 32x       4x     4x 4x 4x 4x 4x     4x 4x                       4x   4x 32x 32x 76x   32x 32x 32x                 44x 44x   44x 44x                   4x             7x 7x   7x 7x 4x   2x 2x       4x 5x     5x       5x 3x 3x 3x       2x       3x     7x             55x   55x 55x   31x 39x   39x 23x 23x 16x         24x     55x      
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> {
        try {
            // Ensure context directory exists
            await fs.mkdir(this.contextDir, { recursive: true });
 
            // Start building the summary content
            const content: string[] = [];
            content.push('# Codebase Summary\n');
            content.push(`*Generated at: ${new Date().toISOString()}*\n`);
 
            // Detect tech stack
            const techStack = await this.detectTechStack(projectRoot);
            content.push('## Tech Stack\n');
            for (const [tech, evidence] of Object.entries(techStack)) {
                Iif (evidence.length > 0) {
                    content.push(`- **${tech}** (detected from: ${evidence.join(', ')})`);
                }
            }
            content.push('\n');
 
            // Analyze directory structure
            content.push('## Directory Structure\n');
            content.push('```');
            const dirStructure = await this.analyzeDirectory(projectRoot, 0);
            content.push(dirStructure);
            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);
            throw error; // Re-throw to let caller handle it
        }
    }
 
    /**
     * Detects technologies used in the project
     */
    private async detectTechStack(dir: string): Promise<Record<string, string[]>> {
        const result: Record<string, string[]> = {};
        
        for (const [tech, patterns] of Object.entries(TECH_PATTERNS)) {
            result[tech] = [];
            for (const pattern of patterns) {
                if (pattern.startsWith('.')) {
                    // For file extensions, we need to search recursively
                    try {
                        const files = await this.findFilesByExtension(dir, pattern);
                        Iif (files.length > 0) {
                            result[tech].push(pattern);
                            break; // One match is enough
                        }
                    } catch (error) {
                        console.warn(`[CodebaseAnalyzer] Error searching for ${pattern} files:`, error);
                    }
                } else {
                    // For specific files, just check if they exist
                    try {
                        const exists = await fs.access(path.join(dir, pattern))
                            .then(() => true)
                            .catch(() => false);
                        Iif (exists) {
                            result[tech].push(pattern);
                        }
                    } catch (error) {
                        console.warn(`[CodebaseAnalyzer] Error checking for ${pattern}:`, error);
                    }
                }
            }
        }
 
        return result;
    }
 
    /**
     * 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);
                    Iif (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 Iif (entry.isFile() && entry.name.endsWith(ext)) {
                    result.push(fullPath);
                }
            }
        } catch (error) {
            console.error(`[CodebaseAnalyzer] Error finding files with extension ${ext}:`, error);
        }
 
        return result;
    }
}