Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 5 additions & 15 deletions src/core/indexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { promises as fs } from 'fs';
import path from 'path';
import { IndexCorruptedError, InvalidSourceChunkError } from '../errors/index.js';
import { glob } from 'glob';
import ignore from 'ignore';
import {
CodebaseMetadata,
CodeChunk,
Expand Down Expand Up @@ -46,6 +45,7 @@ import {
} from '../utils/usage-tracker.js';
import { mergeSmallChunks, validateSourceChunks } from '../utils/chunking.js';
import { getFileCommitDates } from '../utils/git-dates.js';
import { createGitignoreMatcher } from '../utils/gitignore.js';
import {
CODEBASE_CONTEXT_DIRNAME,
EXCLUDED_GLOB_PATTERNS,
Expand Down Expand Up @@ -1288,17 +1288,9 @@ export class CodebaseIndexer {
const seen = new Set<string>();
this.rootPath = await fs.realpath(this.rootPath);

// Read .gitignore if respecting it
let ig: ReturnType<typeof ignore.default> | null = null;
if (this.config.respectGitignore) {
try {
const gitignorePath = path.join(this.rootPath, '.gitignore');
const gitignoreContent = await fs.readFile(gitignorePath, 'utf-8');
ig = ignore.default().add(gitignoreContent);
} catch (_error) {
// No .gitignore or couldn't read it
}
}
const isGitIgnored = this.config.respectGitignore
? createGitignoreMatcher(this.rootPath)
: undefined;

// Scan with glob
const includePatterns = this.getIncludePatterns();
Expand All @@ -1319,7 +1311,6 @@ export class CodebaseIndexer {
}
seen.add(normalizedFile);

const relativePath = path.relative(this.rootPath, file);
const sourcePath = await resolveContainedSourcePath(file, this.rootPath);
if (sourcePath.status !== 'contained') {
addSkippedFile(
Expand All @@ -1335,8 +1326,7 @@ export class CodebaseIndexer {
continue;
}

// Check gitignore
if (ig && ig.ignores(relativePath)) {
if (isGitIgnored && (await isGitIgnored(path.relative(this.rootPath, file)))) {
addSkippedFile(scan, file, 'ignored by .gitignore', this.rootPath);
continue;
}
Expand Down
68 changes: 68 additions & 0 deletions src/utils/gitignore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import ignore, { type Ignore } from 'ignore';

function scopePatterns(contents: string, directory: string): string[] {
// The directory is a literal path even when it contains glob metacharacters.
const prefix = directory.replace(
/[\\*?\[\]]/g,
(char) => `[\\x${char.charCodeAt(0).toString(16)}]`
);
const patterns: string[] = [];
for (const line of contents.replace(/^\uFEFF/, '').split(/\r?\n/)) {
if (line.startsWith('#')) continue;
const negated = line.startsWith('!');
const pattern = negated ? line.slice(1) : line;
const trimmed = pattern.trimEnd();
if (!trimmed || trimmed === '/') continue;

// A final slash marks a directory, while other slashes anchor the rule.
const anchored = trimmed.startsWith('/') || trimmed.replace(/\/$/, '').includes('/');
const base = anchored ? `/${prefix}/` : `/${prefix}/**/`;
const relative = pattern.replace(/^\//, '');
// A directory-only globstar must match at least one directory below its base.
const scoped = `${base}${relative}`.replace(/\/\*\*\/(\s*)$/, '/**/*/$1');
patterns.push(`${negated ? '!' : ''}${scoped}`);
}
return patterns;
}

/** Load the .gitignore rules that apply to each directory once per scan. */
export function createGitignoreMatcher(
rootPath: string
): (relativeFile: string) => Promise<boolean> {
const matchers = new Map<string, Ignore | null>();

async function matcherFor(directory: string): Promise<Ignore | null> {
const cached = matchers.get(directory);
if (cached !== undefined) return cached;

const isRoot = directory === '.';
const inherited = isRoot ? null : await matcherFor(path.posix.dirname(directory));
let matcher = inherited;

// Excluded directories cannot re-include their contents through their own rules.
if (isRoot || !inherited?.ignores(`${directory}/`)) {
try {
const ignoreFile = path.join(rootPath, directory, '.gitignore');
if ((await fs.lstat(ignoreFile)).isFile()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Linked ignore rules disappear

If the root .gitignore is a readable symlink, lstat(...).isFile() returns false and none of its rules are loaded. Previously, scanFiles read the file directly and followed the link. A workspace linking to shared rules containing secrets.ts will now include that source file in the preview and saved index despite respectGitignore: true. Preserve the previous root behavior and add a regression test.

How this was verified: The new file-type check skips linked ignore files, and the shared scan accepts supported source files when the matcher returns false.

const contents = await fs.readFile(ignoreFile, 'utf8');
const local = ignore.default();
if (inherited) local.add(inherited);
matcher = local.add(isRoot ? contents : scopePatterns(contents, directory));
}
} catch {
// Missing or unreadable ignore files leave inherited rules in effect.
}
}

matchers.set(directory, matcher);
return matcher;
}

return async (relativeFile) => {
const file = relativeFile.replaceAll(path.sep, '/');
const matcher = await matcherFor(path.posix.dirname(file));
return matcher?.ignores(file) ?? false;
};
}
76 changes: 76 additions & 0 deletions tests/indexer-preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,82 @@ describe('index preview enumeration', () => {
expect(stats.totalFiles).toBe(1);
});

it('applies package gitignore rules to preview and the installed index', async () => {
root = await fs.mkdtemp(path.join(os.tmpdir(), 'indexer-preview-nested-ignore-'));
const expected = [
'packages/api[beta]/src/generated.ts',
'packages/web/generated.ts',
'packages/web/src/local.ts'
];
const ignored = ['packages/api[beta]/generated.ts', 'packages/api[beta]/src/local.ts'];
const sources = [...expected, ...ignored].sort();
for (const file of sources) {
const filePath = path.join(root, file);
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, 'export const value = 1;\n');
}
await fs.writeFile(
path.join(root, 'packages/api[beta]/.gitignore'),
'/generated.ts\nlocal.ts\n'
);

const indexer = new CodebaseIndexer({ rootPath: root, config: { skipEmbedding: true } });
const preview = await indexer.previewFiles();
await indexer.index();
const artifact: { chunks: Array<{ relativePath: string }> } = JSON.parse(
await fs.readFile(await resolveIndexArtifact(root, 'index.json'), 'utf8')
);

expect({
preview: preview.eligibleFiles,
indexed: [...new Set(artifact.chunks.map((chunk) => chunk.relativePath))].sort(),
skipped: preview.skippedFiles
}).toEqual({
preview: expected,
indexed: expected,
skipped: ignored.map((path) => ({ path, reason: 'ignored by .gitignore' }))
});

const withoutIgnore = await new CodebaseIndexer({
rootPath: root,
config: { skipEmbedding: true, respectGitignore: false }
}).previewFiles();
expect(withoutIgnore.eligibleFiles).toEqual(sources);
});

it('honors nested negations without reopening an excluded parent directory', async () => {
root = await fs.mkdtemp(path.join(os.tmpdir(), 'indexer-preview-ignore-precedence-'));
const files = {
'.gitignore': '*.generated.ts\n**/blocked/\n**/restored/\n',
'packages/api/.gitignore':
'\uFEFF# Package overrides\r\n!keep.generated.ts\r\n!restored/\r\n',
'packages/api/blocked/.gitignore': '!keep.generated.ts\n',
'packages/api/blocked/keep.generated.ts': 'export const blocked = 1;\n',
'packages/api/drop.generated.ts': 'export const drop = 1;\n',
'packages/api/keep.generated.ts': 'export const keep = 1;\n',
'packages/api/restored/keep.generated.ts': 'export const restored = 1;\n',
'packages/docs/.gitignore': '**/\n',
'packages/docs/nested/drop.ts': 'export const nested = 1;\n',
'packages/docs/top.ts': 'export const top = 1;\n',
'packages/web/keep.generated.ts': 'export const outside = 1;\n'
};
for (const [file, contents] of Object.entries(files)) {
const filePath = path.join(root, file);
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, contents);
}

const preview = await new CodebaseIndexer({
rootPath: root,
config: { skipEmbedding: true }
}).previewFiles();
expect(preview.eligibleFiles).toEqual([
'packages/api/keep.generated.ts',
'packages/api/restored/keep.generated.ts',
'packages/docs/top.ts'
]);
});

it('does not enumerate source symlinks whose canonical target is outside the root', async () => {
root = await fs.mkdtemp(path.join(os.tmpdir(), 'indexer-preview-symlink-'));
const outsideRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'indexer-preview-outside-'));
Expand Down
Loading