Skip to content
Open
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
45 changes: 45 additions & 0 deletions packages/core/src/tools/ls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,51 @@ describe('LSTool', () => {
});
});

it('should respect workspace-relative ignore patterns', async () => {
const distDir = path.join(tempRootDir, 'dist');
await fs.mkdir(distDir);
await fs.writeFile(path.join(distDir, 'app.js'), 'content1');
await fs.writeFile(path.join(distDir, 'keep.txt'), 'content2');

const invocation = lsTool.build({
dir_path: distDir,
ignore: ['dist/*.js'],
});
const result = await invocation.execute({ abortSignal });

expect(result.llmContent).not.toContain('app.js');
expect(result.llmContent).toContain('keep.txt');
expect(result.returnDisplay).toEqual({
summary: 'Found 1 item(s).',
files: expect.any(Array),
});
});

it('should respect globstar ignore patterns while keeping basename patterns', async () => {
const logsDir = path.join(tempRootDir, 'logs', 'nested');
await fs.mkdir(logsDir, { recursive: true });
await fs.writeFile(path.join(logsDir, 'error.log'), 'content1');
await fs.writeFile(path.join(logsDir, 'keep.txt'), 'content2');

const globstarInvocation = lsTool.build({
dir_path: logsDir,
ignore: ['**/*.log'],
});
const globstarResult = await globstarInvocation.execute({ abortSignal });

expect(globstarResult.llmContent).not.toContain('error.log');
expect(globstarResult.llmContent).toContain('keep.txt');

const basenameInvocation = lsTool.build({
dir_path: logsDir,
ignore: ['*.log'],
});
const basenameResult = await basenameInvocation.execute({ abortSignal });

expect(basenameResult.llmContent).not.toContain('error.log');
expect(basenameResult.llmContent).toContain('keep.txt');
});

it('should respect gitignore patterns', async () => {
await fs.writeFile(path.join(tempRootDir, 'file1.txt'), 'content1');
await fs.writeFile(path.join(tempRootDir, 'file2.log'), 'content1');
Expand Down
27 changes: 15 additions & 12 deletions packages/core/src/tools/ls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import fs from 'node:fs/promises';
import path from 'node:path';
import picomatch from 'picomatch';
import {
BaseDeclarativeTool,
BaseToolInvocation,
Expand Down Expand Up @@ -93,23 +94,25 @@ class LSToolInvocation extends BaseToolInvocation<LSToolParams, ToolResult> {
}

/**
* Checks if a filename matches any of the ignore patterns
* @param filename Filename to check
* Checks if a path matches any of the ignore patterns. Patterns with a path
* separator are matched against the workspace-relative path, while basename
* patterns keep the historical filename-only behavior.
* @param relativePath Workspace-relative path to check
* @param patterns Array of glob patterns to check against
* @returns True if the filename should be ignored
* @returns True if the path should be ignored
*/
private shouldIgnore(filename: string, patterns?: string[]): boolean {
private shouldIgnore(relativePath: string, patterns?: string[]): boolean {
if (!patterns || patterns.length === 0) {
return false;
}
const normalizedPath = relativePath.replace(/\\/g, '/');
const filename = path.basename(relativePath);
for (const pattern of patterns) {
// Convert glob pattern to RegExp
const regexPattern = pattern
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/\?/g, '.');
const regex = new RegExp(`^${regexPattern}$`);
if (regex.test(filename)) {
const normalizedPattern = pattern.replace(/\\/g, '/');
const hasPathSeparator = normalizedPattern.includes('/');
const matcher = picomatch(normalizedPattern, { dot: true });

if (matcher(hasPathSeparator ? normalizedPath : filename)) {
return true;
}
}
Comment on lines 110 to 118

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.

high

Compiling glob patterns with picomatch inside the loop for every single file is highly inefficient. For directories with many files, this will repeatedly parse and compile the same patterns, leading to significant performance degradation.

To optimize this, compile the matchers once and cache them on the invocation instance (this) to avoid global state and prevent race conditions in concurrent environments.

    const self = this as any;
    if (!self._compiledMatchers) {
      self._compiledMatchers = patterns.map((pattern) => {
        const normalizedPattern = pattern.replace(/\\/g, '/');
        return {
          hasPathSeparator: normalizedPattern.includes('/'),
          matcher: picomatch(normalizedPattern, { dot: true }),
        };
      });
    }

    for (const { hasPathSeparator, matcher } of self._compiledMatchers) {
      if (matcher(hasPathSeparator ? normalizedPath : filename)) {
        return true;
      }
    }
References
  1. Avoid module-level global variables for state like caches to prevent race conditions and memory issues in concurrent environments. Instead, use session-scoped or instance-scoped state.

Expand Down Expand Up @@ -229,7 +232,7 @@ class LSToolInvocation extends BaseToolInvocation<LSToolParams, ToolResult> {
for (const relativePath of filteredPaths) {
const fullPath = path.resolve(this.config.getTargetDir(), relativePath);

if (this.shouldIgnore(path.basename(fullPath), this.params.ignore)) {
if (this.shouldIgnore(relativePath, this.params.ignore)) {
continue;
}

Expand Down
Loading