Elffuss BraidHub

kikocis/VibeCodeViewer public

main · 8.1 KiBRawPermalink
1#!/usr/bin/env node
2// Escanea un directorio y genera src/data.js con:
3// - REPO_TREE: árbol de ficheros (ignorados marcados → sótano)
4// - REPO_META: estado git por fichero y reglas de code ownership
5// Uso: node scan.mjs [rutaRaiz] [--no-git] (por defecto: este repositorio)
6import { readdirSync, statSync, readFileSync, writeFileSync } from 'node:fs';
7import { execSync } from 'node:child_process';
8import { join, basename, dirname, resolve, relative, sep } from 'node:path';
9import { fileURLToPath } from 'node:url';
10import { IgnoreStack, IGNORE_FILES } from './src/ignore.js';
11import { isCodeownersFile, isPackageMeta, parseCodeowners, parsePackageMeta } from './src/ownership.js';
12import { isAnalyzable, extractRefs, resolveAll } from './src/codeLinks.js';
13import { stripCommentsAndStrings, extractDefs, extractTokens, buildSymbolLinks, isIndexable, INDEX_VERSION } from './src/codeIndex.js';
14import { mkdirSync, existsSync } from 'node:fs';
15
16const HERE = dirname(fileURLToPath(import.meta.url));
17const ARGS = process.argv.slice(2);
18const NO_GIT = ARGS.includes('--no-git');
19const ROOT_ARG = ARGS.find(arg => !arg.startsWith('--'));
20const ROOT = resolve(ROOT_ARG ?? HERE);
21const ROOT_LABEL = basename(ROOT);
22const SKIP = new Set(['.git', '.hg', '.svn', '.cache', '__pycache__', 'node_modules', '.DS_Store']);
23
24let total = 0, ignoredCount = 0;
25const ownerRules = [];
26const refsMap = {}, fileRels = [], dirRels = [];
27const defsMap = {}, tokensMap = {};
28
29// caché del análisis por fichero: clave rel|size|mtime
30const CACHE_PATH = join(HERE, '.cache', 'analysis.json');
31let analysisCache = {};
32try { analysisCache = JSON.parse(readFileSync(CACHE_PATH, 'utf8')); } catch { /* primera vez */ }
33const newCache = {};
34let cacheHits = 0, analyzedNew = 0;
35const FLUSH_EVERY = 2000;
36
37function flushCache(obj) {
38 try {
39 if (!existsSync(join(HERE, '.cache'))) mkdirSync(join(HERE, '.cache'));
40 writeFileSync(CACHE_PATH, JSON.stringify(obj));
41 } catch { /* la caché es opcional */ }
42}
43
44function analyzeFile(full, rel, name, size, mtimeMs) {
45 const wantRefs = isAnalyzable(name, size);
46 const wantIndex = isIndexable(name, size);
47 if (!wantRefs && !wantIndex) return;
48 const key = `v${INDEX_VERSION}|${rel}|${size}|${Math.round(mtimeMs)}`;
49 const hit = analysisCache[key];
50 if (hit) {
51 cacheHits++;
52 newCache[key] = hit;
53 if (hit.specs?.length) refsMap[rel] = hit.specs;
54 if (hit.defs?.length) defsMap[rel] = hit.defs;
55 if (hit.tokens?.length) tokensMap[rel] = hit.tokens;
56 return;
57 }
58 let text;
59 try { text = readFileSync(full, 'utf8'); } catch { return; }
60 const entry = {};
61 if (wantRefs) {
62 const specs = extractRefs(name, text);
63 if (specs.length) { refsMap[rel] = specs; entry.specs = specs; }
64 }
65 if (wantIndex) {
66 const clean = stripCommentsAndStrings(text, name);
67 const defs = extractDefs(name, clean);
68 const tokens = [...extractTokens(clean)];
69 if (defs.length) { defsMap[rel] = defs; entry.defs = defs; }
70 if (tokens.length) { tokensMap[rel] = tokens; entry.tokens = tokens; }
71 }
72 newCache[key] = entry;
73 // persistencia incremental: si el proceso muere a medias (memoria, corte),
74 // lo ya analizado queda guardado y la próxima ejecución continúa desde ahí.
75 // Se vuelca el merge para no perder entradas aún no visitadas en esta pasada.
76 if (++analyzedNew % FLUSH_EVERY === 0) flushCache({ ...analysisCache, ...newCache });
77}
78
79function scanDir(path, rel, forced, stack) {
80 const name = basename(path);
81 let entries = [];
82 try { entries = readdirSync(path, { withFileTypes: true }); } catch { return [name, [], []]; }
83 entries.sort((a, b) => a.name.localeCompare(b.name));
84
85 let pushed = 0;
86 for (const e of entries) {
87 if (!e.isFile()) continue;
88 if (IGNORE_FILES.includes(e.name)) {
89 try {
90 stack.push(rel, readFileSync(join(path, e.name), 'utf8').split('\n'));
91 pushed++;
92 } catch { /* ignorar */ }
93 }
94 if (!rel.includes('.git') && (isCodeownersFile(e.name) || isPackageMeta(e.name))) {
95 try {
96 const txt = readFileSync(join(path, e.name), 'utf8');
97 if (isCodeownersFile(e.name)) ownerRules.push(...parseCodeowners(txt));
98 else {
99 const rule = parsePackageMeta(txt, rel);
100 if (rule) ownerRules.push(rule);
101 }
102 } catch { /* ignorar */ }
103 }
104 }
105
106 const dirs = [], files = [];
107 for (const e of entries) {
108 if (SKIP.has(e.name)) continue;
109 const full = join(path, e.name);
110 const childRel = rel ? `${rel}/${e.name}` : e.name;
111 if (e.isDirectory()) {
112 if (childRel === '.git/objects') continue; // ruido binario sin interés
113 const ign = forced || stack.ignored(childRel, true);
114 dirRels.push(childRel);
115 dirs.push(scanDir(full, childRel, ign, stack));
116 } else if (e.isFile()) {
117 let size = 0, mtimeMs = 0;
118 try { const st = statSync(full); size = st.size; mtimeMs = st.mtimeMs; } catch { /* ignorar */ }
119 const ign = forced || stack.ignored(childRel, false);
120 files.push(ign ? [e.name, size, 1] : [e.name, size]);
121 fileRels.push(childRel);
122 total++;
123 if (ign) ignoredCount++;
124 // relaciones de código + índice de símbolos para el modo Blast
125 if (!childRel.startsWith('.git/')) analyzeFile(full, childRel, e.name, size, mtimeMs);
126 }
127 }
128 while (pushed--) stack.pop();
129 return [name, dirs, files];
130}
131
132// ── estado git: status por fichero + líneas añadidas/borradas ─────────────
133function gitMeta() {
134 const run = (cmd) => execSync(cmd, { cwd: ROOT, maxBuffer: 64 * 1024 * 1024 }).toString();
135 let top;
136 try { top = run('git rev-parse --show-toplevel').trim(); } catch { return null; }
137 // prefijo de ROOT dentro del repo (por si se escanea un subdirectorio)
138 const prefix = relative(top, ROOT).split(sep).filter(Boolean).join('/');
139 const toRel = (p) => {
140 p = p.replace(/^"|"$/g, '');
141 if (!prefix) return p;
142 return p.startsWith(prefix + '/') ? p.slice(prefix.length + 1) : null;
143 };
144 const git = {};
145 try {
146 for (const line of run('git status --porcelain -uall').split('\n')) {
147 if (!line.trim()) continue;
148 const xy = line.slice(0, 2);
149 let p = line.slice(3);
150 if (p.includes(' -> ')) p = p.split(' -> ')[1];
151 const rel = toRel(p);
152 if (!rel) continue;
153 let st = 'M';
154 if (xy === '??') st = 'U';
155 else if (xy.includes('A')) st = 'A';
156 else if (xy.includes('R')) st = 'R';
157 else if (xy.includes('D')) st = 'D';
158 git[rel] = [st, 0, 0];
159 }
160 for (const line of run('git diff --numstat HEAD').split('\n')) {
161 const m = line.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);
162 if (!m) continue;
163 const rel = toRel(m[3]);
164 if (!rel) continue;
165 const a = m[1] === '-' ? 0 : +m[1], d = m[2] === '-' ? 0 : +m[2];
166 if (git[rel]) { git[rel][1] = a; git[rel][2] = d; }
167 else git[rel] = ['M', a, d];
168 }
169 } catch { /* repo sin HEAD o git no disponible */ }
170 return git;
171}
172
173const tree = scanDir(ROOT, '', false, new IgnoreStack());
174const symLinks = buildSymbolLinks(defsMap, tokensMap);
175const meta = {
176 git: NO_GIT ? null : gitMeta(),
177 owners: ownerRules,
178 links: resolveAll(refsMap, fileRels, dirRels),
179 codeIndex: { version: INDEX_VERSION, defs: defsMap, symLinks },
180};
181// persiste la caché del análisis (solo las claves vigentes)
182flushCache(newCache);
183const out = `// Generado por scan.mjs — ${new Date().toISOString()} — raíz: ${ROOT_LABEL}
184// dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes, ignorado?]
185export const REPO_TREE = ${JSON.stringify(tree)};
186// git: { ruta: [estado, +líneas, −líneas] } · owners: [[patrón, @owner], …]
187export const REPO_META = ${JSON.stringify(meta)};
188`;
189writeFileSync(join(HERE, 'src', 'data.js'), out);
190const nGit = meta.git ? Object.keys(meta.git).length : 0;
191const nLinks = Object.values(meta.links).reduce((a, l) => a + l.length, 0);
192const nSym = Object.values(symLinks).reduce((a, l) => a + l.length, 0);
193const nDefs = Object.values(defsMap).reduce((a, l) => a + l.length, 0);
194console.log(`OK: ${total} ficheros (${ignoredCount} ignorados) · git: ${meta.git ? nGit + ' cambios' : 'no'} · ownership: ${ownerRules.length} reglas · blast: ${nLinks} imports + ${nSym} aristas de símbolo (${nDefs} defs, caché: ${cacheHits} hits) → src/data.js`);