Open History to see the last commit
1import { mkdtemp, rm, symlink } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join, resolve, sep } from 'node:path'
4import {
5 afterAll,
6 afterEach,
7 beforeAll,
8 describe,
9 expect,
10 it,
11 vi,
12} from 'vitest'
13import { hostBackend } from '../src/first-party/coding/backend'
14import { quoteArg } from '../src/first-party/coding/search'
15import { createWorkspaceTools } from '../src/first-party/coding/workspace'
16import type { WorkspaceBackend } from '../src/first-party/coding/backend'
17import type { OutsideAccess } from '../src/first-party/coding/workspace'
18
19// The bundled rg of `@vscode/ripgrep`. It points at a file that exists, so
20// no test needs the real binary. No test runs it.
21const ripgrep = vi.hoisted(() => ({ rgPath: process.execPath }))
22vi.mock('@vscode/ripgrep', () => ({
23 get rgPath() {
24 return ripgrep.rgPath
25 },
26}))
27
28afterEach(() => {
29 vi.restoreAllMocks()
30 ripgrep.rgPath = process.execPath
31})
32
33interface ExecResult {
34 exitCode: number
35 stdout: string
36 stderr: string
37}
38
39const ok = (stdout: string): ExecResult => ({ exitCode: 0, stdout, stderr: '' })
40const NOT_FOUND: ExecResult = { exitCode: 127, stdout: '', stderr: 'not found' }
41// git runs with no fsmonitor and no hooks: the model can write .git/config.
42const GIT =
43 'git -c core.fsmonitor= -c core.hooksPath= ls-files -z --cached --others --exclude-standard'
44const NOT_GIT: ExecResult = {
45 exitCode: 128,
46 stdout: '',
47 stderr: 'fatal: not a git repository',
48}
49const FILES_NOTE =
50 '[Not all files are shown. Use a pattern or a folder to see fewer.]'
51const MATCHES_NOTE =
52 '[Not all matches are shown. Use a narrower pattern, glob, or folder.]'
53
54const root = resolve(tmpdir(), 'coding-search')
55const hasGit = (await hostBackend.exec('git --version')).exitCode === 0
56// A real process can take seconds to start on a busy machine.
57const SPAWN_TIMEOUT = 60_000
58
59/**
60 * A backend with `files` in memory, by path from `root`. `script` answers
61 * each command. A command that it does not answer is not found.
62 */
63function fakeBackend(
64 files: Record<string, string>,
65 script: (command: string) => ExecResult | undefined = () => undefined,
66) {
67 const encoder = new TextEncoder()
68 const byPath = new Map(
69 Object.entries(files).map(([path, text]) => [
70 join(root, path),
71 encoder.encode(text),
72 ]),
73 )
74 const commands: Array<string> = []
75 /** The env of each command, in the order of `commands`. */
76 const envs: Array<Record<string, string> | undefined> = []
77 const backend: WorkspaceBackend = {
78 readFile: async (path) => {
79 const data = byPath.get(path)
80 if (!data) throw new Error(`No file ${path}`)
81 return data
82 },
83 writeFile: async () => {
84 throw new Error('Read only')
85 },
86 stat: async (path) => {
87 const data = byPath.get(path)
88 if (!data) return undefined
89 return { type: 'file', size: data.length, mtimeMs: 0 }
90 },
91 // No links: each path is its own real path.
92 realpath: async (path) => path,
93 readdir: async (path) => {
94 const prefix = path + sep
95 const entries = new Map<string, 'file' | 'dir'>()
96 for (const file of byPath.keys()) {
97 if (!file.startsWith(prefix)) continue
98 const [name = '', ...rest] = file.slice(prefix.length).split(sep)
99 entries.set(name, rest.length > 0 ? 'dir' : 'file')
100 }
101 // Sorted by name, like the host.
102 return [...entries]
103 .sort(([a], [b]) => (a < b ? -1 : 1))
104 .map(([name, type]) => ({ name, type }))
105 },
106 exec: async (command, options) => {
107 commands.push(command)
108 envs.push(options?.env)
109 return script(command) ?? NOT_FOUND
110 },
111 }
112 return { backend, commands, envs }
113}
114
115/**
116 * `list_files` and `grep` on `backend`, with the workspace at `folder`.
117 * `access` is what the session gives the tools.
118 */
119function searchOn(
120 backend: WorkspaceBackend,
121 folder = root,
122 access?: OutsideAccess,
123) {
124 const { tools } = createWorkspaceTools({ root: folder, backend }, { access })
125 const run = async (name: string, args: object) => {
126 const tool = tools.find((each) => each.name === name)
127 if (!tool?.execute) throw new Error(`No tool ${name}`)
128 const result: unknown = await tool.execute(args)
129 if (typeof result !== 'string') throw new Error(`${name} gave no text`)
130 return result
131 }
132 return {
133 listFiles: (args: object = {}) => run('list_files', args),
134 grep: (args: object) => run('grep', args),
135 }
136}
137
138/** Run `script` for the commands of the host backend, not a real shell. */
139function scriptHostExec(script: (command: string) => ExecResult | undefined) {
140 return vi
141 .spyOn(hostBackend, 'exec')
142 .mockImplementation(async (command) => script(command) ?? NOT_FOUND)
143}
144
145describe('list_files and grep engines', () => {
146 const long = `two${'x'.repeat(3000)}`
147 const files = {
148 'src/b.ts': 'const two = 2\r\n',
149 'src/a.ts': 'one\ntwo\n',
150 'long.txt': `${long}\n`,
151 '.github/ci.yml': 'two: yes\n',
152 'image.png': 'two\0',
153 'node_modules/pkg/i.js': 'two\n',
154 '.git/HEAD': 'two\n',
155 }
156 // What rg prints for `files`: not sorted, with `./`, NUL after each path.
157 // A long line is cut after 2000 bytes, with a note after it.
158 const rgFiles =
159 './src/b.ts\0./src/a.ts\0./long.txt\0./image.png\0./.github/ci.yml\0'
160 const rgMatches = [
161 './src/b.ts\x001:const two = 2\r',
162 './.github/ci.yml\x001:two: yes',
163 `./long.txt\x001:${long.slice(0, 2000)} [... omitted end of long line]`,
164 './src/a.ts\x002:two',
165 '',
166 ].join('\n')
167 const gitFiles =
168 '.github/ci.yml\0image.png\0long.txt\0node_modules/pkg/i.js\0src/a.ts\0src/b.ts\0'
169
170 const engines = [
171 {
172 name: 'rg on the PATH',
173 script: (command: string) => {
174 if (command === 'rg --version') return ok('ripgrep 14.1.0')
175 if (command.startsWith('rg --files ')) return ok(rgFiles)
176 const isGrepForTwo =
177 command.startsWith('rg --line-number ') &&
178 command.endsWith(` -e 'two' .`)
179 return isGrepForTwo ? ok(rgMatches) : undefined
180 },
181 commands: [
182 'rg --version',
183 expect.stringMatching(/^rg --files /),
184 expect.stringMatching(/^rg --line-number /),
185 ],
186 },
187 {
188 name: 'git ls-files',
189 script: (command: string) => (command === GIT ? ok(gitFiles) : undefined),
190 commands: ['rg --version', GIT, GIT],
191 },
192 {
193 name: 'the JS walk',
194 script: (command: string) => (command === GIT ? NOT_GIT : undefined),
195 commands: ['rg --version', GIT, GIT],
196 },
197 ]
198
199 it.each(engines)(
200 '$name gives the same files and matches',
201 async ({ script, commands }) => {
202 const fake = fakeBackend(files, script)
203 const { listFiles, grep } = searchOn(fake.backend)
204
205 expect(await listFiles()).toBe(
206 '.github/ci.yml\nimage.png\nlong.txt\nsrc/a.ts\nsrc/b.ts',
207 )
208 expect(await grep({ pattern: 'two' })).toBe(
209 [
210 '.github/ci.yml:1: two: yes',
211 `long.txt:1: two${'x'.repeat(1997)}`,
212 'src/a.ts:2: two',
213 'src/b.ts:1: const two = 2',
214 ].join('\n'),
215 )
216 // The engine order, and rg looked for once.
217 expect(fake.commands).toEqual(commands)
218
219 expect(await listFiles({ pattern: 'src/**' })).toBe('src/a.ts\nsrc/b.ts')
220 expect(await grep({ pattern: 'two', glob: 'src/**' })).toBe(
221 'src/a.ts:2: two\nsrc/b.ts:1: const two = 2',
222 )
223 },
224 )
225
226 it('runs git without the system config', async () => {
227 const fake = fakeBackend(files, (command) =>
228 command === GIT ? ok(gitFiles) : undefined,
229 )
230 await searchOn(fake.backend).listFiles()
231 const gitEnv = fake.envs[fake.commands.indexOf(GIT)]
232 expect(gitEnv).toEqual({ GIT_CONFIG_NOSYSTEM: '1' })
233 })
234
235 it('runs the bundled rg with the host backend, and does not look on the PATH', async () => {
236 const exec = scriptHostExec(() => ok('./a.ts\0'))
237 expect(await searchOn(hostBackend, tmpdir()).listFiles()).toBe('a.ts')
238 const commands = exec.mock.calls.map(([command]) => command)
239 expect(commands).toHaveLength(1)
240 const bundled = quoteArg(process.execPath, process.platform)
241 expect(commands[0]?.startsWith(`${bundled} --files `)).toBe(true)
242 })
243
244 it('looks for rg on the PATH when the bundled binary is missing', async () => {
245 ripgrep.rgPath = join(tmpdir(), 'no-such-rg-binary')
246 const exec = scriptHostExec((command) => {
247 if (command === 'rg --version') return ok('ripgrep 14.1.0')
248 return command.startsWith('rg --files ') ? ok('./a.ts\0') : undefined
249 })
250 expect(await searchOn(hostBackend, tmpdir()).listFiles()).toBe('a.ts')
251 expect(exec.mock.calls.map(([command]) => command)).toEqual([
252 'rg --version',
253 expect.stringMatching(/^rg --files /),
254 ])
255 })
256
257 it.each([
258 {
259 exitCode: 2,
260 stderr: 'regex parse error',
261 message: 'The search failed: regex parse error',
262 },
263 {
264 exitCode: 124,
265 stderr: '',
266 message: 'The search failed: it took longer than 30 seconds',
267 },
268 ])(
269 'throws when rg ends with exit code $exitCode and no output',
270 async ({ exitCode, stderr, message }) => {
271 const fake = fakeBackend({}, (command) =>
272 command === 'rg --version'
273 ? ok('ripgrep 14.1.0')
274 : { exitCode, stdout: '', stderr },
275 )
276 await expect(
277 searchOn(fake.backend).grep({ pattern: 'two' }),
278 ).rejects.toThrow(message)
279 },
280 )
281
282 it('refuses a pattern with a line break', async () => {
283 const { grep } = searchOn(fakeBackend({}).backend)
284 await expect(grep({ pattern: 'a\nb' })).rejects.toThrow(
285 'The pattern must be one line.',
286 )
287 })
288
289 it('rg: grep drops the lines of a protected file, and lists the files to count them in the same command', async () => {
290 // One shell runs the list, an `echo` of a marker line, and the search,
291 // like `sh` does with `;`.
292 const listAndSearch =
293 /^rg --files .* \. ; echo (-- [\w-]+ --) ; rg --line-number .* \.$/
294 const fake = fakeBackend(
295 { '.env': 'two=1\n', 'a.ts': 'two\n' },
296 (command) => {
297 if (command === 'rg --version') return ok('ripgrep 14.1.0')
298 const marker = listAndSearch.exec(command)?.[1]
299 if (marker === undefined) return undefined
300 const hits = './.env\x001:two=1\n./a.ts\x001:two\n'
301 return ok(`./.env\0./a.ts\0${marker}\n${hits}`)
302 },
303 )
304 // Rules that ask about every .env file, like permissions() does.
305 const { grep } = searchOn(fake.backend, root, {
306 mode: () => 'default',
307 rules: () => (_tool, resources) =>
308 resources.paths?.some((path) => path.endsWith('.env'))
309 ? 'ask'
310 : 'allow',
311 })
312
313 expect(await grep({ pattern: 'two' })).toBe(
314 'a.ts:1: two\n[Skipped 1 file that the permission rules protect.]',
315 )
316 expect(fake.commands).toEqual([
317 'rg --version',
318 expect.stringMatching(listAndSearch),
319 ])
320 })
321
322 it('git: grep with protected files lists the files once', async () => {
323 const fake = fakeBackend(
324 { '.env': 'two=1\n', 'a.ts': 'two\n' },
325 (command) => (command === GIT ? ok('.env\0a.ts\0') : undefined),
326 )
327 const readdir = vi.spyOn(fake.backend, 'readdir')
328 const { grep } = searchOn(fake.backend, root, {
329 mode: () => 'default',
330 rules: () => (_tool, resources) =>
331 resources.paths?.some((path) => path.endsWith('.env'))
332 ? 'ask'
333 : 'allow',
334 })
335
336 expect(await grep({ pattern: 'two' })).toBe(
337 'a.ts:1: two\n[Skipped 1 file that the permission rules protect.]',
338 )
339 expect(fake.commands.filter((command) => command === GIT)).toHaveLength(1)
340 // The link check of the git list reads the root folder once.
341 expect(readdir.mock.calls).toEqual([[root]])
342 })
343})
344
345describe('quoting for the shell of the backend', () => {
346 /** rg on the PATH answers every rg command with no output. */
347 const rgOnPath = (command: string) =>
348 command.startsWith('rg ') ? ok('') : undefined
349
350 /** The rg command that a grep for `a b` runs on `backend`. */
351 async function grepCommand(backend: WorkspaceBackend) {
352 await searchOn(backend).grep({ pattern: 'a b' })
353 return (
354 exec.mock.calls
355 .map(([command]) => command)
356 .find((command) => command.startsWith('rg --line-number')) ?? ''
357 )
358 }
359 const exec = vi.fn(async (command: string) => rgOnPath(command) ?? NOT_FOUND)
360
361 afterEach(() => {
362 exec.mockClear()
363 })
364
365 it.each([
366 { shell: undefined, quoted: `'a b'` },
367 { shell: 'sh' as const, quoted: `'a b'` },
368 { shell: 'cmd' as const, quoted: '^"a^ b^"' },
369 ])('quotes the pattern for shell $shell', async ({ shell, quoted }) => {
370 const backend = { ...fakeBackend({}).backend, shell, exec }
371 expect(await grepCommand(backend)).toContain(` -e ${quoted} .`)
372 })
373
374 it('quotes for the shell of this host in a copy of hostBackend', async () => {
375 const quoted = process.platform === 'win32' ? '^"a^ b^"' : `'a b'`
376 expect(await grepCommand({ ...hostBackend, exec })).toContain(
377 ` -e ${quoted} .`,
378 )
379 })
380})
381
382describe('limits', () => {
383 /** `count` files named `f0000.txt` and up, each with `text`. */
384 const numbered = (count: number, text = '') =>
385 Object.fromEntries(
386 Array.from({ length: count }, (_, index) => [
387 `f${String(index).padStart(4, '0')}.txt`,
388 text,
389 ]),
390 )
391
392 it('lists 1000 files, then a note', async () => {
393 const lines = (
394 await searchOn(fakeBackend(numbered(1001)).backend).listFiles()
395 ).split('\n')
396 expect(lines).toHaveLength(1001)
397 expect(lines[999]).toBe('f0999.txt')
398 expect(lines[1000]).toBe(FILES_NOTE)
399 })
400
401 it('shows 200 matches, then a note', async () => {
402 const fake = fakeBackend({ 'a.txt': 'two\n'.repeat(201) })
403 const lines = (await searchOn(fake.backend).grep({ pattern: 'two' })).split(
404 '\n',
405 )
406 expect(lines).toHaveLength(201)
407 expect(lines[199]).toBe('a.txt:200: two')
408 expect(lines[200]).toBe(MATCHES_NOTE)
409 })
410
411 it('reads up to 16 folders and files at a time in JS, and keeps the order', async () => {
412 const files = Object.fromEntries(
413 Array.from({ length: 40 }, (_, index) => [
414 `d${String(index).padStart(2, '0')}${sep}a.txt`,
415 'two\n',
416 ]),
417 )
418 const { backend } = fakeBackend(files)
419 let running = 0
420 let most = 0
421 /** `fn` with a pause, counting the calls that run at the same time. */
422 const counted =
423 <A extends Array<unknown>, R>(fn: (...args: A) => Promise<R>) =>
424 async (...args: A) => {
425 most = Math.max(most, ++running)
426 await new Promise((done) => setTimeout(done, 1))
427 try {
428 return await fn(...args)
429 } finally {
430 running--
431 }
432 }
433 backend.readdir = counted(backend.readdir)
434 backend.stat = counted(backend.stat)
435 const lines = (await searchOn(backend).grep({ pattern: 'two' })).split('\n')
436 expect(most).toBe(16)
437 expect(lines).toHaveLength(40)
438 expect(lines[0]).toBe('d00/a.txt:1: two')
439 expect(lines[39]).toBe('d39/a.txt:1: two')
440 })
441
442 it('says so when the JS walk stops before the end', async () => {
443 const fake = fakeBackend({ ...numbered(5001), 'z.md': '' })
444 expect(await searchOn(fake.backend).listFiles({ pattern: '*.md' })).toBe(
445 `No files.\n${FILES_NOTE}`,
446 )
447 })
448})
449
450describe('on the host', () => {
451 /** The host backend, but rg is never found. */
452 const withoutRg: WorkspaceBackend = {
453 ...hostBackend,
454 exec: (command, options) =>
455 command.startsWith('rg ')
456 ? Promise.resolve(NOT_FOUND)
457 : hostBackend.exec(command, options),
458 }
459 /** The host backend, but no command runs, so the JS walk runs. */
460 const walkOnly: WorkspaceBackend = {
461 ...hostBackend,
462 exec: async () => NOT_FOUND,
463 }
464 const put = (dir: string, path: string, text: string) =>
465 hostBackend.writeFile(join(dir, path), text)
466
467 it.skipIf(!hasGit)(
468 'leaves out what .gitignore names, through git ls-files',
469 { timeout: SPAWN_TIMEOUT },
470 async () => {
471 const dir = await mkdtemp(join(tmpdir(), 'coding-search-git-'))
472 try {
473 await put(dir, '.gitignore', 'ignored/\n*.log\n')
474 await put(dir, 'src/a.ts', 'two\n')
475 await put(dir, 'ignored/b.ts', 'two\n')
476 await put(dir, 'debug.log', 'two\n')
477 await put(dir, 'node_modules/pkg/i.js', 'two\n')
478 const init = await hostBackend.exec('git init -q', { cwd: dir })
479 expect(init.exitCode).toBe(0)
480
481 const { listFiles, grep } = searchOn(withoutRg, dir)
482 expect(await listFiles()).toBe('.gitignore\nsrc/a.ts')
483 expect(await grep({ pattern: 'two' })).toBe('src/a.ts:1: two')
484 } finally {
485 await rm(dir, { recursive: true, force: true })
486 }
487 },
488 )
489
490 describe('links to outside the workspace', () => {
491 let dir = ''
492 let outside = ''
493 beforeAll(async () => {
494 dir = await mkdtemp(join(tmpdir(), 'coding-search-walk-'))
495 outside = await mkdtemp(join(tmpdir(), 'coding-search-outside-'))
496 await put(dir, 'a.txt', 'two\n')
497 await put(outside, 'secret.txt', 'two\n')
498 // A junction on Windows needs no admin rights. Elsewhere it is a link.
499 await symlink(outside, join(dir, 'linked'), 'junction')
500 // A link to a file can need admin rights on Windows. Without it, the
501 // folder link still covers the tests.
502 await symlink(
503 join(outside, 'secret.txt'),
504 join(dir, 'secret-link.txt'),
505 'file',
506 ).catch(() => undefined)
507 })
508 afterAll(async () => {
509 await rm(outside, { recursive: true, force: true })
510 await rm(dir, { recursive: true, force: true })
511 })
512
513 it('the JS walk leaves the links out', async () => {
514 const { listFiles, grep } = searchOn(walkOnly, dir)
515 expect(await listFiles()).toBe('a.txt')
516 expect(await grep({ pattern: 'two' })).toBe('a.txt:1: two')
517 })
518
519 it.skipIf(!hasGit)(
520 'the git list leaves the links out, and the files in a linked folder',
521 { timeout: SPAWN_TIMEOUT },
522 async () => {
523 const init = await hostBackend.exec('git init -q', { cwd: dir })
524 expect(init.exitCode).toBe(0)
525 const { listFiles, grep } = searchOn(withoutRg, dir)
526 expect(await listFiles()).toBe('a.txt')
527 expect(await grep({ pattern: 'two' })).toBe('a.txt:1: two')
528 },
529 )
530 })
531})
532
533describe('quoteArg', () => {
534 const hostile = [
535 {
536 value: '"; rm -rf x',
537 posix: `'"; rm -rf x'`,
538 win32: '^"\\^"^;^ rm^ -rf^ x^"',
539 },
540 { value: '$(x)', posix: `'$(x)'`, win32: '^"$^(x^)^"' },
541 { value: '`x`', posix: "'`x`'", win32: '^"^`x^`^"' },
542 { value: '%PATH%', posix: `'%PATH%'`, win32: '^"^%PATH^%^"' },
543 { value: 'a & b', posix: `'a & b'`, win32: '^"a^ ^&^ b^"' },
544 { value: 'a | b', posix: `'a | b'`, win32: '^"a^ ^|^ b^"' },
545 { value: `it's`, posix: `'it'\\''s'`, win32: `^"it's^"` },
546 { value: 'C:\\dir\\', posix: `'C:\\dir\\'`, win32: '^"C:\\dir\\\\^"' },
547 ]
548
549 it.each(hostile)(
550 'quotes $value for sh and cmd.exe',
551 ({ value, posix, win32 }) => {
552 expect(quoteArg(value, 'linux')).toBe(posix)
553 expect(quoteArg(value, 'win32')).toBe(win32)
554 },
555 )
556
557 it('refuses a line break for cmd.exe', () => {
558 expect(() => quoteArg('a\nb', 'win32')).toThrow('line break')
559 })
560
561 it(
562 'passes hostile values through the real shell of this host unchanged',
563 { timeout: SPAWN_TIMEOUT },
564 async () => {
565 const values = [...hostile.map((row) => row.value), '']
566 const quote = (value: string) => quoteArg(value, process.platform)
567 const script = 'console.log(JSON.stringify(process.argv.slice(1)))'
568 const command = [process.execPath, '-e', script, ...values]
569 .map(quote)
570 .join(' ')
571 const result = await hostBackend.exec(command)
572 expect(JSON.parse(result.stdout)).toEqual(values)
573 },
574 )
575})