@criogaid/pi-hashline-edit 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +166 -61
- package/package.json +8 -3
- package/src/core/apply.test.ts +459 -313
- package/src/core/apply.ts +251 -215
- package/src/core/errors.ts +9 -0
- package/src/core/hash.test.ts +61 -23
- package/src/core/hash.ts +49 -20
- package/src/core/lines.test.ts +46 -27
- package/src/core/lines.ts +36 -28
- package/src/core/ranges.test.ts +73 -19
- package/src/core/ranges.ts +15 -15
- package/src/core/replace.ts +109 -0
- package/src/core/text.test.ts +3 -3
- package/src/core/text.ts +26 -9
- package/src/core/types.ts +56 -41
- package/src/index.ts +23 -19
- package/src/integration/config-registration.test.ts +206 -0
- package/src/integration/grep-rg.test.ts +879 -251
- package/src/integration/large-text.test.ts +63 -0
- package/src/integration/replace-package.test.ts +41 -0
- package/src/pi/action-fusion.test.ts +612 -207
- package/src/pi/action-fusion.ts +442 -254
- package/src/pi/anchor-format.test.ts +53 -21
- package/src/pi/anchor-format.ts +48 -20
- package/src/pi/budgets.ts +25 -0
- package/src/pi/config.test.ts +178 -35
- package/src/pi/config.ts +96 -37
- package/src/pi/directory-sync.test.ts +55 -0
- package/src/pi/e2e-scenarios.test.ts +360 -0
- package/src/pi/edit-tool.ts +307 -279
- package/src/pi/error-text.ts +26 -0
- package/src/pi/execute.test.ts +1718 -713
- package/src/pi/failure-context.test.ts +110 -83
- package/src/pi/failure-context.ts +232 -73
- package/src/pi/failure-path.test.ts +180 -66
- package/src/pi/file-commit.test.ts +446 -233
- package/src/pi/file-commit.ts +348 -203
- package/src/pi/fusion-card.test.ts +118 -83
- package/src/pi/fusion-card.ts +203 -87
- package/src/pi/grep-output.ts +225 -0
- package/src/pi/grep-render.ts +59 -0
- package/src/pi/grep-scope.ts +139 -0
- package/src/pi/grep-search.ts +231 -0
- package/src/pi/grep-tool.ts +215 -774
- package/src/pi/grep.test.ts +825 -376
- package/src/pi/mutation-outcome.testing.ts +22 -0
- package/src/pi/mutation-result.test.ts +86 -0
- package/src/pi/mutation-result.ts +118 -63
- package/src/pi/mutation-runner.ts +151 -0
- package/src/pi/path.ts +20 -12
- package/src/pi/pi.test.ts +100 -52
- package/src/pi/read-tool.ts +245 -134
- package/src/pi/registration.test.ts +271 -114
- package/src/pi/render.test.ts +227 -84
- package/src/pi/render.ts +86 -116
- package/src/pi/replace-regex.ts +54 -0
- package/src/pi/replace-tool.ts +247 -241
- package/src/pi/replace-worker.mjs +4 -0
- package/src/pi/replace-worker.ts +10 -0
- package/src/pi/replace.test.ts +778 -390
- package/src/pi/result-safety.test.ts +821 -344
- package/src/pi/rg-line-ranges.test.ts +57 -31
- package/src/pi/rg-line-ranges.ts +45 -82
- package/src/pi/rg-process.test.ts +113 -0
- package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
- package/src/pi/rg-text-view.ts +102 -48
- package/src/pi/schema.ts +19 -0
- package/src/pi/text-stream.test.ts +118 -0
- package/src/pi/text-stream.ts +136 -0
- package/src/pi/tool-call.testing.ts +37 -0
- package/src/pi/write-tool.ts +114 -52
- package/src/pi/write.test.ts +250 -97
- package/src/core/index.ts +0 -14
- package/src/pi/rg-line-filter.test.ts +0 -85
- package/src/pi/state.ts +0 -26
package/src/pi/grep-tool.ts
CHANGED
|
@@ -1,541 +1,133 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Override grep:
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* drop to bash pipelines for: multi-pattern AND (`matchMode: "all"` ≈
|
|
8
|
-
* `grep A | grep B`), line exclusion (`excludePattern` ≈ `grep -v`),
|
|
9
|
-
* whole-word matching (`wordMatch` ≈ `-w`), multiple search roots, and
|
|
10
|
-
* files-only / count output (`outputMode` ≈ `rg -l` / `grep -c`).
|
|
11
|
-
*
|
|
12
|
-
* We run ripgrep directly (`--json`) rather than wrap the built-in grep, so we
|
|
13
|
-
* control formatting and can compute each line's hash from its FULL content
|
|
14
|
-
* while displaying a truncated copy. (The built-in grep truncates long lines
|
|
15
|
-
* before formatting; hashing that truncated text would not match what edit
|
|
16
|
-
* verifies against the full line — so the hash must be computed from the full
|
|
17
|
-
* content, independently of what is displayed.)
|
|
18
|
-
*
|
|
19
|
-
* The main rg process uses native OR, or the first required pattern for AND.
|
|
20
|
-
* Batched rg predicates evaluate AND / exclude against candidate lines with the
|
|
21
|
-
* same resolved literal and case modes, so Rust regex semantics remain authoritative
|
|
22
|
-
* throughout. Each batch closes stdin and waits for rg to exit. `limit` counts final
|
|
23
|
-
* results, and context windows are rebuilt only around surviving matches.
|
|
2
|
+
* Override grep: anchored `LINE#HASH│` results feed edit without a re-read.
|
|
3
|
+
* Scope and paths live in grep-scope; search requests and ripgrep events in
|
|
4
|
+
* grep-search; the rg process layer in rg-process; result formatting in
|
|
5
|
+
* grep-output; TUI presentation in grep-render. This module owns the tool
|
|
6
|
+
* schema, the production backend, render wiring, and execution order.
|
|
24
7
|
* @module pi-hashline-edit/pi
|
|
25
8
|
*/
|
|
26
9
|
|
|
27
|
-
import {
|
|
28
|
-
truncateHead,
|
|
29
|
-
formatSize,
|
|
30
|
-
DEFAULT_MAX_BYTES,
|
|
31
|
-
} from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
32
11
|
import { rgPath as bundledRgPath } from "@vscode/ripgrep";
|
|
33
|
-
import { Type } from "typebox";
|
|
12
|
+
import { Type, type Static } from "typebox";
|
|
34
13
|
import { Text } from "@earendil-works/pi-tui";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
|
|
40
|
-
import { canonicalPath } from "./path.ts";
|
|
41
|
-
import { parseHashline, renderToolError } from "./render.ts";
|
|
14
|
+
import { normalizeLineEndings } from "../core/lines.ts";
|
|
15
|
+
import { createAnchorFormatter } from "./anchor-format.ts";
|
|
16
|
+
import { renderToolError } from "./render.ts";
|
|
17
|
+
import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
|
|
42
18
|
import {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
type SearchModes,
|
|
55
|
-
} from "./rg-line-filter.ts";
|
|
19
|
+
filterExplicitFilesByGlob,
|
|
20
|
+
literalFallbackNotice as formatLiteralFallbackNotice,
|
|
21
|
+
REGEX_SYNTAX,
|
|
22
|
+
resolveLiteralMode,
|
|
23
|
+
toArray,
|
|
24
|
+
resolveSearchPaths,
|
|
25
|
+
} from "./grep-scope.ts";
|
|
26
|
+
import { searchMatches, type GrepBackend, type SearchScope } from "./grep-search.ts";
|
|
27
|
+
export type { GrepBackend } from "./grep-search.ts";
|
|
28
|
+
import { toDisplayLines } from "./grep-render.ts";
|
|
29
|
+
import { probeRegex, resolveIgnoreCase, runRgPaths, type SearchModes } from "./rg-process.ts";
|
|
56
30
|
import { runRgTextView } from "./rg-text-view.ts";
|
|
57
|
-
import {
|
|
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
|
-
/** Normalize a `string | string[]` param to an array (`undefined` → `[]`). */
|
|
137
|
-
function toArray(v: string | string[] | undefined): string[] {
|
|
138
|
-
if (v === undefined) return [];
|
|
139
|
-
return Array.isArray(v) ? v : [v];
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function clampContext(context: number | undefined): number {
|
|
143
|
-
if (!context || !Number.isFinite(context) || context < 0) return 0;
|
|
144
|
-
return Math.min(Math.floor(context), GREP_CONTEXT_MAX);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
const grepOverrideSchema = Type.Object({
|
|
148
|
-
pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
149
|
-
description:
|
|
150
|
-
"Non-empty string or array (OR by default). For code snippets with regex punctuation, set literal:true; use an array for alternatives instead of joining literals with |.",
|
|
151
|
-
}),
|
|
152
|
-
matchMode: Type.Optional(
|
|
153
|
-
Type.Union([Type.Literal("any"), Type.Literal("all")], {
|
|
154
|
-
description:
|
|
155
|
-
`"any" (default): OR. "all": AND on the same line (maximum ${MAX_ALL_PATTERNS} patterns).`,
|
|
156
|
-
}),
|
|
157
|
-
),
|
|
158
|
-
excludePattern: Type.Optional(
|
|
159
|
-
Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
160
|
-
description:
|
|
161
|
-
"Drop lines matching any exclusion after pattern matching.",
|
|
162
|
-
}),
|
|
163
|
-
),
|
|
164
|
-
outputMode: Type.Optional(
|
|
165
|
-
Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
|
|
166
|
-
description:
|
|
167
|
-
'"content" (default): anchored lines. "files": paths. "count": matching lines per file and total.',
|
|
168
|
-
}),
|
|
169
|
-
),
|
|
170
|
-
wordMatch: Type.Optional(Type.Boolean({ description: "Whole words in pattern only (rg -w)" })),
|
|
171
|
-
path: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
172
|
-
description:
|
|
173
|
-
"Directory or file to search (string or array of paths; default: current directory)",
|
|
174
|
-
})),
|
|
175
|
-
glob: Type.Optional(
|
|
176
|
-
Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
177
|
-
description: "Filter files by glob pattern; pass an array for multiple filters and prefix exclusions with `!`, e.g. ['*.ts', '!**/*.test.ts']",
|
|
178
|
-
}),
|
|
179
|
-
),
|
|
180
|
-
ignoreCase: Type.Optional(
|
|
181
|
-
Type.Boolean({ description: "true: ignore case; false: match case. Default: ripgrep smart-case across inclusion patterns. The resolved default also applies to exclusions." }),
|
|
182
|
-
),
|
|
183
|
-
literal: Type.Optional(
|
|
184
|
-
Type.Boolean({
|
|
185
|
-
description: "Set true for literal code text, especially calls, brackets, pipes, and backslashes. Set false only for intentional valid regex. Applies to pattern and excludePattern. Automatic mode tries regex for metacharacters; only one pattern without exclusions can fall back, searching the entire input literally.",
|
|
186
|
-
}),
|
|
187
|
-
),
|
|
188
|
-
noIgnore: Type.Optional(Type.Boolean({
|
|
189
|
-
description: "Search files normally excluded by ignore files, including .gitignore, .ignore, and .rgignore. Explicit glob filters still apply.",
|
|
190
|
-
})),
|
|
191
|
-
follow: Type.Optional(Type.Boolean({
|
|
192
|
-
description: "Follow symbolic links during directory traversal. Return resolved target paths. This does not grant additional filesystem access.",
|
|
193
|
-
})),
|
|
194
|
-
pcre2: Type.Optional(Type.Boolean({
|
|
195
|
-
description: "Use PCRE2 for lookarounds and backreferences. Forces regex matching with no literal fallback; incompatible with literal:true. Default: the standard ripgrep engine.",
|
|
196
|
-
})),
|
|
197
|
-
multiline: Type.Optional(Type.Boolean({
|
|
198
|
-
description: "Allow matches to span physical lines. Results and filters still operate on physical lines. Dot matches line breaks only with an inline (?s) flag.",
|
|
199
|
-
})),
|
|
200
|
-
context: Type.Optional(
|
|
201
|
-
Type.Integer({
|
|
202
|
-
minimum: 0,
|
|
203
|
-
maximum: GREP_CONTEXT_MAX,
|
|
204
|
-
description: `Number of lines to show before and after each match (0-${GREP_CONTEXT_MAX}; default: 0); context lines are anchored too`,
|
|
205
|
-
}),
|
|
206
|
-
),
|
|
207
|
-
limit: Type.Optional(
|
|
208
|
-
Type.Number({ description: "Maximum number of matching lines to return (default: 100)" }),
|
|
209
|
-
),
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
interface RgMatch {
|
|
213
|
-
filePath: string;
|
|
214
|
-
lineNumber: number;
|
|
215
|
-
column?: number;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/** @internal — injectable process boundary for deterministic tests. */
|
|
219
|
-
export interface GrepBackend {
|
|
220
|
-
runRg: typeof runRg;
|
|
221
|
-
runRgPaths: typeof runRgPaths;
|
|
222
|
-
resolveIgnoreCase: typeof resolveIgnoreCase;
|
|
223
|
-
validatePatterns: typeof validatePatterns;
|
|
224
|
-
createLinePredicate: typeof createLinePredicate;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
interface SearchScope {
|
|
228
|
-
globs: readonly string[];
|
|
229
|
-
noIgnore: boolean;
|
|
230
|
-
follow: boolean;
|
|
231
|
-
searchPaths: readonly string[];
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
interface FileIdentity {
|
|
235
|
-
dev: number;
|
|
236
|
-
ino: number;
|
|
237
|
-
size: number;
|
|
238
|
-
mtimeMs: number;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function scopeArgs(scope: SearchScope): string[] {
|
|
242
|
-
return [
|
|
243
|
-
"--hidden",
|
|
244
|
-
...(scope.noIgnore ? ["--no-ignore"] : []),
|
|
245
|
-
...(scope.follow ? ["--follow"] : []),
|
|
246
|
-
...scope.globs.flatMap((glob) => ["--glob", glob]),
|
|
247
|
-
];
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
interface SearchPathInfo {
|
|
251
|
-
path: string;
|
|
252
|
-
isFile: boolean;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
function fileKey(path: string): string {
|
|
256
|
-
const absolute = resolve(path);
|
|
257
|
-
return process.platform === "win32" ? absolute.toLowerCase() : absolute;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
async function filterExplicitFilesByGlob(
|
|
261
|
-
backend: GrepBackend,
|
|
262
|
-
rgPath: string,
|
|
263
|
-
scope: SearchScope,
|
|
264
|
-
paths: readonly SearchPathInfo[],
|
|
265
|
-
signal: AbortSignal | undefined,
|
|
266
|
-
warnings: string[],
|
|
267
|
-
): Promise<string[]> {
|
|
268
|
-
const explicitFiles = paths.filter(({ isFile }) => isFile);
|
|
269
|
-
if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
|
|
270
|
-
|
|
271
|
-
const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
|
|
272
|
-
const allowed = new Set<string>();
|
|
273
|
-
// Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
|
|
274
|
-
const args = [
|
|
275
|
-
...COMMON_RG_ARGS,
|
|
276
|
-
...scopeArgs({ ...scope, noIgnore: true, follow: true }),
|
|
277
|
-
"--files",
|
|
278
|
-
"--null",
|
|
279
|
-
"--max-depth=1",
|
|
280
|
-
"--",
|
|
281
|
-
...parents,
|
|
282
|
-
];
|
|
283
|
-
const listed = await backend.runRgPaths(rgPath, args, signal, async (path) => {
|
|
284
|
-
allowed.add(fileKey(path));
|
|
285
|
-
return true;
|
|
286
|
-
});
|
|
287
|
-
recordSearchDiagnostics(listed, warnings);
|
|
288
|
-
return paths
|
|
289
|
-
.filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
|
|
290
|
-
.map(({ path }) => path);
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
async function fileIdentity(path: string): Promise<FileIdentity> {
|
|
294
|
-
const value = await stat(path);
|
|
295
|
-
if (!value.isFile()) throw new Error(`Search target is not a regular file: ${path}`);
|
|
296
|
-
return { dev: value.dev, ino: value.ino, size: value.size, mtimeMs: value.mtimeMs };
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
function sameIdentity(left: FileIdentity, right: FileIdentity): boolean {
|
|
300
|
-
return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function rangeCount(files: ReadonlyMap<string, readonly LineRange[]>): number {
|
|
304
|
-
let total = 0;
|
|
305
|
-
for (const ranges of files.values()) total += ranges.length;
|
|
306
|
-
return total;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
function combineRangeMaps(
|
|
310
|
-
left: ReadonlyMap<string, readonly LineRange[]>,
|
|
311
|
-
right: ReadonlyMap<string, readonly LineRange[]>,
|
|
312
|
-
operation: "union" | "intersect" | "subtract",
|
|
313
|
-
): Map<string, LineRange[]> {
|
|
314
|
-
const result = new Map<string, LineRange[]>();
|
|
315
|
-
const paths = operation === "union" ? new Set([...left.keys(), ...right.keys()]) : new Set(left.keys());
|
|
316
|
-
for (const path of paths) {
|
|
317
|
-
const a = left.get(path) ?? [];
|
|
318
|
-
const b = right.get(path) ?? [];
|
|
319
|
-
const ranges = operation === "union" ? unionRanges(a, b)
|
|
320
|
-
: operation === "intersect" ? intersectRanges(a, b) : subtractRanges(a, b);
|
|
321
|
-
if (ranges.length) result.set(path, ranges);
|
|
322
|
-
}
|
|
323
|
-
if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
|
|
324
|
-
return result;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
async function scanPatternRanges(
|
|
328
|
-
backend: GrepBackend,
|
|
329
|
-
rgPath: string,
|
|
330
|
-
files: readonly string[],
|
|
331
|
-
pattern: string,
|
|
332
|
-
modes: SearchModes,
|
|
333
|
-
word: boolean,
|
|
334
|
-
signal: AbortSignal | undefined,
|
|
335
|
-
lineCounts: Map<string, number>,
|
|
336
|
-
warnings?: string[],
|
|
337
|
-
columns?: Map<string, Map<number, number>>,
|
|
338
|
-
): Promise<Map<string, LineRange[]>> {
|
|
339
|
-
if (files.length === 0) return new Map();
|
|
340
|
-
const args = [
|
|
341
|
-
...matcherArgs(modes, word),
|
|
342
|
-
"--json",
|
|
343
|
-
"--line-number",
|
|
344
|
-
"--threads=1",
|
|
345
|
-
"-e",
|
|
346
|
-
pattern,
|
|
347
|
-
"--",
|
|
348
|
-
...files,
|
|
349
|
-
];
|
|
350
|
-
const result = new Map<string, LineRange[]>();
|
|
351
|
-
const run = await backend.runRg(rgPath, args, signal, async (line) => {
|
|
352
|
-
let event: any;
|
|
353
|
-
try { event = JSON.parse(line); } catch { return true; }
|
|
354
|
-
if (event.type !== "match") return true;
|
|
355
|
-
const data = event.data;
|
|
356
|
-
if (!data?.path || !data?.lines || !Number.isSafeInteger(data.line_number)) {
|
|
357
|
-
throw new Error("Invalid rg match event");
|
|
358
|
-
}
|
|
359
|
-
const filePath = resolve(rgText(data.path));
|
|
360
|
-
if (!files.includes(filePath)) throw new Error("ripgrep returned an unexpected search path");
|
|
361
|
-
let lineCount = lineCounts.get(filePath);
|
|
362
|
-
if (lineCount === undefined) {
|
|
363
|
-
lineCount = splitLines(decodeEditableText(await readFile(filePath))).length;
|
|
364
|
-
lineCounts.set(filePath, lineCount);
|
|
365
|
-
}
|
|
366
|
-
const bytes = rgBytes(data.lines);
|
|
367
|
-
let submatches: RgSubmatch[];
|
|
368
|
-
if (!Array.isArray(data.submatches)) throw new Error("Invalid rg submatch protocol");
|
|
369
|
-
if (data.submatches.length === 0) submatches = [{ start: bytes.length, end: bytes.length }];
|
|
370
|
-
else submatches = data.submatches.map((match: any) => ({ start: match.start, end: match.end }));
|
|
371
|
-
const fileColumns = columns?.get(filePath) ?? new Map<number, number>();
|
|
372
|
-
const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount, columns ? fileColumns : undefined);
|
|
373
|
-
columns?.set(filePath, fileColumns);
|
|
374
|
-
result.set(filePath, unionRanges(result.get(filePath) ?? [], ranges));
|
|
375
|
-
if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
|
|
376
|
-
return true;
|
|
377
|
-
});
|
|
378
|
-
recordSearchDiagnostics(run, warnings);
|
|
379
|
-
return result;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
interface ComplexSearchOptions {
|
|
383
|
-
backend: GrepBackend;
|
|
384
|
-
rgPath: string;
|
|
385
|
-
scope: SearchScope;
|
|
386
|
-
patterns: readonly string[];
|
|
387
|
-
excludes: readonly string[];
|
|
388
|
-
matchMode: "any" | "all";
|
|
389
|
-
modes: SearchModes;
|
|
390
|
-
word: boolean;
|
|
391
|
-
limit: number;
|
|
392
|
-
signal?: AbortSignal;
|
|
393
|
-
warnings: string[];
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMatch[]; matchLimitReached: boolean; identities: Map<string, FileIdentity> }> {
|
|
397
|
-
const { backend, rgPath, scope, patterns, excludes, matchMode, modes, word, limit, signal, warnings } = options;
|
|
398
|
-
const raw: RgMatch[] = [];
|
|
399
|
-
const identities = new Map<string, FileIdentity>();
|
|
400
|
-
const seen = new Set<string>();
|
|
401
|
-
let matchLimitReached = false;
|
|
402
|
-
let batch: string[] = [];
|
|
403
|
-
let batchBytes = 0;
|
|
404
|
-
|
|
405
|
-
const processBatch = async (): Promise<boolean> => {
|
|
406
|
-
const files = batch;
|
|
407
|
-
batch = [];
|
|
408
|
-
batchBytes = 0;
|
|
409
|
-
if (files.length === 0) return true;
|
|
410
|
-
for (const file of files) identities.set(file, await fileIdentity(file));
|
|
411
|
-
const lineCounts = new Map<string, number>();
|
|
412
|
-
const columns = new Map<string, Map<number, number>>();
|
|
413
|
-
|
|
414
|
-
let included = new Map<string, LineRange[]>();
|
|
415
|
-
for (let index = 0; index < patterns.length; index++) {
|
|
416
|
-
const candidates = matchMode === "all" && index > 0 ? files.filter((file) => included.has(file)) : files;
|
|
417
|
-
const ranges = await scanPatternRanges(backend, rgPath, candidates, patterns[index], modes, word, signal, lineCounts, warnings, columns);
|
|
418
|
-
included = index === 0 ? ranges : combineRangeMaps(included, ranges, matchMode === "all" ? "intersect" : "union");
|
|
419
|
-
if (matchMode === "all" && included.size === 0) break;
|
|
420
|
-
}
|
|
421
|
-
if (included.size && excludes.length) {
|
|
422
|
-
let excluded = new Map<string, LineRange[]>();
|
|
423
|
-
const candidates = files.filter((file) => included.has(file));
|
|
424
|
-
for (const pattern of excludes) {
|
|
425
|
-
excluded = combineRangeMaps(
|
|
426
|
-
excluded,
|
|
427
|
-
await scanPatternRanges(backend, rgPath, candidates, pattern, modes, false, signal, lineCounts),
|
|
428
|
-
"union",
|
|
429
|
-
);
|
|
430
|
-
}
|
|
431
|
-
included = combineRangeMaps(included, excluded, "subtract");
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
for (const file of files) {
|
|
435
|
-
if (!sameIdentity(identities.get(file)!, await fileIdentity(file))) {
|
|
436
|
-
throw new Error("File changed during search; rerun the query.");
|
|
437
|
-
}
|
|
438
|
-
for (const [start, end] of included.get(file) ?? []) {
|
|
439
|
-
for (let lineNumber = start; lineNumber < end; lineNumber++) {
|
|
440
|
-
raw.push({ filePath: file, lineNumber, column: columns.get(file)?.get(lineNumber) });
|
|
441
|
-
if (raw.length >= limit) {
|
|
442
|
-
matchLimitReached = true;
|
|
443
|
-
return false;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
return true;
|
|
449
|
-
};
|
|
450
|
-
|
|
451
|
-
const listArgs = [
|
|
452
|
-
...COMMON_RG_ARGS,
|
|
453
|
-
...scopeArgs(scope),
|
|
454
|
-
"--files",
|
|
455
|
-
"--null",
|
|
456
|
-
"--",
|
|
457
|
-
...scope.searchPaths,
|
|
458
|
-
];
|
|
459
|
-
const listed = await backend.runRgPaths(rgPath, listArgs, signal, async (listedPath) => {
|
|
460
|
-
const absolute = resolve(listedPath);
|
|
461
|
-
const filePath = scope.follow ? await realpath(absolute) : absolute;
|
|
462
|
-
if (seen.has(filePath)) return true;
|
|
463
|
-
seen.add(filePath);
|
|
464
|
-
batch.push(filePath);
|
|
465
|
-
batchBytes += Buffer.byteLength(filePath) + 1;
|
|
466
|
-
return batch.length >= FILE_BATCH_SIZE || batchBytes >= FILE_BATCH_ARG_BYTES ? processBatch() : true;
|
|
467
|
-
});
|
|
468
|
-
recordSearchDiagnostics(listed, warnings);
|
|
469
|
-
if (!matchLimitReached && batch.length) await processBatch();
|
|
470
|
-
return { raw, matchLimitReached, identities };
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
/**
|
|
475
|
-
* Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
|
|
476
|
-
* form for the TUI: drop the hash, keep file headers and line numbers. Within each
|
|
477
|
-
* file group, the common leading whitespace shared by all matched lines is folded
|
|
478
|
-
* into a single marker (›) so deep, repeated indentation doesn't eat display width;
|
|
479
|
-
* each line's indentation relative to that common base is preserved. The model still
|
|
480
|
-
* receives the anchored `content` text verbatim — this only affects what the user sees.
|
|
481
|
-
*/
|
|
482
|
-
function countLeading(s: string): number {
|
|
483
|
-
const m = s.match(/^[ \t]*/);
|
|
484
|
-
return m ? m[0].length : 0;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
function toDisplayLines(raw: string, theme: any): string[] {
|
|
488
|
-
const out: string[] = [];
|
|
489
|
-
const lines = raw.split("\n");
|
|
490
|
-
const lineNoWidth = lines.reduce(
|
|
491
|
-
(width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
|
|
492
|
-
0,
|
|
31
|
+
import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
|
|
32
|
+
import { throwIfCancelled } from "./error-text.ts";
|
|
33
|
+
import type { HashlineEditConfig } from "./config.ts";
|
|
34
|
+
|
|
35
|
+
/** Grep parameters; descriptions state the configured defaults. */
|
|
36
|
+
function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
|
|
37
|
+
return Type.Object(
|
|
38
|
+
{
|
|
39
|
+
pattern: Type.Union(
|
|
40
|
+
[Type.String({ minLength: 1 }), Type.Array(Type.String({ minLength: 1 }), { minItems: 1 })],
|
|
41
|
+
{
|
|
42
|
+
description:
|
|
43
|
+
"String or array of strings (an array matches any of them). Regex syntax is ripgrep's Rust regex, not JavaScript: no lookaround or backreferences; ^ and $ match at line boundaries.",
|
|
44
|
+
},
|
|
45
|
+
),
|
|
46
|
+
path: Type.Optional(
|
|
47
|
+
Type.Union(
|
|
48
|
+
[
|
|
49
|
+
Type.String({ minLength: 1 }),
|
|
50
|
+
Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
51
|
+
],
|
|
52
|
+
{
|
|
53
|
+
description:
|
|
54
|
+
"Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
|
|
55
|
+
},
|
|
56
|
+
),
|
|
57
|
+
),
|
|
58
|
+
glob: Type.Optional(
|
|
59
|
+
Type.Union(
|
|
60
|
+
[
|
|
61
|
+
Type.String({ minLength: 1 }),
|
|
62
|
+
Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
|
|
63
|
+
],
|
|
64
|
+
{
|
|
65
|
+
description:
|
|
66
|
+
"Filename glob, or an ordered array of them; prefix exclusions with !, e.g. ['*.ts', '!**/*.test.ts'].",
|
|
67
|
+
},
|
|
68
|
+
),
|
|
69
|
+
),
|
|
70
|
+
literal: Type.Optional(
|
|
71
|
+
Type.Boolean({
|
|
72
|
+
description:
|
|
73
|
+
"true: match the text literally. false: ripgrep Rust regex. Omitted: regex when the pattern has metacharacters; a single invalid pattern falls back to a literal search of the whole string, an invalid array fails.",
|
|
74
|
+
}),
|
|
75
|
+
),
|
|
76
|
+
ignoreCase: Type.Optional(
|
|
77
|
+
Type.Boolean({
|
|
78
|
+
description:
|
|
79
|
+
"true ignores case, false matches case; omitted uses smart-case for the whole query. Inline regex flags still apply.",
|
|
80
|
+
}),
|
|
81
|
+
),
|
|
82
|
+
multiline: Type.Optional(
|
|
83
|
+
Type.Boolean({
|
|
84
|
+
description:
|
|
85
|
+
"Match across lines (default false); every line a match touches is anchored. The . wildcard does not match newlines; use \\n or (?s).",
|
|
86
|
+
}),
|
|
87
|
+
),
|
|
88
|
+
context: Type.Optional(
|
|
89
|
+
Type.Number({
|
|
90
|
+
...GREP_CONTEXT_RANGE,
|
|
91
|
+
description: `Anchored lines shown before and after each match (${GREP_CONTEXT_RANGE.minimum}-${GREP_CONTEXT_RANGE.maximum}, default ${defaultContext}); display only, not matched.`,
|
|
92
|
+
}),
|
|
93
|
+
),
|
|
94
|
+
limit: Type.Optional(
|
|
95
|
+
Type.Number({
|
|
96
|
+
...POSITIVE_SAFE_INTEGER,
|
|
97
|
+
description: `Maximum matching lines, across all files (default ${defaultLimit}).`,
|
|
98
|
+
}),
|
|
99
|
+
),
|
|
100
|
+
outputMode: Type.Optional(
|
|
101
|
+
Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
|
|
102
|
+
description:
|
|
103
|
+
'"content" (default): anchored lines; "files": paths; "count": matching lines per file and total. All modes share limit.',
|
|
104
|
+
}),
|
|
105
|
+
),
|
|
106
|
+
},
|
|
107
|
+
{ additionalProperties: false },
|
|
493
108
|
);
|
|
494
|
-
let i = 0;
|
|
495
|
-
while (i < lines.length) {
|
|
496
|
-
const line = lines[i];
|
|
497
|
-
const h = line.match(/^(.+?) · (\d+ match(?:es)?)$/);
|
|
498
|
-
if (h) {
|
|
499
|
-
out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
|
|
500
|
-
// collect the anchor lines in this file group
|
|
501
|
-
const group: { lineNo: string; content: string }[] = [];
|
|
502
|
-
let j = i + 1;
|
|
503
|
-
while (j < lines.length) {
|
|
504
|
-
const a = parseHashline(lines[j]);
|
|
505
|
-
if (!a) break;
|
|
506
|
-
group.push({ lineNo: a.lineNo, content: a.content });
|
|
507
|
-
j++;
|
|
508
|
-
}
|
|
509
|
-
// common base = min leading whitespace across the group; fold it into a marker
|
|
510
|
-
const base = group.length ? Math.min(...group.map((g) => countLeading(g.content))) : 0;
|
|
511
|
-
const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
|
|
512
|
-
for (const g of group) {
|
|
513
|
-
const body = g.content.slice(base);
|
|
514
|
-
out.push(theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) + marker + theme.fg("toolOutput", body));
|
|
515
|
-
}
|
|
516
|
-
i = j;
|
|
517
|
-
continue;
|
|
518
|
-
}
|
|
519
|
-
if (line.startsWith("[")) out.push(theme.fg("warning", line));
|
|
520
|
-
else out.push(theme.fg("toolOutput", line));
|
|
521
|
-
i++;
|
|
522
|
-
}
|
|
523
|
-
return out;
|
|
524
109
|
}
|
|
110
|
+
type GrepSchema = ReturnType<typeof createGrepSchema>;
|
|
111
|
+
type GrepTool = ToolDefinition<GrepSchema, { incomplete?: true } | undefined>;
|
|
525
112
|
|
|
526
113
|
/** Build the production grep override (a ToolDefinition fragment for registerTool). */
|
|
527
|
-
export function makeGrepOverride(cwd: string) {
|
|
528
|
-
return makeGrepOverrideWithBackend(cwd, {});
|
|
114
|
+
export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
|
|
115
|
+
return makeGrepOverrideWithBackend(cwd, config, {});
|
|
529
116
|
}
|
|
530
117
|
|
|
531
118
|
/** @internal — build a grep override with deterministic process backends for tests. */
|
|
532
|
-
export function makeGrepOverrideWithBackend(
|
|
119
|
+
export function makeGrepOverrideWithBackend(
|
|
120
|
+
cwd: string,
|
|
121
|
+
config: HashlineEditConfig,
|
|
122
|
+
overrides: Partial<GrepBackend>,
|
|
123
|
+
) {
|
|
124
|
+
const { hashLen } = config;
|
|
125
|
+
const grepSchema = createGrepSchema(config.grep);
|
|
533
126
|
const backend: GrepBackend = {
|
|
534
|
-
|
|
127
|
+
search: runRgTextView,
|
|
535
128
|
runRgPaths,
|
|
536
129
|
resolveIgnoreCase,
|
|
537
|
-
|
|
538
|
-
createLinePredicate,
|
|
130
|
+
probeRegex,
|
|
539
131
|
...overrides,
|
|
540
132
|
};
|
|
541
133
|
|
|
@@ -543,19 +135,24 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
|
|
|
543
135
|
name: "grep" as const,
|
|
544
136
|
label: "grep",
|
|
545
137
|
description:
|
|
546
|
-
"Search
|
|
138
|
+
"Search file contents with ripgrep. Content mode returns LINE#HASH anchors usable by edit; files/count modes return paths or matching-line counts. CRLF is searched as LF. Directory searches respect ignore rules and skip linked directories.",
|
|
547
139
|
promptSnippet: "Search file contents with ripgrep",
|
|
548
140
|
promptGuidelines: [
|
|
549
|
-
"Prefer
|
|
550
|
-
|
|
551
|
-
"
|
|
552
|
-
"
|
|
141
|
+
"Prefer grep for file-content searches; use another tool for ignored or linked directories.",
|
|
142
|
+
'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
|
|
143
|
+
"In grep, set literal:true for code with regex punctuation; grep regex is ripgrep (Rust) syntax without lookaround or backreferences.",
|
|
144
|
+
"In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
|
|
145
|
+
"In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
|
|
146
|
+
"Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
|
|
553
147
|
],
|
|
554
|
-
parameters:
|
|
148
|
+
parameters: grepSchema,
|
|
555
149
|
|
|
556
150
|
renderShell: "default" as const,
|
|
557
151
|
|
|
558
|
-
renderCall(
|
|
152
|
+
renderCall(
|
|
153
|
+
args: Static<GrepSchema>,
|
|
154
|
+
theme: Parameters<NonNullable<GrepTool["renderCall"]>>[1],
|
|
155
|
+
) {
|
|
559
156
|
const rawPattern = args?.pattern;
|
|
560
157
|
const patternText = Array.isArray(rawPattern)
|
|
561
158
|
? rawPattern.join(" | ")
|
|
@@ -566,26 +163,19 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
|
|
|
566
163
|
theme.fg("toolTitle", theme.bold("grep ")) +
|
|
567
164
|
theme.fg("accent", `/${patternText}/`) +
|
|
568
165
|
theme.fg("toolOutput", ` in ${pathText}`);
|
|
569
|
-
if (args?.matchMode === "all") text += theme.fg("accent", " all");
|
|
570
|
-
if (args?.excludePattern) {
|
|
571
|
-
const ex = Array.isArray(args.excludePattern)
|
|
572
|
-
? args.excludePattern.join(",")
|
|
573
|
-
: args.excludePattern;
|
|
574
|
-
text += theme.fg("toolOutput", ` -v:${ex}`);
|
|
575
|
-
}
|
|
576
|
-
if (args?.wordMatch) text += theme.fg("toolOutput", " -w");
|
|
577
166
|
if (args?.glob) text += theme.fg("toolOutput", ` (${toArray(args.glob).join(", ")})`);
|
|
578
|
-
if (args?.pcre2) text += theme.fg("toolOutput", " pcre2");
|
|
579
|
-
if (args?.multiline) text += theme.fg("toolOutput", " multiline");
|
|
580
|
-
if (args?.noIgnore) text += theme.fg("toolOutput", " no-ignore");
|
|
581
|
-
if (args?.follow) text += theme.fg("toolOutput", " follow");
|
|
582
167
|
if (args?.outputMode && args.outputMode !== "content")
|
|
583
168
|
text += theme.fg("success", ` → ${args.outputMode}`);
|
|
584
169
|
if (args?.limit !== undefined) text += theme.fg("toolOutput", ` limit ${args.limit}`);
|
|
585
170
|
return new Text(text, 0, 0);
|
|
586
171
|
},
|
|
587
172
|
|
|
588
|
-
renderResult(
|
|
173
|
+
renderResult(
|
|
174
|
+
result: Parameters<NonNullable<GrepTool["renderResult"]>>[0],
|
|
175
|
+
{ isPartial, expanded }: Parameters<NonNullable<GrepTool["renderResult"]>>[1],
|
|
176
|
+
theme: Parameters<NonNullable<GrepTool["renderResult"]>>[2],
|
|
177
|
+
context: Parameters<NonNullable<GrepTool["renderResult"]>>[3],
|
|
178
|
+
) {
|
|
589
179
|
if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
|
|
590
180
|
if (context?.isError) return renderToolError(result, theme);
|
|
591
181
|
const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
|
|
@@ -601,266 +191,117 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
|
|
|
601
191
|
|
|
602
192
|
async execute(
|
|
603
193
|
_toolCallId: string,
|
|
604
|
-
params:
|
|
194
|
+
params: Static<GrepSchema>,
|
|
605
195
|
signal: AbortSignal | undefined,
|
|
606
|
-
_onUpdate:
|
|
607
|
-
)
|
|
608
|
-
|
|
609
|
-
const anchors = createAnchorFormatter();
|
|
196
|
+
_onUpdate: Parameters<GrepTool["execute"]>[3],
|
|
197
|
+
) {
|
|
198
|
+
throwIfCancelled(signal);
|
|
199
|
+
const anchors = createAnchorFormatter(hashLen);
|
|
610
200
|
const warnings: string[] = [];
|
|
611
201
|
|
|
612
202
|
const patterns = toArray(params.pattern).map(normalizeLineEndings);
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
throw new Error("pattern must not be empty");
|
|
616
|
-
}
|
|
617
|
-
|
|
203
|
+
const effectiveLimit = params.limit ?? config.grep.defaultLimit;
|
|
204
|
+
const context = params.context ?? config.grep.defaultContext;
|
|
618
205
|
const rgPath = bundledRgPath;
|
|
619
|
-
const excludes = toArray(params.excludePattern).map(normalizeLineEndings);
|
|
620
|
-
const matchMode: "any" | "all" = params.matchMode ?? "any";
|
|
621
206
|
const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
|
|
207
|
+
const multiline = params.multiline ?? false;
|
|
622
208
|
const globs = toArray(params.glob);
|
|
623
|
-
const engine: SearchModes["engine"] = params.pcre2 ? "pcre2" : "default";
|
|
624
|
-
const multiline = params.multiline === true;
|
|
625
|
-
if (params.pcre2 === true && params.literal === true) {
|
|
626
|
-
throw new Error("pcre2:true cannot be combined with literal:true. Remove pcre2 for literal searches.");
|
|
627
|
-
}
|
|
628
|
-
const allPatterns = [...patterns, ...excludes];
|
|
629
209
|
const literal = await resolveLiteralMode(
|
|
630
|
-
|
|
210
|
+
patterns,
|
|
211
|
+
params.literal,
|
|
212
|
+
multiline,
|
|
213
|
+
rgPath,
|
|
214
|
+
backend,
|
|
215
|
+
signal,
|
|
216
|
+
patterns.length === 1,
|
|
631
217
|
);
|
|
632
|
-
const literalFallback =
|
|
633
|
-
|
|
634
|
-
|
|
218
|
+
const literalFallback =
|
|
219
|
+
params.literal === undefined &&
|
|
220
|
+
literal &&
|
|
221
|
+
patterns.some((pattern) => REGEX_SYNTAX.test(pattern));
|
|
222
|
+
const literalFallbackNotice = literalFallback
|
|
223
|
+
? formatLiteralFallbackNotice(patterns)
|
|
224
|
+
: undefined;
|
|
635
225
|
const matcherIgnoreCase = await backend.resolveIgnoreCase(
|
|
636
|
-
rgPath,
|
|
226
|
+
rgPath,
|
|
227
|
+
patterns,
|
|
228
|
+
{ literal, multiline },
|
|
229
|
+
params.ignoreCase,
|
|
230
|
+
signal,
|
|
637
231
|
);
|
|
638
|
-
const modes: SearchModes = {
|
|
639
|
-
const ctx =
|
|
640
|
-
const searchPaths = (
|
|
641
|
-
const values = toArray(params.path);
|
|
642
|
-
return (values.length ? values : ["."]).map((path) => canonicalPath(cwd, path));
|
|
643
|
-
})();
|
|
232
|
+
const modes: SearchModes = { literal, ignoreCase: matcherIgnoreCase, multiline };
|
|
233
|
+
const ctx = context;
|
|
234
|
+
const { searchPaths, pathInfo } = await resolveSearchPaths(cwd, params.path);
|
|
644
235
|
let scope: SearchScope = {
|
|
645
236
|
globs,
|
|
646
|
-
noIgnore:
|
|
647
|
-
follow:
|
|
237
|
+
noIgnore: false,
|
|
238
|
+
follow: false,
|
|
648
239
|
searchPaths,
|
|
649
240
|
};
|
|
650
241
|
|
|
651
|
-
const pathInfo: SearchPathInfo[] = [];
|
|
652
|
-
for (const searchPath of searchPaths) {
|
|
653
|
-
try { pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() }); }
|
|
654
|
-
catch { throw new Error(`Path not found: ${searchPath}`); }
|
|
655
|
-
}
|
|
656
242
|
scope = {
|
|
657
243
|
...scope,
|
|
658
|
-
searchPaths: await filterExplicitFilesByGlob(
|
|
244
|
+
searchPaths: await filterExplicitFilesByGlob(
|
|
245
|
+
backend,
|
|
246
|
+
rgPath,
|
|
247
|
+
scope,
|
|
248
|
+
pathInfo,
|
|
249
|
+
signal,
|
|
250
|
+
warnings,
|
|
251
|
+
),
|
|
659
252
|
};
|
|
660
|
-
if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
|
|
661
|
-
throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
const effectiveLimit = Math.max(1, limit ?? DEFAULT_LIMIT);
|
|
665
|
-
const complex = engine === "pcre2" || multiline;
|
|
666
|
-
let raw: RgMatch[];
|
|
667
|
-
let matchLimitReached: boolean;
|
|
668
|
-
let strictIdentities: Map<string, FileIdentity> | undefined;
|
|
669
|
-
let linesTruncated = false;
|
|
670
253
|
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
matchLimitReached = false;
|
|
687
|
-
raw = [];
|
|
688
|
-
const args = [
|
|
689
|
-
...matcherArgs(modes, !!wordMatch),
|
|
690
|
-
"--json",
|
|
691
|
-
"--line-number",
|
|
692
|
-
...scopeArgs(scope),
|
|
693
|
-
];
|
|
694
|
-
for (const pattern of matchMode === "all" ? patterns.slice(0, 1) : patterns) args.push("-e", pattern);
|
|
695
|
-
args.push("--", ...scope.searchPaths);
|
|
696
|
-
|
|
697
|
-
const andPredicates = matchMode === "all"
|
|
698
|
-
? patterns.slice(1).map((pattern) => backend.createLinePredicate(rgPath, [pattern], modes, !!wordMatch, signal))
|
|
699
|
-
: [];
|
|
700
|
-
const exclusionPredicate = excludes.length
|
|
701
|
-
? backend.createLinePredicate(rgPath, excludes, modes, false, signal)
|
|
702
|
-
: undefined;
|
|
703
|
-
const predicates: LinePredicate[] = [...andPredicates, ...(exclusionPredicate ? [exclusionPredicate] : [])];
|
|
704
|
-
const batch: { filePath: string; lineNumber: number; line: Buffer; column: number }[] = [];
|
|
705
|
-
let batchBytes = 0;
|
|
706
|
-
const flushBatch = async (): Promise<boolean> => {
|
|
707
|
-
const candidates = batch.splice(0);
|
|
708
|
-
batchBytes = 0;
|
|
709
|
-
const lines = candidates.map(({ line }) => line);
|
|
710
|
-
const decisions = await Promise.all(predicates.map((predicate) => predicate(lines)));
|
|
711
|
-
for (let index = 0; index < candidates.length; index++) {
|
|
712
|
-
if (!decisions.every((results, predicate) =>
|
|
713
|
-
predicate < andPredicates.length ? results[index] : !results[index],
|
|
714
|
-
)) continue;
|
|
715
|
-
raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber, column: candidates[index].column });
|
|
716
|
-
matchCount++;
|
|
717
|
-
if (matchCount >= effectiveLimit) {
|
|
718
|
-
matchLimitReached = true;
|
|
719
|
-
return false;
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
return true;
|
|
723
|
-
};
|
|
724
|
-
const resolvedPaths = new Map<string, string>();
|
|
725
|
-
const seenMatches = new Set<string>();
|
|
726
|
-
const run = await backend.runRg(rgPath, args, signal, async (line) => {
|
|
727
|
-
if (matchCount >= effectiveLimit) return false;
|
|
728
|
-
let event: any;
|
|
729
|
-
try { event = JSON.parse(line); } catch { return true; }
|
|
730
|
-
if (event.type !== "match") return true;
|
|
731
|
-
const data = event.data;
|
|
732
|
-
if (!data?.path || !data?.lines || !Number.isSafeInteger(data.line_number)) return true;
|
|
733
|
-
const reportedPath = resolve(rgText(data.path));
|
|
734
|
-
let filePath = reportedPath;
|
|
735
|
-
if (scope.follow) {
|
|
736
|
-
filePath = resolvedPaths.get(reportedPath) ?? await realpath(reportedPath);
|
|
737
|
-
resolvedPaths.set(reportedPath, filePath);
|
|
738
|
-
}
|
|
739
|
-
const matchKey = `${filePath}\0${data.line_number}`;
|
|
740
|
-
if (seenMatches.has(matchKey)) return true;
|
|
741
|
-
seenMatches.add(matchKey);
|
|
742
|
-
const bytes = rgBytes(data.lines);
|
|
743
|
-
batch.push({ filePath, lineNumber: data.line_number, line: bytes,
|
|
744
|
-
column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length });
|
|
745
|
-
batchBytes += bytes.length;
|
|
746
|
-
if (predicates.length === 0 || batch.length >= FILTER_BATCH_SIZE || batchBytes >= FILTER_BATCH_BYTES) {
|
|
747
|
-
return flushBatch();
|
|
748
|
-
}
|
|
749
|
-
return true;
|
|
750
|
-
});
|
|
751
|
-
if (signal?.aborted) throw new Error("Operation aborted");
|
|
752
|
-
recordSearchDiagnostics(run, warnings);
|
|
753
|
-
if (batch.length && matchCount < effectiveLimit) await flushBatch();
|
|
754
|
-
}
|
|
254
|
+
const result =
|
|
255
|
+
scope.searchPaths.length === 0
|
|
256
|
+
? { raw: [], matchLimitReached: false, revisions: new Map<string, string>() }
|
|
257
|
+
: await searchMatches({
|
|
258
|
+
backend,
|
|
259
|
+
rgPath,
|
|
260
|
+
scope,
|
|
261
|
+
patterns,
|
|
262
|
+
modes,
|
|
263
|
+
limit: effectiveLimit,
|
|
264
|
+
outputMode,
|
|
265
|
+
signal,
|
|
266
|
+
warnings,
|
|
267
|
+
});
|
|
268
|
+
const { raw, matchLimitReached } = result;
|
|
755
269
|
|
|
756
270
|
if (raw.length === 0) {
|
|
757
|
-
if (warnings.length)
|
|
271
|
+
if (warnings.length)
|
|
272
|
+
throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
|
|
758
273
|
return {
|
|
759
|
-
content: [
|
|
274
|
+
content: [
|
|
275
|
+
{
|
|
276
|
+
type: "text" as const,
|
|
277
|
+
text:
|
|
278
|
+
"No matches found" +
|
|
279
|
+
(literalFallbackNotice ? `\n\n[${literalFallbackNotice}]` : ""),
|
|
280
|
+
},
|
|
281
|
+
],
|
|
760
282
|
details: undefined,
|
|
761
283
|
};
|
|
762
284
|
}
|
|
763
285
|
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
const content = decodeEditableText(bytes);
|
|
784
|
-
if (strictIdentities) {
|
|
785
|
-
const baseline = strictIdentities.get(filePath);
|
|
786
|
-
if (!baseline || !sameIdentity(baseline, await fileIdentity(filePath))) {
|
|
787
|
-
throw new Error("File changed during search; rerun the query.");
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
return splitLines(content);
|
|
791
|
-
};
|
|
792
|
-
|
|
793
|
-
const formatPath = (filePath: string): string => {
|
|
794
|
-
const absolute = resolve(cwd, filePath);
|
|
795
|
-
const rel = relative(cwd, absolute);
|
|
796
|
-
return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
|
797
|
-
? rel.replace(/\\/g, "/")
|
|
798
|
-
: absolute;
|
|
799
|
-
};
|
|
800
|
-
|
|
801
|
-
const blocks: string[] = [];
|
|
802
|
-
if (outputMode === "content") {
|
|
803
|
-
for (const [filePath, matchLines] of byFile) {
|
|
804
|
-
const lines = await getFile(filePath);
|
|
805
|
-
if (!lines) continue;
|
|
806
|
-
const columns = new Map(matchLines.map(match => [match.lineNumber, match.column]));
|
|
807
|
-
// Context windows are rebuilt from surviving matches so context
|
|
808
|
-
// lines of a filtered-out match never leak.
|
|
809
|
-
const windowSet = new Set<number>();
|
|
810
|
-
for (const { lineNumber } of matchLines) {
|
|
811
|
-
for (
|
|
812
|
-
let n = Math.max(1, lineNumber - ctx);
|
|
813
|
-
n <= Math.min(lines.length, lineNumber + ctx);
|
|
814
|
-
n++
|
|
815
|
-
) windowSet.add(n);
|
|
816
|
-
}
|
|
817
|
-
const header = `${formatPath(filePath)} · ${matchLines.length} match${matchLines.length !== 1 ? "es" : ""}\n`;
|
|
818
|
-
const rows: string[] = [];
|
|
819
|
-
for (const n of [...windowSet].sort((a, b) => a - b)) {
|
|
820
|
-
const content = lines[n - 1] ?? "";
|
|
821
|
-
const { text: display, wasTruncated } = previewLine(displayCarriageReturns(content), columns.get(n));
|
|
822
|
-
if (wasTruncated) linesTruncated = true;
|
|
823
|
-
rows.push(anchors.row(n, content, display));
|
|
824
|
-
}
|
|
825
|
-
blocks.push(`${header}${rows.join("\n")}`);
|
|
826
|
-
}
|
|
827
|
-
} else if (outputMode === "files") {
|
|
828
|
-
for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
|
|
829
|
-
} else {
|
|
830
|
-
let total = 0;
|
|
831
|
-
for (const [filePath, matchLines] of byFile) {
|
|
832
|
-
blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
|
|
833
|
-
total += matchLines.length;
|
|
834
|
-
}
|
|
835
|
-
blocks.push(
|
|
836
|
-
`Total: ${total} match${total !== 1 ? "es" : ""} in ${byFile.size} file${byFile.size !== 1 ? "s" : ""}`,
|
|
837
|
-
);
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
if (!blocks.length && warnings.length) throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
|
|
841
|
-
let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
|
|
842
|
-
const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
|
|
843
|
-
output = truncation.content;
|
|
844
|
-
|
|
845
|
-
const notices: string[] = literalFallback ? [LITERAL_FALLBACK_NOTICE] : [];
|
|
846
|
-
if (matchLimitReached) {
|
|
847
|
-
notices.push(
|
|
848
|
-
`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
|
|
849
|
-
);
|
|
850
|
-
}
|
|
851
|
-
if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
|
|
852
|
-
if (linesTruncated) {
|
|
853
|
-
notices.push(
|
|
854
|
-
`Partial line previews show up to ${GREP_MAX_LINE_LENGTH} characters near a match (context-only lines show the start). Columns are 1-based UTF-16 positions; anchors hash full lines. Use read for full content`,
|
|
855
|
-
);
|
|
856
|
-
}
|
|
857
|
-
if (notices.length) output += `\n\n[${notices.join(". ")}]`;
|
|
858
|
-
output += formatSearchWarnings(warnings);
|
|
859
|
-
|
|
860
|
-
return {
|
|
861
|
-
content: [{ type: "text" as const, text: output }],
|
|
862
|
-
details: warnings.length ? { incomplete: true } : undefined,
|
|
863
|
-
};
|
|
286
|
+
const { blocks, linesTruncated } = await formatMatches({
|
|
287
|
+
cwd,
|
|
288
|
+
raw,
|
|
289
|
+
outputMode,
|
|
290
|
+
context: ctx,
|
|
291
|
+
anchors,
|
|
292
|
+
signal,
|
|
293
|
+
warnings,
|
|
294
|
+
searchRevisions: result.revisions,
|
|
295
|
+
});
|
|
296
|
+
return assembleGrepOutput({
|
|
297
|
+
blocks,
|
|
298
|
+
warnings,
|
|
299
|
+
outputMode,
|
|
300
|
+
literalFallbackNotice,
|
|
301
|
+
matchLimitReached,
|
|
302
|
+
effectiveLimit,
|
|
303
|
+
linesTruncated,
|
|
304
|
+
});
|
|
864
305
|
},
|
|
865
|
-
};
|
|
306
|
+
} satisfies GrepTool;
|
|
866
307
|
}
|