import fs from 'fs/promises';
import path from 'path';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const ignore = require('ignore');
/**
* Handles .gitignore parsing and file filtering
*/
export class GitignoreHandler {
private ig: any;
private loaded = false;
constructor() {
this.ig = ignore();
}
/**
* Load and parse .gitignore from the specified directory
*/
async load(basePath: string): Promise<void> {
const gitignorePath = path.join(basePath, '.gitignore');
try {
const content = await fs.readFile(gitignorePath, 'utf-8');
this.ig.add(content);
this.loaded = true;
} catch (error) {
// No .gitignore found, that's okay - no files will be ignored
this.loaded = false;
}
// Always ignore common patterns
this.ig.add([
'.git',
'node_modules',
'.DS_Store',
'*.log'
]);
}
/**
* Check if a file path should be ignored
*/
shouldIgnore(relativePath: string): boolean {
if (!relativePath) return false;
// Normalize path separators for cross-platform compatibility
const normalizedPath = relativePath.split(path.sep).join('/');
return this.ig.ignores(normalizedPath);
}
/**
* Check if gitignore was loaded
*/
isLoaded(): boolean {
return this.loaded;
}
}