@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 +78 -369
- package/README.zh-CN.md +162 -0
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +11 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +328 -161
- package/src/core/apply.ts +129 -95
- package/src/core/case-fold.test.ts +44 -0
- package/src/core/case-fold.ts +77 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +184 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +32 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +51 -0
- package/src/core/replace-schema.ts +41 -0
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +40 -56
- package/src/core/search-analysis.test.ts +208 -0
- package/src/core/search-analysis.ts +379 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +20 -17
- package/src/index.ts +24 -16
- package/src/integration/config-registration.test.ts +42 -28
- package/src/integration/fusion-dispatch.test.ts +62 -127
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +273 -0
- package/src/integration/grep-js-completeness.test.ts +218 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +133 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +407 -0
- package/src/integration/grep-rg.test.ts +294 -436
- package/src/integration/grep-scan-budget.test.ts +111 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +56 -1
- package/src/integration/model-budget-lifecycle.test.ts +137 -0
- package/src/integration/mutation-file-types.test.ts +12 -26
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +97 -0
- package/src/integration/publication-read-changes.test.ts +376 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +36 -0
- package/src/integration/replace-worker-boundary.test.ts +117 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +54 -0
- package/src/pi/action-fusion.test.ts +256 -251
- package/src/pi/action-fusion.ts +121 -332
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +16 -3
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +46 -0
- package/src/pi/argument-error.ts +76 -0
- package/src/pi/argument-format.test.ts +197 -0
- package/src/pi/argument-validation.test.ts +780 -49
- package/src/pi/argument-validation.ts +55 -58
- package/src/pi/budgets.ts +48 -21
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +29 -15
- package/src/pi/config.ts +27 -13
- package/src/pi/diagnostic-buffer.test.ts +51 -16
- package/src/pi/diagnostic-buffer.ts +13 -16
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +103 -99
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +407 -429
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +265 -88
- package/src/pi/failure-context.ts +165 -181
- package/src/pi/failure-path.test.ts +179 -117
- package/src/pi/file-commit.test.ts +90 -73
- package/src/pi/file-commit.ts +216 -178
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +233 -51
- package/src/pi/fusion-card.ts +246 -142
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +191 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +187 -151
- package/src/pi/grep-render.ts +31 -25
- package/src/pi/grep-scope.ts +62 -54
- package/src/pi/grep-search.ts +327 -241
- package/src/pi/grep-tool.ts +126 -147
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +813 -713
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +6 -7
- package/src/pi/mutation-result.test.ts +45 -91
- package/src/pi/mutation-result.ts +86 -114
- package/src/pi/mutation-runner.ts +81 -81
- package/src/pi/output-budgets.test.ts +175 -0
- package/src/pi/path.ts +10 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +108 -142
- package/src/pi/read.test.ts +155 -96
- package/src/pi/regex-worker-contract.ts +55 -0
- package/src/pi/regex-worker.ts +95 -0
- package/src/pi/registration.test.ts +148 -124
- package/src/pi/render.test.ts +361 -84
- package/src/pi/render.ts +150 -32
- package/src/pi/replace-regex.ts +13 -48
- package/src/pi/replace-tool.ts +52 -158
- package/src/pi/replace-worker-contract.ts +10 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +191 -340
- package/src/pi/report-cause.ts +103 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +524 -0
- package/src/pi/report.test.ts +343 -0
- package/src/pi/report.ts +285 -0
- package/src/pi/result-safety.test.ts +216 -481
- package/src/pi/rg-process.test.ts +101 -76
- package/src/pi/rg-process.ts +130 -177
- package/src/pi/rg-regex.test.ts +67 -0
- package/src/pi/rg-regex.ts +715 -0
- package/src/pi/text-stream.test.ts +97 -69
- package/src/pi/text-stream.ts +97 -76
- package/src/pi/tool-call.testing.ts +20 -46
- package/src/pi/write-tool.ts +50 -41
- package/src/pi/write.test.ts +71 -95
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +324 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/integration/forget-grep.test.ts +0 -98
- package/src/pi/forget-tool.ts +0 -268
- package/src/pi/forget.test.ts +0 -343
- package/src/pi/forget.testing.ts +0 -273
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
package/src/pi/grep-search.ts
CHANGED
|
@@ -1,267 +1,353 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Native RegExp matching in a bounded worker pool. grep-candidates supplies absolute paths
|
|
3
|
+
* and optional candidate lines; this module owns queue backpressure, worker cleanup, and
|
|
4
|
+
* each matched file's revision.
|
|
5
|
+
*
|
|
6
|
+
* @module pi-hashline-edit/pi
|
|
7
|
+
*/
|
|
8
|
+
import { stat } from "node:fs/promises";
|
|
9
|
+
import { availableParallelism } from "node:os";
|
|
10
|
+
import { countLines } from "../core/lines.ts";
|
|
11
|
+
import type { GrepQuery, LineSearchInput, SearchInput } from "../core/search.ts";
|
|
12
|
+
import { SEARCH_RESULT_SCHEMA, type SearchResult } from "../core/search-schema.ts";
|
|
4
13
|
import { scanTextFile } from "./text-stream.ts";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
runRgPaths,
|
|
13
|
-
type SearchModes,
|
|
14
|
-
} from "./rg-process.ts";
|
|
15
|
-
import { submatchesToLineRanges } from "./rg-line-ranges.ts";
|
|
16
|
-
import { rawMatchRevision, type RawMatchRevision } from "./rg-match-bytes.ts";
|
|
17
|
-
import { searchChangedError, throwIfCancelled } from "./error-text.ts";
|
|
14
|
+
import { recordSearchDiagnostics, type GrepBackend } from "./rg-process.ts";
|
|
15
|
+
import type { SearchScope } from "./grep-scope.ts";
|
|
16
|
+
import { listCandidates, type Candidate } from "./grep-candidates.ts";
|
|
17
|
+
import { withRegexWorker } from "./regex-worker.ts";
|
|
18
|
+
import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
|
|
19
|
+
import { fileReadWarning, throwIfCancelled } from "./error-text.ts";
|
|
20
|
+
import { formatByteSize } from "./budgets.ts";
|
|
18
21
|
|
|
19
|
-
/**
|
|
20
|
-
export
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
? `ripgrep exited with code ${result.code}`
|
|
25
|
-
: "");
|
|
26
|
-
if (!message) return;
|
|
27
|
-
if (!warnings) throw new Error(message);
|
|
28
|
-
warnings.push(message);
|
|
22
|
+
/** Matching physical lines in ascending order, with the revision they were searched against. */
|
|
23
|
+
export interface GrepFileMatch {
|
|
24
|
+
readonly filePath: string;
|
|
25
|
+
readonly rows: readonly SearchResult["lines"][number][];
|
|
26
|
+
readonly snapshot: SearchFileSnapshot;
|
|
29
27
|
}
|
|
30
28
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
matchedText?: string;
|
|
36
|
-
/** Shared whole-event digest: a limited row still depends on every byte in its raw match. */
|
|
37
|
-
rawMatch?: RawMatchRevision;
|
|
29
|
+
/** A matched file as it was searched; content output re-verifies it before display. */
|
|
30
|
+
interface SearchFileSnapshot {
|
|
31
|
+
readonly revision: string;
|
|
32
|
+
readonly validUtf8: boolean;
|
|
38
33
|
}
|
|
39
34
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
35
|
+
/** Whole-file input of a multiline query; README's search limits link here. */
|
|
36
|
+
export const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
|
|
37
|
+
/** Line-mode requests end after a line feed once they reach this many UTF-16 units. */
|
|
38
|
+
const SEARCH_CHUNK_UNITS = 1024 * 1024;
|
|
39
|
+
/** Maximum UTF-16 code units in one physical line; independent of its encoded byte length. */
|
|
40
|
+
const MAX_SEARCH_LINE_UNITS = MAX_MULTILINE_SEARCH_BYTES;
|
|
41
|
+
const MAX_SEARCH_HEAP_MB = 512;
|
|
42
|
+
const MAX_SEARCH_WORKERS = 4;
|
|
43
|
+
const SEARCH_WORKERS = Math.max(1, Math.min(MAX_SEARCH_WORKERS, availableParallelism() - 1));
|
|
44
|
+
/** Listed files that may wait, searched or not, for an earlier file's result to commit. */
|
|
45
|
+
const MAX_UNCOMMITTED_FILES = 16 * SEARCH_WORKERS;
|
|
46
|
+
class SearchFileLimitError extends Error {
|
|
47
|
+
constructor(multiline: boolean) {
|
|
48
|
+
super(
|
|
49
|
+
multiline
|
|
50
|
+
? `Multiline search requires a file of at most ${formatByteSize(MAX_MULTILINE_SEARCH_BYTES)}.`
|
|
51
|
+
: `Search requires lines of at most ${MAX_SEARCH_LINE_UNITS} UTF-16 code units.`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
49
54
|
}
|
|
50
55
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
+
/** A worker failure inside a file scan; never classify it as a file-read warning. */
|
|
57
|
+
class ScanWorkerFailure {
|
|
58
|
+
readonly error: unknown;
|
|
59
|
+
constructor(error: unknown) {
|
|
60
|
+
this.error = error;
|
|
61
|
+
}
|
|
56
62
|
}
|
|
57
63
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
readonly
|
|
64
|
-
readonly
|
|
64
|
+
const decodeReply = workerReplyDecoder(SEARCH_RESULT_SCHEMA);
|
|
65
|
+
type Rows = SearchResult["lines"];
|
|
66
|
+
type Run = (input: SearchInput | LineSearchInput) => Promise<SearchResult>;
|
|
67
|
+
/** A listed candidate and its position in the listing. */
|
|
68
|
+
interface Queued {
|
|
69
|
+
readonly candidate: Candidate;
|
|
70
|
+
readonly position: number;
|
|
65
71
|
}
|
|
72
|
+
/** A searched candidate, including fatal failures that only matter before the ordered cutoff. */
|
|
73
|
+
type Settled =
|
|
74
|
+
| { readonly file?: GrepFileMatch; readonly warning?: string }
|
|
75
|
+
| { readonly error: unknown };
|
|
66
76
|
|
|
67
|
-
|
|
77
|
+
/**
|
|
78
|
+
* The candidate lines among the next lines of a request source, as the LF view shows them.
|
|
79
|
+
* `next` indexes the first candidate in source; a returned line number is 1-based in source.
|
|
80
|
+
* `lengths` holds each selected line's length, and `lines` the lines a worker matches.
|
|
81
|
+
*/
|
|
82
|
+
function selectLines(source: string, offset: number, wanted: readonly number[], next: number) {
|
|
83
|
+
const numbers: number[] = [];
|
|
84
|
+
const lengths: number[] = [];
|
|
85
|
+
const texts: string[] = [];
|
|
86
|
+
let start = 0;
|
|
87
|
+
let line = offset + 1;
|
|
88
|
+
for (; next < wanted.length; next++) {
|
|
89
|
+
while (line < wanted[next] && start < source.length) {
|
|
90
|
+
const lf = source.indexOf("\n", start);
|
|
91
|
+
start = lf === -1 ? source.length : lf + 1;
|
|
92
|
+
line++;
|
|
93
|
+
}
|
|
94
|
+
if (start >= source.length) break;
|
|
95
|
+
const lf = source.indexOf("\n", start);
|
|
96
|
+
// A CRLF line feeds its view without the CR; a CR before the end of the file stays.
|
|
97
|
+
const end = lf === -1 ? source.length : source[lf - 1] === "\r" ? lf - 1 : lf;
|
|
98
|
+
numbers.push(line - offset);
|
|
99
|
+
lengths.push(end - start);
|
|
100
|
+
texts.push(source.slice(start, end), "\n");
|
|
101
|
+
}
|
|
102
|
+
return { numbers, lengths, lines: texts.join("") };
|
|
103
|
+
}
|
|
68
104
|
|
|
69
|
-
/**
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
105
|
+
/**
|
|
106
|
+
* Match one file. Without multiline each line matches alone, so requests split after a
|
|
107
|
+
* line feed; a multiline query sends the whole file. Undefined when the file has NUL.
|
|
108
|
+
*/
|
|
109
|
+
async function searchFile(
|
|
110
|
+
{ filePath, lines: wanted }: Candidate,
|
|
111
|
+
query: GrepQuery,
|
|
112
|
+
room: () => number,
|
|
113
|
+
run: Run,
|
|
114
|
+
signal: AbortSignal,
|
|
115
|
+
): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
|
|
116
|
+
if (query.multiline && (await stat(filePath)).size > MAX_MULTILINE_SEARCH_BYTES)
|
|
117
|
+
throw new SearchFileLimitError(true);
|
|
118
|
+
const rows: Rows = [];
|
|
119
|
+
let lineOffset = 0;
|
|
120
|
+
let nextWanted = 0;
|
|
121
|
+
const check = async (input: SearchInput | LineSearchInput, lines: number) => {
|
|
122
|
+
let result: SearchResult;
|
|
123
|
+
try {
|
|
124
|
+
result = await run(input);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
throw new ScanWorkerFailure(error);
|
|
127
|
+
}
|
|
128
|
+
if (result.totalLines !== lines || result.lines.length > input.limit)
|
|
129
|
+
throw invalidWorkerResult();
|
|
130
|
+
let previous = 0;
|
|
131
|
+
for (const row of result.lines) {
|
|
132
|
+
if (row.lineNumber <= previous || row.lineNumber > lines) throw invalidWorkerResult();
|
|
133
|
+
previous = row.lineNumber;
|
|
134
|
+
}
|
|
135
|
+
return result.lines;
|
|
136
|
+
};
|
|
137
|
+
const send = async (source: string) => {
|
|
138
|
+
const lines = countLines(source);
|
|
139
|
+
let candidates = lines;
|
|
140
|
+
if (wanted) {
|
|
141
|
+
let end = nextWanted;
|
|
142
|
+
while (end < wanted.length && wanted[end] <= lineOffset + lines) end++;
|
|
143
|
+
candidates = end - nextWanted;
|
|
144
|
+
}
|
|
145
|
+
const limit = room() - rows.length;
|
|
146
|
+
if (candidates > 0 && limit > 0) {
|
|
147
|
+
// Selecting most lines costs more than matching them all, with the same results.
|
|
148
|
+
if (wanted && candidates * 2 <= lines) {
|
|
149
|
+
const selected = selectLines(source, lineOffset, wanted, nextWanted);
|
|
150
|
+
const found = await check({ lines: selected.lines, query, limit }, candidates);
|
|
151
|
+
for (const { lineNumber, column } of found) {
|
|
152
|
+
if (column > selected.lengths[lineNumber - 1]) throw invalidWorkerResult();
|
|
153
|
+
rows.push({ lineNumber: lineOffset + selected.numbers[lineNumber - 1], column });
|
|
154
|
+
}
|
|
155
|
+
} else {
|
|
156
|
+
for (const { lineNumber, column } of await check({ source, query, limit }, lines)) {
|
|
157
|
+
if (column > source.length) throw invalidWorkerResult();
|
|
158
|
+
rows.push({ lineNumber: lineOffset + lineNumber, column });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (wanted) nextWanted += candidates;
|
|
163
|
+
lineOffset += lines;
|
|
164
|
+
};
|
|
76
165
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
166
|
+
let pending = "";
|
|
167
|
+
/** Length of pending through its last line feed. */
|
|
168
|
+
let complete = 0;
|
|
169
|
+
let lineUnits = 0;
|
|
170
|
+
const stats = await scanTextFile(filePath, {
|
|
171
|
+
onChunk: async (text, bytesRead) => {
|
|
172
|
+
if (query.multiline) {
|
|
173
|
+
if (bytesRead <= MAX_MULTILINE_SEARCH_BYTES) pending += text;
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
let start = 0;
|
|
177
|
+
for (;;) {
|
|
178
|
+
const lf = text.indexOf("\n", start);
|
|
179
|
+
lineUnits += (lf === -1 ? text.length : lf) - start;
|
|
180
|
+
if (lineUnits > MAX_SEARCH_LINE_UNITS) throw new SearchFileLimitError(false);
|
|
181
|
+
if (lf === -1) break;
|
|
182
|
+
lineUnits = 0;
|
|
183
|
+
complete = pending.length + lf + 1;
|
|
184
|
+
start = lf + 1;
|
|
185
|
+
}
|
|
186
|
+
pending += text;
|
|
187
|
+
if (complete >= SEARCH_CHUNK_UNITS) {
|
|
188
|
+
const source = pending.slice(0, complete);
|
|
189
|
+
pending = pending.slice(complete);
|
|
190
|
+
complete = 0;
|
|
191
|
+
await send(source);
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
signal,
|
|
195
|
+
decoding: "lossy",
|
|
196
|
+
});
|
|
197
|
+
if (stats.hasNul) return undefined;
|
|
198
|
+
if (stats.byteLength > MAX_MULTILINE_SEARCH_BYTES && query.multiline)
|
|
199
|
+
throw new SearchFileLimitError(true);
|
|
200
|
+
await send(pending);
|
|
201
|
+
return {
|
|
202
|
+
rows,
|
|
203
|
+
snapshot: { revision: stats.revision, validUtf8: stats.validUtf8 },
|
|
204
|
+
};
|
|
83
205
|
}
|
|
84
206
|
|
|
85
|
-
/**
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
207
|
+
/**
|
|
208
|
+
* Search every candidate file in scope. Paths stream from rg in listing order into a queue that
|
|
209
|
+
* at most SEARCH_WORKERS workers drain; a worker starts only when no idle one can take a path.
|
|
210
|
+
* Workers finish in any order, so results commit in listing order: every run returns the same
|
|
211
|
+
* files, rows, and warnings, and a limit keeps the first matches in that order.
|
|
212
|
+
*/
|
|
213
|
+
export async function searchFiles(options: {
|
|
214
|
+
readonly backend: GrepBackend;
|
|
215
|
+
readonly rgPath: string;
|
|
216
|
+
readonly scope: SearchScope;
|
|
217
|
+
readonly query: GrepQuery;
|
|
218
|
+
readonly limit: number;
|
|
219
|
+
readonly timeoutMs: number;
|
|
220
|
+
readonly signal?: AbortSignal;
|
|
221
|
+
readonly warnings: string[];
|
|
222
|
+
}) {
|
|
223
|
+
const { backend, rgPath, scope, query, limit, timeoutMs, signal, warnings } = options;
|
|
224
|
+
const files: GrepFileMatch[] = [];
|
|
225
|
+
/** Committed matches; a file still searching gets at most the remaining room. */
|
|
226
|
+
let matches = 0;
|
|
227
|
+
let matchLimitReached = false;
|
|
228
|
+
let failure: { error: unknown } | undefined;
|
|
229
|
+
const failed = new AbortController();
|
|
230
|
+
const poolSignal = signal ? AbortSignal.any([signal, failed.signal]) : failed.signal;
|
|
231
|
+
const fail = (error: unknown) => {
|
|
232
|
+
failure ??= { error };
|
|
233
|
+
failed.abort();
|
|
234
|
+
};
|
|
94
235
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
236
|
+
const queue: Queued[] = [];
|
|
237
|
+
let listed = false;
|
|
238
|
+
const idle: (() => void)[] = [];
|
|
239
|
+
const space: (() => void)[] = [];
|
|
240
|
+
const stopped = () => failure !== undefined || matchLimitReached;
|
|
241
|
+
const releaseAll = () => {
|
|
242
|
+
for (const wake of idle.splice(0)) wake();
|
|
243
|
+
for (const wake of space.splice(0)) wake();
|
|
244
|
+
};
|
|
245
|
+
const next = async (): Promise<Queued | undefined> => {
|
|
246
|
+
while (!queue.length && !listed && !stopped())
|
|
247
|
+
await new Promise<void>((wake) => idle.push(wake));
|
|
248
|
+
space.shift()?.();
|
|
249
|
+
return stopped() ? undefined : queue.shift();
|
|
250
|
+
};
|
|
106
251
|
|
|
107
|
-
/**
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
252
|
+
/** Searched candidates by listing position, until every earlier one has committed. */
|
|
253
|
+
const settled = new Map<number, Settled>();
|
|
254
|
+
let enqueued = 0;
|
|
255
|
+
let committed = 0;
|
|
256
|
+
const commit = () => {
|
|
257
|
+
for (let result = settled.get(committed); result && !stopped(); ) {
|
|
258
|
+
settled.delete(committed++);
|
|
259
|
+
if ("error" in result) fail(result.error);
|
|
260
|
+
else if (result.warning) warnings.push(result.warning);
|
|
261
|
+
else if (result.file) {
|
|
262
|
+
const rows = result.file.rows.slice(0, limit - matches);
|
|
263
|
+
files.push({ ...result.file, rows });
|
|
264
|
+
matches += rows.length;
|
|
265
|
+
if (matches >= limit) matchLimitReached = true;
|
|
266
|
+
}
|
|
267
|
+
result = settled.get(committed);
|
|
268
|
+
}
|
|
269
|
+
releaseAll();
|
|
270
|
+
};
|
|
113
271
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
)
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
}
|
|
272
|
+
const searchPath = async ({ candidate, position }: Queued, run: Run) => {
|
|
273
|
+
const { filePath } = candidate;
|
|
274
|
+
let result: Settled;
|
|
275
|
+
try {
|
|
276
|
+
const found = await searchFile(candidate, query, () => limit - matches, run, poolSignal);
|
|
277
|
+
result = found?.rows.length ? { file: { filePath, ...found } } : {};
|
|
278
|
+
} catch (error) {
|
|
279
|
+
throwIfCancelled(poolSignal);
|
|
280
|
+
const warning =
|
|
281
|
+
error instanceof SearchFileLimitError
|
|
282
|
+
? `${filePath}: ${error.message}`
|
|
283
|
+
: fileReadWarning(filePath, error, poolSignal);
|
|
284
|
+
result = warning
|
|
285
|
+
? { warning }
|
|
286
|
+
: { error: error instanceof ScanWorkerFailure ? error.error : error };
|
|
287
|
+
}
|
|
288
|
+
settled.set(position, result);
|
|
289
|
+
commit();
|
|
290
|
+
// Nothing after a fatal candidate can be needed; retire its worker without reusing a failure.
|
|
291
|
+
return !("error" in result);
|
|
292
|
+
};
|
|
130
293
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
294
|
+
const workers: Promise<void>[] = [];
|
|
295
|
+
const startWorker = () =>
|
|
296
|
+
withRegexWorker<SearchInput | LineSearchInput, SearchResult, void>(
|
|
297
|
+
new URL("./grep-worker.mjs", import.meta.url),
|
|
298
|
+
decodeReply,
|
|
299
|
+
timeoutMs,
|
|
300
|
+
poolSignal,
|
|
301
|
+
async (run) => {
|
|
302
|
+
for (let file = await next(); file !== undefined; file = await next())
|
|
303
|
+
if (!(await searchPath(file, run))) break;
|
|
304
|
+
},
|
|
305
|
+
{ maxOldGenerationSizeMb: MAX_SEARCH_HEAP_MB },
|
|
306
|
+
).catch((error) => {
|
|
307
|
+
fail(error);
|
|
308
|
+
releaseAll();
|
|
309
|
+
});
|
|
139
310
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
311
|
+
const enqueue = async (candidate: Candidate) => {
|
|
312
|
+
if (stopped()) return false;
|
|
313
|
+
queue.push({ candidate, position: enqueued++ });
|
|
314
|
+
if (idle.length) idle.shift()!();
|
|
315
|
+
else if (workers.length < SEARCH_WORKERS) workers.push(startWorker());
|
|
316
|
+
// A slow early file holds back every later result; bound what waits behind it.
|
|
317
|
+
while (
|
|
318
|
+
(queue.length >= SEARCH_WORKERS || enqueued - committed >= MAX_UNCOMMITTED_FILES) &&
|
|
319
|
+
!stopped()
|
|
320
|
+
)
|
|
321
|
+
await new Promise<void>((wake) => space.push(wake));
|
|
322
|
+
return !stopped();
|
|
323
|
+
};
|
|
324
|
+
let selection: Awaited<ReturnType<typeof listCandidates>>;
|
|
325
|
+
try {
|
|
326
|
+
selection = await listCandidates({
|
|
327
|
+
backend,
|
|
328
|
+
rgPath,
|
|
157
329
|
scope,
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const run = await backend.search(rgPath, request, signal, async (line, view) => {
|
|
163
|
-
if (raw.length >= limit) return false;
|
|
164
|
-
let event: RgJsonEvent;
|
|
165
|
-
try {
|
|
166
|
-
event = JSON.parse(line);
|
|
167
|
-
} catch {
|
|
168
|
-
return true;
|
|
169
|
-
}
|
|
170
|
-
if (event.type !== "match") return true;
|
|
171
|
-
const data = event.data;
|
|
172
|
-
if (
|
|
173
|
-
!data?.path ||
|
|
174
|
-
!data.lines ||
|
|
175
|
-
typeof data.line_number !== "number" ||
|
|
176
|
-
!Number.isSafeInteger(data.line_number)
|
|
177
|
-
)
|
|
178
|
-
return true;
|
|
179
|
-
const filePath = resolve(rgText(data.path));
|
|
180
|
-
if (unreadableFiles.has(filePath)) return true;
|
|
181
|
-
let snapshot = snapshots.get(filePath);
|
|
182
|
-
if (view.kind === "raw") {
|
|
183
|
-
if (snapshot && snapshot.revision !== view.snapshot.revision) throw searchChangedError();
|
|
184
|
-
snapshot = view.snapshot;
|
|
185
|
-
snapshots.set(filePath, snapshot);
|
|
186
|
-
}
|
|
187
|
-
if (!snapshot && needsSnapshot) {
|
|
188
|
-
try {
|
|
189
|
-
snapshot = await scanFileSnapshot(filePath, signal);
|
|
190
|
-
if (!snapshot) {
|
|
191
|
-
unreadableFiles.add(filePath);
|
|
192
|
-
return true;
|
|
193
|
-
}
|
|
194
|
-
snapshots.set(filePath, snapshot);
|
|
195
|
-
} catch (error) {
|
|
196
|
-
const warning = fileReadWarning(filePath, error, signal);
|
|
197
|
-
if (!warning) throw error;
|
|
198
|
-
warnings.push(warning);
|
|
199
|
-
unreadableFiles.add(filePath);
|
|
200
|
-
return true;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
if (snapshot && snapshot.validUtf8 !== (view.kind === "lf")) throw searchChangedError();
|
|
204
|
-
const startLine = data.line_number;
|
|
205
|
-
const bytes = rgBytes(data.lines);
|
|
206
|
-
const text = bytes.toString("utf8");
|
|
207
|
-
const rawMatch =
|
|
208
|
-
view.kind === "raw" ? rawMatchRevision(bytes, startLine, data.absolute_offset) : undefined;
|
|
209
|
-
// Valid text is already the LF view; normalizing it twice would strip a content CR.
|
|
210
|
-
const matchedText = (view.kind === "raw" ? normalizeLineEndings(text) : text).replace(
|
|
211
|
-
/\n$/,
|
|
212
|
-
"",
|
|
213
|
-
);
|
|
214
|
-
const addMatch = (match: RgMatch) => {
|
|
215
|
-
const matchKey = `${filePath}\0${match.lineNumber}`;
|
|
216
|
-
if (seenMatches.has(matchKey)) return true;
|
|
217
|
-
seenMatches.add(matchKey);
|
|
218
|
-
raw.push(match);
|
|
219
|
-
if (raw.length >= limit) {
|
|
220
|
-
matchLimitReached = true;
|
|
221
|
-
return false;
|
|
222
|
-
}
|
|
223
|
-
return true;
|
|
224
|
-
};
|
|
225
|
-
if (!modes.multiline) {
|
|
226
|
-
return addMatch({
|
|
227
|
-
filePath,
|
|
228
|
-
lineNumber: startLine,
|
|
229
|
-
column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
|
|
230
|
-
matchedText,
|
|
231
|
-
rawMatch,
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
|
|
235
|
-
const columns = new Map<number, number>();
|
|
236
|
-
const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
|
|
237
|
-
const ranges = submatchesToLineRanges(
|
|
238
|
-
bytes,
|
|
239
|
-
startLine,
|
|
240
|
-
submatches,
|
|
241
|
-
// Multiline always loads a snapshot above.
|
|
242
|
-
snapshot!.totalLines,
|
|
243
|
-
columns,
|
|
244
|
-
);
|
|
245
|
-
const texts = matchedText.split("\n");
|
|
246
|
-
for (const [start, end] of ranges) {
|
|
247
|
-
for (let lineNumber = start; lineNumber < end; lineNumber++) {
|
|
248
|
-
if (
|
|
249
|
-
!addMatch({
|
|
250
|
-
filePath,
|
|
251
|
-
lineNumber,
|
|
252
|
-
column: columns.get(lineNumber),
|
|
253
|
-
matchedText: texts[lineNumber - startLine],
|
|
254
|
-
rawMatch,
|
|
255
|
-
})
|
|
256
|
-
)
|
|
257
|
-
return false;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return true;
|
|
330
|
+
query,
|
|
331
|
+
signal: poolSignal,
|
|
332
|
+
stopped,
|
|
333
|
+
onCandidate: enqueue,
|
|
261
334
|
});
|
|
335
|
+
} catch (error) {
|
|
336
|
+
fail(error);
|
|
337
|
+
throw error;
|
|
338
|
+
} finally {
|
|
339
|
+
listed = true;
|
|
340
|
+
releaseAll();
|
|
341
|
+
await Promise.all(workers);
|
|
262
342
|
throwIfCancelled(signal);
|
|
263
|
-
|
|
264
|
-
if (matchLimitReached) break;
|
|
343
|
+
if (failure) throw failure.error;
|
|
265
344
|
}
|
|
266
|
-
|
|
345
|
+
// After every file's warning, so their order does not depend on when the listing ends.
|
|
346
|
+
if (selection.listing) recordSearchDiagnostics(selection.listing, warnings);
|
|
347
|
+
return {
|
|
348
|
+
files,
|
|
349
|
+
matchLimitReached,
|
|
350
|
+
candidates: selection.candidates,
|
|
351
|
+
scanLimitReached: selection.scanLimitReached,
|
|
352
|
+
};
|
|
267
353
|
}
|