Elffuss BraidHub

kikocis/VibeCodeViewer public

main · 2.6 KiBRawPermalink
1// Parser del fichero .git/index (v2/v3) para estimar el estado git desde el
2// navegador, donde no hay binario git: un fichero presente en el índice con
3// el mismo tamaño y mtime se considera limpio; si difiere → modificado; si
4// no está en el índice → sin seguimiento. (v4 usa compresión de rutas y no
5// se soporta: en ese caso el modo git queda deshabilitado.)
6export function parseGitIndex(buf) {
7 const dv = new DataView(buf);
8 if (buf.byteLength < 12 || dv.getUint32(0) !== 0x44495243) return null; // 'DIRC'
9 const version = dv.getUint32(4);
10 if (version < 2 || version > 3) return null;
11 const count = dv.getUint32(8);
12 const bytes = new Uint8Array(buf);
13 const td = new TextDecoder();
14 const map = new Map();
15 let off = 12;
16 for (let i = 0; i < count; i++) {
17 if (off + 62 > buf.byteLength) return null;
18 const start = off;
19 const mtime = dv.getUint32(off + 8);
20 const size = dv.getUint32(off + 36);
21 const flags = dv.getUint16(off + 60);
22 let nameOff = off + 62;
23 if (version === 3 && (flags & 0x4000)) nameOff += 2;
24 let end = nameOff;
25 while (end < buf.byteLength && bytes[end] !== 0) end++;
26 map.set(td.decode(bytes.subarray(nameOff, end)), { size, mtime });
27 // la entrada se rellena con NULs hasta múltiplo de 8 (mínimo 1)
28 off = start + Math.ceil((end + 1 - start) / 8) * 8;
29 }
30 return map;
31}
32
33// commit de HEAD desde el navegador: resuelve la ref de .git/HEAD contra
34// refs/… o packed-refs. Es la clave de los snapshots consolidados de la caché.
35export async function readHeadCommit(gitDir) {
36 const readText = async (dir, name) => (await (await dir.getFileHandle(name)).getFile()).text();
37 try {
38 const head = (await readText(gitDir, 'HEAD')).trim();
39 const m = head.match(/^ref:\s*(\S+)/);
40 if (!m) return /^[0-9a-f]{40,64}$/.test(head) ? head : null; // detached
41 const parts = m[1].split('/');
42 try {
43 let dir = gitDir;
44 for (const p of parts.slice(0, -1)) dir = await dir.getDirectoryHandle(p);
45 return (await readText(dir, parts[parts.length - 1])).trim();
46 } catch {
47 const packed = await readText(gitDir, 'packed-refs');
48 for (const line of packed.split('\n')) {
49 if (line.endsWith(' ' + m[1])) return line.split(' ')[0];
50 }
51 }
52 } catch { /* sin HEAD legible */ }
53 return null;
54}
55
56// estado aproximado de un fichero del árbol frente al índice
57export function gitStatusOf(index, relPath, size, lastModifiedMs) {
58 const ent = index.get(relPath);
59 if (!ent) return 'U';
60 if (ent.size !== size) return 'M';
61 if (Math.abs(lastModifiedMs / 1000 - ent.mtime) > 2) return 'M';
62 return null; // limpio
63}