@criogaid/pi-hashline-edit 0.5.0 → 0.6.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 +66 -22
- package/package.json +6 -6
- package/src/core/apply.test.ts +66 -16
- package/src/core/apply.ts +36 -19
- package/src/core/lines.ts +3 -3
- package/src/core/text.test.ts +30 -1
- package/src/core/text.ts +8 -3
- package/src/index.ts +2 -0
- package/src/integration/forget-grep.test.ts +98 -0
- package/src/integration/fusion-dispatch.test.ts +343 -0
- package/src/integration/grep-rg.test.ts +466 -111
- package/src/integration/large-text.test.ts +3 -5
- package/src/integration/mutation-file-types.test.ts +44 -0
- package/src/pi/action-fusion.test.ts +158 -79
- package/src/pi/action-fusion.ts +105 -34
- package/src/pi/anchor-format.test.ts +46 -0
- package/src/pi/anchor-format.ts +21 -2
- package/src/pi/argument-validation.test.ts +136 -0
- package/src/pi/argument-validation.ts +103 -0
- package/src/pi/budgets.ts +4 -1
- package/src/pi/config.test.ts +1 -0
- package/src/pi/config.ts +4 -0
- package/src/pi/diagnostic-buffer.test.ts +58 -0
- package/src/pi/diagnostic-buffer.ts +59 -0
- package/src/pi/directory-sync.test.ts +1 -1
- package/src/pi/edit-tool.ts +56 -37
- package/src/pi/execute.test.ts +185 -645
- package/src/pi/failure-context.test.ts +4 -3
- package/src/pi/failure-path.test.ts +3 -3
- package/src/pi/file-commit.test.ts +24 -17
- package/src/pi/file-commit.ts +36 -9
- package/src/pi/file-snapshot.test.ts +24 -0
- package/src/pi/forget-tool.ts +268 -0
- package/src/pi/forget.test.ts +343 -0
- package/src/pi/forget.testing.ts +273 -0
- package/src/pi/fusion-card.test.ts +26 -0
- package/src/pi/fusion-card.ts +21 -6
- package/src/pi/grep-output.ts +82 -55
- package/src/pi/grep-render.ts +8 -11
- package/src/pi/grep-scope.ts +6 -31
- package/src/pi/grep-search.ts +94 -58
- package/src/pi/grep-tool.ts +50 -59
- package/src/pi/grep.test.ts +412 -208
- package/src/pi/mutation-result.test.ts +23 -0
- package/src/pi/mutation-runner.ts +8 -4
- package/src/pi/path.ts +16 -2
- package/src/pi/pi.test.ts +4 -3
- package/src/pi/read-tool.ts +59 -27
- package/src/pi/read.test.ts +361 -0
- package/src/pi/registration.test.ts +121 -4
- package/src/pi/render.test.ts +172 -15
- package/src/pi/render.ts +28 -5
- package/src/pi/replace-tool.ts +18 -27
- package/src/pi/replace.test.ts +8 -107
- package/src/pi/result-safety.test.ts +123 -149
- package/src/pi/rg-match-bytes.ts +95 -0
- package/src/pi/rg-process.test.ts +40 -59
- package/src/pi/rg-process.ts +8 -5
- package/src/pi/rg-text-view.ts +59 -9
- package/src/pi/text-stream.test.ts +153 -0
- package/src/pi/text-stream.ts +33 -13
- package/src/pi/tool-call.testing.ts +50 -0
- package/src/pi/tool-prompts.ts +15 -0
- package/src/pi/write-tool.ts +19 -26
- package/src/pi/write.test.ts +70 -61
- package/src/pi/e2e-scenarios.test.ts +0 -360
package/src/pi/fusion-card.ts
CHANGED
|
@@ -22,7 +22,7 @@ const RESULT_TYPE = "hashline-then-run-result";
|
|
|
22
22
|
|
|
23
23
|
type CommandCardData = Pick<
|
|
24
24
|
ActionFusionProgress,
|
|
25
|
-
"toolCallId" | "commandText" | "command" | "output" | "reason"
|
|
25
|
+
"toolCallId" | "commandText" | "command" | "output" | "reason" | "timing"
|
|
26
26
|
>;
|
|
27
27
|
|
|
28
28
|
function commandCardData({
|
|
@@ -31,8 +31,16 @@ function commandCardData({
|
|
|
31
31
|
command,
|
|
32
32
|
output,
|
|
33
33
|
reason,
|
|
34
|
+
timing,
|
|
34
35
|
}: ActionFusionProgress): CommandCardData {
|
|
35
|
-
return {
|
|
36
|
+
return {
|
|
37
|
+
toolCallId,
|
|
38
|
+
commandText,
|
|
39
|
+
command,
|
|
40
|
+
output,
|
|
41
|
+
...(reason ? { reason } : {}),
|
|
42
|
+
...(timing ? { timing } : {}),
|
|
43
|
+
};
|
|
36
44
|
}
|
|
37
45
|
|
|
38
46
|
/** Render one durable transcript card per fused command without adding model context. */
|
|
@@ -82,6 +90,10 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
82
90
|
const pending = current.command === "waiting" || current.command === "running";
|
|
83
91
|
const interrupted = pending && !active.has(current.toolCallId);
|
|
84
92
|
const status = interrupted ? "interrupted (final status unknown)" : current.command;
|
|
93
|
+
const countdown =
|
|
94
|
+
current.command === "running" && !interrupted && current.timing
|
|
95
|
+
? ` · ${current.timing.remainingSeconds}s remaining`
|
|
96
|
+
: "";
|
|
85
97
|
const failed = current.command === "failed" || current.command === "timeout";
|
|
86
98
|
const color =
|
|
87
99
|
pending || current.command === "cancelled"
|
|
@@ -101,10 +113,13 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
101
113
|
: "customMessageBg";
|
|
102
114
|
box.setBgFn((line) => theme.bg(background, line));
|
|
103
115
|
statusText.setText(
|
|
104
|
-
`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`,
|
|
116
|
+
`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
|
|
105
117
|
);
|
|
106
118
|
const context = {
|
|
107
|
-
args: {
|
|
119
|
+
args: {
|
|
120
|
+
command: current.commandText,
|
|
121
|
+
...(current.timing ? { timeout: current.timing.timeoutSeconds } : {}),
|
|
122
|
+
},
|
|
108
123
|
toolCallId: current.toolCallId,
|
|
109
124
|
cwd: currentCwd,
|
|
110
125
|
state: rendererState,
|
|
@@ -186,10 +201,10 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
|
|
|
186
201
|
| { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
|
|
187
202
|
| undefined;
|
|
188
203
|
const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
|
|
189
|
-
//
|
|
204
|
+
// Pi serializes fused failures into one diagnostic; retain it when the card expands.
|
|
190
205
|
const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
|
|
191
206
|
shell.result = fusedError
|
|
192
|
-
? renderToolError(result, theme)
|
|
207
|
+
? renderToolError(result, theme, options.expanded)
|
|
193
208
|
: tool.renderResult!(result, { ...options, isPartial }, theme, {
|
|
194
209
|
...context,
|
|
195
210
|
isPartial,
|
package/src/pi/grep-output.ts
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { scanTextLines } from "./text-stream.ts";
|
|
8
|
-
import { formatKiB, GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
|
|
4
|
+
import { createAnchorFormatter, displayCarriageReturns, plainRow } from "./anchor-format.ts";
|
|
5
|
+
import { fileReadWarning, type RgMatch, type SearchFileSnapshot } from "./grep-search.ts";
|
|
6
|
+
import { scanTextFile, scanTextLines } from "./text-stream.ts";
|
|
7
|
+
import { GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
|
|
9
8
|
import { searchChangedError } from "./error-text.ts";
|
|
9
|
+
import { serializePath } from "./path.ts";
|
|
10
|
+
import { rawMatchVerifier } from "./rg-match-bytes.ts";
|
|
10
11
|
|
|
11
12
|
/** UTF-16 units kept before the match column when a preview window is cut. */
|
|
12
13
|
const GREP_PREVIEW_LEAD = 100;
|
|
13
14
|
const MAX_CONCURRENT_FILE_READS = 16;
|
|
15
|
+
const INVALID_UTF8_PREVIEW_NOTICE =
|
|
16
|
+
"Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors";
|
|
14
17
|
|
|
15
18
|
/** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
|
|
16
19
|
function formatFileHeader(path: string, matches: number): string {
|
|
@@ -30,10 +33,9 @@ export function isNoticeLine(line: string): boolean {
|
|
|
30
33
|
|
|
31
34
|
export function formatSearchWarnings(warnings: readonly string[]): string {
|
|
32
35
|
if (!warnings.length) return "";
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
}
|
|
36
|
-
return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? `\nAdditional search diagnostics omitted (${formatKiB(MAX_SEARCH_DIAGNOSTIC_BYTES)} limit).` : ""}]`;
|
|
36
|
+
const diagnostics = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
|
|
37
|
+
for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
|
|
38
|
+
return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${diagnostics.toString().trimEnd()}]`;
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
|
|
@@ -57,11 +59,11 @@ interface FormatMatchesOptions {
|
|
|
57
59
|
anchors: ReturnType<typeof createAnchorFormatter>;
|
|
58
60
|
signal?: AbortSignal;
|
|
59
61
|
warnings: string[];
|
|
60
|
-
|
|
62
|
+
searchSnapshots: ReadonlyMap<string, SearchFileSnapshot>;
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
export async function formatMatches(options: FormatMatchesOptions) {
|
|
64
|
-
const { cwd, raw, outputMode, context, anchors, signal, warnings,
|
|
66
|
+
const { cwd, raw, outputMode, context, anchors, signal, warnings, searchSnapshots } = options;
|
|
65
67
|
const byFile = new Map<string, RgMatch[]>();
|
|
66
68
|
for (const match of raw) {
|
|
67
69
|
const lines = byFile.get(match.filePath) ?? [];
|
|
@@ -69,17 +71,13 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
69
71
|
byFile.set(match.filePath, lines);
|
|
70
72
|
}
|
|
71
73
|
for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
|
|
72
|
-
const formatPath = (filePath: string): string =>
|
|
73
|
-
const absolute = resolve(cwd, filePath);
|
|
74
|
-
const rel = relative(cwd, absolute);
|
|
75
|
-
return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
|
76
|
-
? rel.replace(/\\/g, "/")
|
|
77
|
-
: absolute;
|
|
78
|
-
};
|
|
74
|
+
const formatPath = (filePath: string): string => serializePath(cwd, filePath);
|
|
79
75
|
const blocks: string[] = [];
|
|
80
76
|
let linesTruncated = false;
|
|
81
|
-
|
|
82
|
-
|
|
77
|
+
const fileEntries = [...byFile.entries()].filter(
|
|
78
|
+
([, matches]) => outputMode === "content" || matches.some((match) => match.rawMatch),
|
|
79
|
+
);
|
|
80
|
+
if (fileEntries.length) {
|
|
83
81
|
const fileResults = new Array<{ block?: string; warning?: string }>(fileEntries.length);
|
|
84
82
|
let nextIndex = 0;
|
|
85
83
|
const workerAbort = new AbortController();
|
|
@@ -93,19 +91,42 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
93
91
|
while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
|
|
94
92
|
const current = nextIndex++;
|
|
95
93
|
const [filePath, matchLines] = fileEntries[current];
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
matchLines.map((match) => [match.lineNumber, match.matchedText]),
|
|
94
|
+
const verifyRaw = rawMatchVerifier(
|
|
95
|
+
new Set(matchLines.flatMap((match) => (match.rawMatch ? [match.rawMatch] : []))),
|
|
99
96
|
);
|
|
100
|
-
const windowSet = new Set<number>();
|
|
101
|
-
for (const { lineNumber } of matchLines) {
|
|
102
|
-
for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
|
|
103
|
-
windowSet.add(n);
|
|
104
|
-
}
|
|
105
|
-
const rows: string[] = [];
|
|
106
|
-
const matchedRows = new Set<number>();
|
|
107
|
-
const hash = createHash("sha256");
|
|
108
97
|
try {
|
|
98
|
+
if (outputMode !== "content") {
|
|
99
|
+
const hash = createHash("sha256");
|
|
100
|
+
await scanTextFile(
|
|
101
|
+
filePath,
|
|
102
|
+
undefined,
|
|
103
|
+
scanSignal,
|
|
104
|
+
(bytes) => {
|
|
105
|
+
hash.update(bytes);
|
|
106
|
+
verifyRaw.write(bytes);
|
|
107
|
+
},
|
|
108
|
+
"lossy",
|
|
109
|
+
);
|
|
110
|
+
verifyRaw.end();
|
|
111
|
+
if (hash.digest("hex") !== searchSnapshots.get(filePath)!.revision)
|
|
112
|
+
throw searchChangedError();
|
|
113
|
+
fileResults[current] = {};
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
|
|
117
|
+
const matchedTexts = new Map(
|
|
118
|
+
matchLines.map((match) => [match.lineNumber, match.matchedText]),
|
|
119
|
+
);
|
|
120
|
+
const windowSet = new Set<number>();
|
|
121
|
+
for (const { lineNumber } of matchLines) {
|
|
122
|
+
for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
|
|
123
|
+
windowSet.add(n);
|
|
124
|
+
}
|
|
125
|
+
const rows: string[] = [];
|
|
126
|
+
const matchedRows = new Set<number>();
|
|
127
|
+
const hash = createHash("sha256");
|
|
128
|
+
// Content-mode search snapshots every file before recording its matches.
|
|
129
|
+
const snapshot = searchSnapshots.get(filePath)!;
|
|
109
130
|
const stats = await scanTextLines(
|
|
110
131
|
filePath,
|
|
111
132
|
(number) => windowSet.has(number),
|
|
@@ -121,20 +142,32 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
121
142
|
columns.get(line.number),
|
|
122
143
|
);
|
|
123
144
|
if (wasTruncated) linesTruncated = true;
|
|
124
|
-
rows.push(
|
|
145
|
+
rows.push(
|
|
146
|
+
snapshot.validUtf8
|
|
147
|
+
? anchors.row(line.number, line.text, display)
|
|
148
|
+
: plainRow(line.number, display),
|
|
149
|
+
);
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
signal: scanSignal,
|
|
153
|
+
onBytes: (bytes) => {
|
|
154
|
+
hash.update(bytes);
|
|
155
|
+
verifyRaw.write(bytes);
|
|
156
|
+
},
|
|
157
|
+
decoding: "lossy",
|
|
125
158
|
},
|
|
126
|
-
{ signal: scanSignal, onBytes: (bytes) => hash.update(bytes) },
|
|
127
159
|
);
|
|
128
|
-
|
|
160
|
+
verifyRaw.end();
|
|
161
|
+
if (stats.hasNul) throw searchChangedError();
|
|
129
162
|
if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
|
|
130
163
|
throw searchChangedError();
|
|
131
164
|
}
|
|
132
|
-
|
|
133
|
-
if (searchRevision && searchRevision !== hash.digest("hex")) {
|
|
165
|
+
if (snapshot.revision !== hash.digest("hex")) {
|
|
134
166
|
throw searchChangedError();
|
|
135
167
|
}
|
|
136
168
|
const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
|
|
137
|
-
|
|
169
|
+
const notice = snapshot.validUtf8 ? "" : `\n[${INVALID_UTF8_PREVIEW_NOTICE}]`;
|
|
170
|
+
fileResults[current] = { block: header + rows.join("\n") + notice };
|
|
138
171
|
} catch (error) {
|
|
139
172
|
const warning = fileReadWarning(filePath, error, scanSignal);
|
|
140
173
|
if (!warning) throw error;
|
|
@@ -152,13 +185,16 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
152
185
|
);
|
|
153
186
|
await Promise.all(workers);
|
|
154
187
|
if (failed) throw failure;
|
|
155
|
-
for (const result of fileResults) {
|
|
156
|
-
if (result.warning)
|
|
157
|
-
|
|
188
|
+
for (const [index, result] of fileResults.entries()) {
|
|
189
|
+
if (result.warning) {
|
|
190
|
+
warnings.push(result.warning);
|
|
191
|
+
byFile.delete(fileEntries[index][0]);
|
|
192
|
+
} else if (result.block) blocks.push(result.block);
|
|
158
193
|
}
|
|
159
|
-
}
|
|
194
|
+
}
|
|
195
|
+
if (outputMode === "files") {
|
|
160
196
|
for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
|
|
161
|
-
} else {
|
|
197
|
+
} else if (outputMode === "count" && byFile.size) {
|
|
162
198
|
let total = 0;
|
|
163
199
|
for (const [filePath, matchLines] of byFile) {
|
|
164
200
|
blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
|
|
@@ -175,8 +211,6 @@ interface AssembleGrepOutputOptions {
|
|
|
175
211
|
blocks: readonly string[];
|
|
176
212
|
warnings: readonly string[];
|
|
177
213
|
outputMode: "content" | "files" | "count";
|
|
178
|
-
/** Notice for an invalid regex that was searched literally; undefined when no fallback happened. */
|
|
179
|
-
literalFallbackNotice: string | undefined;
|
|
180
214
|
matchLimitReached: boolean;
|
|
181
215
|
effectiveLimit: number;
|
|
182
216
|
linesTruncated: boolean;
|
|
@@ -186,15 +220,8 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
186
220
|
content: [{ type: "text"; text: string }];
|
|
187
221
|
details: { incomplete: true } | undefined;
|
|
188
222
|
} {
|
|
189
|
-
const {
|
|
190
|
-
|
|
191
|
-
warnings,
|
|
192
|
-
outputMode,
|
|
193
|
-
literalFallbackNotice,
|
|
194
|
-
matchLimitReached,
|
|
195
|
-
effectiveLimit,
|
|
196
|
-
linesTruncated,
|
|
197
|
-
} = options;
|
|
223
|
+
const { blocks, warnings, outputMode, matchLimitReached, effectiveLimit, linesTruncated } =
|
|
224
|
+
options;
|
|
198
225
|
|
|
199
226
|
if (!blocks.length && warnings.length) {
|
|
200
227
|
throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
|
|
@@ -203,7 +230,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
203
230
|
const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
|
|
204
231
|
output = truncation.content;
|
|
205
232
|
|
|
206
|
-
const notices: string[] =
|
|
233
|
+
const notices: string[] = [];
|
|
207
234
|
if (matchLimitReached) {
|
|
208
235
|
notices.push(
|
|
209
236
|
`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
|
package/src/pi/grep-render.ts
CHANGED
|
@@ -1,25 +1,22 @@
|
|
|
1
1
|
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
2
|
+
import { parseDisplayRow } from "./anchor-format.ts";
|
|
3
3
|
import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
|
|
4
4
|
|
|
5
|
-
/**
|
|
6
|
-
* Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
|
|
7
|
-
* form for the TUI: drop the hash, keep file headers and line numbers. Within each
|
|
8
|
-
* file group, the common leading whitespace shared by all matched lines is folded
|
|
9
|
-
* into a single marker (›) so deep, repeated indentation doesn't eat display width;
|
|
10
|
-
* each line's indentation relative to that common base is preserved. The model still
|
|
11
|
-
* receives the anchored `content` text verbatim — this only affects what the user sees.
|
|
12
|
-
*/
|
|
13
5
|
function countLeading(s: string): number {
|
|
14
6
|
const m = s.match(/^[ \t]*/);
|
|
15
7
|
return m ? m[0].length : 0;
|
|
16
8
|
}
|
|
17
9
|
|
|
10
|
+
/**
|
|
11
|
+
* Render grouped grep results for the TUI. Anchored and plain preview rows share
|
|
12
|
+
* aligned line numbers and folded leading indentation; anchored rows lose their
|
|
13
|
+
* hashes. The model receives the original content text, including preview notices.
|
|
14
|
+
*/
|
|
18
15
|
export function toDisplayLines(raw: string, theme: Theme): string[] {
|
|
19
16
|
const out: string[] = [];
|
|
20
17
|
const lines = raw.split("\n");
|
|
21
18
|
const lineNoWidth = lines.reduce(
|
|
22
|
-
(width, line) => Math.max(width,
|
|
19
|
+
(width, line) => Math.max(width, parseDisplayRow(line)?.lineNo.length ?? 0),
|
|
23
20
|
0,
|
|
24
21
|
);
|
|
25
22
|
let i = 0;
|
|
@@ -32,7 +29,7 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
|
|
|
32
29
|
const group: { lineNo: string; content: string }[] = [];
|
|
33
30
|
let j = i + 1;
|
|
34
31
|
while (j < lines.length) {
|
|
35
|
-
const a =
|
|
32
|
+
const a = parseDisplayRow(lines[j]);
|
|
36
33
|
if (!a) break;
|
|
37
34
|
group.push({ lineNo: a.lineNo, content: a.content });
|
|
38
35
|
j++;
|
package/src/pi/grep-scope.ts
CHANGED
|
@@ -10,9 +10,7 @@ import {
|
|
|
10
10
|
} from "./grep-search.ts";
|
|
11
11
|
import { throwIfCancelled } from "./error-text.ts";
|
|
12
12
|
|
|
13
|
-
export const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
|
|
14
13
|
const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
|
|
15
|
-
const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
|
|
16
14
|
/**
|
|
17
15
|
* Lookaround and backreferences: valid in JavaScript/PCRE, rejected by ripgrep's default engine.
|
|
18
16
|
* The construct must be unescaped: an even run of backslashes (escaped backslashes) may precede it.
|
|
@@ -26,43 +24,20 @@ function regexDialectHint(patterns: readonly string[]): string | undefined {
|
|
|
26
24
|
: undefined;
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
/**
|
|
30
|
-
export function
|
|
31
|
-
const hint = regexDialectHint(patterns);
|
|
32
|
-
return hint ? `${LITERAL_FALLBACK_NOTICE}; ${hint}` : LITERAL_FALLBACK_NOTICE;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function withDialectHint(message: string, patterns: readonly string[]): string {
|
|
36
|
-
const hint = regexDialectHint(patterns);
|
|
37
|
-
return hint ? `${message}\n${hint}.` : message;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export async function resolveLiteralMode(
|
|
27
|
+
/** Reject a regex query ripgrep cannot parse before any file is searched. */
|
|
28
|
+
export async function assertValidRegex(
|
|
41
29
|
patterns: readonly string[],
|
|
42
|
-
explicit: boolean | undefined,
|
|
43
30
|
multiline: boolean,
|
|
44
31
|
rgPath: string,
|
|
45
32
|
backend: GrepBackend,
|
|
46
33
|
signal: AbortSignal | undefined,
|
|
47
|
-
|
|
48
|
-
): Promise<boolean> {
|
|
49
|
-
if (explicit === true) return true;
|
|
50
|
-
if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern)))
|
|
51
|
-
return true;
|
|
52
|
-
|
|
34
|
+
): Promise<void> {
|
|
53
35
|
const result = await backend.probeRegex(rgPath, patterns, multiline, signal);
|
|
54
36
|
throwIfCancelled(signal);
|
|
55
|
-
if (result.code === 0 || result.code === 1) return
|
|
37
|
+
if (result.code === 0 || result.code === 1) return;
|
|
56
38
|
if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
throw new Error(
|
|
60
|
-
withDialectHint(
|
|
61
|
-
`Invalid regex in compound query; automatic literal fallback is disabled. Fix the regex or set literal:true for all patterns.\n${result.stderr.trim()}`,
|
|
62
|
-
patterns,
|
|
63
|
-
),
|
|
64
|
-
);
|
|
65
|
-
return true;
|
|
39
|
+
const hint = regexDialectHint(patterns) ?? "set literal:true to search the text exactly";
|
|
40
|
+
throw new Error(`${result.stderr.trim()}\n${hint}.`);
|
|
66
41
|
}
|
|
67
42
|
throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
|
|
68
43
|
}
|
package/src/pi/grep-search.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { resolve } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { normalizeLineEndings } from "../core/lines.ts";
|
|
4
4
|
import { scanTextFile } from "./text-stream.ts";
|
|
5
5
|
import {
|
|
6
6
|
type RgRunResult,
|
|
@@ -13,7 +13,8 @@ import {
|
|
|
13
13
|
type SearchModes,
|
|
14
14
|
} from "./rg-process.ts";
|
|
15
15
|
import { submatchesToLineRanges } from "./rg-line-ranges.ts";
|
|
16
|
-
import {
|
|
16
|
+
import { rawMatchRevision, type RawMatchRevision } from "./rg-match-bytes.ts";
|
|
17
|
+
import { searchChangedError, throwIfCancelled } from "./error-text.ts";
|
|
17
18
|
|
|
18
19
|
/** Surface incomplete search diagnostics without discarding confirmed matches. */
|
|
19
20
|
export function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
|
|
@@ -32,6 +33,8 @@ export interface RgMatch {
|
|
|
32
33
|
lineNumber: number;
|
|
33
34
|
column?: number;
|
|
34
35
|
matchedText?: string;
|
|
36
|
+
/** Shared whole-event digest: a limited row still depends on every byte in its raw match. */
|
|
37
|
+
rawMatch?: RawMatchRevision;
|
|
35
38
|
}
|
|
36
39
|
|
|
37
40
|
interface RgJsonEvent {
|
|
@@ -40,6 +43,7 @@ interface RgJsonEvent {
|
|
|
40
43
|
path?: Parameters<typeof rgText>[0];
|
|
41
44
|
lines?: Parameters<typeof rgBytes>[0];
|
|
42
45
|
line_number?: number;
|
|
46
|
+
absolute_offset?: number;
|
|
43
47
|
submatches?: { start: number; end: number }[];
|
|
44
48
|
};
|
|
45
49
|
}
|
|
@@ -55,15 +59,19 @@ export interface SearchScope {
|
|
|
55
59
|
export interface SearchRequest {
|
|
56
60
|
/** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
|
|
57
61
|
readonly matcher: readonly string[];
|
|
62
|
+
/** Original patterns for raw-byte files; omitted when they equal the LF-view patterns. */
|
|
63
|
+
readonly rawMatcher?: readonly string[];
|
|
58
64
|
readonly scope: SearchScope;
|
|
59
65
|
}
|
|
60
66
|
|
|
67
|
+
export type SearchTextView = { kind: "lf" } | { kind: "raw"; snapshot: SearchFileSnapshot };
|
|
68
|
+
|
|
61
69
|
/** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
|
|
62
70
|
export type SearchRunner = (
|
|
63
71
|
rgPath: string,
|
|
64
72
|
request: SearchRequest,
|
|
65
73
|
signal: AbortSignal | undefined,
|
|
66
|
-
onLine: (line: string) => boolean | Promise<boolean>,
|
|
74
|
+
onLine: (line: string, view: SearchTextView) => boolean | Promise<boolean>,
|
|
67
75
|
) => Promise<RgRunResult>;
|
|
68
76
|
|
|
69
77
|
/** @internal — injectable process boundary for deterministic tests. */
|
|
@@ -96,10 +104,28 @@ interface SearchMatchesOptions {
|
|
|
96
104
|
warnings: string[];
|
|
97
105
|
}
|
|
98
106
|
|
|
99
|
-
|
|
107
|
+
/** What a matched file looked like when searched; content output re-verifies it before display. */
|
|
108
|
+
export interface SearchFileSnapshot {
|
|
109
|
+
revision: string;
|
|
110
|
+
validUtf8: boolean;
|
|
111
|
+
totalLines: number;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Snapshot a matched file; undefined when it contains NUL and must be skipped. */
|
|
115
|
+
async function scanFileSnapshot(
|
|
116
|
+
filePath: string,
|
|
117
|
+
signal?: AbortSignal,
|
|
118
|
+
): Promise<SearchFileSnapshot | undefined> {
|
|
100
119
|
const hash = createHash("sha256");
|
|
101
|
-
const stats = await scanTextFile(
|
|
102
|
-
|
|
120
|
+
const stats = await scanTextFile(
|
|
121
|
+
filePath,
|
|
122
|
+
undefined,
|
|
123
|
+
signal,
|
|
124
|
+
(bytes) => hash.update(bytes),
|
|
125
|
+
"lossy",
|
|
126
|
+
);
|
|
127
|
+
if (stats.hasNul) return undefined;
|
|
128
|
+
return { revision: hash.digest("hex"), validUtf8: stats.validUtf8, totalLines: stats.totalLines };
|
|
103
129
|
}
|
|
104
130
|
|
|
105
131
|
export function fileReadWarning(
|
|
@@ -113,22 +139,27 @@ export function fileReadWarning(
|
|
|
113
139
|
|
|
114
140
|
export async function searchMatches(options: SearchMatchesOptions) {
|
|
115
141
|
const { backend, rgPath, scope, patterns, modes, limit, outputMode, signal, warnings } = options;
|
|
142
|
+
// Content rows and multiline line mapping read the file; the text view already skips NUL files.
|
|
143
|
+
const needsSnapshot = outputMode === "content" || modes.multiline;
|
|
116
144
|
const raw: RgMatch[] = [];
|
|
117
|
-
const
|
|
118
|
-
const lineCounts = new Map<string, number>();
|
|
145
|
+
const snapshots = new Map<string, SearchFileSnapshot>();
|
|
119
146
|
let matchLimitReached = false;
|
|
120
147
|
const unreadableFiles = new Set<string>();
|
|
121
148
|
const seenMatches = new Set<string>();
|
|
122
149
|
// rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
|
|
123
150
|
const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
|
|
124
151
|
for (const group of patternGroups) {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
152
|
+
const args = [...matcherArgs(modes), "--json", "--line-number"];
|
|
153
|
+
const normalized = group.map(normalizeLineEndings);
|
|
154
|
+
const matcher = [...args, ...normalized.flatMap((pattern) => ["-e", pattern])];
|
|
155
|
+
const request: SearchRequest = {
|
|
156
|
+
matcher,
|
|
157
|
+
scope,
|
|
158
|
+
...(group.some((pattern, index) => pattern !== normalized[index])
|
|
159
|
+
? { rawMatcher: [...args, ...group.flatMap((pattern) => ["-e", pattern])] }
|
|
160
|
+
: {}),
|
|
161
|
+
};
|
|
162
|
+
const run = await backend.search(rgPath, request, signal, async (line, view) => {
|
|
132
163
|
if (raw.length >= limit) return false;
|
|
133
164
|
let event: RgJsonEvent;
|
|
134
165
|
try {
|
|
@@ -146,26 +177,44 @@ export async function searchMatches(options: SearchMatchesOptions) {
|
|
|
146
177
|
)
|
|
147
178
|
return true;
|
|
148
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();
|
|
149
204
|
const startLine = data.line_number;
|
|
150
205
|
const bytes = rgBytes(data.lines);
|
|
151
|
-
const
|
|
152
|
-
|
|
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) => {
|
|
153
215
|
const matchKey = `${filePath}\0${match.lineNumber}`;
|
|
154
216
|
if (seenMatches.has(matchKey)) return true;
|
|
155
217
|
seenMatches.add(matchKey);
|
|
156
|
-
if (outputMode === "content" && !revisions.has(filePath)) {
|
|
157
|
-
try {
|
|
158
|
-
const stats = await scanFileRevision(filePath, signal);
|
|
159
|
-
if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
|
|
160
|
-
revisions.set(filePath, stats.revision);
|
|
161
|
-
} catch (error) {
|
|
162
|
-
const warning = fileReadWarning(filePath, error, signal);
|
|
163
|
-
if (!warning) throw error;
|
|
164
|
-
warnings.push(warning);
|
|
165
|
-
unreadableFiles.add(filePath);
|
|
166
|
-
return true;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
218
|
raw.push(match);
|
|
170
219
|
if (raw.length >= limit) {
|
|
171
220
|
matchLimitReached = true;
|
|
@@ -178,45 +227,32 @@ export async function searchMatches(options: SearchMatchesOptions) {
|
|
|
178
227
|
filePath,
|
|
179
228
|
lineNumber: startLine,
|
|
180
229
|
column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
|
|
181
|
-
matchedText
|
|
230
|
+
matchedText,
|
|
231
|
+
rawMatch,
|
|
182
232
|
});
|
|
183
233
|
}
|
|
184
|
-
if (unreadableFiles.has(filePath)) return true;
|
|
185
234
|
if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
|
|
186
|
-
let lineCount = lineCounts.get(filePath);
|
|
187
|
-
if (lineCount === undefined) {
|
|
188
|
-
try {
|
|
189
|
-
const stats =
|
|
190
|
-
outputMode === "content"
|
|
191
|
-
? await scanFileRevision(filePath, signal)
|
|
192
|
-
: await scanTextFile(filePath, undefined, signal);
|
|
193
|
-
if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
|
|
194
|
-
lineCount = stats.totalLines;
|
|
195
|
-
lineCounts.set(filePath, lineCount);
|
|
196
|
-
if ("revision" in stats && typeof stats.revision === "string") {
|
|
197
|
-
revisions.set(filePath, stats.revision);
|
|
198
|
-
}
|
|
199
|
-
} catch (error) {
|
|
200
|
-
const warning = fileReadWarning(filePath, error, signal);
|
|
201
|
-
if (!warning) throw error;
|
|
202
|
-
warnings.push(warning);
|
|
203
|
-
unreadableFiles.add(filePath);
|
|
204
|
-
return true;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
235
|
const columns = new Map<number, number>();
|
|
208
236
|
const submatches = data.submatches.length ? data.submatches : [{ start: 0, end: 0 }];
|
|
209
|
-
const ranges = submatchesToLineRanges(
|
|
210
|
-
|
|
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");
|
|
211
246
|
for (const [start, end] of ranges) {
|
|
212
247
|
for (let lineNumber = start; lineNumber < end; lineNumber++) {
|
|
213
248
|
if (
|
|
214
|
-
!
|
|
249
|
+
!addMatch({
|
|
215
250
|
filePath,
|
|
216
251
|
lineNumber,
|
|
217
252
|
column: columns.get(lineNumber),
|
|
218
253
|
matchedText: texts[lineNumber - startLine],
|
|
219
|
-
|
|
254
|
+
rawMatch,
|
|
255
|
+
})
|
|
220
256
|
)
|
|
221
257
|
return false;
|
|
222
258
|
}
|
|
@@ -227,5 +263,5 @@ export async function searchMatches(options: SearchMatchesOptions) {
|
|
|
227
263
|
recordSearchDiagnostics(run, warnings);
|
|
228
264
|
if (matchLimitReached) break;
|
|
229
265
|
}
|
|
230
|
-
return { raw, matchLimitReached,
|
|
266
|
+
return { raw, matchLimitReached, snapshots };
|
|
231
267
|
}
|