-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathripGrep.test.ts
More file actions
898 lines (768 loc) · 32.4 KB
/
ripGrep.test.ts
File metadata and controls
898 lines (768 loc) · 32.4 KB
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
describe,
it,
expect,
beforeEach,
afterEach,
vi,
type Mock,
} from 'vitest';
import type { RipGrepToolParams } from './ripGrep.js';
import { RipGrepTool } from './ripGrep.js';
import path from 'node:path';
import fs from 'node:fs/promises';
import os, { EOL } from 'node:os';
import type { Config } from '../config/config.js';
import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
import { spawn } from 'node:child_process';
import { runRipgrep } from '../utils/ripgrepUtils.js';
import { DEFAULT_FILE_FILTERING_OPTIONS } from '../config/constants.js';
// Mock ripgrepUtils
vi.mock('../utils/ripgrepUtils.js', () => ({
runRipgrep: vi.fn(),
}));
// Mock child_process for ripgrep calls
vi.mock('child_process', () => ({
spawn: vi.fn(),
}));
const mockSpawn = vi.mocked(spawn);
describe('RipGrepTool', () => {
let tempRootDir: string;
let grepTool: RipGrepTool;
let fileExclusionsMock: { getGlobExcludes: () => string[] };
const abortSignal = new AbortController().signal;
const mockConfig = {
getTargetDir: () => tempRootDir,
getWorkspaceContext: () => createMockWorkspaceContext(tempRootDir),
getWorkingDir: () => tempRootDir,
getDebugMode: () => false,
getUseBuiltinRipgrep: () => true,
getTruncateToolOutputThreshold: () => 25000,
getTruncateToolOutputLines: () => 1000,
} as unknown as Config;
beforeEach(async () => {
vi.clearAllMocks();
mockSpawn.mockReset();
tempRootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'grep-tool-root-'));
fileExclusionsMock = {
getGlobExcludes: vi.fn().mockReturnValue([]),
};
Object.assign(mockConfig, {
getFileExclusions: () => fileExclusionsMock,
getFileFilteringOptions: () => DEFAULT_FILE_FILTERING_OPTIONS,
});
grepTool = new RipGrepTool(mockConfig);
// Create some test files and directories
await fs.writeFile(
path.join(tempRootDir, 'fileA.txt'),
'hello world\nsecond line with world',
);
await fs.writeFile(
path.join(tempRootDir, 'fileB.js'),
'const foo = "bar";\nfunction baz() { return "hello"; }',
);
await fs.mkdir(path.join(tempRootDir, 'sub'));
await fs.writeFile(
path.join(tempRootDir, 'sub', 'fileC.txt'),
'another world in sub dir',
);
await fs.writeFile(
path.join(tempRootDir, 'sub', 'fileD.md'),
'# Markdown file\nThis is a test.',
);
});
afterEach(async () => {
await fs.rm(tempRootDir, { recursive: true, force: true });
});
describe('validateToolParams', () => {
it('should return null for valid params (pattern only)', () => {
const params: RipGrepToolParams = { pattern: 'hello' };
expect(grepTool.validateToolParams(params)).toBeNull();
});
it('should return null for valid params (pattern and path)', () => {
const params: RipGrepToolParams = { pattern: 'hello', path: '.' };
expect(grepTool.validateToolParams(params)).toBeNull();
});
it('should return null for valid params (pattern, path, and glob)', () => {
const params: RipGrepToolParams = {
pattern: 'hello',
path: '.',
glob: '*.txt',
};
expect(grepTool.validateToolParams(params)).toBeNull();
});
it('should return error if pattern is missing', () => {
const params = { path: '.' } as unknown as RipGrepToolParams;
expect(grepTool.validateToolParams(params)).toBe(
`params must have required property 'pattern'`,
);
});
it('should surface an error for invalid regex pattern', () => {
const params: RipGrepToolParams = { pattern: '[[' };
expect(grepTool.validateToolParams(params)).toContain(
'Invalid regular expression pattern: [[',
);
});
it('should return error if path does not exist', () => {
const params: RipGrepToolParams = {
pattern: 'hello',
path: 'nonexistent',
};
// Check for the core error message, as the full path might vary
expect(grepTool.validateToolParams(params)).toContain(
'Path does not exist:',
);
expect(grepTool.validateToolParams(params)).toContain('nonexistent');
});
it('should allow path to be a file', () => {
const filePath = path.join(tempRootDir, 'fileA.txt');
const params: RipGrepToolParams = { pattern: 'hello', path: filePath };
expect(grepTool.validateToolParams(params)).toBeNull();
});
});
describe('execute', () => {
it('should find matches for a simple pattern in all files', async () => {
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileA.txt:1:hello world${EOL}fileA.txt:2:second line with world${EOL}sub/fileC.txt:1:another world in sub dir${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'world' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 3 matches for pattern "world" in the workspace directory',
);
expect(result.llmContent).toContain('fileA.txt:1:hello world');
expect(result.llmContent).toContain('fileA.txt:2:second line with world');
expect(result.llmContent).toContain(
'sub/fileC.txt:1:another world in sub dir',
);
expect(result.returnDisplay).toBe('Found 3 matches');
});
it('should find matches in a specific path', async () => {
// Setup specific mock for this test - searching in 'sub' should only return matches from that directory
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileC.txt:1:another world in sub dir${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'world', path: 'sub' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 1 match for pattern "world" in path "sub"',
);
expect(result.llmContent).toContain(
'fileC.txt:1:another world in sub dir',
);
expect(result.returnDisplay).toBe('Found 1 match');
});
it('should use target directory when path is not provided', async () => {
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileA.txt:1:hello world${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'world' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 1 match for pattern "world" in the workspace directory',
);
});
it('should find matches with a glob filter', async () => {
// Setup specific mock for this test
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileB.js:2:function baz() { return "hello"; }${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'hello', glob: '*.js' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 1 match for pattern "hello" in the workspace directory (filter: "*.js"):',
);
expect(result.llmContent).toContain(
'fileB.js:2:function baz() { return "hello"; }',
);
expect(result.returnDisplay).toBe('Found 1 match');
});
it('should find matches with a glob filter and path', async () => {
await fs.writeFile(
path.join(tempRootDir, 'sub', 'another.js'),
'const greeting = "hello";',
);
// Setup specific mock for this test - searching for 'hello' in 'sub' with '*.js' filter
(runRipgrep as Mock).mockResolvedValue({
stdout: `another.js:1:const greeting = "hello";${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = {
pattern: 'hello',
path: 'sub',
glob: '*.js',
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 1 match for pattern "hello" in path "sub" (filter: "*.js")',
);
expect(result.llmContent).toContain(
'another.js:1:const greeting = "hello";',
);
expect(result.returnDisplay).toBe('Found 1 match');
});
it('should pass .qwenignore to ripgrep when respected', async () => {
await fs.writeFile(
path.join(tempRootDir, '.qwenignore'),
'ignored.txt\n',
);
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'secret' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'No matches found for pattern "secret" in the workspace directory.',
);
expect(result.returnDisplay).toBe('No matches found');
});
it('should include .qwenignore matches when disabled in config', async () => {
await fs.writeFile(path.join(tempRootDir, '.qwenignore'), 'kept.txt\n');
await fs.writeFile(path.join(tempRootDir, 'kept.txt'), 'keep me');
Object.assign(mockConfig, {
getFileFilteringOptions: () => ({
respectGitIgnore: true,
respectQwenIgnore: false,
}),
});
(runRipgrep as Mock).mockResolvedValue({
stdout: `kept.txt:1:keep me${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'keep' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 1 match for pattern "keep" in the workspace directory:',
);
expect(result.llmContent).toContain('kept.txt:1:keep me');
expect(result.returnDisplay).toBe('Found 1 match');
});
it('should disable gitignore when configured', async () => {
Object.assign(mockConfig, {
getFileFilteringOptions: () => ({
respectGitIgnore: false,
respectQwenIgnore: true,
}),
});
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'ignored' };
const invocation = grepTool.build(params);
await invocation.execute(abortSignal);
});
it('should truncate llm content when exceeding maximum length', async () => {
const longMatch = 'fileA.txt:1:' + 'a'.repeat(30_000);
(runRipgrep as Mock).mockResolvedValue({
stdout: `${longMatch}${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'a+' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(String(result.llmContent).length).toBeLessThanOrEqual(26_000);
expect(result.llmContent).toMatch(/\[\d+ lines? truncated\] \.\.\./);
expect(result.returnDisplay).toContain('truncated');
});
it('should return "No matches found" when pattern does not exist', async () => {
// Setup specific mock for no matches
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'nonexistentpattern' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'No matches found for pattern "nonexistentpattern" in the workspace directory.',
);
expect(result.returnDisplay).toBe('No matches found');
});
it('should throw validation error for invalid regex pattern', async () => {
const params: RipGrepToolParams = { pattern: '[[' };
expect(() => grepTool.build(params)).toThrow(
'Invalid regular expression pattern: [[',
);
});
it('should handle regex special characters correctly', async () => {
// Setup specific mock for this test - regex pattern 'foo.*bar' should match 'const foo = "bar";'
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileB.js:1:const foo = "bar";${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'foo.*bar' }; // Matches 'const foo = "bar";'
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 1 match for pattern "foo.*bar" in the workspace directory:',
);
expect(result.llmContent).toContain('fileB.js:1:const foo = "bar";');
});
it('should be case-insensitive by default (JS fallback)', async () => {
// Setup specific mock for this test - case insensitive search for 'HELLO'
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileA.txt:1:hello world${EOL}fileB.js:2:function baz() { return "hello"; }${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'HELLO' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(
'Found 2 matches for pattern "HELLO" in the workspace directory:',
);
expect(result.llmContent).toContain('fileA.txt:1:hello world');
expect(result.llmContent).toContain(
'fileB.js:2:function baz() { return "hello"; }',
);
});
it('should throw an error if params are invalid', async () => {
const params = { path: '.' } as unknown as RipGrepToolParams; // Invalid: pattern missing
expect(() => grepTool.build(params)).toThrow(
/params must have required property 'pattern'/,
);
});
it('should search within a single file when path is a file', async () => {
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileA.txt:1:hello world${EOL}fileA.txt:2:second line with world${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = {
pattern: 'world',
path: path.join(tempRootDir, 'fileA.txt'),
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('Found 2 matches');
expect(result.llmContent).toContain('fileA.txt:1:hello world');
expect(result.llmContent).toContain('fileA.txt:2:second line with world');
expect(result.returnDisplay).toBe('Found 2 matches');
});
it('should throw an error if ripgrep is not available', async () => {
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: new Error('ripgrep binary not found.'),
});
const params: RipGrepToolParams = { pattern: 'world' };
const invocation = grepTool.build(params);
expect(await invocation.execute(abortSignal)).toStrictEqual({
llmContent:
'Error during grep search operation: ripgrep binary not found.',
returnDisplay: 'Error: ripgrep binary not found.',
});
});
});
describe('multi-directory workspace', () => {
it('should search across all workspace directories when no path is specified', async () => {
const secondDir = await fs.mkdtemp(
path.join(os.tmpdir(), 'grep-tool-second-'),
);
await fs.writeFile(
path.join(secondDir, 'extra.txt'),
'hello from second dir',
);
const multiDirConfig = {
...mockConfig,
getWorkspaceContext: () =>
createMockWorkspaceContext(tempRootDir, [secondDir]),
} as unknown as Config;
const multiDirGrepTool = new RipGrepTool(multiDirConfig);
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileA.txt:1:hello world${EOL}${secondDir}/extra.txt:1:hello from second dir${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'hello' };
const invocation = multiDirGrepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('across 2 workspace directories');
expect(result.llmContent).toContain('Found 2 matches');
// Verify both paths were passed to runRipgrep
expect(runRipgrep).toHaveBeenCalledWith(
expect.arrayContaining([tempRootDir, secondDir]),
expect.anything(),
);
await fs.rm(secondDir, { recursive: true, force: true });
});
it('should search only specified path when path is given (ignoring multi-dir)', async () => {
const secondDir = await fs.mkdtemp(
path.join(os.tmpdir(), 'grep-tool-second-'),
);
await fs.writeFile(path.join(secondDir, 'other.txt'), 'other content');
const multiDirConfig = {
...mockConfig,
getWorkspaceContext: () =>
createMockWorkspaceContext(tempRootDir, [secondDir]),
} as unknown as Config;
const multiDirGrepTool = new RipGrepTool(multiDirConfig);
(runRipgrep as Mock).mockResolvedValue({
stdout: `fileC.txt:1:another world in sub dir${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'world', path: 'sub' };
const invocation = multiDirGrepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('in path "sub"');
expect(result.llmContent).not.toContain('across');
await fs.rm(secondDir, { recursive: true, force: true });
});
it('should load .qwenignore from each workspace directory', async () => {
const secondDir = await fs.mkdtemp(
path.join(os.tmpdir(), 'grep-tool-second-'),
);
await fs.writeFile(path.join(secondDir, '.qwenignore'), 'ignored.txt\n');
await fs.writeFile(
path.join(tempRootDir, '.qwenignore'),
'other-ignored.txt\n',
);
const multiDirConfig = {
...mockConfig,
getWorkspaceContext: () =>
createMockWorkspaceContext(tempRootDir, [secondDir]),
} as unknown as Config;
const multiDirGrepTool = new RipGrepTool(multiDirConfig);
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'test' };
const invocation = multiDirGrepTool.build(params);
await invocation.execute(abortSignal);
// Verify both .qwenignore files were passed
const rgArgs = (runRipgrep as Mock).mock.calls[0][0] as string[];
const ignoreFileArgs = rgArgs.filter(
(a: string, i: number) => i > 0 && rgArgs[i - 1] === '--ignore-file',
);
expect(ignoreFileArgs).toContain(path.join(tempRootDir, '.qwenignore'));
expect(ignoreFileArgs).toContain(path.join(secondDir, '.qwenignore'));
await fs.rm(secondDir, { recursive: true, force: true });
});
it('should deduplicate matches from overlapping workspace directories', async () => {
// This tests the fix: when ripgrep receives overlapping search paths
// (e.g. /parent and /parent/sub), it may report the same file twice.
// The deduplication layer must remove duplicates.
const subDir = path.join(tempRootDir, 'sub');
const multiDirConfig = {
...mockConfig,
getWorkspaceContext: () =>
createMockWorkspaceContext(tempRootDir, [subDir]),
} as unknown as Config;
const multiDirGrepTool = new RipGrepTool(multiDirConfig);
// Simulate ripgrep returning the same file:line twice (once from each search root)
const dupLine = `${path.join(subDir, 'fileC.txt')}:1:hello world`;
(runRipgrep as Mock).mockResolvedValue({
stdout: `${dupLine}${EOL}${dupLine}${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'hello' };
const invocation = multiDirGrepTool.build(params);
const result = await invocation.execute(abortSignal);
// Despite two identical lines in the raw output, only 1 match should be reported.
expect(result.llmContent).toContain('Found 1 match');
});
});
describe('abort signal handling', () => {
it('should handle AbortSignal during search', async () => {
const controller = new AbortController();
const params: RipGrepToolParams = { pattern: 'world' };
const invocation = grepTool.build(params);
controller.abort();
const result = await invocation.execute(controller.signal);
expect(result).toBeDefined();
});
});
describe('error handling and edge cases', () => {
it('should handle workspace boundary violations', async () => {
const params: RipGrepToolParams = { pattern: 'test', path: '../outside' };
// External paths are allowed; permission is deferred to getDefaultPermission()
const invocation = grepTool.build(params);
const permission = await invocation.getDefaultPermission();
expect(permission).toBe('ask');
});
it('should handle empty directories gracefully', async () => {
const emptyDir = path.join(tempRootDir, 'empty');
await fs.mkdir(emptyDir);
// Setup specific mock for this test - searching in empty directory should return no matches
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'test', path: 'empty' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('No matches found');
expect(result.returnDisplay).toBe('No matches found');
});
it('should handle empty files correctly', async () => {
await fs.writeFile(path.join(tempRootDir, 'empty.txt'), '');
// Setup specific mock for this test - searching for anything in empty files should return no matches
(runRipgrep as Mock).mockResolvedValue({
stdout: '',
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'anything' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('No matches found');
});
it('should handle special characters in file names', async () => {
const specialFileName = 'file with spaces & symbols!.txt';
await fs.writeFile(
path.join(tempRootDir, specialFileName),
'hello world with special chars',
);
// Setup specific mock for this test - searching for 'world' should find the file with special characters
(runRipgrep as Mock).mockResolvedValue({
stdout: `file with spaces & symbols!.txt:1:hello world with special chars${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'world' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain(specialFileName);
expect(result.llmContent).toContain('hello world with special chars');
});
it('should handle deeply nested directories', async () => {
const deepPath = path.join(tempRootDir, 'a', 'b', 'c', 'd', 'e');
await fs.mkdir(deepPath, { recursive: true });
await fs.writeFile(
path.join(deepPath, 'deep.txt'),
'content in deep directory',
);
// Setup specific mock for this test - searching for 'deep' should find the deeply nested file
(runRipgrep as Mock).mockResolvedValue({
stdout: `a/b/c/d/e/deep.txt:1:content in deep directory${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'deep' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('deep.txt');
expect(result.llmContent).toContain('content in deep directory');
});
});
describe('regex pattern validation', () => {
it('should handle complex regex patterns', async () => {
await fs.writeFile(
path.join(tempRootDir, 'code.js'),
'function getName() { return "test"; }\nconst getValue = () => "value";',
);
// Setup specific mock for this test - regex pattern should match function declarations
(runRipgrep as Mock).mockResolvedValue({
stdout: `code.js:1:function getName() { return "test"; }${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'function\\s+\\w+\\s*\\(' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('function getName()');
expect(result.llmContent).not.toContain('const getValue');
});
it('should handle case sensitivity correctly in JS fallback', async () => {
await fs.writeFile(
path.join(tempRootDir, 'case.txt'),
'Hello World\nhello world\nHELLO WORLD',
);
// Setup specific mock for this test - case insensitive search should match all variants
(runRipgrep as Mock).mockResolvedValue({
stdout: `case.txt:1:Hello World${EOL}case.txt:2:hello world${EOL}case.txt:3:HELLO WORLD${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: 'hello' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('Hello World');
expect(result.llmContent).toContain('hello world');
expect(result.llmContent).toContain('HELLO WORLD');
});
it('should handle escaped regex special characters', async () => {
await fs.writeFile(
path.join(tempRootDir, 'special.txt'),
'Price: $19.99\nRegex: [a-z]+ pattern\nEmail: test@example.com',
);
// Setup specific mock for this test - escaped regex pattern should match price format
(runRipgrep as Mock).mockResolvedValue({
stdout: `special.txt:1:Price: $19.99${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = { pattern: '\\$\\d+\\.\\d+' };
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('Price: $19.99');
expect(result.llmContent).not.toContain('Email: test@example.com');
});
});
describe('glob pattern filtering', () => {
it('should handle multiple file extensions in glob pattern', async () => {
await fs.writeFile(
path.join(tempRootDir, 'test.ts'),
'typescript content',
);
await fs.writeFile(path.join(tempRootDir, 'test.tsx'), 'tsx content');
await fs.writeFile(
path.join(tempRootDir, 'test.js'),
'javascript content',
);
await fs.writeFile(path.join(tempRootDir, 'test.txt'), 'text content');
// Setup specific mock for this test - glob pattern should filter to only ts/tsx files
(runRipgrep as Mock).mockResolvedValue({
stdout: `test.ts:1:typescript content${EOL}test.tsx:1:tsx content${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = {
pattern: 'content',
glob: '*.{ts,tsx}',
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('test.ts');
expect(result.llmContent).toContain('test.tsx');
expect(result.llmContent).not.toContain('test.js');
expect(result.llmContent).not.toContain('test.txt');
});
it('should handle directory patterns in glob', async () => {
await fs.mkdir(path.join(tempRootDir, 'src'), { recursive: true });
await fs.writeFile(
path.join(tempRootDir, 'src', 'main.ts'),
'source code',
);
await fs.writeFile(path.join(tempRootDir, 'other.ts'), 'other code');
// Setup specific mock for this test - glob pattern should filter to only src/** files
(runRipgrep as Mock).mockResolvedValue({
stdout: `src/main.ts:1:source code${EOL}`,
truncated: false,
error: undefined,
});
const params: RipGrepToolParams = {
pattern: 'code',
glob: 'src/**',
};
const invocation = grepTool.build(params);
const result = await invocation.execute(abortSignal);
expect(result.llmContent).toContain('main.ts');
expect(result.llmContent).not.toContain('other.ts');
});
});
describe('getDescription', () => {
it('should generate correct description with pattern only', () => {
const params: RipGrepToolParams = { pattern: 'testPattern' };
const invocation = grepTool.build(params);
expect(invocation.getDescription()).toBe("'testPattern'");
});
it('should generate correct description with pattern and glob', () => {
const params: RipGrepToolParams = {
pattern: 'testPattern',
glob: '*.ts',
};
const invocation = grepTool.build(params);
expect(invocation.getDescription()).toBe(
"'testPattern' (filter: '*.ts')",
);
});
it('should generate correct description with pattern and path', async () => {
const dirPath = path.join(tempRootDir, 'src', 'app');
await fs.mkdir(dirPath, { recursive: true });
const params: RipGrepToolParams = {
pattern: 'testPattern',
path: path.join('src', 'app'),
};
const invocation = grepTool.build(params);
expect(invocation.getDescription()).toContain(
"'testPattern' in path 'src",
);
expect(invocation.getDescription()).toContain("app'");
});
it('should generate correct description with default search path', () => {
const params: RipGrepToolParams = { pattern: 'testPattern' };
const invocation = grepTool.build(params);
expect(invocation.getDescription()).toBe("'testPattern'");
});
it('should generate correct description with pattern, glob, and path', async () => {
const dirPath = path.join(tempRootDir, 'src', 'app');
await fs.mkdir(dirPath, { recursive: true });
const params: RipGrepToolParams = {
pattern: 'testPattern',
glob: '*.ts',
path: path.join('src', 'app'),
};
const invocation = grepTool.build(params);
expect(invocation.getDescription()).toContain(
"'testPattern' in path 'src",
);
expect(invocation.getDescription()).toContain("(filter: '*.ts')");
});
it('should use path when specified in description', () => {
const params: RipGrepToolParams = { pattern: 'testPattern', path: '.' };
const invocation = grepTool.build(params);
expect(invocation.getDescription()).toBe("'testPattern' in path '.'");
});
});
describe('getDefaultPermission', () => {
it('should return allow when no path is specified', async () => {
const params: RipGrepToolParams = { pattern: 'hello' };
const invocation = grepTool.build(params);
const permission = await invocation.getDefaultPermission();
expect(permission).toBe('allow');
});
it('should return allow for paths within workspace', async () => {
const params: RipGrepToolParams = { pattern: 'hello', path: '.' };
const invocation = grepTool.build(params);
const permission = await invocation.getDefaultPermission();
expect(permission).toBe('allow');
});
it('should return allow for subdirectories within workspace', async () => {
const params: RipGrepToolParams = { pattern: 'hello', path: 'sub' };
const invocation = grepTool.build(params);
const permission = await invocation.getDefaultPermission();
expect(permission).toBe('allow');
});
it('should return ask for paths outside workspace', async () => {
const params: RipGrepToolParams = { pattern: 'hello', path: '/tmp' };
const invocation = grepTool.build(params);
const permission = await invocation.getDefaultPermission();
expect(permission).toBe('ask');
});
});
});