codebase-onboarder 0.4.1 → 0.6.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 +74 -2
- package/cli/explorer/advanced.js +457 -0
- package/cli/explorer/app.js +391 -0
- package/cli/explorer/commands.js +369 -0
- package/cli/explorer/github.js +75 -0
- package/cli/explorer/graphs.js +178 -0
- package/cli/explorer/session.js +251 -0
- package/cli/explorer/views.js +650 -0
- package/cli/explorer/wrap.js +49 -0
- package/cli/main.js +82 -10
- package/cli/ui.js +31 -2
- package/package.json +1 -1
- package/public/js/about.js +20 -7
- package/server/gitRemote.js +61 -0
- package/server/layout.js +41 -14
- package/shared/analyzer/github.js +81 -0
|
@@ -0,0 +1,650 @@
|
|
|
1
|
+
// The views: the website's screens, drawn as text.
|
|
2
|
+
//
|
|
3
|
+
// Every function here is pure — `(repo, args) => string` — and none of them
|
|
4
|
+
// print. That is what makes the terminal app testable: the tests assert on the
|
|
5
|
+
// strings, with no TTY, no readline, and no process to spawn. The app layer
|
|
6
|
+
// decides where they go.
|
|
7
|
+
//
|
|
8
|
+
// The drawing primitives are the same ones the CLI banner and the server's
|
|
9
|
+
// startup line already use (`server/layout.js` for geometry, `cli/ui.js` for
|
|
10
|
+
// color), so a panel here is fitted and elided to the terminal exactly the way
|
|
11
|
+
// every other panel in this project is, including after a resize.
|
|
12
|
+
|
|
13
|
+
import { bold, cyan, dim, ok, warn, bad, panel, row, fit, termWidth } from '../ui.js';
|
|
14
|
+
import { labelled } from './graphs.js';
|
|
15
|
+
import { fileFacts, readRepoFile, resolveTarget, searchRepo, explainRepoFile, explainRepoFolder, explainRepoOverview } from './session.js';
|
|
16
|
+
import { scanCaveats } from '../../shared/analyzer/explainLocal.js';
|
|
17
|
+
import { wrapText } from './wrap.js';
|
|
18
|
+
|
|
19
|
+
const MAX = 200; // a ceiling on any list, so one command cannot flood a terminal
|
|
20
|
+
|
|
21
|
+
// Glyphs degrade for terminals that cannot show them. TUIKit's rule: a missing
|
|
22
|
+
// glyph is a rendering bug the user should never have to report, so the ASCII
|
|
23
|
+
// set is a first-class path, not a fallback we hope nobody needs.
|
|
24
|
+
const GLYPHS = process.platform === 'win32' && !process.env.WT_SESSION
|
|
25
|
+
? { dir: '+', file: '-', entry: '>', hub: '*', arrow: '->', warn: '!', good: '+' }
|
|
26
|
+
: { dir: '▸', file: '·', entry: '▶', hub: '◆', arrow: '→', warn: '⚠', good: '✓' };
|
|
27
|
+
|
|
28
|
+
// The footer is a hint bar, and a hint bar that wraps is worse than no hint bar
|
|
29
|
+
// — it is the first thing printed, so it sets the impression of everything else.
|
|
30
|
+
// On a narrow terminal it drops hints rather than wrapping.
|
|
31
|
+
function hintBar(hints) {
|
|
32
|
+
// The room is the terminal minus the 2-space lead. The `Math.max(8, …)` that
|
|
33
|
+
// used to be here was a floor *above* the available width on an 8-column
|
|
34
|
+
// terminal, which guarantees an overflow — the exact opposite of what a
|
|
35
|
+
// hint bar is for. Below the width of one hint, the hint is cut to fit
|
|
36
|
+
// rather than allowed to wrap.
|
|
37
|
+
const room = Math.max(1, termWidth() - 2);
|
|
38
|
+
const parts = [];
|
|
39
|
+
for (const h of hints) {
|
|
40
|
+
const next = parts.length ? parts.join(' · ') + ' · ' + h : h;
|
|
41
|
+
if (next.length > room) break;
|
|
42
|
+
parts.push(h);
|
|
43
|
+
}
|
|
44
|
+
const line = parts.join(' · ') || hints[0].slice(0, room);
|
|
45
|
+
return dim(' ' + line);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// `wrapText` now lives in `./wrap.js`, shared with the command table's help screen.
|
|
49
|
+
|
|
50
|
+
// -------------------------------------------------------------- overview ---
|
|
51
|
+
|
|
52
|
+
// The landing view. Answers "what am I looking at, and where do I start" in one
|
|
53
|
+
// screen — the same three questions the site's first paint answers.
|
|
54
|
+
export function overview(repo) {
|
|
55
|
+
const s = repo.scan.stats;
|
|
56
|
+
const h = repo.health;
|
|
57
|
+
const langs = repo.languages.slice(0, 4).map((l) => `${l.label} ${l.loc}`).join(', ')
|
|
58
|
+
+ (repo.languages.length > 4 ? `, +${repo.languages.length - 4} more` : '');
|
|
59
|
+
|
|
60
|
+
const rows = [
|
|
61
|
+
row('folder', repo.root),
|
|
62
|
+
row('files', `${s.filesParsed} parsed` + (s.skipped ? dim(` (${s.skipped} skipped)`) : '') + ` · ${s.edgeCount} imports`),
|
|
63
|
+
row('languages', langs || '—'),
|
|
64
|
+
];
|
|
65
|
+
if (repo.manifest.packageName) rows.push(row('package', repo.manifest.packageName));
|
|
66
|
+
rows.push(row('license', repo.scan.license?.name || 'unknown'));
|
|
67
|
+
if (repo.facts.entries.length) rows.push(row('start at', repo.facts.entries.slice(0, 3).join(', ')));
|
|
68
|
+
if (repo.facts.hubs.length) {
|
|
69
|
+
const top = repo.facts.hubs[0];
|
|
70
|
+
rows.push(row('top hub', `${top.path} ${dim(`(${top.fanIn} files)`)}`));
|
|
71
|
+
}
|
|
72
|
+
rows.push(row('health', gradeColor(h.grade) + dim(' score ') + `${h.score}/100`));
|
|
73
|
+
|
|
74
|
+
const notes = scanCaveats(repo.scan);
|
|
75
|
+
const out = [panel(repo.name, rows)];
|
|
76
|
+
if (notes.length) out.push(dim(wrapText(notes.join('\n'))));
|
|
77
|
+
out.push(hintBar(['tour explains it', 'tree lists it', 'find searches it', 'help lists everything']));
|
|
78
|
+
return out.join('\n');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function gradeColor(grade) {
|
|
82
|
+
if (grade === 'A' || grade === 'B') return ok(grade);
|
|
83
|
+
if (grade === 'C') return warn(grade);
|
|
84
|
+
return bad(grade);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ------------------------------------------------------------------ tree ---
|
|
88
|
+
|
|
89
|
+
// The file tree. Directories first, then files, each marked with the role that
|
|
90
|
+
// makes it worth noticing — an entry point or a hub is the two things a new
|
|
91
|
+
// reader is looking for, and marking them here saves a separate `hubs` command
|
|
92
|
+
// on every repo.
|
|
93
|
+
export function tree(repo, { sub = '', depth = 2, limit = MAX } = {}) {
|
|
94
|
+
const files = repo.scan.files;
|
|
95
|
+
const prefix = String(sub || '').replace(/^\/+|\/+$/g, '');
|
|
96
|
+
const scoped = prefix ? files.filter((f) => f.path.startsWith(prefix + '/')) : files;
|
|
97
|
+
if (!scoped.length) return dim(` Nothing under ${prefix || 'the root'}.`);
|
|
98
|
+
|
|
99
|
+
const root = { name: prefix || repo.name, path: prefix, dirs: new Map(), files: [] };
|
|
100
|
+
for (const f of scoped) {
|
|
101
|
+
const rel = prefix ? f.path.slice(prefix.length + 1) : f.path;
|
|
102
|
+
const parts = rel.split('/');
|
|
103
|
+
let node = root;
|
|
104
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
105
|
+
const name = parts[i];
|
|
106
|
+
if (!node.dirs.has(name)) {
|
|
107
|
+
node.dirs.set(name, {
|
|
108
|
+
name,
|
|
109
|
+
path: node.path ? `${node.path}/${name}` : name,
|
|
110
|
+
dirs: new Map(),
|
|
111
|
+
files: [],
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
node = node.dirs.get(name);
|
|
115
|
+
}
|
|
116
|
+
node.files.push(f);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const lines = [];
|
|
120
|
+
let budget = Math.min(Number(limit) || MAX, MAX);
|
|
121
|
+
const walk = (node, depthLeft, indent) => {
|
|
122
|
+
for (const child of [...node.dirs.values()].sort((a, b) => a.name.localeCompare(b.name))) {
|
|
123
|
+
if (budget <= 0) return;
|
|
124
|
+
const room = Math.max(4, termWidth() - indent.length - 2 - 4);
|
|
125
|
+
lines.push(labelled(dim(GLYPHS.dir + ' '), child.name, dim(` ${countUnder(child)}`), { pad: indent.length }));
|
|
126
|
+
budget--;
|
|
127
|
+
if (depthLeft > 1) walk(child, depthLeft - 1, indent + ' ');
|
|
128
|
+
}
|
|
129
|
+
for (const f of node.files) {
|
|
130
|
+
if (budget <= 0) return;
|
|
131
|
+
lines.push(fileLine(repo, f, indent.length));
|
|
132
|
+
budget--;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
walk(root, Math.max(1, Number(depth) || 2), ' ');
|
|
136
|
+
|
|
137
|
+
const out = [dim(fit(` tree · ${prefix || '.'} ${scoped.length} files, depth ${Math.max(1, Number(depth) || 2)}`, Math.max(4, termWidth() - 2))), lines.join('\n')];
|
|
138
|
+
if (budget <= 0) out.push(dim(wrapText('… list stopped early — tree <folder> <depth> to go deeper', ' ')));
|
|
139
|
+
return out.join('\n');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function fileLine(repo, f, indent = 2) {
|
|
143
|
+
const role = fileFacts(repo, f).role;
|
|
144
|
+
const badge = role === 'entry' ? ok(GLYPHS.entry) : role === 'hub' ? warn(GLYPHS.hub) : dim(GLYPHS.file);
|
|
145
|
+
// The name is the identifying part; the extension and line count are the first
|
|
146
|
+
// things to go when there is no room. `tree` on a phone-width terminal should
|
|
147
|
+
// still list the files, just less verbosely.
|
|
148
|
+
const tail = ' ' + dim(String(f.ext || '').padEnd(6)) + dim(String(f.loc || 0).padStart(5));
|
|
149
|
+
// The depth indent is part of the budget — it used to be prepended by the
|
|
150
|
+
// caller, which made every nested row as many cells too wide as its depth.
|
|
151
|
+
return labelled(badge + ' ', f.name, tail, { pad: indent });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function countUnder(node) {
|
|
155
|
+
let n = node.files.length;
|
|
156
|
+
for (const d of node.dirs.values()) n += countUnder(d);
|
|
157
|
+
return n;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ------------------------------------------------------------------ find ---
|
|
161
|
+
|
|
162
|
+
// Search, using the site's query language. The result rows carry the same three
|
|
163
|
+
// things the site's palette shows — path, line, snippet — fitted to the
|
|
164
|
+
// terminal, with the path keeping the room it needs because it is what
|
|
165
|
+
// identifies the hit.
|
|
166
|
+
export function find(repo, { query = '', limit = 12 } = {}) {
|
|
167
|
+
if (!String(query).trim()) {
|
|
168
|
+
return dim(wrapText('Try: find resolveImport · find ext:rs -test · find "exact phrase" · find /regex/', ' '));
|
|
169
|
+
}
|
|
170
|
+
const res = searchRepo(repo, query, { limit: Math.min(Number(limit) || 12, MAX) });
|
|
171
|
+
if (res.error) return bad(' ' + res.error);
|
|
172
|
+
if (!res.results.length) return dim(wrapText(`No match for "${query}" in ${res.indexed} indexed files.`, ' '));
|
|
173
|
+
|
|
174
|
+
const w = termWidth();
|
|
175
|
+
// Path, line number and snippet share the terminal. The snippet is the least
|
|
176
|
+
// identifying part, so it goes first on a narrow terminal; `labelled` owns the
|
|
177
|
+
// indent, which is why the row cannot be `indent + name + count` glued
|
|
178
|
+
// together and then be a few cells too wide.
|
|
179
|
+
const lineRoom = 5;
|
|
180
|
+
const lines = res.results.map((r) => {
|
|
181
|
+
const snippetRoom = w - 2 - lineRoom - 2;
|
|
182
|
+
const snip = snippetRoom > 10 ? dim(' ' + fit(r.snippet, snippetRoom, { tail: false })) : '';
|
|
183
|
+
return labelled('', r.path, dim(String(r.line).padStart(lineRoom)) + snip, { pad: 2 });
|
|
184
|
+
});
|
|
185
|
+
const kind = res.advanced ? 'filtered query' : 'query';
|
|
186
|
+
const head = dim(fit(` ${res.total} match${res.total === 1 ? '' : 'es'} (${kind}) across ${res.indexed} indexed files`, Math.max(1, w - 2)));
|
|
187
|
+
return [head, ...lines, hintBar(['show <path> to read one', 'deps <path> to trace it'])].join('\n');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ------------------------------------------------------------------ show ---
|
|
191
|
+
|
|
192
|
+
// Read a file in the terminal. This is the one view that cannot be pure — it
|
|
193
|
+
// touches the disk — so it is the one async view, and it goes through the same
|
|
194
|
+
// containment check the HTTP route uses rather than reaching for a path itself.
|
|
195
|
+
export async function show(repo, { target = '', from = 0, count = 0 } = {}) {
|
|
196
|
+
const found = resolveTarget(repo, target);
|
|
197
|
+
if (found.error) return targetError(found);
|
|
198
|
+
if (found.folder) return dim(` ${found.folder.path} is a folder — tree ${found.folder.path} 2, or explain ${found.folder.path}`);
|
|
199
|
+
|
|
200
|
+
const file = found.file;
|
|
201
|
+
const text = await readRepoFile(repo, file.path);
|
|
202
|
+
const lines = text.split('\n');
|
|
203
|
+
// `null` here means the argument was present but not a usable line number
|
|
204
|
+
// (`show f 1.5`), which the command layer turns into a message rather than a
|
|
205
|
+
// silent fallback. A string means a caller passed a bad value, so say so
|
|
206
|
+
// instead of coercing it into a nonsensical range.
|
|
207
|
+
if (from === null || count === null) {
|
|
208
|
+
return bad(wrapText('Line numbers must be whole numbers.', ' ')) + dim(fit(' Try: `show ' + file.name + ' 40 20`', Math.max(1, termWidth() - 2)));
|
|
209
|
+
}
|
|
210
|
+
const start = Math.max(1, from || 1);
|
|
211
|
+
const room = count > 0 ? Math.min(count, 400) : Math.min(lines.length, 40);
|
|
212
|
+
const end = Math.min(lines.length, start + room - 1);
|
|
213
|
+
|
|
214
|
+
const gutter = String(end).length;
|
|
215
|
+
const body = lines.slice(start - 1, end).map((line, i) => {
|
|
216
|
+
const n = String(start + i).padStart(gutter);
|
|
217
|
+
return dim(n + ' ') + fit(line.replace(/\t/g, ' '), Math.max(20, termWidth() - gutter - 3), { tail: false });
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
const f = fileFacts(repo, file);
|
|
221
|
+
const head = panel(file.path, [
|
|
222
|
+
{ label: 'role', value: f.role },
|
|
223
|
+
{ label: 'size', value: `${f.loc} loc` + (f.complexity ? ` · complexity ${f.complexity}` : '') },
|
|
224
|
+
{ label: 'graph', value: `${f.fanIn} in ${f.fanOut} out` + (f.inCycle ? ' ' + bad('in a cycle') : '') },
|
|
225
|
+
]);
|
|
226
|
+
const shown = `${start}–${end} of ${lines.length}`;
|
|
227
|
+
return [head, dim(` ${shown}`), ...body, hintBar([`deps ${file.name} for connections`, `explain ${file.name} in prose`])].join('\n');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Render a resolver miss the same way everywhere: the reason, then the
|
|
231
|
+
// candidates. A "did you mean" is only useful if it is actionable.
|
|
232
|
+
//
|
|
233
|
+
// The reason is word-wrapped, because a miss on a long path or an unfamiliar
|
|
234
|
+
// filename produces a long sentence, and the commands that surface this
|
|
235
|
+
// (symbols, blast, graph, blame) do not each remember to wrap it.
|
|
236
|
+
export function targetError(found) {
|
|
237
|
+
// The room is the terminal minus the 2-space lead. The `Math.max(8, …)` that
|
|
238
|
+
// used to be here was itself the bug on an 8-column terminal: a floor above the
|
|
239
|
+
// available width guarantees an overflow, which is the one thing this function
|
|
240
|
+
// exists to prevent. `wrapText` already clamps to a single cell.
|
|
241
|
+
const w = termWidth();
|
|
242
|
+
const room = Math.max(1, w - 6);
|
|
243
|
+
const lines = [bad(' ' + wrapText(found.error, ' ', room))];
|
|
244
|
+
if (found.candidates) {
|
|
245
|
+
for (const c of found.candidates) lines.push(' ' + cyan(fit(c, Math.max(1, w - 4))));
|
|
246
|
+
lines.push(dim(fit(' show <one of these>', Math.max(1, w - 2))));
|
|
247
|
+
}
|
|
248
|
+
return lines.join('\n');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ------------------------------------------------------------------ deps ---
|
|
252
|
+
|
|
253
|
+
// What a file connects to, in both directions, plus the verdict the graph has
|
|
254
|
+
// on it. The two lists are the point: "what does this pull in" and "what breaks
|
|
255
|
+
// if this breaks" are different questions and a single edge count answers
|
|
256
|
+
// neither.
|
|
257
|
+
export function deps(repo, { target = '', limit = 15 } = {}) {
|
|
258
|
+
const found = resolveTarget(repo, target);
|
|
259
|
+
if (found.error) return targetError(found);
|
|
260
|
+
if (found.folder) return dim(` ${found.folder.path} is a folder — try a file inside it.`);
|
|
261
|
+
|
|
262
|
+
const p = found.file.path;
|
|
263
|
+
const imports = (repo.facts.importsOf[p] || []).slice(0, limit);
|
|
264
|
+
const importers = (repo.facts.importers[p] || []).slice(0, limit);
|
|
265
|
+
const f = fileFacts(repo, found.file);
|
|
266
|
+
const w = termWidth();
|
|
267
|
+
|
|
268
|
+
const head = [panel(found.file.path, [
|
|
269
|
+
{ label: 'role', value: f.role },
|
|
270
|
+
{ label: 'dependents', value: `${f.fanIn} file${f.fanIn === 1 ? '' : 's'} import this` },
|
|
271
|
+
{ label: 'imports', value: `${f.fanOut} file${f.fanOut === 1 ? '' : 's'} pulled in` },
|
|
272
|
+
])];
|
|
273
|
+
if (f.inCycle) head.push(bad(fit(' ' + GLYPHS.warn + ' part of a circular import — refactoring here ripples', Math.max(1, w - 2))));
|
|
274
|
+
|
|
275
|
+
const list = (title, items) => {
|
|
276
|
+
if (!items.length) return dim(fit(` ${title}: none`, Math.max(1, w - 2)));
|
|
277
|
+
return [dim(fit(` ${title}:`, Math.max(1, w - 2))), ...items.map((x) => ' ' + cyan(fit(x, Math.max(1, w - 4))))].join('\n');
|
|
278
|
+
};
|
|
279
|
+
return [...head, list('imports', imports), list('imported by', importers)].join('\n');
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// --------------------------------------------------------------- explain ---
|
|
283
|
+
|
|
284
|
+
// The prose explanation, straight from `explainLocal.js` — the same notes the
|
|
285
|
+
// site shows when no AI key is configured, with no key required and nothing
|
|
286
|
+
// sent anywhere. Markdown backticks are the one bit of markup kept, turned into
|
|
287
|
+
// terminal emphasis.
|
|
288
|
+
export function explain(repo, { target = '' } = {}) {
|
|
289
|
+
if (!String(target).trim()) return renderProse(explainRepoOverview(repo));
|
|
290
|
+
const found = resolveTarget(repo, target);
|
|
291
|
+
if (found.error) return targetError(found);
|
|
292
|
+
if (found.folder) return renderProse(explainRepoFolder(repo, found.folder));
|
|
293
|
+
return renderProse(explainRepoFile(repo, found.file));
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// `**bold**` and `` `code` `` are the only two marks `explainLocal` emits. They
|
|
297
|
+
// become terminal styling; everything else passes through untouched, so the
|
|
298
|
+
// prose still reads correctly with color off. Wrapping happens on the plain
|
|
299
|
+
// text first, then the marks are styled in place — styling after wrapping keeps
|
|
300
|
+
// the wrap from having to measure escape sequences.
|
|
301
|
+
function renderProse(md) {
|
|
302
|
+
return String(md)
|
|
303
|
+
.split('\n\n')
|
|
304
|
+
.map((para) => {
|
|
305
|
+
const styled = para
|
|
306
|
+
.replace(/`([^`]+)`/g, (_, c) => '\u0000' + c + '\u0000')
|
|
307
|
+
.replace(/\*\*([^*]+)\*\*/g, (_, c) => '\u0001' + c + '\u0001');
|
|
308
|
+
return wrapText(styled)
|
|
309
|
+
.replace(/\u0000([^\u0000]+)\u0000/g, (_, c) => cyan(c))
|
|
310
|
+
.replace(/\u0001([^\u0001]+)\u0001/g, (_, c) => bold(c));
|
|
311
|
+
})
|
|
312
|
+
.join('\n\n');
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// ------------------------------------------------------------------ tour ---
|
|
316
|
+
|
|
317
|
+
// The guided read. The same eight stops the site and the MCP server hand out,
|
|
318
|
+
// in the same order, with the same one-line reason for each — a person at the
|
|
319
|
+
// prompt and an agent asking the MCP server are being told the same thing about
|
|
320
|
+
// the same repository.
|
|
321
|
+
export function tour(repo) {
|
|
322
|
+
if (!repo.tour.length) return dim(wrapText('No tour stops found — is this a code repository?', ' '));
|
|
323
|
+
const lines = repo.tour.map((stop, i) => {
|
|
324
|
+
// The number is the marker and the path is the value, so the tour stops use
|
|
325
|
+
// the same helper as every other ranked list and cannot outgrow the terminal.
|
|
326
|
+
const head = labelled(dim(String(i + 1).padStart(2) + '. '), stop.path, '', { pad: 2 });
|
|
327
|
+
return [head, dim(wrapText(stop.why, ' '))].join('\n');
|
|
328
|
+
});
|
|
329
|
+
return [dim(fit(' reading order', Math.max(4, termWidth() - 2))), ...lines, hintBar(['show <path> to read one'])].join('\n');
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ---------------------------------------------------------------- health ---
|
|
333
|
+
|
|
334
|
+
// The health report. The grade leads because that is the question; the
|
|
335
|
+
// breakdown follows because a letter with no reasons is not actionable.
|
|
336
|
+
export function health(repo) {
|
|
337
|
+
const h = repo.health;
|
|
338
|
+
const w = termWidth();
|
|
339
|
+
const rows = [
|
|
340
|
+
{ label: 'grade', value: gradeColor(h.grade) + dim(` score ${h.score}/100`) },
|
|
341
|
+
{ label: 'debt', value: `${h.totals.crit} critical · ${h.totals.high} high findings` },
|
|
342
|
+
{ label: 'complexity', value: `avg ${h.totals.avgCx} per file` },
|
|
343
|
+
{ label: 'orphans', value: `${Math.round(h.totals.orphanRatio * 100)}% of files import nothing` },
|
|
344
|
+
{ label: 'cycles', value: String(h.totals.cycles) },
|
|
345
|
+
];
|
|
346
|
+
if (h.effortHours) rows.push({ label: 'effort', value: `~${h.effortHours}h to address (${h.debtCategory})` });
|
|
347
|
+
|
|
348
|
+
const risky = [...(h.perFile || [])]
|
|
349
|
+
.filter((f) => (f.risk || 0) > 0)
|
|
350
|
+
.sort((a, b) => b.risk - a.risk)
|
|
351
|
+
.slice(0, 8);
|
|
352
|
+
const out = [panel('health', rows)];
|
|
353
|
+
if (risky.length) {
|
|
354
|
+
out.push(dim(fit(' riskiest files:', Math.max(4, termWidth() - 2))));
|
|
355
|
+
for (const f of risky) {
|
|
356
|
+
// Risk is an integer 0–100; printing "58.00" would imply a precision the
|
|
357
|
+
// number does not have. The suffix is dropped on a narrow terminal rather
|
|
358
|
+
// than allowed to push the path off the edge.
|
|
359
|
+
const risk = Number(f.risk);
|
|
360
|
+
const tail = dim(` risk ${risk}${f.blast !== undefined ? ` blast ${f.blast}` : ''}`);
|
|
361
|
+
out.push(labelled(warn(GLYPHS.warn + ' '), cyan(f.path), tail, { pad: 4 }));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (h.breakdown?.length) {
|
|
365
|
+
// The breakdown is the score itemized — each entry is what a factor cost.
|
|
366
|
+
// Showing the label without the points would explain the grade without
|
|
367
|
+
// showing the arithmetic, which is the part that makes it actionable.
|
|
368
|
+
out.push(dim(fit(' what moved the score:', Math.max(4, termWidth() - 2))));
|
|
369
|
+
for (const b of h.breakdown) {
|
|
370
|
+
out.push(labelled(dim('· '), b.label, bad(String(b.points)), { pad: 4 }));
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return out.join('\n');
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ------------------------------------------------------------------ hubs ---
|
|
377
|
+
|
|
378
|
+
// The load-bearing files: the ones everything else reaches for. Ranked, because
|
|
379
|
+
// "which file is load-bearing" only has an answer as an ordering.
|
|
380
|
+
export function hubs(repo, { limit = 12 } = {}) {
|
|
381
|
+
const list = repo.facts.hubs.slice(0, Math.min(Number(limit) || 12, MAX));
|
|
382
|
+
if (!list.length) return dim(wrapText('No hubs — nothing here is imported by two or more files.', ' '));
|
|
383
|
+
const w = termWidth();
|
|
384
|
+
const top = list[0].fanIn || 1;
|
|
385
|
+
// The bar is decoration and is the tail, so it is the first thing dropped on a
|
|
386
|
+
// narrow terminal. The in/out counts are the reason the file is on the list.
|
|
387
|
+
const barRoom = Math.max(0, Math.min(24, w - 30));
|
|
388
|
+
return [dim(fit(' most depended-on files', Math.max(4, w - 2))), ...list.map((h) => {
|
|
389
|
+
const bar = barRoom > 4 ? dim(' ' + '█'.repeat(Math.max(1, Math.round((h.fanIn / top) * barRoom)))) : '';
|
|
390
|
+
return labelled('', h.path, dim(` ${h.fanIn} in / ${h.fanOut} out`) + bar, { pad: 2 });
|
|
391
|
+
})].join('\n');
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// ---------------------------------------------------------------- layers ---
|
|
395
|
+
|
|
396
|
+
// Import depth, shallowest first. This is the architecture as a staircase:
|
|
397
|
+
// layer 0 is what runs, and each step down is something it can reach.
|
|
398
|
+
export function layers(repo, { limit = 12 } = {}) {
|
|
399
|
+
const ls = repo.layers.layers;
|
|
400
|
+
const w = termWidth();
|
|
401
|
+
if (!ls.length) return dim(wrapText('No layers — no import chain starts anywhere we recognize.'));
|
|
402
|
+
const out = [dim(fit(' import depth', Math.max(4, termWidth() - 2)))];
|
|
403
|
+
ls.slice(0, Math.min(Number(limit) || 12, 40)).forEach((files, i) => {
|
|
404
|
+
// The "+N more" note is the tail, so a terminal that cannot hold the path
|
|
405
|
+
// *and* the note drops the note rather than overflowing. Same rule as every
|
|
406
|
+
// other labelled row, which is why it goes through the same helper.
|
|
407
|
+
const more = files.length > 3 ? dim(` +${files.length - 3} more`) : '';
|
|
408
|
+
out.push(labelled(dim(` layer ${i} (${files.length}) `), cyan(files.slice(0, 3).join(', ')), more));
|
|
409
|
+
});
|
|
410
|
+
if (repo.layers.unreachable.length) {
|
|
411
|
+
out.push(dim(wrapText(`${repo.layers.unreachable.length} files are not reachable from any entry point`)));
|
|
412
|
+
}
|
|
413
|
+
return out.join('\n');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// -------------------------------------------------------------- patterns ---
|
|
417
|
+
|
|
418
|
+
// The architecture, in prose. These are the observations `detectPatterns`
|
|
419
|
+
// makes, in the order a senior dev would mention them.
|
|
420
|
+
export function patterns(repo) {
|
|
421
|
+
if (!repo.patterns.length) return dim(wrapText('No patterns stood out.', ' '));
|
|
422
|
+
const out = [dim(fit(' what this codebase looks like', Math.max(4, termWidth() - 2)))];
|
|
423
|
+
for (const p of repo.patterns) {
|
|
424
|
+
const mark = p.tone === 'good' ? ok(GLYPHS.good) : p.tone === 'warn' ? bad(GLYPHS.warn) : warn('·');
|
|
425
|
+
out.push(' ' + mark + ' ' + dim(fit(p.title, Math.max(4, termWidth() - 4))));
|
|
426
|
+
out.push(dim(wrapText(p.detail, ' ')));
|
|
427
|
+
if (p.paths?.length) {
|
|
428
|
+
out.push(dim(' ' + fit(p.paths.slice(0, 4).join(' '), Math.max(4, termWidth() - 4))));
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return out.join('\n');
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// ----------------------------------------------------------------- stats ---
|
|
435
|
+
|
|
436
|
+
// The numbers, grouped by the question each answers: what is it made of, where
|
|
437
|
+
// is the bulk of it, and what is the heaviest thing in it.
|
|
438
|
+
export function stats(repo, { limit = 10 } = {}) {
|
|
439
|
+
const n = Math.min(Number(limit) || 10, MAX);
|
|
440
|
+
const s = repo.scan.stats;
|
|
441
|
+
const top = [...repo.scan.files].sort((a, b) => (b.loc || 0) - (a.loc || 0)).slice(0, n);
|
|
442
|
+
const folders = [...repo.scan.folders].sort((a, b) => (b.loc || 0) - (a.loc || 0)).slice(0, n);
|
|
443
|
+
const cx = [...repo.scan.files].filter((f) => f.complexity > 0).sort((a, b) => b.complexity - a.complexity).slice(0, 5);
|
|
444
|
+
|
|
445
|
+
const totalLoc = repo.languages.reduce((s2, l) => s2 + l.loc, 0);
|
|
446
|
+
// One label column for every ranked list, sized from the terminal rather than
|
|
447
|
+
// hardcoded at 34. The old fixed padding meant a 20-column terminal got 45
|
|
448
|
+
// columns of output — the number was right and the layout was still wrong.
|
|
449
|
+
const w = termWidth();
|
|
450
|
+
const labels = [
|
|
451
|
+
...repo.languages.slice(0, 8).map((l) => l.label),
|
|
452
|
+
...folders.map((d) => d.path),
|
|
453
|
+
...top.map((f) => f.path),
|
|
454
|
+
...cx.map((f) => f.path),
|
|
455
|
+
];
|
|
456
|
+
const labelRoom = Math.max(4, Math.min(34, Math.max(0, ...labels.map((s) => s.length)) + 1, Math.floor(w * 0.45)));
|
|
457
|
+
// The number keeps at least 4 cells and the label gets the rest, so the row is
|
|
458
|
+
// `indent + label + number` and never exceeds the terminal at any width.
|
|
459
|
+
const numRoom = Math.max(4, Math.min(7, w - labelRoom - 5));
|
|
460
|
+
const statRow = (s, n) => labelled('', s, dim(String(n).padStart(numRoom)), { pad: 4 });
|
|
461
|
+
|
|
462
|
+
const out = [panel('stats', [
|
|
463
|
+
{ label: 'files', value: `${s.filesParsed} parsed of ${s.filesTotal} seen` },
|
|
464
|
+
{ label: 'lines', value: `${totalLoc} code` + (s.truncated ? warn(' (partial scan)') : '') },
|
|
465
|
+
{ label: 'imports', value: `${s.edgeCount} resolved` + (s.imports?.total ? dim(` ${s.imports.confidence}% placed`) : '') },
|
|
466
|
+
{ label: 'tests', value: `${repo.facts.testCoverage.ratio}% of non-test files are covered by a test import` },
|
|
467
|
+
])];
|
|
468
|
+
|
|
469
|
+
out.push(dim(fit(' languages', Math.max(4, w - 2))));
|
|
470
|
+
for (const l of repo.languages.slice(0, 8)) out.push(statRow(l.label, l.loc));
|
|
471
|
+
|
|
472
|
+
if (folders.length) {
|
|
473
|
+
out.push(dim(fit(' biggest folders (loc)', Math.max(4, termWidth() - 2))));
|
|
474
|
+
for (const d of folders) out.push(statRow(d.path, d.loc));
|
|
475
|
+
}
|
|
476
|
+
if (top.length) {
|
|
477
|
+
out.push(dim(fit(' biggest files (loc)', Math.max(4, termWidth() - 2))));
|
|
478
|
+
for (const f of top) out.push(statRow(f.path, f.loc));
|
|
479
|
+
}
|
|
480
|
+
if (cx.length) {
|
|
481
|
+
out.push(dim(fit(' most complex', Math.max(4, w - 2))));
|
|
482
|
+
for (const f of cx) out.push(statRow(f.path, f.complexity));
|
|
483
|
+
}
|
|
484
|
+
return out.join('\n');
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// -------------------------------------------------------------- security ---
|
|
488
|
+
|
|
489
|
+
export function security(repo, { limit = 12 } = {}) {
|
|
490
|
+
const sec = repo.security;
|
|
491
|
+
const w = termWidth();
|
|
492
|
+
if (!sec.total) return ok(wrapText('No findings from the built-in rules.', ' '));
|
|
493
|
+
const order = ['critical', 'high', 'medium', 'low', 'info'];
|
|
494
|
+
const counts = order.filter((k) => sec.counts[k]).map((k) => `${sec.counts[k]} ${k}`).join(' · ');
|
|
495
|
+
const out = [panel('security', [
|
|
496
|
+
{ label: 'grade', value: gradeColor(sec.grade) + dim(` score ${sec.score}/100`) },
|
|
497
|
+
{ label: 'findings', value: counts },
|
|
498
|
+
])];
|
|
499
|
+
for (const f of sec.files.slice(0, Math.min(Number(limit) || 12, MAX))) {
|
|
500
|
+
const mark = (f.worst === 'critical' || f.worst === 'high' ? bad : warn)(GLYPHS.warn + ' ');
|
|
501
|
+
out.push(labelled(mark, cyan(f.path), dim(` ${f.count} · worst ${f.worst}`), { pad: 4 }));
|
|
502
|
+
}
|
|
503
|
+
out.push(dim(wrapText('Pattern-based heuristics only — not a substitute for a real audit.')));
|
|
504
|
+
return out.join('\n');
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ----------------------------------------------------------------- stack ---
|
|
508
|
+
|
|
509
|
+
// The dependency picture the site shows, from the same `analyzeStack`. Columns
|
|
510
|
+
// are computed from the widest *actual* value rather than fixed padding, so a
|
|
511
|
+
// long scoped package name shrinks the columns instead of pushing the row off
|
|
512
|
+
// the right edge.
|
|
513
|
+
export function stack(repo, { limit = 20 } = {}) {
|
|
514
|
+
const st = repo.stack;
|
|
515
|
+
const w = termWidth();
|
|
516
|
+
if (!st.items.length) return dim(wrapText('No recognized dependencies (no package manifest found?).', ' '));
|
|
517
|
+
const items = st.items.slice(0, Math.min(Number(limit) || 20, MAX));
|
|
518
|
+
|
|
519
|
+
const out = [dim(fit(' stack ' + (st.pm.join(', ') || 'no package manager'), Math.max(1, w - 2)))];
|
|
520
|
+
for (const it of items) {
|
|
521
|
+
// Same shape as every other row: the name is the value, the category and
|
|
522
|
+
// version are the tail, and the tail is what a narrow terminal drops. The
|
|
523
|
+
// old version computed its own column budget and was three cells wide.
|
|
524
|
+
const tail = dim(it.category) + (it.version ? ' ' + it.version : '') + (it.dev ? ' dev' : '');
|
|
525
|
+
out.push(labelled('', it.name, tail, { pad: 4 }));
|
|
526
|
+
}
|
|
527
|
+
return out.join('\n');
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ----------------------------------------------------------------- entry ---
|
|
531
|
+
|
|
532
|
+
export function entry(repo) {
|
|
533
|
+
if (!repo.facts.entries.length) {
|
|
534
|
+
return dim(wrapText('No entry points recognized. tour falls back to the most depended-on files.'));
|
|
535
|
+
}
|
|
536
|
+
const w = termWidth();
|
|
537
|
+
return [dim(fit(' entry points', Math.max(4, termWidth() - 2))), ...repo.facts.entries.map((p) => {
|
|
538
|
+
const out = repo.facts.fanOut[p] || 0;
|
|
539
|
+
return labelled(ok(GLYPHS.entry + ' '), cyan(p), dim(` reaches ${out} files`), { pad: 4 });
|
|
540
|
+
})].join('\n');
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// ------------------------------------------------------------- externals ---
|
|
544
|
+
|
|
545
|
+
// Outside packages, and who pulls them in. Dependency drift is the useful part:
|
|
546
|
+
// declared-but-unused and used-but-undeclared are the two lists a dependency
|
|
547
|
+
// audit actually acts on.
|
|
548
|
+
export function externals(repo) {
|
|
549
|
+
const ext = repo.scan.externals || [];
|
|
550
|
+
if (!ext.length) return dim(wrapText('No external imports found.'));
|
|
551
|
+
const w = termWidth();
|
|
552
|
+
const sorted = [...ext].sort((a, b) => (b.usedBy?.length || 0) - (a.usedBy?.length || 0));
|
|
553
|
+
const shown = sorted.slice(0, 30);
|
|
554
|
+
// Two columns when they fit, one per line when they do not. A scoped package
|
|
555
|
+
// name is long enough on its own to push a fixed-width column off a narrow
|
|
556
|
+
// terminal, so the column width follows the data.
|
|
557
|
+
const nameRoom = Math.max(8, Math.min(28, Math.max(...shown.map((x) => String(x.name).length))));
|
|
558
|
+
const out = [dim(fit(' external packages', Math.max(4, w - 2)))];
|
|
559
|
+
if (w < nameRoom + 16) {
|
|
560
|
+
for (const x of shown) {
|
|
561
|
+
out.push(labelled('', `${x.name} · ${x.usedBy?.length || 0} files`, '', { pad: 4 }));
|
|
562
|
+
}
|
|
563
|
+
} else {
|
|
564
|
+
for (const x of shown) {
|
|
565
|
+
out.push(labelled('', x.name, dim(`${x.usedBy?.length || 0} files`), { pad: 4 }));
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
const drift = repo.facts.depsDrift;
|
|
569
|
+
if (drift?.undeclaredImported?.length) {
|
|
570
|
+
out.push(dim(fit(' imported but not declared', Math.max(4, termWidth() - 2))));
|
|
571
|
+
out.push(wrapText(drift.undeclaredImported.join(', '), ' ').split('\n').map(warn).join('\n'));
|
|
572
|
+
}
|
|
573
|
+
if (drift?.unusedDeclared?.length) {
|
|
574
|
+
out.push(dim(fit(' declared but never imported', Math.max(4, termWidth() - 2))));
|
|
575
|
+
out.push(dim(wrapText(drift.unusedDeclared.join(', '), ' ')));
|
|
576
|
+
}
|
|
577
|
+
return out.join('\n');
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// ----------------------------------------------------------------- about ---
|
|
581
|
+
|
|
582
|
+
// Which binary is answering. When the terminal and the website disagree, this
|
|
583
|
+
// is the first thing to ask.
|
|
584
|
+
export function about(repo, version = '') {
|
|
585
|
+
const rows = [
|
|
586
|
+
{ label: 'version', value: version },
|
|
587
|
+
{ label: 'repo', value: repo.root },
|
|
588
|
+
{ label: 'indexed', value: `${repo.searchIndex?.totalDocs ?? 0} files for find` },
|
|
589
|
+
{ label: 'scanned', value: `${repo.scan.scannedAt}` },
|
|
590
|
+
];
|
|
591
|
+
if (repo.gitUrl) rows.push({ label: 'from', value: repo.gitUrl });
|
|
592
|
+
if (repo.cloneDir) rows.push({ label: 'clone', value: 'a temp clone — removed when you leave' });
|
|
593
|
+
return panel('onboarder', rows);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// `github` — the terminal's answer to the site's "From the remote" section:
|
|
597
|
+
// what GitHub says about this repository, as opposed to what reading the code
|
|
598
|
+
// says about it. The distinction is the point. Stars and issues are about the
|
|
599
|
+
// project's standing; `health` and `risks` are about the code in front of you,
|
|
600
|
+
// and neither can tell you the other.
|
|
601
|
+
//
|
|
602
|
+
// The result is passed in rather than fetched here, because every function in
|
|
603
|
+
// this file is pure and testable with no network. `ctx.github()` does the asking.
|
|
604
|
+
export function github(repo, result) {
|
|
605
|
+
if (!result) {
|
|
606
|
+
return dim(wrapText('Not a GitHub repository, so there is nothing to ask GitHub about.', ' '));
|
|
607
|
+
}
|
|
608
|
+
if (!result.ok) {
|
|
609
|
+
return [bad(fit(' ' + result.reason, Math.max(1, termWidth() - 2))), dim(wrapText(githubHintText(repo), ' '))].join('\n');
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const f = result.facts;
|
|
613
|
+
const rows = [
|
|
614
|
+
row('repo', result.repoPath),
|
|
615
|
+
row('stars', String(f.stars)),
|
|
616
|
+
row('forks', String(f.forks)),
|
|
617
|
+
row('watching', String(f.watching)),
|
|
618
|
+
row('open issues', String(f.issues)),
|
|
619
|
+
];
|
|
620
|
+
if (f.license) rows.push(row('license', f.license));
|
|
621
|
+
if (f.branch) rows.push(row('branch', f.branch));
|
|
622
|
+
if (f.created) rows.push(row('created', shortDate(f.created)));
|
|
623
|
+
if (f.pushed) rows.push(row('last push', shortDate(f.pushed)));
|
|
624
|
+
if (f.archived) rows.push(row('note', 'this repository is archived'));
|
|
625
|
+
|
|
626
|
+
const out = [panel(result.repoPath, rows)];
|
|
627
|
+
if (f.description) out.push(dim(wrapText(f.description)));
|
|
628
|
+
if (f.topics.length) out.push(dim(fit(' topics ' + f.topics.join(' '), Math.max(1, termWidth() - 2))));
|
|
629
|
+
if (f.homepage) out.push(dim(fit(' site ' + f.homepage, Math.max(1, termWidth() - 2))));
|
|
630
|
+
// Double quotes rather than an escaped apostrophe: the previous spelling of
|
|
631
|
+
// this line was a `\\'` inside a single-quoted string, which is a syntax error
|
|
632
|
+
// waiting for the next person to touch the file.
|
|
633
|
+
out.push(dim(wrapText("These are GitHub's numbers, not this repo's. `health` and `risks` are about the code.", ' ')));
|
|
634
|
+
return out.join('\n');
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// Returned as plain text and wrapped by the caller: a hint line is exactly the
|
|
638
|
+
// kind of prose that overflows, because it is written once and never measured.
|
|
639
|
+
function githubHintText(repo) {
|
|
640
|
+
if (repo.gitUrl) return 'It is a clone, so the URL is known — the ask itself failed.';
|
|
641
|
+
return 'No origin remote here, so there is no URL to ask about.';
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// `2024-01-05T…` → `Jan 2024`. A day is noise next to a five-year-old project, and
|
|
645
|
+
// a full timestamp is four columns wider than the label it sits beside.
|
|
646
|
+
function shortDate(iso) {
|
|
647
|
+
const d = new Date(iso);
|
|
648
|
+
if (Number.isNaN(d.getTime())) return String(iso);
|
|
649
|
+
return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short' });
|
|
650
|
+
}
|