reuse GitIgnoreParser for loading .geminiignore (#1025)

This commit is contained in:
Anas H. Sulaiman
2025-06-13 17:17:08 -04:00
committed by GitHub
parent 54f0d9d0e5
commit bb67d31739
5 changed files with 82 additions and 136 deletions

View File

@@ -17,43 +17,53 @@ export class GitIgnoreParser implements GitIgnoreFilter {
private projectRoot: string;
private isGitRepo: boolean = false;
private ig: Ignore = ignore();
private patterns: string[] = [];
constructor(projectRoot: string) {
this.projectRoot = path.resolve(projectRoot);
}
async initialize(): Promise<void> {
async initialize(patternsFileName?: string): Promise<void> {
const patternFiles = [];
if (patternsFileName && patternsFileName !== '') {
patternFiles.push(patternsFileName);
}
this.isGitRepo = isGitRepository(this.projectRoot);
if (this.isGitRepo) {
const gitIgnoreFiles = [
path.join(this.projectRoot, '.gitignore'),
path.join(this.projectRoot, '.git', 'info', 'exclude'),
];
patternFiles.push('.gitignore');
patternFiles.push(path.join('.git', 'info', 'exclude'));
// Always ignore .git directory regardless of .gitignore content
this.addPatterns(['.git']);
for (const gitIgnoreFile of gitIgnoreFiles) {
try {
const content = await fs.readFile(gitIgnoreFile, 'utf-8');
const patterns = content.split('\n').map((p) => p.trim());
this.addPatterns(patterns);
} catch (_error) {
// File doesn't exist or can't be read, continue silently
}
}
for (const pf of patternFiles) {
try {
await this.loadPatterns(pf);
} catch (_error) {
// File doesn't exist or can't be read, continue silently
}
}
}
async loadPatterns(patternsFileName: string): Promise<void> {
const content = await fs.readFile(
path.join(this.projectRoot, patternsFileName),
'utf-8',
);
const patterns = content
.split('\n')
.map((p) => p.trim())
.filter((p) => p !== '' && !p.startsWith('#'));
this.addPatterns(patterns);
}
private addPatterns(patterns: string[]) {
this.ig.add(patterns);
this.patterns.push(...patterns);
}
isIgnored(filePath: string): boolean {
if (!this.isGitRepo) {
return false;
}
const relativePath = path.isAbsolute(filePath)
? path.relative(this.projectRoot, filePath)
: filePath;
@@ -67,11 +77,10 @@ export class GitIgnoreParser implements GitIgnoreFilter {
normalizedPath = normalizedPath.substring(2);
}
const ignored = this.ig.ignores(normalizedPath);
return ignored;
return this.ig.ignores(normalizedPath);
}
getGitRepoRoot(): string {
return this.projectRoot;
getPatterns(): string[] {
return this.patterns;
}
}