File size: 12,909 Bytes
1f21206 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | /**
* SearchService — 工作区文件搜索 & 会话历史搜索
*
* 优先使用 ripgrep (rg),不可用时降级到 grep。
*/
import { spawn } from 'child_process'
import * as fs from 'fs/promises'
import * as path from 'path'
import * as os from 'os'
import { ApiError } from '../middleware/errorHandler.js'
export type SearchResult = {
file: string
line: number
text: string
context?: string[]
}
export type SessionSearchResult = {
sessionId: string
title: string
matchCount: number
matches: Array<{ line: number; text: string }>
}
export class SearchService {
// ---------------------------------------------------------------------------
// 工作区搜索
// ---------------------------------------------------------------------------
/** 使用 ripgrep 搜索工作目录 */
async searchWorkspace(
query: string,
options?: {
cwd?: string
maxResults?: number
glob?: string
caseSensitive?: boolean
},
): Promise<SearchResult[]> {
if (!query) {
throw ApiError.badRequest('Search query is required')
}
const cwd = options?.cwd || process.cwd()
const maxResults = options?.maxResults || 200
// 尝试 rg,降级到 grep
const hasRg = await this.commandExists('rg')
if (hasRg) {
try {
return await this.searchWithRipgrep(query, cwd, maxResults, options)
} catch {
// rg 执行失败,降级到 grep
}
}
const hasGrep = await this.commandExists('grep')
if (hasGrep) {
try {
return await this.searchWithGrep(query, cwd, maxResults, options)
} catch {
// grep failed or is not available; fall back to a portable search.
}
}
return this.searchWithFilesystem(query, cwd, maxResults, options)
}
// ---------------------------------------------------------------------------
// 会话历史搜索
// ---------------------------------------------------------------------------
/** 搜索会话历史文件 */
async searchSessions(query: string): Promise<SessionSearchResult[]> {
if (!query) {
throw ApiError.badRequest('Search query is required')
}
const configDir =
process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')
const projectsDir = path.join(configDir, 'projects')
const results: SessionSearchResult[] = []
try {
await fs.access(projectsDir)
} catch {
// 目录不存在,返回空
return results
}
// 遍历 projects/ 下的 JSONL 会话文件
const entries = await this.walkJsonlFiles(projectsDir)
const lowerQuery = query.toLowerCase()
for (const filePath of entries) {
try {
const raw = await fs.readFile(filePath, 'utf-8')
const lines = raw.split('\n').filter(Boolean)
const matches: Array<{ line: number; text: string }> = []
let title = path.basename(filePath, '.jsonl')
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
if (line.toLowerCase().includes(lowerQuery)) {
// 尝试提取可读文本
try {
const obj = JSON.parse(line) as Record<string, unknown>
const text =
typeof obj.message === 'string'
? obj.message
: typeof obj.content === 'string'
? obj.content
: line.slice(0, 200)
// 提取 title
if (i === 0 && typeof obj.title === 'string') {
title = obj.title
}
matches.push({ line: i + 1, text: text.slice(0, 300) })
} catch {
matches.push({ line: i + 1, text: line.slice(0, 200) })
}
}
}
if (matches.length > 0) {
const sessionId = path.basename(filePath, '.jsonl')
results.push({
sessionId,
title,
matchCount: matches.length,
matches: matches.slice(0, 20), // 每个会话最多 20 条匹配
})
}
} catch {
// 跳过无法读取的文件
}
}
return results
}
// ---------------------------------------------------------------------------
// ripgrep 搜索
// ---------------------------------------------------------------------------
private async searchWithRipgrep(
query: string,
cwd: string,
maxResults: number,
options?: {
glob?: string
caseSensitive?: boolean
},
): Promise<SearchResult[]> {
const args = ['--json', '--max-count', String(maxResults)]
if (options?.caseSensitive === false) {
args.push('--ignore-case')
}
// 添加上下文行
args.push('-C', '4')
if (options?.glob) {
args.push('--glob', options.glob)
}
args.push('--', query, cwd)
const output = await this.runCommand('rg', args)
return this.parseRipgrepJson(output, maxResults)
}
/** 解析 ripgrep JSON 输出 */
private parseRipgrepJson(
output: string,
maxResults: number,
): SearchResult[] {
const results: SearchResult[] = []
const lines = output.split('\n').filter(Boolean)
// 收集上下文:key = `${file}:${matchLine}`
const contextMap = new Map<
string,
{ file: string; line: number; text: string; context: string[] }
>()
for (const line of lines) {
try {
const obj = JSON.parse(line) as Record<string, unknown>
if (obj.type === 'match') {
const data = obj.data as {
path?: { text?: string }
line_number?: number
lines?: { text?: string }
submatches?: unknown[]
}
const file = data.path?.text || ''
const lineNum = data.line_number || 0
const text = (data.lines?.text || '').replace(/\n$/, '')
const key = `${file}:${lineNum}`
contextMap.set(key, { file, line: lineNum, text, context: [] })
} else if (obj.type === 'context') {
// 上下文行归属到最近的 match
const data = obj.data as {
path?: { text?: string }
line_number?: number
lines?: { text?: string }
}
const text = (data.lines?.text || '').replace(/\n$/, '')
// 附加到最后一个相同文件的 match
const file = data.path?.text || ''
for (const [key, entry] of contextMap) {
if (key.startsWith(file + ':')) {
entry.context.push(text)
}
}
}
} catch {
// 跳过无法解析的行
}
}
for (const entry of contextMap.values()) {
if (results.length >= maxResults) break
results.push({
file: entry.file,
line: entry.line,
text: entry.text,
context: entry.context.length > 0 ? entry.context : undefined,
})
}
return results
}
// ---------------------------------------------------------------------------
// grep 降级
// ---------------------------------------------------------------------------
private async searchWithGrep(
query: string,
cwd: string,
maxResults: number,
options?: {
glob?: string
caseSensitive?: boolean
},
): Promise<SearchResult[]> {
const args = ['-rn', '--max-count', String(maxResults)]
if (options?.caseSensitive === false) {
args.push('-i')
}
if (options?.glob) {
args.push('--include', options.glob)
}
args.push('--', query, cwd)
const output = await this.runCommand('grep', args)
return this.parseGrepOutput(output, maxResults)
}
/** 解析 grep 输出 (file:line:text) */
private parseGrepOutput(output: string, maxResults: number): SearchResult[] {
const results: SearchResult[] = []
const lines = output.split('\n').filter(Boolean)
for (const line of lines) {
if (results.length >= maxResults) break
// grep -n 输出格式: file:line:text
const match = line.match(/^(.+?):(\d+):(.*)$/)
if (match) {
results.push({
file: match[1],
line: parseInt(match[2], 10),
text: match[3],
})
}
}
return results
}
// ---------------------------------------------------------------------------
// Portable filesystem fallback
// ---------------------------------------------------------------------------
private async searchWithFilesystem(
query: string,
cwd: string,
maxResults: number,
options?: {
glob?: string
caseSensitive?: boolean
},
): Promise<SearchResult[]> {
const results: SearchResult[] = []
const needle = options?.caseSensitive === false ? query.toLowerCase() : query
await this.searchDirectory(cwd, needle, results, maxResults, {
caseSensitive: options?.caseSensitive !== false,
glob: options?.glob,
})
return results
}
private async searchDirectory(
dir: string,
needle: string,
results: SearchResult[],
maxResults: number,
options: {
caseSensitive: boolean
glob?: string
},
): Promise<void> {
if (results.length >= maxResults) return
let entries: import('fs').Dirent[]
try {
entries = await fs.readdir(dir, { withFileTypes: true })
} catch {
return
}
for (const entry of entries) {
if (results.length >= maxResults) return
if (entry.name === 'node_modules' || entry.name === '.git') continue
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
await this.searchDirectory(fullPath, needle, results, maxResults, options)
continue
}
if (!entry.isFile()) continue
if (options.glob && !this.matchesSimpleGlob(entry.name, options.glob)) continue
await this.searchFile(fullPath, needle, results, maxResults, options.caseSensitive)
}
}
private async searchFile(
filePath: string,
needle: string,
results: SearchResult[],
maxResults: number,
caseSensitive: boolean,
): Promise<void> {
let content: string
try {
const buffer = await fs.readFile(filePath)
if (buffer.includes(0)) return
content = buffer.toString('utf8')
} catch {
return
}
const lines = content.split(/\r?\n/)
for (let index = 0; index < lines.length && results.length < maxResults; index++) {
const haystack = caseSensitive ? lines[index] : lines[index].toLowerCase()
if (!haystack.includes(needle)) continue
results.push({
file: filePath,
line: index + 1,
text: lines[index],
})
}
}
private matchesSimpleGlob(fileName: string, glob: string): boolean {
if (!glob.includes('*')) return fileName === glob
const escaped = glob.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')
return new RegExp(`^${escaped}$`).test(fileName)
}
// ---------------------------------------------------------------------------
// 工具方法
// ---------------------------------------------------------------------------
/** 运行外部命令,返回 stdout */
private runCommand(cmd: string, args: string[]): Promise<string> {
return new Promise((resolve, reject) => {
const proc = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] })
const chunks: Buffer[] = []
proc.stdout.on('data', (chunk: Buffer) => chunks.push(chunk))
proc.on('close', (code) => {
const output = Buffer.concat(chunks).toString('utf-8')
// rg/grep 返回 1 表示无匹配,不视为错误
if (code === 0 || code === 1) {
resolve(output)
} else {
reject(
new Error(`Command "${cmd}" exited with code ${code}: ${output}`),
)
}
})
proc.on('error', (err) => {
reject(err)
})
})
}
/** 检测命令是否存在 */
private commandExists(cmd: string): Promise<boolean> {
return new Promise((resolve) => {
const lookup = process.platform === 'win32' ? 'where' : 'which'
const proc = spawn(lookup, [cmd], { stdio: 'ignore' })
proc.on('close', (code) => resolve(code === 0))
proc.on('error', () => resolve(false))
})
}
/** 递归查找 .jsonl 文件 */
private async walkJsonlFiles(dir: string): Promise<string[]> {
const results: string[] = []
try {
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
const sub = await this.walkJsonlFiles(fullPath)
results.push(...sub)
} else if (entry.name.endsWith('.jsonl')) {
results.push(fullPath)
}
}
} catch {
// 跳过不可访问的目录
}
return results
}
}
|