diff options
| author | Eddie Santos <[email protected]> | 2025-06-05 10:15:27 -0700 |
|---|---|---|
| committer | GitHub <[email protected]> | 2025-06-05 10:15:27 -0700 |
| commit | 422c763a55c28394df359bd9b31388c8d9765fc8 (patch) | |
| tree | fefda70212927409936ad326de5ec50ad515bfea /packages/cli/src | |
| parent | 1d20cedf033f9c9a8f27812020fead584510bf84 (diff) | |
Add support for `.geminiignore` file (#757)
Diffstat (limited to 'packages/cli/src')
| -rw-r--r-- | packages/cli/src/config/config.ts | 2 | ||||
| -rw-r--r-- | packages/cli/src/gemini.tsx | 10 | ||||
| -rw-r--r-- | packages/cli/src/utils/loadIgnorePatterns.test.ts | 226 | ||||
| -rw-r--r-- | packages/cli/src/utils/loadIgnorePatterns.ts | 71 |
4 files changed, 307 insertions, 2 deletions
diff --git a/packages/cli/src/config/config.ts b/packages/cli/src/config/config.ts index 952ecbcf..dd55b26d 100644 --- a/packages/cli/src/config/config.ts +++ b/packages/cli/src/config/config.ts @@ -123,6 +123,7 @@ export interface LoadCliConfigResult { export async function loadCliConfig( settings: Settings, + geminiIgnorePatterns: string[], ): Promise<LoadCliConfigResult> { loadEnvironment(); @@ -211,6 +212,7 @@ export async function loadCliConfig( vertexai: useVertexAI, showMemoryUsage: argv.show_memory_usage || settings.showMemoryUsage || false, + geminiIgnorePatterns, accessibility: settings.accessibility, // Git-aware file filtering settings fileFilteringRespectGitIgnore: settings.fileFiltering?.respectGitIgnore, diff --git a/packages/cli/src/gemini.tsx b/packages/cli/src/gemini.tsx index fc42bdec..f9b73074 100644 --- a/packages/cli/src/gemini.tsx +++ b/packages/cli/src/gemini.tsx @@ -17,6 +17,7 @@ import { LoadedSettings, loadSettings } from './config/settings.js'; import { themeManager } from './ui/themes/theme-manager.js'; import { getStartupWarnings } from './utils/startupWarnings.js'; import { runNonInteractive } from './nonInteractiveCli.js'; +import { loadGeminiIgnorePatterns } from './utils/loadIgnorePatterns.js'; import { ApprovalMode, Config, @@ -56,9 +57,12 @@ async function main() { process.env.GEMINI_CODE_SANDBOX_IMAGE; // Corrected to GEMINI_SANDBOX_IMAGE_NAME } - const settings = loadSettings(process.cwd()); + const workspaceRoot = process.cwd(); + const settings = loadSettings(workspaceRoot); + const geminiIgnorePatterns = loadGeminiIgnorePatterns(workspaceRoot); + const { config, modelWasSwitched, originalModelBeforeSwitch, finalModel } = - await loadCliConfig(settings.merged); + await loadCliConfig(settings.merged, geminiIgnorePatterns); // Initialize centralized FileDiscoveryService await config.getFileService(); @@ -150,6 +154,7 @@ main().catch((error) => { } process.exit(1); }); + async function loadNonInteractiveConfig( config: Config, settings: LoadedSettings, @@ -185,6 +190,7 @@ async function loadNonInteractiveConfig( }; const nonInteractiveConfigResult = await loadCliConfig( nonInteractiveSettings, + config.getGeminiIgnorePatterns(), ); return nonInteractiveConfigResult.config; } diff --git a/packages/cli/src/utils/loadIgnorePatterns.test.ts b/packages/cli/src/utils/loadIgnorePatterns.test.ts new file mode 100644 index 00000000..6cec9d51 --- /dev/null +++ b/packages/cli/src/utils/loadIgnorePatterns.test.ts @@ -0,0 +1,226 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { + vi, + describe, + it, + expect, + beforeEach, + afterEach, + Mock, + beforeAll, +} from 'vitest'; +import * as path from 'node:path'; +import { loadGeminiIgnorePatterns } from './loadIgnorePatterns.js'; +import os from 'node:os'; + +// Define the type for our mock function explicitly. +type ReadFileSyncMockType = Mock< + (path: string, encoding: string) => string | Buffer +>; + +// Declare a variable to hold our mock function instance. +let mockedFsReadFileSync: ReadFileSyncMockType; + +vi.mock('node:fs', async () => { + const actualFsModule = + await vi.importActual<typeof import('node:fs')>('node:fs'); + return { + ...actualFsModule, + readFileSync: vi.fn(), // The factory creates and returns the vi.fn() instance. + }; +}); + +let actualFs: typeof import('node:fs'); + +describe('loadGeminiIgnorePatterns', () => { + let tempDir: string; + let consoleLogSpy: Mock< + (message?: unknown, ...optionalParams: unknown[]) => void + >; + let consoleWarnSpy: Mock< + (message?: unknown, ...optionalParams: unknown[]) => void + >; + + beforeAll(async () => { + actualFs = await vi.importActual<typeof import('node:fs')>('node:fs'); + const mockedFsModule = await import('node:fs'); + mockedFsReadFileSync = + mockedFsModule.readFileSync as unknown as ReadFileSyncMockType; + }); + + beforeEach(() => { + tempDir = actualFs.mkdtempSync( + path.join(os.tmpdir(), 'gemini-ignore-test-'), + ); + consoleLogSpy = vi + .spyOn(console, 'log') + .mockImplementation(() => {}) as Mock< + (message?: unknown, ...optionalParams: unknown[]) => void + >; + consoleWarnSpy = vi + .spyOn(console, 'warn') + .mockImplementation(() => {}) as Mock< + (message?: unknown, ...optionalParams: unknown[]) => void + >; + mockedFsReadFileSync.mockReset(); + }); + + afterEach(() => { + if (actualFs.existsSync(tempDir)) { + actualFs.rmSync(tempDir, { recursive: true, force: true }); + } + consoleLogSpy.mockRestore(); + consoleWarnSpy.mockRestore(); + }); + + it('should load and parse patterns from .geminiignore, ignoring comments and empty lines', () => { + const ignoreContent = [ + '# This is a comment', + 'pattern1', + ' pattern2 ', // Should be trimmed + '', // Empty line + 'pattern3 # Inline comment', // Handled by trim + '*.log', + '!important.file', + ].join('\n'); + const ignoreFilePath = path.join(tempDir, '.geminiignore'); + actualFs.writeFileSync(ignoreFilePath, ignoreContent); + + mockedFsReadFileSync.mockImplementation((p: string, encoding: string) => { + if (p === ignoreFilePath && encoding === 'utf-8') return ignoreContent; + throw new Error( + `Mock fs.readFileSync: Unexpected call with path: ${p}, encoding: ${encoding}`, + ); + }); + + const patterns = loadGeminiIgnorePatterns(tempDir); + + expect(patterns).toEqual([ + 'pattern1', + 'pattern2', + 'pattern3 # Inline comment', + '*.log', + '!important.file', + ]); + expect(consoleLogSpy).toHaveBeenCalledWith( + expect.stringContaining('Loaded 5 patterns from .geminiignore'), + ); + expect(mockedFsReadFileSync).toHaveBeenCalledWith(ignoreFilePath, 'utf-8'); + }); + + it('should return an empty array and log info if .geminiignore is not found', () => { + const ignoreFilePath = path.join(tempDir, '.geminiignore'); + mockedFsReadFileSync.mockImplementation((p: string, encoding: string) => { + if (p === ignoreFilePath && encoding === 'utf-8') { + const error = new Error('File not found') as NodeJS.ErrnoException; + error.code = 'ENOENT'; + throw error; + } + throw new Error( + `Mock fs.readFileSync: Unexpected call with path: ${p}, encoding: ${encoding}`, + ); + }); + + const patterns = loadGeminiIgnorePatterns(tempDir); + expect(patterns).toEqual([]); + expect(consoleLogSpy).toHaveBeenCalledWith( + '[INFO] No .geminiignore file found. Proceeding without custom ignore patterns.', + ); + expect(mockedFsReadFileSync).toHaveBeenCalledWith(ignoreFilePath, 'utf-8'); + }); + + it('should return an empty array if .geminiignore is empty', () => { + const ignoreFilePath = path.join(tempDir, '.geminiignore'); + actualFs.writeFileSync(ignoreFilePath, ''); + mockedFsReadFileSync.mockImplementation((p: string, encoding: string) => { + if (p === ignoreFilePath && encoding === 'utf-8') return ''; // Return string for empty file + throw new Error( + `Mock fs.readFileSync: Unexpected call with path: ${p}, encoding: ${encoding}`, + ); + }); + + const patterns = loadGeminiIgnorePatterns(tempDir); + expect(patterns).toEqual([]); + expect(consoleLogSpy).not.toHaveBeenCalledWith( + expect.stringContaining('Loaded 0 patterns from .geminiignore'), + ); + expect(consoleLogSpy).not.toHaveBeenCalledWith( + expect.stringContaining('No .geminiignore file found'), + ); + expect(mockedFsReadFileSync).toHaveBeenCalledWith(ignoreFilePath, 'utf-8'); + }); + + it('should return an empty array if .geminiignore contains only comments and empty lines', () => { + const ignoreContent = [ + '# Comment 1', + ' # Comment 2 with leading spaces', + '', + ' ', // Whitespace only line + ].join('\n'); + const ignoreFilePath = path.join(tempDir, '.geminiignore'); + actualFs.writeFileSync(ignoreFilePath, ignoreContent); + mockedFsReadFileSync.mockImplementation((p: string, encoding: string) => { + if (p === ignoreFilePath && encoding === 'utf-8') return ignoreContent; + throw new Error( + `Mock fs.readFileSync: Unexpected call with path: ${p}, encoding: ${encoding}`, + ); + }); + + const patterns = loadGeminiIgnorePatterns(tempDir); + expect(patterns).toEqual([]); + expect(consoleLogSpy).not.toHaveBeenCalledWith( + expect.stringContaining('Loaded 0 patterns from .geminiignore'), + ); + expect(consoleLogSpy).not.toHaveBeenCalledWith( + expect.stringContaining('No .geminiignore file found'), + ); + expect(mockedFsReadFileSync).toHaveBeenCalledWith(ignoreFilePath, 'utf-8'); + }); + + it('should handle read errors (other than ENOENT) and log a warning', () => { + const ignoreFilePath = path.join(tempDir, '.geminiignore'); + mockedFsReadFileSync.mockImplementation((p: string, encoding: string) => { + if (p === ignoreFilePath && encoding === 'utf-8') { + const error = new Error('Test read error') as NodeJS.ErrnoException; + error.code = 'EACCES'; + throw error; + } + throw new Error( + `Mock fs.readFileSync: Unexpected call with path: ${p}, encoding: ${encoding}`, + ); + }); + + const patterns = loadGeminiIgnorePatterns(tempDir); + expect(patterns).toEqual([]); + expect(consoleWarnSpy).toHaveBeenCalledWith( + expect.stringContaining( + `[WARN] Could not read .geminiignore file at ${ignoreFilePath}: Test read error`, + ), + ); + expect(mockedFsReadFileSync).toHaveBeenCalledWith(ignoreFilePath, 'utf-8'); + }); + + it('should correctly handle patterns with inline comments if not starting with #', () => { + const ignoreContent = 'src/important # but not this part'; + const ignoreFilePath = path.join(tempDir, '.geminiignore'); + actualFs.writeFileSync(ignoreFilePath, ignoreContent); + mockedFsReadFileSync.mockImplementation((p: string, encoding: string) => { + if (p === ignoreFilePath && encoding === 'utf-8') return ignoreContent; + throw new Error( + `Mock fs.readFileSync: Unexpected call with path: ${p}, encoding: ${encoding}`, + ); + }); + + const patterns = loadGeminiIgnorePatterns(tempDir); + expect(patterns).toEqual(['src/important # but not this part']); + expect(consoleLogSpy).toHaveBeenCalledWith( + expect.stringContaining('Loaded 1 patterns from .geminiignore'), + ); + expect(mockedFsReadFileSync).toHaveBeenCalledWith(ignoreFilePath, 'utf-8'); + }); +}); diff --git a/packages/cli/src/utils/loadIgnorePatterns.ts b/packages/cli/src/utils/loadIgnorePatterns.ts new file mode 100644 index 00000000..3d0a1968 --- /dev/null +++ b/packages/cli/src/utils/loadIgnorePatterns.ts @@ -0,0 +1,71 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +const GEMINI_IGNORE_FILE_NAME = '.geminiignore'; + +/** + * Loads and parses a .geminiignore file from the given workspace root. + * The .geminiignore file follows a format similar to .gitignore: + * - Each line specifies a glob pattern. + * - Lines are trimmed of leading and trailing whitespace. + * - Blank lines (after trimming) are ignored. + * - Lines starting with a pound sign (#) (after trimming) are treated as comments and ignored. + * - Patterns are case-sensitive and follow standard glob syntax. + * - If a # character appears elsewhere in a line (not at the start after trimming), + * it is considered part of the glob pattern. + * + * @param workspaceRoot The absolute path to the workspace root where the .geminiignore file is expected. + * @returns An array of glob patterns extracted from the .geminiignore file. Returns an empty array + * if the file does not exist or contains no valid patterns. + */ +export function loadGeminiIgnorePatterns(workspaceRoot: string): string[] { + const ignoreFilePath = path.join(workspaceRoot, GEMINI_IGNORE_FILE_NAME); + const patterns: string[] = []; + + try { + const fileContent = fs.readFileSync(ignoreFilePath, 'utf-8'); + const lines = fileContent.split(/\r?\n/); + + for (const line of lines) { + const trimmedLine = line.trim(); + if (trimmedLine && !trimmedLine.startsWith('#')) { + patterns.push(trimmedLine); + } + } + if (patterns.length > 0) { + console.log( + `[INFO] Loaded ${patterns.length} patterns from .geminiignore`, + ); + } + } catch (error: unknown) { + if ( + error instanceof Error && + 'code' in error && + typeof error.code === 'string' + ) { + if (error.code === 'ENOENT') { + // .geminiignore not found, which is fine. + console.log( + '[INFO] No .geminiignore file found. Proceeding without custom ignore patterns.', + ); + } else { + // Other error reading the file (e.g., permissions) + console.warn( + `[WARN] Could not read .geminiignore file at ${ignoreFilePath}: ${error.message}`, + ); + } + } else { + // For other types of errors, or if code is not available + console.warn( + `[WARN] An unexpected error occurred while trying to read ${ignoreFilePath}: ${String(error)}`, + ); + } + } + return patterns; +} |
