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