@swayamkothari/codepulse 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +240 -2
- package/bin/codepulse.js +6 -0
- package/package.json +60 -4
- package/src/analyzers/complexity/cognitive.js +170 -0
- package/src/analyzers/complexity/cyclomatic.js +96 -0
- package/src/analyzers/complexity/index.js +232 -0
- package/src/analyzers/dependencies/cycle-detector.js +107 -0
- package/src/analyzers/dependencies/graph-builder.js +118 -0
- package/src/analyzers/dependencies/import-extractor.js +85 -0
- package/src/analyzers/dependencies/index.js +152 -0
- package/src/analyzers/duplication/index.js +366 -0
- package/src/analyzers/duplication/normalizer.js +238 -0
- package/src/analyzers/index.js +9 -0
- package/src/analyzers/smells/index.js +213 -0
- package/src/cli/argument-parser.js +45 -0
- package/src/cli/commands/analyze.js +146 -0
- package/src/cli/commands/compare.js +121 -0
- package/src/cli/commands/history.js +91 -0
- package/src/cli/commands/init.js +51 -0
- package/src/cli/commands/rules.js +110 -0
- package/src/config/loader.js +142 -0
- package/src/config/validator.js +130 -0
- package/src/core/analyzer.js +198 -0
- package/src/core/file-filter.js +95 -0
- package/src/core/project-scanner.js +119 -0
- package/src/history/comparison-engine.js +86 -0
- package/src/history/snapshot-manager.js +190 -0
- package/src/index.js +16 -0
- package/src/reporters/html.js +313 -0
- package/src/reporters/json.js +45 -0
- package/src/reporters/terminal.js +197 -0
- package/src/rules/defaults.js +145 -0
- package/src/rules/registry.js +75 -0
- package/src/scoring/score-calculator.js +299 -0
- package/src/scoring/weights.js +53 -0
- package/src/utils/ast-utils.js +173 -0
- package/src/utils/file-utils.js +64 -0
- package/src/utils/logger.js +54 -0
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML Reporter
|
|
3
|
+
*
|
|
4
|
+
* Generates a self-contained, single-file HTML report.
|
|
5
|
+
* No external dependencies — all CSS and JS are inlined.
|
|
6
|
+
*
|
|
7
|
+
* Sections:
|
|
8
|
+
* • Header (project info + timestamp)
|
|
9
|
+
* • Overall score gauge (SVG arc)
|
|
10
|
+
* • Sub-score cards (5 dimensions)
|
|
11
|
+
* • Recommendation banner
|
|
12
|
+
* • Issue table (sortable, filterable by severity)
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { writeFileSync } from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import * as logger from '../utils/logger.js';
|
|
18
|
+
|
|
19
|
+
const SEVERITY_ORDER = { critical: 4, high: 3, medium: 2, low: 1 };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {object} result — full analyzer result (with result.scores populated)
|
|
23
|
+
* @param {object} options — CLI options: { output, severity }
|
|
24
|
+
*/
|
|
25
|
+
export async function renderHtml(result, options = {}) {
|
|
26
|
+
const html = _buildHtml(result, options);
|
|
27
|
+
|
|
28
|
+
const dest = options.output
|
|
29
|
+
? path.resolve(options.output)
|
|
30
|
+
: path.join(process.cwd(), 'codepulse-report.html');
|
|
31
|
+
|
|
32
|
+
writeFileSync(dest, html, 'utf8');
|
|
33
|
+
logger.success(`HTML report written to ${dest}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ── HTML builder ──────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
function _buildHtml(result, options) {
|
|
39
|
+
const sc = result.scores;
|
|
40
|
+
const minSev = options.severity ?? 'low';
|
|
41
|
+
const minOrd = SEVERITY_ORDER[minSev] ?? 1;
|
|
42
|
+
const visible = (result.issues ?? [])
|
|
43
|
+
.filter(i => (SEVERITY_ORDER[i.severity] ?? 0) >= minOrd)
|
|
44
|
+
.sort((a, b) =>
|
|
45
|
+
(SEVERITY_ORDER[b.severity] ?? 0) - (SEVERITY_ORDER[a.severity] ?? 0) ||
|
|
46
|
+
a.filePath.localeCompare(b.filePath) ||
|
|
47
|
+
(a.line ?? 0) - (b.line ?? 0)
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
const ts = result.timestamp
|
|
51
|
+
? new Date(result.timestamp).toLocaleString()
|
|
52
|
+
: new Date().toLocaleString();
|
|
53
|
+
|
|
54
|
+
return `<!DOCTYPE html>
|
|
55
|
+
<html lang="en">
|
|
56
|
+
<head>
|
|
57
|
+
<meta charset="UTF-8">
|
|
58
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
59
|
+
<title>CodePulse Report — ${_esc(path.basename(result.rootDir ?? 'project'))}</title>
|
|
60
|
+
<style>
|
|
61
|
+
${_css()}
|
|
62
|
+
</style>
|
|
63
|
+
</head>
|
|
64
|
+
<body>
|
|
65
|
+
<div class="container">
|
|
66
|
+
|
|
67
|
+
${_header(result, ts)}
|
|
68
|
+
${sc ? _scoreSection(sc) : '<p class="warn">Scores not available.</p>'}
|
|
69
|
+
${sc ? _recommendationBanner(sc) : ''}
|
|
70
|
+
${_issueSection(visible, result.rootDir ?? '')}
|
|
71
|
+
|
|
72
|
+
</div>
|
|
73
|
+
<script>${_js()}</script>
|
|
74
|
+
</body>
|
|
75
|
+
</html>`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ── Sections ──────────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
function _header(result, ts) {
|
|
81
|
+
const fnCount = (result.files ?? []).reduce((s, f) => s + (f.metrics?.functionCount ?? 0), 0);
|
|
82
|
+
const errorRow = result.filesWithErrors > 0
|
|
83
|
+
? `<tr><td>Parse errors</td><td class="warn">${result.filesWithErrors}</td></tr>`
|
|
84
|
+
: '';
|
|
85
|
+
|
|
86
|
+
return `<header>
|
|
87
|
+
<h1><span class="brand">CodePulse</span> Code Health Report</h1>
|
|
88
|
+
<table class="meta">
|
|
89
|
+
<tr><td>Project</td><td>${_esc(result.rootDir ?? '')}</td></tr>
|
|
90
|
+
<tr><td>Files analyzed</td><td>${result.filesAnalyzed ?? 0}</td></tr>
|
|
91
|
+
${errorRow}
|
|
92
|
+
<tr><td>Total lines</td><td>${result.metrics?.totalLines ?? 0}</td></tr>
|
|
93
|
+
<tr><td>Functions</td><td>${fnCount}</td></tr>
|
|
94
|
+
<tr><td>Issues found</td><td>${(result.issues ?? []).length}</td></tr>
|
|
95
|
+
<tr><td>Duration</td><td>${result.duration ?? 0} ms</td></tr>
|
|
96
|
+
<tr><td>Generated</td><td>${_esc(ts)}</td></tr>
|
|
97
|
+
</table>
|
|
98
|
+
</header>`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function _scoreSection(sc) {
|
|
102
|
+
const gaugeColor = sc.overall >= 80 ? '#22c55e' : sc.overall >= 60 ? '#f59e0b' : '#ef4444';
|
|
103
|
+
// SVG arc gauge (semicircle, 0–180 degrees)
|
|
104
|
+
const pct = sc.overall / 100;
|
|
105
|
+
const r = 70;
|
|
106
|
+
const cx = 90;
|
|
107
|
+
const cy = 90;
|
|
108
|
+
const startX = cx - r;
|
|
109
|
+
const startY = cy;
|
|
110
|
+
// Angle: 180° → 0° (right half of a circle, top-arc)
|
|
111
|
+
const angle = Math.PI * (1 - pct);
|
|
112
|
+
const endX = cx + r * Math.cos(angle);
|
|
113
|
+
const endY = cy - r * Math.sin(angle);
|
|
114
|
+
const large = pct > 0.5 ? 1 : 0;
|
|
115
|
+
|
|
116
|
+
const arcPath = `M ${startX},${startY} A ${r},${r} 0 ${large} 1 ${endX.toFixed(2)},${endY.toFixed(2)}`;
|
|
117
|
+
const trackPath = `M ${startX},${startY} A ${r},${r} 0 1 1 ${cx + r},${cy}`;
|
|
118
|
+
|
|
119
|
+
const cards = ['complexity','duplication','maintainability','dependencies','hygiene']
|
|
120
|
+
.map(dim => _scoreCard(dim, sc.breakdown[dim], sc.weights[dim], dim === sc.weakest))
|
|
121
|
+
.join('\n');
|
|
122
|
+
|
|
123
|
+
return `<section class="scores">
|
|
124
|
+
<div class="gauge-wrap">
|
|
125
|
+
<svg viewBox="0 0 180 100" class="gauge">
|
|
126
|
+
<path d="${trackPath}" fill="none" stroke="#2d2d2d" stroke-width="14" stroke-linecap="round"/>
|
|
127
|
+
<path d="${arcPath}" fill="none" stroke="${gaugeColor}" stroke-width="14" stroke-linecap="round"/>
|
|
128
|
+
<text x="${cx}" y="${cy - 10}" text-anchor="middle" class="gauge-score" fill="${gaugeColor}">${sc.overall}</text>
|
|
129
|
+
<text x="${cx}" y="${cy + 8}" text-anchor="middle" class="gauge-label" fill="#aaa">${_esc(sc.label)}</text>
|
|
130
|
+
</svg>
|
|
131
|
+
<p class="gauge-caption">Overall Health Score</p>
|
|
132
|
+
</div>
|
|
133
|
+
<div class="cards">
|
|
134
|
+
${cards}
|
|
135
|
+
</div>
|
|
136
|
+
</section>`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function _scoreCard(dim, sub, weight, isWeakest) {
|
|
140
|
+
const color = sub.score >= 80 ? '#22c55e' : sub.score >= 60 ? '#f59e0b' : '#ef4444';
|
|
141
|
+
const weakClass = isWeakest ? ' weakest' : '';
|
|
142
|
+
const topReason = sub.reasons[0] ? `<p class="reason">${_esc(sub.reasons[0])}</p>` : '';
|
|
143
|
+
return `<div class="card${weakClass}">
|
|
144
|
+
<div class="card-score" style="color:${color}">${sub.score}</div>
|
|
145
|
+
<div class="card-dim">${_cap(dim)}</div>
|
|
146
|
+
<div class="card-label" style="color:${color}">${_esc(sub.label)}</div>
|
|
147
|
+
<div class="card-weight">weight ×${(weight * 100).toFixed(0)}%</div>
|
|
148
|
+
${topReason}
|
|
149
|
+
${isWeakest ? '<div class="weakest-badge">▶ Weakest</div>' : ''}
|
|
150
|
+
</div>`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function _recommendationBanner(sc) {
|
|
154
|
+
return `<section class="recommendation">
|
|
155
|
+
<strong>Recommendation:</strong> ${_esc(sc.recommendation)}
|
|
156
|
+
</section>`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function _issueSection(visible, rootDir) {
|
|
160
|
+
if (visible.length === 0) {
|
|
161
|
+
return `<section class="issues">
|
|
162
|
+
<h2>Issues</h2>
|
|
163
|
+
<p class="ok">No issues found — great work!</p>
|
|
164
|
+
</section>`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const rows = visible.map(issue => {
|
|
168
|
+
const relPath = issue.filePath.startsWith(rootDir)
|
|
169
|
+
? issue.filePath.slice(rootDir.length + 1)
|
|
170
|
+
: issue.filePath;
|
|
171
|
+
const loc = `${relPath}:${issue.line ?? '?'}`;
|
|
172
|
+
return `<tr data-sev="${_esc(issue.severity)}">
|
|
173
|
+
<td><span class="badge sev-${_esc(issue.severity)}">${_esc(issue.severity)}</span></td>
|
|
174
|
+
<td>${_esc(issue.message)}</td>
|
|
175
|
+
<td class="mono">${_esc(loc)}</td>
|
|
176
|
+
<td class="mono dim">${_esc(issue.ruleId)}</td>
|
|
177
|
+
<td class="dim">${_esc(issue.suggestion ?? '')}</td>
|
|
178
|
+
</tr>`;
|
|
179
|
+
}).join('\n');
|
|
180
|
+
|
|
181
|
+
return `<section class="issues">
|
|
182
|
+
<h2>Issues <span class="count">(${visible.length})</span></h2>
|
|
183
|
+
<div class="filter-bar">
|
|
184
|
+
<label>Filter:
|
|
185
|
+
<select id="sev-filter" onchange="filterIssues(this.value)">
|
|
186
|
+
<option value="">All severities</option>
|
|
187
|
+
<option value="critical">Critical</option>
|
|
188
|
+
<option value="high">High</option>
|
|
189
|
+
<option value="medium">Medium</option>
|
|
190
|
+
<option value="low">Low</option>
|
|
191
|
+
</select>
|
|
192
|
+
</label>
|
|
193
|
+
<label style="margin-left:1rem">Search:
|
|
194
|
+
<input id="search" type="text" placeholder="file or message…" oninput="filterIssues()">
|
|
195
|
+
</label>
|
|
196
|
+
</div>
|
|
197
|
+
<table class="issue-table" id="issue-table">
|
|
198
|
+
<thead>
|
|
199
|
+
<tr>
|
|
200
|
+
<th onclick="sortTable(0)">Severity</th>
|
|
201
|
+
<th onclick="sortTable(1)">Message</th>
|
|
202
|
+
<th onclick="sortTable(2)">Location</th>
|
|
203
|
+
<th onclick="sortTable(3)">Rule</th>
|
|
204
|
+
<th onclick="sortTable(4)">Suggestion</th>
|
|
205
|
+
</tr>
|
|
206
|
+
</thead>
|
|
207
|
+
<tbody id="issue-body">
|
|
208
|
+
${rows}
|
|
209
|
+
</tbody>
|
|
210
|
+
</table>
|
|
211
|
+
</section>`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── CSS ───────────────────────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
function _css() {
|
|
217
|
+
return `
|
|
218
|
+
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
219
|
+
body{background:#0f0f0f;color:#e2e8f0;font-family:'Segoe UI',system-ui,sans-serif;font-size:14px;line-height:1.6}
|
|
220
|
+
.container{max-width:1100px;margin:0 auto;padding:2rem 1.5rem}
|
|
221
|
+
|
|
222
|
+
/* Header */
|
|
223
|
+
header{margin-bottom:2rem}
|
|
224
|
+
h1{font-size:1.6rem;font-weight:700;color:#38bdf8;margin-bottom:1rem}
|
|
225
|
+
.brand{color:#818cf8}
|
|
226
|
+
table.meta{border-collapse:collapse;font-size:13px;color:#94a3b8}
|
|
227
|
+
table.meta td{padding:2px 12px 2px 0}
|
|
228
|
+
table.meta td:first-child{color:#64748b;min-width:140px}
|
|
229
|
+
|
|
230
|
+
/* Scores */
|
|
231
|
+
.scores{display:flex;align-items:flex-start;gap:2rem;margin-bottom:2rem;flex-wrap:wrap}
|
|
232
|
+
.gauge-wrap{display:flex;flex-direction:column;align-items:center;min-width:180px}
|
|
233
|
+
.gauge{width:180px;height:110px}
|
|
234
|
+
.gauge-score{font-size:28px;font-weight:700}
|
|
235
|
+
.gauge-label{font-size:11px}
|
|
236
|
+
.gauge-caption{font-size:12px;color:#64748b;margin-top:4px}
|
|
237
|
+
.cards{display:flex;flex-wrap:wrap;gap:12px;flex:1}
|
|
238
|
+
.card{background:#1e1e2e;border:1px solid #2d2d3f;border-radius:10px;padding:1rem;min-width:140px;flex:1}
|
|
239
|
+
.card.weakest{border-color:#f59e0b}
|
|
240
|
+
.card-score{font-size:2rem;font-weight:700}
|
|
241
|
+
.card-dim{font-weight:600;font-size:0.9rem;color:#cbd5e1;margin-top:2px}
|
|
242
|
+
.card-label{font-size:0.75rem;margin-top:1px}
|
|
243
|
+
.card-weight{font-size:0.7rem;color:#475569;margin-top:4px}
|
|
244
|
+
.reason{font-size:0.7rem;color:#64748b;margin-top:6px;line-height:1.4}
|
|
245
|
+
.weakest-badge{font-size:0.7rem;color:#f59e0b;margin-top:6px;font-weight:600}
|
|
246
|
+
|
|
247
|
+
/* Recommendation */
|
|
248
|
+
.recommendation{background:#1e2a1e;border-left:4px solid #22c55e;border-radius:4px;padding:0.75rem 1rem;margin-bottom:2rem;font-size:0.9rem;color:#bbf7d0}
|
|
249
|
+
|
|
250
|
+
/* Issues */
|
|
251
|
+
.issues h2{font-size:1.1rem;font-weight:600;margin-bottom:1rem;color:#94a3b8}
|
|
252
|
+
.count{color:#475569;font-size:0.9rem;font-weight:400}
|
|
253
|
+
.ok{color:#22c55e}
|
|
254
|
+
.warn{color:#f59e0b}
|
|
255
|
+
.filter-bar{margin-bottom:0.75rem;display:flex;align-items:center;flex-wrap:wrap;gap:4px;font-size:13px;color:#64748b}
|
|
256
|
+
.filter-bar select,.filter-bar input{background:#1e1e2e;border:1px solid #2d2d3f;border-radius:4px;padding:3px 6px;color:#e2e8f0;font-size:13px;margin-left:4px}
|
|
257
|
+
.issue-table{width:100%;border-collapse:collapse;font-size:13px}
|
|
258
|
+
.issue-table th{background:#1e1e2e;color:#64748b;text-align:left;padding:6px 8px;cursor:pointer;user-select:none;border-bottom:1px solid #2d2d3f}
|
|
259
|
+
.issue-table th:hover{color:#94a3b8}
|
|
260
|
+
.issue-table td{padding:6px 8px;border-bottom:1px solid #1a1a2e;vertical-align:top}
|
|
261
|
+
.issue-table tr:hover td{background:#1e1e2e}
|
|
262
|
+
.mono{font-family:'Consolas','Courier New',monospace;font-size:12px;white-space:nowrap}
|
|
263
|
+
.dim{color:#475569}
|
|
264
|
+
.badge{display:inline-block;padding:1px 6px;border-radius:4px;font-size:11px;font-weight:700;text-transform:uppercase}
|
|
265
|
+
.sev-critical{background:#7f1d1d;color:#fca5a5}
|
|
266
|
+
.sev-high{background:#78350f;color:#fcd34d}
|
|
267
|
+
.sev-medium{background:#1e3a5f;color:#93c5fd}
|
|
268
|
+
.sev-low{background:#1e293b;color:#94a3b8}
|
|
269
|
+
`;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ── JS ────────────────────────────────────────────────────────────────────────
|
|
273
|
+
|
|
274
|
+
function _js() {
|
|
275
|
+
return `
|
|
276
|
+
function filterIssues(sev){
|
|
277
|
+
const sevVal = sev !== undefined ? sev : document.getElementById('sev-filter').value;
|
|
278
|
+
const search = document.getElementById('search').value.toLowerCase();
|
|
279
|
+
document.querySelectorAll('#issue-body tr').forEach(tr => {
|
|
280
|
+
const matchSev = !sevVal || tr.dataset.sev === sevVal;
|
|
281
|
+
const text = tr.textContent.toLowerCase();
|
|
282
|
+
const matchSearch = !search || text.includes(search);
|
|
283
|
+
tr.style.display = matchSev && matchSearch ? '' : 'none';
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
let _sortDir = {};
|
|
287
|
+
function sortTable(col){
|
|
288
|
+
const tbody = document.getElementById('issue-body');
|
|
289
|
+
const rows = Array.from(tbody.querySelectorAll('tr'));
|
|
290
|
+
const dir = (_sortDir[col] = !_sortDir[col]);
|
|
291
|
+
rows.sort((a,b) => {
|
|
292
|
+
const av = a.cells[col]?.textContent.trim() ?? '';
|
|
293
|
+
const bv = b.cells[col]?.textContent.trim() ?? '';
|
|
294
|
+
return dir ? av.localeCompare(bv) : bv.localeCompare(av);
|
|
295
|
+
});
|
|
296
|
+
rows.forEach(r => tbody.appendChild(r));
|
|
297
|
+
}
|
|
298
|
+
`;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ── Utils ─────────────────────────────────────────────────────────────────────
|
|
302
|
+
|
|
303
|
+
function _esc(str) {
|
|
304
|
+
return String(str ?? '')
|
|
305
|
+
.replace(/&/g, '&')
|
|
306
|
+
.replace(/</g, '<')
|
|
307
|
+
.replace(/>/g, '>')
|
|
308
|
+
.replace(/"/g, '"');
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function _cap(str) {
|
|
312
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
313
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Reporter
|
|
3
|
+
*
|
|
4
|
+
* Serializes the analysis result to JSON and either writes it to a file
|
|
5
|
+
* or prints it to stdout.
|
|
6
|
+
*
|
|
7
|
+
* The output is the full result object — every field is included so the
|
|
8
|
+
* consumer can derive any downstream metric without re-running the analysis.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { writeFileSync } from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {object} result — full analyzer result
|
|
16
|
+
* @param {object} options — CLI options: { output }
|
|
17
|
+
*/
|
|
18
|
+
export async function renderJson(result, options = {}) {
|
|
19
|
+
// Build a serializable copy (strip any residual AST nodes just in case)
|
|
20
|
+
const payload = _sanitize(result);
|
|
21
|
+
const json = JSON.stringify(payload, null, 2);
|
|
22
|
+
|
|
23
|
+
if (options.output) {
|
|
24
|
+
const dest = path.resolve(options.output);
|
|
25
|
+
writeFileSync(dest, json, 'utf8');
|
|
26
|
+
|
|
27
|
+
const { default: chalk } = await import('chalk');
|
|
28
|
+
console.log(chalk.green(`✔ JSON report written to ${dest}`));
|
|
29
|
+
} else {
|
|
30
|
+
console.log(json);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Remove non-serializable / excessively large fields from file entries.
|
|
38
|
+
* AST and raw source code are stripped; everything else is kept.
|
|
39
|
+
*/
|
|
40
|
+
function _sanitize(result) {
|
|
41
|
+
return {
|
|
42
|
+
...result,
|
|
43
|
+
files: (result.files ?? []).map(({ ast: _ast, code: _code, ...rest }) => rest),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal Reporter
|
|
3
|
+
*
|
|
4
|
+
* Renders a full-colour analysis report to stdout using chalk and cli-table3.
|
|
5
|
+
*
|
|
6
|
+
* Layout:
|
|
7
|
+
* ┌─ Header (project info) ──────────────────────────────────────────┐
|
|
8
|
+
* │ Overall health score + label │
|
|
9
|
+
* │ Score breakdown table (5 dimensions) │
|
|
10
|
+
* │ Weakest dimension + recommendation │
|
|
11
|
+
* │ Issue summary (counts by severity) │
|
|
12
|
+
* │ Detailed findings (filtered by --severity, capped at maxFindings)│
|
|
13
|
+
* └──────────────────────────────────────────────────────────────────┘
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const SEVERITY_ORDER = { critical: 4, high: 3, medium: 2, low: 1 };
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {object} result — full analyzer result (with result.scores populated)
|
|
20
|
+
* @param {object} options — CLI options: { severity, output, maxFindings }
|
|
21
|
+
*/
|
|
22
|
+
export async function renderTerminal(result, options = {}) {
|
|
23
|
+
const { default: chalk } = await import('chalk');
|
|
24
|
+
const { default: Table } = await import('cli-table3');
|
|
25
|
+
|
|
26
|
+
const minSeverity = options.severity ?? 'low';
|
|
27
|
+
const minOrder = SEVERITY_ORDER[minSeverity] ?? 1;
|
|
28
|
+
const maxItems = options.maxFindings ?? 50;
|
|
29
|
+
|
|
30
|
+
const W = 70;
|
|
31
|
+
const div = chalk.dim('─'.repeat(W));
|
|
32
|
+
const divHeavy = chalk.dim('═'.repeat(W));
|
|
33
|
+
|
|
34
|
+
// ── Header ───────────────────────────────────────────────────────────────
|
|
35
|
+
console.log('\n' + divHeavy);
|
|
36
|
+
console.log(
|
|
37
|
+
' ' + chalk.bold.cyan('CODEPULSE') +
|
|
38
|
+
chalk.dim(' ─ Code Health Report') +
|
|
39
|
+
chalk.dim(` v${result.version ?? '0.1.0'}`)
|
|
40
|
+
);
|
|
41
|
+
console.log(divHeavy);
|
|
42
|
+
console.log(` ${chalk.dim('Project:')} ${chalk.white(result.rootDir)}`);
|
|
43
|
+
console.log(` ${chalk.dim('Files analyzed:')} ${chalk.white(result.filesAnalyzed)}` +
|
|
44
|
+
(result.filesWithErrors > 0 ? chalk.red(` (${result.filesWithErrors} parse errors)`) : ''));
|
|
45
|
+
console.log(` ${chalk.dim('Total lines:')} ${chalk.white(result.metrics?.totalLines ?? 0)}`);
|
|
46
|
+
console.log(` ${chalk.dim('Functions:')} ${chalk.white(_countFunctions(result))}`);
|
|
47
|
+
console.log(` ${chalk.dim('Issues found:')} ${chalk.white(result.issues.length)}`);
|
|
48
|
+
console.log(` ${chalk.dim('Duration:')} ${chalk.white(result.duration + 'ms')}`);
|
|
49
|
+
console.log(div);
|
|
50
|
+
|
|
51
|
+
// ── Overall score ─────────────────────────────────────────────────────────
|
|
52
|
+
if (result.scores) {
|
|
53
|
+
const sc = result.scores;
|
|
54
|
+
const scoreStr = _scoreColor(chalk, sc.overall)(`${sc.overall}/100`);
|
|
55
|
+
const labelStr = _scoreColor(chalk, sc.overall)(`[${sc.label}]`);
|
|
56
|
+
console.log(`\n ${chalk.bold('Overall Health Score:')} ${scoreStr} ${labelStr}`);
|
|
57
|
+
|
|
58
|
+
// ── Breakdown table ─────────────────────────────────────────────────────
|
|
59
|
+
console.log('');
|
|
60
|
+
const table = new Table({
|
|
61
|
+
head: [
|
|
62
|
+
chalk.dim('Dimension'),
|
|
63
|
+
chalk.dim('Score'),
|
|
64
|
+
chalk.dim('Grade'),
|
|
65
|
+
chalk.dim('Weight'),
|
|
66
|
+
chalk.dim('Top finding'),
|
|
67
|
+
],
|
|
68
|
+
colWidths: [18, 8, 16, 9, 24],
|
|
69
|
+
style: { head: [], border: ['dim'] },
|
|
70
|
+
chars: {
|
|
71
|
+
'top': '─', 'top-mid': '┬', 'top-left': '┌', 'top-right': '┐',
|
|
72
|
+
'bottom': '─', 'bottom-mid': '┴', 'bottom-left': '└', 'bottom-right': '┘',
|
|
73
|
+
'left': '│', 'right': '│', 'mid': '─', 'mid-mid': '┼', 'middle': '│',
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const dims = ['complexity', 'duplication', 'maintainability', 'dependencies', 'hygiene'];
|
|
78
|
+
for (const dim of dims) {
|
|
79
|
+
const sub = sc.breakdown[dim];
|
|
80
|
+
const wt = sc.weights[dim];
|
|
81
|
+
const isWeakest = dim === sc.weakest;
|
|
82
|
+
const scoreCol = _scoreColor(chalk, sub.score)(`${sub.score}`);
|
|
83
|
+
const labelCol = _scoreColor(chalk, sub.score)(sub.label);
|
|
84
|
+
const dimLabel = isWeakest
|
|
85
|
+
? chalk.yellow.bold(`▶ ${_cap(dim)}`)
|
|
86
|
+
: chalk.white(_cap(dim));
|
|
87
|
+
const topReason = sub.reasons[0]
|
|
88
|
+
? _truncate(sub.reasons[0], 22)
|
|
89
|
+
: chalk.dim('—');
|
|
90
|
+
|
|
91
|
+
table.push([dimLabel, scoreCol, labelCol, chalk.dim(`×${(wt * 100).toFixed(0)}%`), chalk.dim(topReason)]);
|
|
92
|
+
}
|
|
93
|
+
console.log(table.toString());
|
|
94
|
+
|
|
95
|
+
// ── Recommendation ────────────────────────────────────────────────────
|
|
96
|
+
console.log(`\n ${chalk.bold('Recommendation:')} ${chalk.yellow(sc.recommendation)}`);
|
|
97
|
+
} else {
|
|
98
|
+
console.log(chalk.yellow('\n Scores not available.'));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ── Issue summary ─────────────────────────────────────────────────────────
|
|
102
|
+
const bySev = _groupBySeverity(result.issues);
|
|
103
|
+
console.log(`\n${div}`);
|
|
104
|
+
console.log(` ${chalk.bold('Issues by Severity:')}`);
|
|
105
|
+
if (Object.keys(bySev).length === 0) {
|
|
106
|
+
console.log(` ${chalk.green('None — great work!')}`);
|
|
107
|
+
} else {
|
|
108
|
+
if (bySev.critical) console.log(` ${chalk.bgRed.white.bold(' CRITICAL ')} ${chalk.red.bold(bySev.critical)}`);
|
|
109
|
+
if (bySev.high) console.log(` ${chalk.red(' HIGH ')} ${chalk.red(bySev.high)}`);
|
|
110
|
+
if (bySev.medium) console.log(` ${chalk.yellow(' MEDIUM ')} ${chalk.yellow(bySev.medium)}`);
|
|
111
|
+
if (bySev.low) console.log(` ${chalk.gray(' LOW ')} ${chalk.gray(bySev.low)}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── Detailed findings ─────────────────────────────────────────────────────
|
|
115
|
+
const visible = result.issues.filter(i => (SEVERITY_ORDER[i.severity] ?? 0) >= minOrder);
|
|
116
|
+
// Sort: severity desc, then file, then line
|
|
117
|
+
visible.sort((a, b) =>
|
|
118
|
+
(SEVERITY_ORDER[b.severity] ?? 0) - (SEVERITY_ORDER[a.severity] ?? 0) ||
|
|
119
|
+
a.filePath.localeCompare(b.filePath) ||
|
|
120
|
+
(a.line ?? 0) - (b.line ?? 0)
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
if (visible.length > 0) {
|
|
124
|
+
console.log(`\n${div}`);
|
|
125
|
+
console.log(` ${chalk.bold(`Findings`)} ${chalk.dim(`(severity ≥ ${minSeverity}, showing ${Math.min(visible.length, maxItems)} of ${visible.length})`)}`);
|
|
126
|
+
console.log('');
|
|
127
|
+
|
|
128
|
+
let currentFile = null;
|
|
129
|
+
let shown = 0;
|
|
130
|
+
for (const issue of visible) {
|
|
131
|
+
if (shown >= maxItems) break;
|
|
132
|
+
|
|
133
|
+
const relPath = issue.filePath.startsWith(result.rootDir)
|
|
134
|
+
? issue.filePath.slice(result.rootDir.length + 1)
|
|
135
|
+
: issue.filePath;
|
|
136
|
+
|
|
137
|
+
if (relPath !== currentFile) {
|
|
138
|
+
currentFile = relPath;
|
|
139
|
+
console.log(` ${chalk.cyan.bold(relPath)}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const loc = chalk.dim(`line ${issue.line ?? '?'}${issue.column != null ? ':' + issue.column : ''}`);
|
|
143
|
+
const sev = _sevBadge(chalk, issue.severity);
|
|
144
|
+
const rule = chalk.dim(`[${issue.ruleId}]`);
|
|
145
|
+
console.log(` ${sev} ${chalk.white(issue.message)} ${rule}`);
|
|
146
|
+
console.log(` ${loc}`);
|
|
147
|
+
if (issue.suggestion) {
|
|
148
|
+
console.log(` ${chalk.dim('→')} ${chalk.dim(issue.suggestion)}`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
shown++;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (visible.length > maxItems) {
|
|
155
|
+
console.log(chalk.dim(`\n … and ${visible.length - maxItems} more. Use --format json for the full list.`));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
console.log('\n' + divHeavy + '\n');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
163
|
+
|
|
164
|
+
function _countFunctions(result) {
|
|
165
|
+
return result.files.reduce((sum, f) => sum + (f.metrics?.functionCount ?? 0), 0);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function _groupBySeverity(issues) {
|
|
169
|
+
return issues.reduce((acc, i) => {
|
|
170
|
+
acc[i.severity] = (acc[i.severity] ?? 0) + 1;
|
|
171
|
+
return acc;
|
|
172
|
+
}, {});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function _scoreColor(chalk, score) {
|
|
176
|
+
if (score >= 80) return chalk.green.bold;
|
|
177
|
+
if (score >= 60) return chalk.yellow.bold;
|
|
178
|
+
return chalk.red.bold;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function _sevBadge(chalk, severity) {
|
|
182
|
+
switch (severity) {
|
|
183
|
+
case 'critical': return chalk.bgRed.white.bold(' CRIT ');
|
|
184
|
+
case 'high': return chalk.red(' HIGH ');
|
|
185
|
+
case 'medium': return chalk.yellow(' MED ');
|
|
186
|
+
case 'low': return chalk.gray(' LOW ');
|
|
187
|
+
default: return chalk.gray(' INFO ');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function _cap(str) {
|
|
192
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function _truncate(str, max) {
|
|
196
|
+
return str.length <= max ? str : str.slice(0, max - 1) + '…';
|
|
197
|
+
}
|