|
| 1 | +/*! |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | +import * as vscode from 'vscode' |
| 6 | +import { getLogger } from '../../shared/logger/logger' |
| 7 | +import { sanitizePath, InvokeOutput, OutputKind } from './toolShared' |
| 8 | +import fs from '../../shared/fs/fs' |
| 9 | +import { Writable } from 'stream' |
| 10 | +import { ChildProcess, ChildProcessOptions } from '../../shared/utilities/processUtils' |
| 11 | +import { rgPath } from 'vscode-ripgrep' |
| 12 | +import path from 'path' |
| 13 | + |
| 14 | +export interface GrepSearchParams { |
| 15 | + path?: string |
| 16 | + query: string |
| 17 | + caseSensitive?: boolean |
| 18 | + excludePattern?: string |
| 19 | + includePattern?: string |
| 20 | + explanation?: string |
| 21 | +} |
| 22 | + |
| 23 | +export class GrepSearch { |
| 24 | + private fsPath: string | undefined |
| 25 | + private query: string |
| 26 | + private caseSensitive: boolean |
| 27 | + private excludePattern?: string |
| 28 | + private includePattern?: string |
| 29 | + private readonly logger = getLogger('grepSearch') |
| 30 | + |
| 31 | + constructor(params: GrepSearchParams) { |
| 32 | + this.fsPath = params.path |
| 33 | + this.query = params.query |
| 34 | + this.caseSensitive = params.caseSensitive ?? false |
| 35 | + this.excludePattern = params.excludePattern |
| 36 | + this.includePattern = params.includePattern |
| 37 | + } |
| 38 | + |
| 39 | + public async validate(): Promise<void> { |
| 40 | + if (!this.query || this.query.trim().length === 0) { |
| 41 | + throw new Error('Grep search query cannot be empty.') |
| 42 | + } |
| 43 | + |
| 44 | + // Handle optional path parameter |
| 45 | + if (!this.fsPath || this.fsPath.trim().length === 0) { |
| 46 | + // Use current workspace folder as default if path is not provided |
| 47 | + const workspaceFolders = vscode.workspace.workspaceFolders |
| 48 | + if (!workspaceFolders || workspaceFolders.length === 0) { |
| 49 | + throw new Error('Path cannot be empty and no workspace folder is available.') |
| 50 | + } |
| 51 | + this.fsPath = workspaceFolders[0].uri.fsPath |
| 52 | + this.logger.debug(`Using default workspace folder: ${this.fsPath}`) |
| 53 | + } |
| 54 | + |
| 55 | + const sanitized = sanitizePath(this.fsPath) |
| 56 | + this.fsPath = sanitized |
| 57 | + |
| 58 | + const pathUri = vscode.Uri.file(this.fsPath) |
| 59 | + let pathExists: boolean |
| 60 | + try { |
| 61 | + pathExists = await fs.existsDir(pathUri) |
| 62 | + if (!pathExists) { |
| 63 | + throw new Error(`Path: "${this.fsPath}" does not exist or cannot be accessed.`) |
| 64 | + } |
| 65 | + } catch (err) { |
| 66 | + throw new Error(`Path: "${this.fsPath}" does not exist or cannot be accessed. (${err})`) |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public queueDescription(updates: Writable): void { |
| 71 | + const searchDirectory = this.getSearchDirectory(this.fsPath) |
| 72 | + updates.write(`Grepping for "${this.query}" in directory: ${searchDirectory}`) |
| 73 | + updates.end() |
| 74 | + } |
| 75 | + |
| 76 | + public async invoke(updates?: Writable): Promise<InvokeOutput> { |
| 77 | + const searchDirectory = this.getSearchDirectory(this.fsPath) |
| 78 | + try { |
| 79 | + const results = await this.executeRipgrep(updates) |
| 80 | + return this.createOutput(results) |
| 81 | + } catch (error: any) { |
| 82 | + this.logger.error(`Failed to search in "${searchDirectory}": ${error.message || error}`) |
| 83 | + throw new Error(`Failed to search in "${searchDirectory}": ${error.message || error}`) |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private getSearchDirectory(fsPath?: string): string { |
| 88 | + const workspaceFolders = vscode.workspace.workspaceFolders |
| 89 | + const searchLocation = fsPath |
| 90 | + ? fsPath |
| 91 | + : !workspaceFolders || workspaceFolders.length === 0 |
| 92 | + ? '' |
| 93 | + : workspaceFolders[0].uri.fsPath |
| 94 | + return searchLocation |
| 95 | + } |
| 96 | + |
| 97 | + private async executeRipgrep(updates?: Writable): Promise<string> { |
| 98 | + const searchDirectory = this.getSearchDirectory(this.fsPath) |
| 99 | + return new Promise(async (resolve, reject) => { |
| 100 | + const args: string[] = [] |
| 101 | + |
| 102 | + // Add search options |
| 103 | + if (!this.caseSensitive) { |
| 104 | + args.push('-i') // Case insensitive search |
| 105 | + } |
| 106 | + args.push('--line-number') // Show line numbers |
| 107 | + |
| 108 | + // No heading (don't group matches by file) |
| 109 | + args.push('--no-heading') |
| 110 | + |
| 111 | + // Don't use color in output |
| 112 | + args.push('--color', 'never') |
| 113 | + |
| 114 | + // Add include/exclude patterns |
| 115 | + if (this.includePattern) { |
| 116 | + // Support multiple include patterns |
| 117 | + const patterns = this.includePattern.split(',') |
| 118 | + for (const pattern of patterns) { |
| 119 | + args.push('--glob', pattern.trim()) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + if (this.excludePattern) { |
| 124 | + // Support multiple exclude patterns |
| 125 | + const patterns = this.excludePattern.split(',') |
| 126 | + for (const pattern of patterns) { |
| 127 | + args.push('--glob', `!${pattern.trim()}`) |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + // Add search pattern and path |
| 132 | + args.push(this.query, searchDirectory) |
| 133 | + |
| 134 | + this.logger.debug(`Executing ripgrep with args: ${args.join(' ')}`) |
| 135 | + |
| 136 | + const options: ChildProcessOptions = { |
| 137 | + collect: true, |
| 138 | + logging: 'yes', |
| 139 | + rejectOnErrorCode: (code) => { |
| 140 | + if (code !== 0 && code !== 1) { |
| 141 | + this.logger.error(`Ripgrep process exited with code ${code}`) |
| 142 | + return new Error(`Ripgrep process exited with code ${code}`) |
| 143 | + } |
| 144 | + return new Error() |
| 145 | + }, |
| 146 | + } |
| 147 | + |
| 148 | + try { |
| 149 | + const rg = new ChildProcess(rgPath, args, options) |
| 150 | + const result = await rg.run() |
| 151 | + this.logger.info(`Executing ripgrep with exitCode: ${result.exitCode}`) |
| 152 | + // Process the output to format with file URLs and remove matched content |
| 153 | + const processedOutput = this.processRipgrepOutput(result.stdout) |
| 154 | + |
| 155 | + // If updates is provided, write the processed output |
| 156 | + if (updates) { |
| 157 | + updates.write('\n\nGreped Results:\n\n') |
| 158 | + updates.write(processedOutput) |
| 159 | + } |
| 160 | + |
| 161 | + this.logger.info(`Processed ripgrep result: ${processedOutput}`) |
| 162 | + resolve(processedOutput) |
| 163 | + } catch (err) { |
| 164 | + reject(err) |
| 165 | + } |
| 166 | + }) |
| 167 | + } |
| 168 | + |
| 169 | + /** |
| 170 | + * Process ripgrep output to: |
| 171 | + * 1. Remove matched content (keep only file:line) |
| 172 | + * 2. Add file URLs for clickable links |
| 173 | + */ |
| 174 | + private processRipgrepOutput(output: string): string { |
| 175 | + if (!output || output.trim() === '') { |
| 176 | + return 'No matches found.' |
| 177 | + } |
| 178 | + |
| 179 | + const lines = output.split('\n') |
| 180 | + const processedLines = lines |
| 181 | + .map((line) => { |
| 182 | + if (!line || line.trim() === '') { |
| 183 | + return '' |
| 184 | + } |
| 185 | + |
| 186 | + // Extract file path and line number |
| 187 | + const parts = line.split(':') |
| 188 | + if (parts.length < 2) { |
| 189 | + return line |
| 190 | + } |
| 191 | + |
| 192 | + const filePath = parts[0] |
| 193 | + const lineNumber = parts[1] |
| 194 | + |
| 195 | + const fileName = path.basename(filePath) |
| 196 | + const fileUri = vscode.Uri.file(filePath) |
| 197 | + |
| 198 | + // Format as a markdown link |
| 199 | + return `[${fileName}:${lineNumber}](${fileUri}:${lineNumber})` |
| 200 | + }) |
| 201 | + .filter(Boolean) |
| 202 | + |
| 203 | + return processedLines.join('\n') |
| 204 | + } |
| 205 | + |
| 206 | + private createOutput(content: string): InvokeOutput { |
| 207 | + return { |
| 208 | + output: { |
| 209 | + kind: OutputKind.Text, |
| 210 | + content: content || 'No matches found.', |
| 211 | + }, |
| 212 | + } |
| 213 | + } |
| 214 | +} |
0 commit comments