| 51 | } |
| 52 | |
| 53 | export class Ignore { |
| 54 | private readonly allPatterns: string[] = []; |
| 55 | private dirIgnorer = ignore(); |
| 56 | private fileIgnorer = ignore(); |
| 57 | |
| 58 | /** |
| 59 | * Adds one or more ignore patterns. |
| 60 | * @param patterns A single pattern string or an array of pattern strings. |
| 61 | * Each pattern can be a glob-like string similar to .gitignore rules. |
| 62 | * @returns The `Ignore` instance for chaining. |
| 63 | */ |
| 64 | add(patterns: string | string[]): this { |
| 65 | if (typeof patterns === 'string') { |
| 66 | patterns = patterns.split(/\r?\n/); |
| 67 | } |
| 68 | |
| 69 | for (const p of patterns) { |
| 70 | const pattern = p.trim(); |
| 71 | |
| 72 | if (pattern === '' || pattern.startsWith('#')) { |
| 73 | continue; |
| 74 | } |
| 75 | |
| 76 | this.allPatterns.push(pattern); |
| 77 | |
| 78 | const isPositiveDirPattern = |
| 79 | pattern.endsWith('/') && !pattern.startsWith('!'); |
| 80 | |
| 81 | if (isPositiveDirPattern) { |
| 82 | this.dirIgnorer.add(pattern); |
| 83 | } else { |
| 84 | // An ambiguous pattern (e.g., "build") could match a file or a |
| 85 | // directory. To optimize the file system crawl, we use a heuristic: |
| 86 | // patterns without a dot in the last segment are included in the |
| 87 | // directory exclusion check. |
| 88 | // |
| 89 | // This heuristic can fail. For example, an ignore pattern of "my.assets" |
| 90 | // intended to exclude a directory will not be treated as a directory |
| 91 | // pattern because it contains a ".". This results in crawling a |
| 92 | // directory that should have been excluded, reducing efficiency. |
| 93 | // Correctness is still maintained. The incorrectly crawled directory |
| 94 | // will be filtered out by the final ignore check. |
| 95 | // |
| 96 | // For maximum crawl efficiency, users should explicitly mark directory |
| 97 | // patterns with a trailing slash (e.g., "my.assets/"). |
| 98 | this.fileIgnorer.add(pattern); |
| 99 | if (!hasFileExtension(pattern)) { |
| 100 | this.dirIgnorer.add(pattern); |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | return this; |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Returns a predicate that matches explicit directory ignore patterns (patterns ending with '/'). |
| 110 | * @returns {(dirPath: string) => boolean} |
nothing calls this directly
no outgoing calls
no test coverage detected