-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathgitIgnoreParser.ts
More file actions
75 lines (62 loc) · 1.97 KB
/
gitIgnoreParser.ts
File metadata and controls
75 lines (62 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import ignore, { type Ignore } from 'ignore';
import { isGitRepository } from './gitUtils.js';
export interface GitIgnoreFilter {
isIgnored(filePath: string): boolean;
getPatterns(): string[];
}
export class GitIgnoreParser implements GitIgnoreFilter {
private projectRoot: string;
private ig: Ignore = ignore();
private patterns: string[] = [];
constructor(projectRoot: string) {
this.projectRoot = path.resolve(projectRoot);
}
loadGitRepoPatterns(): void {
if (!isGitRepository(this.projectRoot)) return;
// Always ignore .git directory regardless of .gitignore content
this.addPatterns(['.git']);
const patternFiles = ['.gitignore', path.join('.git', 'info', 'exclude')];
for (const pf of patternFiles) {
this.loadPatterns(pf);
}
}
loadPatterns(patternsFileName: string): void {
const patternsFilePath = path.join(this.projectRoot, patternsFileName);
let content: string;
try {
content = fs.readFileSync(patternsFilePath, 'utf-8');
} catch (_error) {
// ignore file not found
return;
}
const patterns = (content ?? '')
.split('\n')
.map((p) => p.trim())
.filter((p) => p !== '' && !p.startsWith('#'));
this.addPatterns(patterns);
}
addPatterns(patterns: string[]): void {
this.ig.add(patterns);
this.patterns.push(...patterns);
}
isIgnored(filePath: string): boolean {
const resolved = path.resolve(this.projectRoot, filePath);
const relativePath = path.relative(this.projectRoot, resolved);
if (relativePath === '' || relativePath.startsWith('..')) {
return false;
}
// Even in windows, Ignore expects forward slashes.
const normalizedPath = relativePath.replace(/\\/g, '/');
return this.ig.ignores(normalizedPath);
}
getPatterns(): string[] {
return this.patterns;
}
}