| 1 | // Matcher de patrones .gitignore / .dockerignore (subconjunto razonable). |
| 2 | // Compartido por el escáner de node (scan.mjs) y el del navegador (fsScan.js). |
| 3 | export const IGNORE_FILES = ['.gitignore', '.dockerignore', '.npmignore']; |
| 4 | |
| 5 | export function globToRegex(p) { |
| 6 | let rx = ''; |
| 7 | for (let i = 0; i < p.length; i++) { |
| 8 | const c = p[i]; |
| 9 | if (c === '*') { |
| 10 | if (p[i + 1] === '*') { |
| 11 | if (p[i + 2] === '/') { rx += '(?:[^/]+/)*'; i += 2; } |
| 12 | else { rx += '.*'; i += 1; } |
| 13 | } else rx += '[^/]*'; |
| 14 | } else if (c === '?') { |
| 15 | rx += '[^/]'; |
| 16 | } else { |
| 17 | rx += c.replace(/[.+^${}()|[\]\\]/g, '\\$&'); |
| 18 | } |
| 19 | } |
| 20 | return rx; |
| 21 | } |
| 22 | |
| 23 | function makeRule(line) { |
| 24 | line = line.trim(); |
| 25 | if (!line || line.startsWith('#')) return null; |
| 26 | let neg = false; |
| 27 | if (line.startsWith('!')) { neg = true; line = line.slice(1); } |
| 28 | let dirOnly = false; |
| 29 | if (line.endsWith('/')) { dirOnly = true; line = line.slice(0, -1); } |
| 30 | let body; |
| 31 | if (line.startsWith('/')) body = globToRegex(line.slice(1)); |
| 32 | else if (line.includes('/')) body = globToRegex(line); |
| 33 | else body = '(?:[^/]+/)*' + globToRegex(line); // sin barra: basename a cualquier nivel |
| 34 | try { |
| 35 | return { re: new RegExp(`^${body}$`), neg, dirOnly }; |
| 36 | } catch { |
| 37 | return null; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export class IgnoreStack { |
| 42 | constructor() { this.layers = []; } |
| 43 | |
| 44 | // base: ruta relativa (desde la raíz del escaneo) del dir que contiene el fichero de ignore |
| 45 | push(base, lines) { |
| 46 | this.layers.push({ base, rules: lines.map(makeRule).filter(Boolean) }); |
| 47 | } |
| 48 | |
| 49 | pop() { this.layers.pop(); } |
| 50 | |
| 51 | // relPath con '/'; el escáner propaga: si un dir se ignora, todo su contenido también |
| 52 | ignored(relPath, isDir) { |
| 53 | let state = false; |
| 54 | for (const layer of this.layers) { |
| 55 | let sub = relPath; |
| 56 | if (layer.base) { |
| 57 | if (!relPath.startsWith(layer.base + '/')) continue; |
| 58 | sub = relPath.slice(layer.base.length + 1); |
| 59 | } |
| 60 | for (const r of layer.rules) { |
| 61 | if (r.dirOnly && !isDir) continue; |
| 62 | if (r.re.test(sub)) state = !r.neg; |
| 63 | } |
| 64 | } |
| 65 | return state; |
| 66 | } |
| 67 | } |