@criogaid/pi-hashline-edit 0.11.0 → 0.13.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/LICENSE +1 -0
- package/README.md +73 -17
- package/README.zh-CN.md +74 -18
- package/package.json +8 -7
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +15 -2
- package/src/core/apply.ts +6 -10
- package/src/core/case-fold.test.ts +16 -25
- package/src/core/case-fold.ts +4 -4
- package/src/core/character-set.test.ts +1 -6
- package/src/core/character-set.ts +7 -61
- package/src/core/regex.ts +2 -32
- package/src/core/replace.test.ts +51 -0
- package/src/core/replace.ts +10 -4
- package/src/core/search-analysis.test.ts +66 -61
- package/src/core/search-analysis.ts +24 -39
- package/src/core/search-matrix.test.ts +2 -2
- package/src/core/search-matrix.testing.ts +6 -16
- package/src/core/search-schema.ts +0 -1
- package/src/core/search.test.ts +6 -19
- package/src/core/search.ts +10 -8
- package/src/index.ts +28 -3
- package/src/integration/config-registration.test.ts +77 -4
- package/src/integration/fusion-dispatch.test.ts +47 -2
- package/src/integration/grep-errors.test.ts +31 -0
- package/src/integration/grep-flags.test.ts +13 -196
- package/src/integration/grep-js-completeness.test.ts +41 -8
- package/src/integration/grep-line-candidates.test.ts +4 -33
- package/src/integration/grep-matrix.test.ts +1 -1
- package/src/integration/grep-path-matrix.test.ts +59 -65
- package/src/integration/grep-prefilter-coverage.test.ts +26 -8
- package/src/integration/grep-process-limits.test.ts +46 -0
- package/src/integration/grep-regex.test.ts +7 -2
- package/src/integration/grep-rg.test.ts +106 -12
- package/src/integration/grep-translation.test.ts +14 -7
- package/src/integration/model-budget-lifecycle.test.ts +41 -2
- package/src/integration/npm-package.test.ts +12 -10
- package/src/integration/npm-package.testing.ts +147 -1
- package/src/integration/replace-package.testing.ts +2 -2
- package/src/integration/report-replay.test.ts +4 -0
- package/src/pi/AGENTS.md +23 -15
- package/src/pi/action-fusion.test.ts +38 -4
- package/src/pi/action-fusion.ts +23 -19
- package/src/pi/argument-diagnostics.ts +28 -48
- package/src/pi/argument-validation.test.ts +103 -6
- package/src/pi/argument-validation.ts +55 -31
- package/src/pi/budgets.ts +19 -10
- package/src/pi/config.test.ts +1 -1
- package/src/pi/diagnostic-buffer.test.ts +1 -0
- package/src/pi/edit-tool.ts +3 -3
- package/src/pi/execute.test.ts +4 -0
- package/src/pi/failure-context.test.ts +24 -3
- package/src/pi/failure-context.ts +36 -42
- package/src/pi/failure-path.test.ts +8 -3
- package/src/pi/file-commit.test.ts +109 -52
- package/src/pi/file-commit.ts +62 -56
- package/src/pi/fusion-card.ts +12 -7
- package/src/pi/grep-candidates.test.ts +5 -5
- package/src/pi/grep-candidates.ts +80 -48
- package/src/pi/grep-matrix.test.ts +14 -29
- package/src/pi/grep-order.test.ts +132 -9
- package/src/pi/grep-output.ts +173 -48
- package/src/pi/grep-render.ts +40 -34
- package/src/pi/grep-rg.testing.ts +9 -6
- package/src/pi/grep-scope.ts +51 -29
- package/src/pi/grep-search.ts +96 -71
- package/src/pi/grep-tool.ts +28 -34
- package/src/pi/grep.test.ts +348 -83
- package/src/pi/model-budgets.test.ts +56 -6
- package/src/pi/model-budgets.ts +7 -4
- package/src/pi/mutation-result.test.ts +25 -1
- package/src/pi/mutation-result.ts +7 -2
- package/src/pi/mutation-runner.ts +4 -5
- package/src/pi/output-budgets.test.ts +3 -1
- package/src/pi/path.ts +18 -4
- package/src/pi/pi.test.ts +22 -0
- package/src/pi/read-delegation.test.ts +119 -0
- package/src/pi/read-tool.ts +109 -61
- package/src/pi/read.test.ts +351 -17
- package/src/pi/regex-worker.test.ts +42 -0
- package/src/pi/regex-worker.ts +17 -11
- package/src/pi/registration.test.ts +157 -102
- package/src/pi/render.test.ts +97 -0
- package/src/pi/render.ts +9 -9
- package/src/pi/replace-tool.ts +5 -2
- package/src/pi/report-schema.ts +75 -37
- package/src/pi/report.test.ts +73 -31
- package/src/pi/report.ts +12 -5
- package/src/pi/rg-process.ts +41 -5
- package/src/pi/rg-regex.test.ts +12 -39
- package/src/pi/rg-regex.ts +31 -79
- package/src/pi/text-stream.test.ts +3 -0
- package/src/pi/text-stream.ts +1 -1
- package/src/testing/regex-translation-corpus.ts +39 -96
package/src/pi/grep-output.ts
CHANGED
|
@@ -4,9 +4,8 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @module pi-hashline-edit/pi
|
|
6
6
|
*/
|
|
7
|
-
import { truncateHead } from "@earendil-works/pi-coding-agent";
|
|
8
7
|
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
9
|
-
import { plainRow, type AnchorFormatter } from "./anchor-format.ts";
|
|
8
|
+
import { displayCarriageReturns, plainRow, type AnchorFormatter } from "./anchor-format.ts";
|
|
10
9
|
import type { GrepFileMatch, searchFiles } from "./grep-search.ts";
|
|
11
10
|
import type { SearchWarning } from "./error-text.ts";
|
|
12
11
|
import { MAX_UNNARROWED_SCAN_BYTES } from "./grep-candidates.ts";
|
|
@@ -14,7 +13,7 @@ import { rereadMatches, type LineCollector } from "./grep-reread.ts";
|
|
|
14
13
|
import { formatByteSize, type OutputBudgets } from "./budgets.ts";
|
|
15
14
|
import { HashlineError } from "../core/errors.ts";
|
|
16
15
|
import { serializePath } from "./path.ts";
|
|
17
|
-
import type { Report, SuccessFacts } from "./report-schema.ts";
|
|
16
|
+
import type { OutcomeVariant, Report, SuccessFacts } from "./report-schema.ts";
|
|
18
17
|
|
|
19
18
|
/** How grep presents matches; the tool's schema offers these and this module formats each. */
|
|
20
19
|
export const GREP_OUTPUT_MODES = ["content", "files", "count"] as const;
|
|
@@ -52,8 +51,8 @@ function searchDiagnostics(
|
|
|
52
51
|
return diagnostics.toString().trimEnd();
|
|
53
52
|
}
|
|
54
53
|
|
|
55
|
-
/** How the search was bounded; stated with success and failure alike. */
|
|
56
|
-
type SearchFacts = Pick<Report, "scanLimit">;
|
|
54
|
+
/** How the search was bounded and which named paths it skipped; stated with success and failure alike. */
|
|
55
|
+
type SearchFacts = Pick<Report, "scanLimit" | "missing">;
|
|
57
56
|
|
|
58
57
|
/** No result can be returned from an incomplete search: report it rather than "no matches". */
|
|
59
58
|
function searchIncompleteError(
|
|
@@ -68,24 +67,63 @@ function searchIncompleteError(
|
|
|
68
67
|
});
|
|
69
68
|
}
|
|
70
69
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
70
|
+
/** A row's displayed text; `kept` counts the UTF-16 units shown when the line was cut. */
|
|
71
|
+
interface Preview {
|
|
72
|
+
readonly text: string;
|
|
73
|
+
readonly kept?: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Slices start and end on this so an astral character is never split. */
|
|
77
|
+
const LOW_SURROGATE = /[\uDC00-\uDFFF]/;
|
|
78
|
+
|
|
79
|
+
function previewLine(text: string, column = 0, maxUnits: number): Preview {
|
|
80
|
+
if (text.length <= maxUnits) return { text };
|
|
77
81
|
const lead = Math.min(GREP_PREVIEW_LEAD, Math.floor(maxUnits / 5));
|
|
78
82
|
let start = Math.max(0, Math.min(column - lead, text.length - maxUnits));
|
|
79
|
-
|
|
80
|
-
if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
|
|
83
|
+
if (start > 0 && LOW_SURROGATE.test(text[start])) start++;
|
|
81
84
|
let end = Math.min(text.length, start + maxUnits);
|
|
82
|
-
if (end < text.length &&
|
|
85
|
+
if (end < text.length && LOW_SURROGATE.test(text[end])) end--;
|
|
86
|
+
if (end === start) return { text: "…", kept: 0 };
|
|
83
87
|
return {
|
|
84
88
|
text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`,
|
|
85
|
-
|
|
89
|
+
kept: end - start,
|
|
86
90
|
};
|
|
87
91
|
}
|
|
88
92
|
|
|
93
|
+
/**
|
|
94
|
+
* The widest preview narrower than `maxUnits` that `fits`: a column range, or, when the range
|
|
95
|
+
* label crowds out the match, the matched character alone.
|
|
96
|
+
*/
|
|
97
|
+
function narrowPreview(
|
|
98
|
+
text: string,
|
|
99
|
+
column: number | undefined,
|
|
100
|
+
maxUnits: number,
|
|
101
|
+
fits: (preview: Preview) => boolean,
|
|
102
|
+
): Preview {
|
|
103
|
+
let preview: Preview = { text: "…", kept: 0 };
|
|
104
|
+
let low = 1;
|
|
105
|
+
let high = Math.min(maxUnits, text.length) - 1;
|
|
106
|
+
while (low <= high) {
|
|
107
|
+
const middle = Math.floor((low + high) / 2);
|
|
108
|
+
const candidate = previewLine(text, column, middle);
|
|
109
|
+
if (fits(candidate)) {
|
|
110
|
+
preview = candidate;
|
|
111
|
+
low = middle + 1;
|
|
112
|
+
} else {
|
|
113
|
+
high = middle - 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (preview.kept !== 0 || !text.length) return preview;
|
|
117
|
+
let start = Math.min(column ?? 0, text.length - 1);
|
|
118
|
+
if (LOW_SURROGATE.test(text[start])) start--;
|
|
119
|
+
const character = String.fromCodePoint(text.codePointAt(start)!);
|
|
120
|
+
const compact = {
|
|
121
|
+
text: `${start ? "…" : ""}${character}${start + character.length < text.length ? "…" : ""}`,
|
|
122
|
+
kept: character.length,
|
|
123
|
+
};
|
|
124
|
+
return fits(compact) ? compact : preview;
|
|
125
|
+
}
|
|
126
|
+
|
|
89
127
|
interface FormatMatchesOptions {
|
|
90
128
|
readonly cwd: string;
|
|
91
129
|
readonly files: readonly GrepFileMatch[];
|
|
@@ -99,36 +137,67 @@ interface FormatMatchesOptions {
|
|
|
99
137
|
interface FormattedBlock {
|
|
100
138
|
readonly lines: readonly string[];
|
|
101
139
|
readonly invalidUtf8?: string;
|
|
102
|
-
/**
|
|
103
|
-
readonly
|
|
140
|
+
/** Indices of hits in a block with context rows. */
|
|
141
|
+
readonly hitIndices?: readonly number[];
|
|
142
|
+
/** The first hit's row fitted as row one, when another row precedes it. */
|
|
143
|
+
readonly firstHitRow?: string;
|
|
144
|
+
/** Rows that establish a narrower displayed preview, indexed from the file header. */
|
|
145
|
+
readonly previewMinimums?: readonly { index: number; units: number }[];
|
|
104
146
|
}
|
|
105
147
|
|
|
106
|
-
/**
|
|
148
|
+
/**
|
|
149
|
+
* One file's content block: its header, then a row for each line the second read shows. The
|
|
150
|
+
* first row is narrowed to the space remaining after its header.
|
|
151
|
+
*/
|
|
107
152
|
function contentBlock(
|
|
108
153
|
{ filePath, rows, snapshot }: GrepFileMatch,
|
|
109
|
-
{ cwd, anchors, budget }: FormatMatchesOptions,
|
|
154
|
+
{ cwd, anchors, budget, context }: FormatMatchesOptions,
|
|
110
155
|
): LineCollector<FormattedBlock> {
|
|
111
156
|
const columns = new Map(rows.map((match) => [match.lineNumber, match.column]));
|
|
112
157
|
const displayPath = serializePath(cwd, filePath);
|
|
113
|
-
const
|
|
114
|
-
|
|
158
|
+
const header = formatFileHeader(displayPath, rows.length);
|
|
159
|
+
const lines = [header];
|
|
160
|
+
const firstRowBytes = budget.grepBytes - Buffer.byteLength(header) - 1;
|
|
161
|
+
const previewMinimums: { index: number; units: number }[] = [];
|
|
162
|
+
const hitIndices: number[] | undefined = context > 0 ? [] : undefined;
|
|
163
|
+
let firstHitRow: string | undefined;
|
|
115
164
|
return {
|
|
116
165
|
onLine(number, text) {
|
|
117
166
|
// Rows make CR visible one unit for one, so preview columns stay source columns.
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
if (
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
167
|
+
const column = columns.get(number);
|
|
168
|
+
const row = (display: string) =>
|
|
169
|
+
snapshot.validUtf8 ? anchors.row(number, text, display) : plainRow(number, display);
|
|
170
|
+
let preview = previewLine(text, column, budget.grepPreviewUnits);
|
|
171
|
+
const firstHit = hitIndices?.length === 0 && column !== undefined;
|
|
172
|
+
if (lines.length === 1 || firstHit) {
|
|
173
|
+
// A row is its prefix followed by the CR-visible preview.
|
|
174
|
+
const prefixBytes = Buffer.byteLength(row(""));
|
|
175
|
+
const rowBytes = (candidate: Preview) =>
|
|
176
|
+
prefixBytes + Buffer.byteLength(displayCarriageReturns(candidate.text));
|
|
177
|
+
const fits = (candidate: Preview) => rowBytes(candidate) <= firstRowBytes;
|
|
178
|
+
const fitted = fits(preview)
|
|
179
|
+
? preview
|
|
180
|
+
: narrowPreview(text, column, budget.grepPreviewUnits, fits);
|
|
181
|
+
// Row one shows the fitted preview. A later first hit keeps its regular preview here and
|
|
182
|
+
// records the row it would show as row one once context rows are removed.
|
|
183
|
+
if (lines.length === 1) preview = fitted;
|
|
184
|
+
else firstHitRow = row(fitted.text);
|
|
185
|
+
}
|
|
186
|
+
if (column !== undefined) hitIndices?.push(lines.length);
|
|
187
|
+
if (
|
|
188
|
+
preview.kept !== undefined &&
|
|
189
|
+
preview.kept < (previewMinimums.at(-1)?.units ?? Infinity)
|
|
190
|
+
) {
|
|
191
|
+
previewMinimums.push({ index: lines.length, units: preview.kept });
|
|
192
|
+
}
|
|
193
|
+
lines.push(row(preview.text));
|
|
127
194
|
},
|
|
128
195
|
finish: () => ({
|
|
129
196
|
lines,
|
|
130
197
|
invalidUtf8: snapshot.validUtf8 ? undefined : displayPath,
|
|
131
|
-
|
|
198
|
+
previewMinimums,
|
|
199
|
+
hitIndices,
|
|
200
|
+
firstHitRow,
|
|
132
201
|
}),
|
|
133
202
|
};
|
|
134
203
|
}
|
|
@@ -176,10 +245,59 @@ interface AssembleGrepOutputOptions {
|
|
|
176
245
|
readonly budget: OutputBudgets;
|
|
177
246
|
}
|
|
178
247
|
|
|
248
|
+
/**
|
|
249
|
+
* The blocks' lines that fit in `maxBytes` when joined by line feeds, kept in order until the first
|
|
250
|
+
* that does not fit; content blocks are separated by an empty line. `shown` counts each reached
|
|
251
|
+
* block's kept lines, its separator excluded.
|
|
252
|
+
*/
|
|
253
|
+
function fitPayload(blocks: readonly (readonly string[])[], separated: boolean, maxBytes: number) {
|
|
254
|
+
const kept: string[] = [];
|
|
255
|
+
const shown: number[] = [];
|
|
256
|
+
let bytes = 0;
|
|
257
|
+
const keep = (line: string) => {
|
|
258
|
+
const cost = Buffer.byteLength(line) + (kept.length ? 1 : 0);
|
|
259
|
+
if (bytes + cost > maxBytes) return false;
|
|
260
|
+
kept.push(line);
|
|
261
|
+
bytes += cost;
|
|
262
|
+
return true;
|
|
263
|
+
};
|
|
264
|
+
for (const lines of blocks) {
|
|
265
|
+
if (separated && shown.length && !keep("")) return { kept, shown, truncated: true };
|
|
266
|
+
shown.push(0);
|
|
267
|
+
for (const line of lines) {
|
|
268
|
+
if (!keep(line)) return { kept, shown, truncated: true };
|
|
269
|
+
shown[shown.length - 1]++;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return { kept, shown, truncated: false };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Would the same byte budget show more hits if context rows were removed? */
|
|
276
|
+
function contextHidesHit(
|
|
277
|
+
blocks: readonly FormattedBlock[],
|
|
278
|
+
shown: readonly number[],
|
|
279
|
+
maxBytes: number,
|
|
280
|
+
): boolean {
|
|
281
|
+
let shownHits = 0;
|
|
282
|
+
const hitsOnly: string[][] = [];
|
|
283
|
+
for (const [i, { lines, hitIndices, firstHitRow }] of blocks.entries()) {
|
|
284
|
+
if (!hitIndices) return false;
|
|
285
|
+
shownHits += hitIndices.filter((index) => index < (shown[i] ?? 0)).length;
|
|
286
|
+
hitsOnly.push([
|
|
287
|
+
lines[0],
|
|
288
|
+
firstHitRow ?? lines[hitIndices[0]],
|
|
289
|
+
...hitIndices.slice(1).map((index) => lines[index]),
|
|
290
|
+
]);
|
|
291
|
+
}
|
|
292
|
+
const withoutContext = fitPayload(hitsOnly, true, maxBytes).shown;
|
|
293
|
+
return withoutContext.reduce((sum, count) => sum + Math.max(0, count - 1), 0) > shownHits;
|
|
294
|
+
}
|
|
295
|
+
|
|
179
296
|
/** Join the payload within the call's byte budget and state each limit, omission, and diagnostic once. */
|
|
180
297
|
function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
181
298
|
payload: string;
|
|
182
299
|
facts: SuccessFacts<"grep">;
|
|
300
|
+
next?: OutcomeVariant;
|
|
183
301
|
} {
|
|
184
302
|
const {
|
|
185
303
|
formatted,
|
|
@@ -202,33 +320,36 @@ function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
202
320
|
searchFacts,
|
|
203
321
|
);
|
|
204
322
|
}
|
|
205
|
-
const
|
|
206
|
-
blocks.map((block) => block.lines
|
|
207
|
-
|
|
323
|
+
const { kept, shown, truncated } = fitPayload(
|
|
324
|
+
blocks.map((block) => block.lines),
|
|
325
|
+
outputMode === "content",
|
|
326
|
+
budget.grepBytes,
|
|
208
327
|
);
|
|
209
328
|
const invalidUtf8: string[] = [];
|
|
210
|
-
let
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
if (block.invalidUtf8 &&
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
329
|
+
let previewLimit: number | undefined;
|
|
330
|
+
for (const [i, count] of shown.entries()) {
|
|
331
|
+
const block = blocks[i];
|
|
332
|
+
// A file shown only by its header has no preview rows.
|
|
333
|
+
if (block.invalidUtf8 && count > 1) invalidUtf8.push(block.invalidUtf8);
|
|
334
|
+
for (const { index, units } of block.previewMinimums ?? []) {
|
|
335
|
+
if (index >= count) break;
|
|
336
|
+
previewLimit = Math.min(previewLimit ?? Infinity, units);
|
|
337
|
+
}
|
|
218
338
|
}
|
|
219
339
|
// One complete content or count block already states its path and match count.
|
|
220
|
-
const countsShown = outputMode !== "files" && blocks.length === 1 && !
|
|
340
|
+
const countsShown = outputMode !== "files" && blocks.length === 1 && !truncated;
|
|
221
341
|
return {
|
|
222
|
-
payload:
|
|
342
|
+
payload: kept.join("\n"),
|
|
223
343
|
facts: {
|
|
224
344
|
...(countsShown ? {} : { matches, files }),
|
|
225
345
|
...searchFacts,
|
|
226
346
|
matchLimit: matchLimitReached ? effectiveLimit : undefined,
|
|
227
|
-
outputLimit:
|
|
228
|
-
linePreviewLimit:
|
|
347
|
+
outputLimit: truncated ? formatByteSize(budget.grepBytes) : undefined,
|
|
348
|
+
linePreviewLimit: previewLimit,
|
|
229
349
|
invalidUtf8: invalidUtf8.length ? invalidUtf8 : undefined,
|
|
230
350
|
diagnostics: warnings.length ? searchDiagnostics(warnings, cwd, budget) : undefined,
|
|
231
351
|
},
|
|
352
|
+
next: truncated && contextHidesHit(blocks, shown, budget.grepBytes) ? "contextRows" : undefined,
|
|
232
353
|
};
|
|
233
354
|
}
|
|
234
355
|
|
|
@@ -241,14 +362,18 @@ export async function grepOutput(
|
|
|
241
362
|
readonly search: Omit<Awaited<ReturnType<typeof searchFiles>>, "warnings">;
|
|
242
363
|
/** Scope and search warnings, in the order those stages produced them. */
|
|
243
364
|
readonly warnings: readonly SearchWarning[];
|
|
365
|
+
/** Resolved paths that do not exist; the other paths were searched. */
|
|
366
|
+
readonly missing: readonly string[];
|
|
244
367
|
readonly effectiveLimit: number;
|
|
245
368
|
/** A literal pattern contains `|`, which matches only that character. */
|
|
246
369
|
readonly literalPipe: boolean;
|
|
247
370
|
},
|
|
248
|
-
): Promise<{ payload?: string; facts: SuccessFacts<"grep"
|
|
249
|
-
const { cwd, search, warnings, outputMode, effectiveLimit, literalPipe, budget } =
|
|
371
|
+
): Promise<{ payload?: string; facts: SuccessFacts<"grep">; next?: OutcomeVariant }> {
|
|
372
|
+
const { cwd, search, warnings, missing, outputMode, effectiveLimit, literalPipe, budget } =
|
|
373
|
+
options;
|
|
250
374
|
const searchFacts: SearchFacts = {
|
|
251
375
|
scanLimit: search.scanLimitReached ? formatByteSize(MAX_UNNARROWED_SCAN_BYTES) : undefined,
|
|
376
|
+
missing: missing.length ? [...missing] : undefined,
|
|
252
377
|
};
|
|
253
378
|
if (search.files.length === 0) {
|
|
254
379
|
if (warnings.length)
|
package/src/pi/grep-render.ts
CHANGED
|
@@ -18,45 +18,51 @@ function indentation(text: string): number {
|
|
|
18
18
|
* hashes. Notices are report facts, which the card renders from the report.
|
|
19
19
|
*/
|
|
20
20
|
export function toDisplayLines(raw: string, theme: Theme): string[] {
|
|
21
|
-
const out: string[] = [];
|
|
22
21
|
const lines = raw.split("\n");
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
22
|
+
type Header = NonNullable<ReturnType<typeof parseFileHeader>>;
|
|
23
|
+
type Row = NonNullable<ReturnType<typeof parseDisplayRow>>;
|
|
24
|
+
const blocks: (string | { header: Header; rows: Row[] })[] = [];
|
|
25
|
+
let lineNoWidth = 0;
|
|
26
|
+
// A filename can look like a row, and a source row can end like a header.
|
|
27
|
+
// Parse each group before measuring its rows so the header contributes no width.
|
|
28
|
+
for (let index = 0; index < lines.length; index++) {
|
|
29
29
|
const line = lines[index];
|
|
30
30
|
const header = parseFileHeader(line);
|
|
31
|
-
if (header) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
theme.fg("dim", ` ${lineNo.padStart(lineNoWidth)}: `) +
|
|
51
|
-
marker +
|
|
52
|
-
theme.fg("toolOutput", content.slice(base)),
|
|
53
|
-
);
|
|
54
|
-
}
|
|
55
|
-
index = next;
|
|
31
|
+
if (!header) {
|
|
32
|
+
blocks.push(line);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const rows: Row[] = [];
|
|
36
|
+
while (index + 1 < lines.length) {
|
|
37
|
+
const row = parseDisplayRow(lines[index + 1]);
|
|
38
|
+
if (!row) break;
|
|
39
|
+
rows.push(row);
|
|
40
|
+
lineNoWidth = Math.max(lineNoWidth, row.lineNo.length);
|
|
41
|
+
index++;
|
|
42
|
+
}
|
|
43
|
+
blocks.push({ header, rows });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const out: string[] = [];
|
|
47
|
+
for (const group of blocks) {
|
|
48
|
+
if (typeof group === "string") {
|
|
49
|
+
out.push(theme.fg("toolOutput", group));
|
|
56
50
|
continue;
|
|
57
51
|
}
|
|
58
|
-
|
|
59
|
-
|
|
52
|
+
const { path, summary } = group.header;
|
|
53
|
+
out.push(theme.fg("success", path) + theme.fg("dim", ` · ${summary}`));
|
|
54
|
+
// Fold shared indentation without spreading an unbounded number of rows.
|
|
55
|
+
const base = group.rows.length
|
|
56
|
+
? group.rows.reduce((min, { content }) => Math.min(min, indentation(content)), Infinity)
|
|
57
|
+
: 0;
|
|
58
|
+
const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
|
|
59
|
+
for (const { lineNo, content } of group.rows) {
|
|
60
|
+
out.push(
|
|
61
|
+
theme.fg("dim", ` ${lineNo.padStart(lineNoWidth)}: `) +
|
|
62
|
+
marker +
|
|
63
|
+
theme.fg("toolOutput", content.slice(base)),
|
|
64
|
+
);
|
|
65
|
+
}
|
|
60
66
|
}
|
|
61
67
|
return out;
|
|
62
68
|
}
|
|
@@ -5,15 +5,17 @@ import type { HashlineEditConfig } from "./config.ts";
|
|
|
5
5
|
import type { OutputBudgetProvider } from "./budgets.ts";
|
|
6
6
|
|
|
7
7
|
import * as real from "./rg-process.ts";
|
|
8
|
-
export type MockRg = Pick<typeof real, "runRgPaths" | "runRgLines"
|
|
9
|
-
const overrides = new AsyncLocalStorage<
|
|
8
|
+
export type MockRg = Partial<Pick<typeof real, "runRgPaths" | "runRgLines" | "rgRejectsPatterns">>;
|
|
9
|
+
const overrides = new AsyncLocalStorage<MockRg>();
|
|
10
10
|
const moduleMock = mock.module("./rg-process.ts", {
|
|
11
11
|
namedExports: {
|
|
12
12
|
...real,
|
|
13
|
-
runRgPaths: (...args: Parameters<
|
|
13
|
+
runRgPaths: (...args: Parameters<typeof real.runRgPaths>) =>
|
|
14
14
|
(overrides.getStore()?.runRgPaths ?? real.runRgPaths)(...args),
|
|
15
|
-
runRgLines: (...args: Parameters<
|
|
15
|
+
runRgLines: (...args: Parameters<typeof real.runRgLines>) =>
|
|
16
16
|
(overrides.getStore()?.runRgLines ?? real.runRgLines)(...args),
|
|
17
|
+
rgRejectsPatterns: (...args: Parameters<typeof real.rgRejectsPatterns>) =>
|
|
18
|
+
(overrides.getStore()?.rgRejectsPatterns ?? real.rgRejectsPatterns)(...args),
|
|
17
19
|
},
|
|
18
20
|
});
|
|
19
21
|
|
|
@@ -27,7 +29,7 @@ const { listCandidates } = await import("./grep-candidates.ts");
|
|
|
27
29
|
export function makeMockGrep(
|
|
28
30
|
cwd: string,
|
|
29
31
|
config: HashlineEditConfig,
|
|
30
|
-
rg:
|
|
32
|
+
rg: MockRg,
|
|
31
33
|
budgets?: OutputBudgetProvider,
|
|
32
34
|
) {
|
|
33
35
|
const tool = factories.makeGrepOverride(cwd, config, budgets);
|
|
@@ -41,7 +43,7 @@ export function makeMockGrep(
|
|
|
41
43
|
export function searchWithMockRg({
|
|
42
44
|
backend,
|
|
43
45
|
...options
|
|
44
|
-
}: Parameters<typeof searchFiles>[0] & { readonly backend:
|
|
46
|
+
}: Parameters<typeof searchFiles>[0] & { readonly backend: MockRg }) {
|
|
45
47
|
return overrides.run(backend, () => searchFiles(options));
|
|
46
48
|
}
|
|
47
49
|
|
|
@@ -51,6 +53,7 @@ export async function fileCandidateArgs(query: GrepQuery): Promise<string[]> {
|
|
|
51
53
|
await overrides.run(
|
|
52
54
|
{
|
|
53
55
|
runRgLines: async () => ({ code: 2, stderr: "", stopped: false }),
|
|
56
|
+
rgRejectsPatterns: async () => true,
|
|
54
57
|
runRgPaths: async (args) => {
|
|
55
58
|
captured = args.slice(0, args.indexOf("--null"));
|
|
56
59
|
return { code: 1, stderr: "", stopped: false };
|
package/src/pi/grep-scope.ts
CHANGED
|
@@ -32,10 +32,14 @@ interface SearchPathInfo {
|
|
|
32
32
|
readonly isFile: boolean;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* Canonical search paths, the working directory when none is given, and the missing ones. The
|
|
37
|
+
* call fails when every path is missing, or when a missing path is a wildcard meant for glob.
|
|
38
|
+
*/
|
|
36
39
|
export async function resolveSearchPaths(cwd: string, path: readonly string[] | undefined) {
|
|
37
40
|
const pathInfo: SearchPathInfo[] = [];
|
|
38
41
|
const missing: string[] = [];
|
|
42
|
+
let wildcard = false;
|
|
39
43
|
for (const value of path ?? ["."]) {
|
|
40
44
|
const searchPath = canonicalPath(cwd, value);
|
|
41
45
|
try {
|
|
@@ -44,34 +48,52 @@ export async function resolveSearchPaths(cwd: string, path: readonly string[] |
|
|
|
44
48
|
// Only a missing path is PATH_NOT_FOUND; other filesystem errors keep their cause.
|
|
45
49
|
if (errnoCode(error) !== "ENOENT") throw error;
|
|
46
50
|
missing.push(searchPath);
|
|
51
|
+
// The working directory and Windows namespace syntax are not caller globs.
|
|
52
|
+
const name = process.platform === "win32" ? value.replace(/^@?\\\\\?\\/, "") : value;
|
|
53
|
+
wildcard ||= !name.startsWith("file://") && /[*?]/.test(name);
|
|
47
54
|
}
|
|
48
55
|
}
|
|
49
|
-
if (missing.length)
|
|
56
|
+
if (wildcard || (missing.length && pathInfo.length === 0))
|
|
50
57
|
throw new HashlineError("PATH_NOT_FOUND", PATH_ERROR_MESSAGES.PATH_NOT_FOUND, {
|
|
51
58
|
facts: { missing },
|
|
52
|
-
...(
|
|
59
|
+
...(wildcard ? { next: "useGlob" as const } : {}),
|
|
53
60
|
});
|
|
54
|
-
return pathInfo;
|
|
61
|
+
return { paths: pathInfo, missing };
|
|
55
62
|
}
|
|
56
63
|
|
|
57
|
-
/**
|
|
58
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Listed file spellings, grouped by the folded path that a case-insensitive filesystem may treat
|
|
66
|
+
* as one file. A lookup finds the same file without folding distinct files together.
|
|
67
|
+
*/
|
|
68
|
+
export class ListedFiles {
|
|
69
|
+
private readonly spellings = new Map<string, string[]>();
|
|
59
70
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
71
|
+
private static key(path: string): string {
|
|
72
|
+
return resolve(path).toLowerCase();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
add(path: string): void {
|
|
76
|
+
const key = ListedFiles.key(path);
|
|
77
|
+
const spellings = this.spellings.get(key);
|
|
78
|
+
if (spellings) spellings.push(path);
|
|
79
|
+
else this.spellings.set(key, [path]);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async has(path: string): Promise<boolean> {
|
|
83
|
+
const spellings = this.spellings.get(ListedFiles.key(path)) ?? [];
|
|
84
|
+
const absolute = resolve(path);
|
|
85
|
+
if (spellings.some((spelling) => resolve(spelling) === absolute)) return true;
|
|
86
|
+
if (!spellings.length) return false;
|
|
87
|
+
const identity = (spelling: string) =>
|
|
88
|
+
stat(spelling, { bigint: true }).then(
|
|
89
|
+
({ dev, ino }) => `${dev}:${ino}`,
|
|
90
|
+
() => undefined,
|
|
91
|
+
);
|
|
92
|
+
const named = await identity(path);
|
|
93
|
+
for (const spelling of spellings)
|
|
94
|
+
if (named !== undefined && (await identity(spelling)) === named) return true;
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
75
97
|
}
|
|
76
98
|
|
|
77
99
|
/**
|
|
@@ -88,7 +110,7 @@ export async function filterExplicitFilesByGlob(
|
|
|
88
110
|
return { searchPaths: paths.map(({ path }) => path), warnings: [] };
|
|
89
111
|
|
|
90
112
|
const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
|
|
91
|
-
const allowed = new
|
|
113
|
+
const allowed = new ListedFiles();
|
|
92
114
|
// Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
|
|
93
115
|
const args = [
|
|
94
116
|
...COMMON_RG_ARGS,
|
|
@@ -103,18 +125,18 @@ export async function filterExplicitFilesByGlob(
|
|
|
103
125
|
...parents,
|
|
104
126
|
];
|
|
105
127
|
const listed = await runRgPaths(args, signal, async (path) => {
|
|
106
|
-
|
|
107
|
-
allowed.set(key, [...(allowed.get(key) ?? []), path]);
|
|
128
|
+
allowed.add(path);
|
|
108
129
|
return true;
|
|
109
130
|
});
|
|
110
131
|
const admitted = new Set<string>();
|
|
111
|
-
for (const { path } of explicitFiles) if (await
|
|
132
|
+
for (const { path } of explicitFiles) if (await allowed.has(path)) admitted.add(path);
|
|
133
|
+
const searchPaths = paths
|
|
134
|
+
.filter(({ path, isFile }) => !isFile || admitted.has(path))
|
|
135
|
+
.map(({ path }) => path);
|
|
112
136
|
// Listing diagnostics about sibling entries matter only when they may explain an exclusion.
|
|
113
|
-
const diagnostic =
|
|
137
|
+
const diagnostic = searchPaths.length < paths.length ? searchDiagnostic(listed) : undefined;
|
|
114
138
|
return {
|
|
115
|
-
searchPaths
|
|
116
|
-
.filter(({ path, isFile }) => !isFile || admitted.has(path))
|
|
117
|
-
.map(({ path }) => path),
|
|
139
|
+
searchPaths,
|
|
118
140
|
warnings: diagnostic ? [diagnostic] : [],
|
|
119
141
|
};
|
|
120
142
|
}
|