|
| 1 | +import chalk from "chalk"; |
| 2 | + |
| 3 | +import { |
| 4 | + computeCodebaseMetrics, |
| 5 | + formatBytes, |
| 6 | + type CodebaseMetrics, |
| 7 | +} from "../metrics.js"; |
| 8 | +import { resolveRepo, type RepoSource } from "../repo-resolver.js"; |
| 9 | +import { scanRepositoryFiles } from "../services/clone-service.js"; |
| 10 | + |
| 11 | +/** Options accepted by the `bootcamp metrics` command. */ |
| 12 | +export interface MetricsCommandOptions { |
| 13 | + branch?: string; |
| 14 | + /** Emit the report as JSON for machine consumption. */ |
| 15 | + json?: boolean; |
| 16 | + /** Exit non-zero when the approachability score is below `minScore` (CI gate). */ |
| 17 | + check?: boolean; |
| 18 | + /** Minimum passing approachability score for `--check` (0-100). Defaults to 70. */ |
| 19 | + minScore?: number; |
| 20 | + /** Maximum files to scan. Defaults to 500. */ |
| 21 | + maxFiles?: number; |
| 22 | + /** Keep the temporary clone (remote repos only). */ |
| 23 | + keepTemp?: boolean; |
| 24 | + verbose?: boolean; |
| 25 | +} |
| 26 | + |
| 27 | +function scoreColor(score: number): typeof chalk.green { |
| 28 | + if (score >= 80) return chalk.green; |
| 29 | + if (score >= 60) return chalk.yellow; |
| 30 | + return chalk.red; |
| 31 | +} |
| 32 | + |
| 33 | +/** Render a compact horizontal bar for a 0-100 percentage. */ |
| 34 | +function bar(percentage: number, width = 20): string { |
| 35 | + const filled = Math.round((Math.min(100, Math.max(0, percentage)) / 100) * width); |
| 36 | + return "█".repeat(filled) + "░".repeat(width - filled); |
| 37 | +} |
| 38 | + |
| 39 | +function printReport(metrics: CodebaseMetrics, repoName: string): void { |
| 40 | + const appr = metrics.approachability; |
| 41 | + const emoji = appr.score >= 80 ? "🟢" : appr.score >= 60 ? "🟡" : "🔴"; |
| 42 | + const color = scoreColor(appr.score); |
| 43 | + |
| 44 | + console.log(chalk.bold("\n📊 Codebase Metrics")); |
| 45 | + console.log(chalk.dim(`Repository: ${repoName}`)); |
| 46 | + console.log( |
| 47 | + chalk.dim( |
| 48 | + `${metrics.totalFiles} files · ${formatBytes(metrics.totalBytes)} · size class: ${metrics.sizeClass}\n` |
| 49 | + ) |
| 50 | + ); |
| 51 | + |
| 52 | + console.log(`${emoji} ` + chalk.bold("Approachability ") + color.bold(`${appr.score}/100 (Grade: ${appr.grade})`)); |
| 53 | + if (appr.factors.length > 0) { |
| 54 | + for (const factor of appr.factors) { |
| 55 | + console.log(chalk.dim(` • ${factor}`)); |
| 56 | + } |
| 57 | + } |
| 58 | + console.log(); |
| 59 | + |
| 60 | + console.log(chalk.bold("Composition")); |
| 61 | + console.log( |
| 62 | + chalk.dim(" ") + |
| 63 | + chalk.cyan(`${metrics.sourceFiles} source`) + |
| 64 | + chalk.dim(" · ") + |
| 65 | + `${metrics.testFiles} test` + |
| 66 | + chalk.dim(" · ") + |
| 67 | + `${metrics.docFiles} docs` + |
| 68 | + chalk.dim(" · ") + |
| 69 | + `${metrics.configFiles} config` + |
| 70 | + chalk.dim(" · ") + |
| 71 | + `${metrics.otherFiles} other` |
| 72 | + ); |
| 73 | + console.log( |
| 74 | + chalk.dim( |
| 75 | + ` avg file ${formatBytes(metrics.averageFileBytes)} · median ${formatBytes(metrics.medianFileBytes)} · test:source ${metrics.testToSourceRatio.toFixed(2)}` |
| 76 | + ) |
| 77 | + ); |
| 78 | + console.log(); |
| 79 | + |
| 80 | + if (metrics.languages.length > 0) { |
| 81 | + console.log(chalk.bold("Languages")); |
| 82 | + for (const lang of metrics.languages) { |
| 83 | + const label = lang.language.padEnd(14); |
| 84 | + console.log( |
| 85 | + ` ${chalk.cyan(label)} ${chalk.dim(bar(lang.percentage))} ${lang.percentage.toFixed(1)}% ` + |
| 86 | + chalk.dim(`(${lang.files} file${lang.files === 1 ? "" : "s"})`) |
| 87 | + ); |
| 88 | + } |
| 89 | + console.log(); |
| 90 | + } |
| 91 | + |
| 92 | + if (metrics.directories.length > 0) { |
| 93 | + console.log(chalk.bold("Top-level distribution")); |
| 94 | + for (const dir of metrics.directories) { |
| 95 | + const label = dir.path.padEnd(20); |
| 96 | + console.log( |
| 97 | + ` ${chalk.cyan(label)} ${dir.percentage.toFixed(1)}% ` + |
| 98 | + chalk.dim(`(${dir.files} file${dir.files === 1 ? "" : "s"}, ${formatBytes(dir.bytes)})`) |
| 99 | + ); |
| 100 | + } |
| 101 | + console.log(); |
| 102 | + } |
| 103 | + |
| 104 | + if (metrics.hotspots.length > 0) { |
| 105 | + console.log(chalk.bold("Largest files") + chalk.dim(" (review hotspots)")); |
| 106 | + for (const hotspot of metrics.hotspots) { |
| 107 | + console.log(` ${chalk.dim(formatBytes(hotspot.bytes).padStart(9))} ` + chalk.cyan(hotspot.path)); |
| 108 | + } |
| 109 | + console.log(); |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +/** |
| 114 | + * Run the standalone `bootcamp metrics` command: clone/resolve the target repo, |
| 115 | + * scan it, compute deterministic codebase metrics, and report them (human or |
| 116 | + * JSON). With `--check`, exits non-zero when the approachability score is below |
| 117 | + * `--min-score`. Reuses the same `computeCodebaseMetrics` engine that powers |
| 118 | + * `METRICS.md`. |
| 119 | + */ |
| 120 | +export async function runMetricsCommand(repoUrl: string, opts: MetricsCommandOptions): Promise<void> { |
| 121 | + const minScore = typeof opts.minScore === "number" && Number.isFinite(opts.minScore) ? opts.minScore : 70; |
| 122 | + |
| 123 | + let repoSource: RepoSource; |
| 124 | + try { |
| 125 | + repoSource = await resolveRepo(repoUrl, process.cwd(), opts.branch || undefined); |
| 126 | + } catch (error: unknown) { |
| 127 | + console.error( |
| 128 | + chalk.red(`Failed to resolve repository: ${error instanceof Error ? error.message : String(error)}`) |
| 129 | + ); |
| 130 | + process.exit(1); |
| 131 | + return; |
| 132 | + } |
| 133 | + |
| 134 | + let exitCode = 0; |
| 135 | + try { |
| 136 | + const scan = await scanRepositoryFiles(repoSource.path, opts.maxFiles ?? 500); |
| 137 | + const metrics = computeCodebaseMetrics(scan); |
| 138 | + |
| 139 | + if (opts.json) { |
| 140 | + console.log( |
| 141 | + JSON.stringify( |
| 142 | + { |
| 143 | + repo: repoSource.repoInfo.fullName, |
| 144 | + filesScanned: scan.files.length, |
| 145 | + ...metrics, |
| 146 | + }, |
| 147 | + null, |
| 148 | + 2 |
| 149 | + ) |
| 150 | + ); |
| 151 | + } else { |
| 152 | + printReport(metrics, repoSource.repoInfo.fullName); |
| 153 | + } |
| 154 | + |
| 155 | + if (opts.check && metrics.approachability.score < minScore) { |
| 156 | + if (!opts.json) { |
| 157 | + console.error( |
| 158 | + chalk.red( |
| 159 | + `❌ Approachability ${metrics.approachability.score}/100 is below the required minimum of ${minScore}.` |
| 160 | + ) |
| 161 | + ); |
| 162 | + } |
| 163 | + exitCode = 1; |
| 164 | + } |
| 165 | + } catch (error: unknown) { |
| 166 | + console.error( |
| 167 | + chalk.red(`Metrics analysis failed: ${error instanceof Error ? error.message : String(error)}`) |
| 168 | + ); |
| 169 | + exitCode = 1; |
| 170 | + } finally { |
| 171 | + if (opts.keepTemp && !repoSource.isLocal) { |
| 172 | + console.log(chalk.gray(`Temporary clone kept at: ${repoSource.path}`)); |
| 173 | + } else { |
| 174 | + await repoSource.cleanup(); |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + if (exitCode !== 0) { |
| 179 | + process.exit(exitCode); |
| 180 | + } |
| 181 | +} |
0 commit comments