#!/usr/bin/env -S deno run --allow-all /** * Advanced coverage analysis and reporting */ import { parseArgs } from "https://deno.land/std@0.220.0/cli/parse_args.ts"; import { exists } from "https://deno.land/std@0.220.0/fs/exists.ts"; import { ensureDir } from "https://deno.land/std@0.220.0/fs/ensure_dir.ts"; import { walk } from "https://deno.land/std@0.220.0/fs/walk.ts"; interface CoverageData { url: string; ranges: Array<{ start: { line: number; col: number }; end: { line: number; col: number }; }>; } interface FileCoverage { path: string; totalLines: number; coveredLines: number; uncoveredLines: number[]; coverage: number; functions: FunctionCoverage[]; } interface FunctionCoverage { name: string; line: number; covered: boolean; } interface CoverageReport { timestamp: string; summary: { totalFiles: number; totalLines: number; coveredLines: number; coverage: number; thresholds: { statements: number; branches: number; functions: number; lines: number; }; passed: boolean; }; files: FileCoverage[]; uncoveredFiles: string[]; } class CoverageAnalyzer { private sourceDir: string; private coverageDir: string; private outputDir: string; private thresholds: { statements: number; branches: number; functions: number; lines: number; }; constructor(options: { sourceDir: string; coverageDir: string; outputDir: string; thresholds: { statements: number; branches: number; functions: number; lines: number; }; }) { this.sourceDir = options.sourceDir; this.coverageDir = options.coverageDir; this.outputDir = options.outputDir; this.thresholds = options.thresholds; } async generateReport(): Promise { console.log("šŸ“Š Analyzing coverage data..."); await ensureDir(this.outputDir); // Load coverage data const coverageData = await this.loadCoverageData(); // Get all source files const sourceFiles = await this.getSourceFiles(); // Analyze each file const fileAnalysis = await this.analyzeFiles(sourceFiles, coverageData); // Find uncovered files const coveredFiles = new Set(coverageData.map(d => this.normalizePath(d.url))); const uncoveredFiles = sourceFiles.filter(file => !coveredFiles.has(file)); // Calculate summary const summary = this.calculateSummary(fileAnalysis, uncoveredFiles.length); const report: CoverageReport = { timestamp: new Date().toISOString(), summary, files: fileAnalysis, uncoveredFiles, }; // Generate various report formats await this.generateHTMLReport(report); await this.generateJSONReport(report); await this.generateTextReport(report); await this.generateBadges(report); return report; } private async loadCoverageData(): Promise { const coverageFiles: CoverageData[] = []; if (!await exists(this.coverageDir)) { throw new Error(`Coverage directory not found: ${this.coverageDir}`); } for await (const entry of walk(this.coverageDir, { exts: [".json"], includeDirs: false })) { const content = await Deno.readTextFile(entry.path); const data = JSON.parse(content); if (data.url && data.ranges) { coverageFiles.push(data); } } return coverageFiles; } private async getSourceFiles(): Promise { const files: string[] = []; for await (const entry of walk(this.sourceDir, { exts: [".ts"], includeDirs: false, skip: [/\.test\.ts$/, /test\.ts$/, /tests?\//] })) { // Normalize path const relativePath = entry.path.replace(Deno.cwd() + "/", ""); files.push(relativePath); } return files; } private normalizePath(url: string): string { // Convert file:// URLs to relative paths if (url.startsWith("file://")) { url = url.replace("file://", ""); } // Remove leading slash and make relative to cwd const cwd = Deno.cwd(); if (url.startsWith(cwd)) { url = url.replace(cwd + "/", ""); } return url; } private async analyzeFiles(sourceFiles: string[], coverageData: CoverageData[]): Promise { const analysis: FileCoverage[] = []; for (const file of sourceFiles) { const coverage = coverageData.find(d => this.normalizePath(d.url) === file); const fileAnalysis = await this.analyzeFile(file, coverage); analysis.push(fileAnalysis); } return analysis; } private async analyzeFile(filePath: string, coverage?: CoverageData): Promise { const content = await Deno.readTextFile(filePath); const lines = content.split('\n'); const totalLines = lines.filter(line => line.trim() && !line.trim().startsWith('//')).length; if (!coverage) { return { path: filePath, totalLines, coveredLines: 0, uncoveredLines: Array.from({ length: totalLines }, (_, i) => i + 1), coverage: 0, functions: this.extractFunctions(content, false), }; } // Analyze covered lines const coveredLines = new Set(); for (const range of coverage.ranges) { for (let line = range.start.line; line <= range.end.line; line++) { coveredLines.add(line); } } const uncoveredLines: number[] = []; for (let i = 1; i <= lines.length; i++) { const line = lines[i - 1].trim(); if (line && !line.startsWith('//') && !coveredLines.has(i)) { uncoveredLines.push(i); } } const coveragePercent = totalLines > 0 ? ((totalLines - uncoveredLines.length) / totalLines) * 100 : 100; return { path: filePath, totalLines, coveredLines: totalLines - uncoveredLines.length, uncoveredLines, coverage: coveragePercent, functions: this.extractFunctions(content, true, coveredLines), }; } private extractFunctions(content: string, checkCoverage: boolean, coveredLines?: Set): FunctionCoverage[] { const functions: FunctionCoverage[] = []; const lines = content.split('\n'); // Simple regex patterns for TypeScript functions const patterns = [ /^\s*(?:export\s+)?(?:async\s+)?function\s+(\w+)/, /^\s*(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(/, /^\s*(?:public|private|protected)?\s*(?:async\s+)?(\w+)\s*\(/, /^\s*(\w+)\s*:\s*\([^)]*\)\s*=>/, ]; for (let i = 0; i < lines.length; i++) { const line = lines[i]; for (const pattern of patterns) { const match = line.match(pattern); if (match) { const functionName = match[1]; const lineNumber = i + 1; const covered = checkCoverage ? (coveredLines?.has(lineNumber) ?? false) : false; functions.push({ name: functionName, line: lineNumber, covered, }); break; } } } return functions; } private calculateSummary(files: FileCoverage[], uncoveredFileCount: number): CoverageReport['summary'] { const totalFiles = files.length + uncoveredFileCount; const totalLines = files.reduce((sum, file) => sum + file.totalLines, 0); const coveredLines = files.reduce((sum, file) => sum + file.coveredLines, 0); const coverage = totalLines > 0 ? (coveredLines / totalLines) * 100 : 100; const passed = coverage >= this.thresholds.lines; return { totalFiles, totalLines, coveredLines, coverage, thresholds: this.thresholds, passed, }; } private async generateHTMLReport(report: CoverageReport): Promise { const fileRows = report.files .sort((a, b) => a.coverage - b.coverage) .map(file => { const coverageClass = file.coverage >= 80 ? 'high' : file.coverage >= 60 ? 'medium' : 'low'; const coverageBar = `
`; return ` ${file.path} ${file.coverage.toFixed(2)}% ${coverageBar} ${file.coveredLines}/${file.totalLines} ${file.uncoveredLines.length} ${file.functions.filter(f => f.covered).length}/${file.functions.length} `; }).join(''); const uncoveredRows = report.uncoveredFiles.map(file => ` ${file} 0%
0/0 - 0/0 `).join(''); const fileDetails = report.files.map(file => { const uncoveredLinesStr = file.uncoveredLines.length > 0 ? file.uncoveredLines.slice(0, 20).join(', ') + (file.uncoveredLines.length > 20 ? '...' : '') : 'All lines covered'; const functionRows = file.functions.map(func => ` ${func.name} ${func.line} ${func.covered ? 'āœ…' : 'āŒ'} `).join(''); return `

šŸ“„ ${file.path}

Coverage: ${file.coverage.toFixed(2)}%
Lines: ${file.coveredLines}/${file.totalLines}
Functions: ${file.functions.filter(f => f.covered).length}/${file.functions.length}
${file.uncoveredLines.length > 0 ? `

Uncovered Lines:

${uncoveredLinesStr}

` : ''} ${file.functions.length > 0 ? `

Functions:

${functionRows}
Function Line Covered
` : ''}
`; }).join(''); const html = ` Claude-Flow Coverage Report

šŸ“Š Claude-Flow Coverage Report

Generated: ${report.timestamp}
${report.summary.passed ? 'āœ… Coverage thresholds passed' : 'āŒ Coverage thresholds not met'}

Overall Coverage

${report.summary.coverage.toFixed(2)}%
Threshold: ${this.thresholds.lines}%

Total Files

${report.summary.totalFiles}

Covered Lines

${report.summary.coveredLines}
of ${report.summary.totalLines}

Uncovered Files

${report.uncoveredFiles.length}

šŸ“ File Coverage

${fileRows} ${uncoveredRows}
File Coverage Progress Lines Uncovered Functions

šŸ“„ File Details

${fileDetails}
`; await Deno.writeTextFile(`${this.outputDir}/coverage-detailed.html`, html); console.log(" āœ… Detailed HTML coverage report generated"); } private async generateJSONReport(report: CoverageReport): Promise { await Deno.writeTextFile( `${this.outputDir}/coverage-report.json`, JSON.stringify(report, null, 2) ); console.log(" āœ… JSON coverage report generated"); } private async generateTextReport(report: CoverageReport): Promise { const lines: string[] = []; lines.push("šŸ“Š CLAUDE-FLOW COVERAGE REPORT"); lines.push("=".repeat(50)); lines.push(`Generated: ${report.timestamp}`); lines.push(""); lines.push("šŸ“ˆ SUMMARY"); lines.push("-".repeat(20)); lines.push(`Overall Coverage: ${report.summary.coverage.toFixed(2)}%`); lines.push(`Total Files: ${report.summary.totalFiles}`); lines.push(`Covered Lines: ${report.summary.coveredLines}/${report.summary.totalLines}`); lines.push(`Uncovered Files: ${report.uncoveredFiles.length}`); lines.push(""); lines.push("šŸŽÆ THRESHOLDS"); lines.push("-".repeat(20)); lines.push(`Lines: ${report.summary.coverage.toFixed(2)}% (threshold: ${report.summary.thresholds.lines}%)`); lines.push(`Status: ${report.summary.passed ? 'āœ… PASSED' : 'āŒ FAILED'}`); lines.push(""); if (report.files.length > 0) { lines.push("šŸ“ FILES BY COVERAGE"); lines.push("-".repeat(20)); const sortedFiles = [...report.files].sort((a, b) => a.coverage - b.coverage); for (const file of sortedFiles) { const status = file.coverage >= 80 ? 'āœ…' : file.coverage >= 60 ? 'āš ļø' : 'āŒ'; lines.push(`${status} ${file.path}: ${file.coverage.toFixed(2)}% (${file.coveredLines}/${file.totalLines} lines)`); if (file.uncoveredLines.length > 0 && file.uncoveredLines.length <= 10) { lines.push(` Uncovered lines: ${file.uncoveredLines.join(', ')}`); } else if (file.uncoveredLines.length > 10) { lines.push(` Uncovered lines: ${file.uncoveredLines.slice(0, 10).join(', ')}... (+${file.uncoveredLines.length - 10} more)`); } } lines.push(""); } if (report.uncoveredFiles.length > 0) { lines.push("🚫 UNCOVERED FILES"); lines.push("-".repeat(20)); for (const file of report.uncoveredFiles) { lines.push(`āŒ ${file}`); } lines.push(""); } lines.push("šŸ’” RECOMMENDATIONS"); lines.push("-".repeat(20)); const lowCoverageFiles = report.files.filter(f => f.coverage < 60); if (lowCoverageFiles.length > 0) { lines.push("• Focus on improving coverage for these files:"); for (const file of lowCoverageFiles.slice(0, 5)) { lines.push(` - ${file.path} (${file.coverage.toFixed(2)}%)`); } } if (report.uncoveredFiles.length > 0) { lines.push("• Add tests for uncovered files:"); for (const file of report.uncoveredFiles.slice(0, 5)) { lines.push(` - ${file}`); } } if (report.summary.coverage >= 90) { lines.push("• Excellent coverage! Consider adding edge case tests."); } else if (report.summary.coverage >= 80) { lines.push("• Good coverage! Focus on critical paths and error handling."); } else { lines.push("• Coverage needs improvement. Add tests for core functionality first."); } await Deno.writeTextFile(`${this.outputDir}/coverage-report.txt`, lines.join('\n')); console.log(" āœ… Text coverage report generated"); } private async generateBadges(report: CoverageReport): Promise { const coverage = report.summary.coverage; const color = coverage >= 90 ? 'brightgreen' : coverage >= 80 ? 'green' : coverage >= 70 ? 'yellow' : coverage >= 60 ? 'orange' : 'red'; const badgeUrl = `https://img.shields.io/badge/coverage-${coverage.toFixed(1)}%25-${color}`; const badgeMarkdown = `![Coverage](${badgeUrl})`; const badgeHTML = `Coverage ${coverage.toFixed(1)}%`; const badges = { url: badgeUrl, markdown: badgeMarkdown, html: badgeHTML, coverage: coverage.toFixed(1), color, status: report.summary.passed ? 'passed' : 'failed', }; await Deno.writeTextFile( `${this.outputDir}/coverage-badges.json`, JSON.stringify(badges, null, 2) ); console.log(" āœ… Coverage badges generated"); } } async function main(): Promise { const args = parseArgs(Deno.args, { string: ["source-dir", "coverage-dir", "output-dir"], boolean: ["help"], default: { "source-dir": "./src", "coverage-dir": "./tests/results/coverage", "output-dir": "./tests/results", }, alias: { h: "help", s: "source-dir", c: "coverage-dir", o: "output-dir", }, }); if (args.help) { console.log(` šŸ“Š Claude-Flow Coverage Analysis Tool USAGE: coverage-report.ts [OPTIONS] OPTIONS: --source-dir, -s Source code directory (default: ./src) --coverage-dir, -c Coverage data directory (default: ./tests/results/coverage) --output-dir, -o Output directory for reports (default: ./tests/results) --help, -h Show this help EXAMPLES: # Generate coverage report with defaults ./scripts/coverage-report.ts # Custom directories ./scripts/coverage-report.ts --source-dir ./lib --coverage-dir ./coverage --output-dir ./reports `); return; } const thresholds = { statements: 80, branches: 75, functions: 80, lines: 80, }; const analyzer = new CoverageAnalyzer({ sourceDir: args["source-dir"], coverageDir: args["coverage-dir"], outputDir: args["output-dir"], thresholds, }); try { const report = await analyzer.generateReport(); console.log("\nšŸ“Š COVERAGE SUMMARY"); console.log("=".repeat(40)); console.log(`Overall Coverage: ${report.summary.coverage.toFixed(2)}%`); console.log(`Total Files: ${report.summary.totalFiles}`); console.log(`Covered Lines: ${report.summary.coveredLines}/${report.summary.totalLines}`); console.log(`Uncovered Files: ${report.uncoveredFiles.length}`); const status = report.summary.passed ? "āœ… PASSED" : "āŒ FAILED"; console.log(`Status: ${status}`); console.log(`\nšŸ“„ Reports generated in: ${args["output-dir"]}`); console.log(` - Detailed HTML: coverage-detailed.html`); console.log(` - JSON Data: coverage-report.json`); console.log(` - Text Summary: coverage-report.txt`); console.log(` - Badges: coverage-badges.json`); Deno.exit(report.summary.passed ? 0 : 1); } catch (error) { console.error("āŒ Coverage analysis failed:", error.message); Deno.exit(1); } } if (import.meta.main) { main(); }