@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 +161 -304
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +10 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +189 -60
- package/src/core/apply.ts +110 -74
- package/src/core/case-fold.test.ts +40 -0
- package/src/core/case-fold.ts +81 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +170 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/lines.ts +7 -0
- package/src/core/regex.ts +21 -0
- package/src/core/replace-schema.ts +34 -0
- package/src/core/replace.ts +37 -54
- package/src/core/search-analysis.test.ts +199 -0
- package/src/core/search-analysis.ts +375 -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 +16 -11
- package/src/index.ts +25 -15
- package/src/integration/config-registration.test.ts +30 -24
- package/src/integration/forget-grep.test.ts +52 -2
- package/src/integration/fusion-dispatch.test.ts +21 -105
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +280 -0
- package/src/integration/grep-js-completeness.test.ts +208 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-path-matrix.test.ts +132 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +410 -0
- package/src/integration/grep-rg.test.ts +220 -402
- package/src/integration/grep-scan-budget.test.ts +89 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +57 -1
- package/src/integration/model-budget-lifecycle.test.ts +128 -0
- package/src/integration/mutation-file-types.test.ts +12 -25
- 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 +123 -0
- package/src/integration/publication-read-changes.test.ts +344 -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 +33 -0
- package/src/integration/replace-worker-boundary.test.ts +107 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +55 -0
- package/src/pi/action-fusion.test.ts +253 -103
- package/src/pi/action-fusion.ts +116 -290
- package/src/pi/anchor-format.ts +9 -0
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +43 -0
- package/src/pi/argument-error.ts +78 -0
- package/src/pi/argument-format.test.ts +208 -0
- package/src/pi/argument-validation.test.ts +742 -45
- package/src/pi/argument-validation.ts +56 -59
- package/src/pi/budgets.ts +45 -16
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +14 -10
- package/src/pi/config.ts +21 -7
- package/src/pi/diagnostic-buffer.test.ts +52 -16
- package/src/pi/diagnostic-buffer.ts +11 -14
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +100 -93
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +362 -315
- package/src/pi/extension-loading.test.ts +14 -0
- package/src/pi/extension-loading.testing.ts +3 -0
- package/src/pi/failure-context.test.ts +220 -88
- package/src/pi/failure-context.ts +161 -180
- package/src/pi/failure-path.test.ts +85 -88
- package/src/pi/file-commit.test.ts +78 -45
- package/src/pi/file-commit.ts +218 -151
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/forget-tool.ts +189 -90
- package/src/pi/forget.test.ts +309 -22
- package/src/pi/forget.testing.ts +41 -113
- package/src/pi/fusion-card.test.ts +40 -14
- package/src/pi/fusion-card.ts +84 -50
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +193 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-output.ts +181 -138
- package/src/pi/grep-render.ts +28 -25
- package/src/pi/grep-scope.ts +61 -53
- package/src/pi/grep-search.ts +299 -242
- package/src/pi/grep-tool.ts +150 -140
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +631 -632
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +5 -5
- package/src/pi/mutation-result.test.ts +21 -74
- package/src/pi/mutation-result.ts +74 -87
- package/src/pi/mutation-runner.ts +83 -75
- package/src/pi/output-budgets.test.ts +166 -0
- package/src/pi/path.ts +7 -0
- package/src/pi/read-tool.ts +151 -137
- package/src/pi/read.test.ts +39 -33
- package/src/pi/regex-worker-contract.ts +73 -0
- package/src/pi/regex-worker.ts +101 -0
- package/src/pi/registration.test.ts +111 -92
- package/src/pi/render.test.ts +193 -19
- package/src/pi/render.ts +137 -29
- package/src/pi/replace-regex.ts +11 -44
- package/src/pi/replace-tool.ts +38 -145
- package/src/pi/replace-worker-contract.ts +19 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +93 -160
- package/src/pi/report-cause.ts +99 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +512 -0
- package/src/pi/report.test.ts +276 -0
- package/src/pi/report.ts +288 -0
- package/src/pi/result-safety.test.ts +122 -427
- package/src/pi/rg-process.test.ts +78 -79
- package/src/pi/rg-process.ts +124 -177
- package/src/pi/rg-regex.test.ts +50 -0
- package/src/pi/rg-regex.ts +709 -0
- package/src/pi/text-stream.test.ts +67 -38
- package/src/pi/text-stream.ts +96 -75
- package/src/pi/tool-call.testing.ts +3 -39
- package/src/pi/write-tool.ts +45 -34
- package/src/pi/write.test.ts +45 -37
- 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 +308 -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/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
|
@@ -1,94 +1,93 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import {
|
|
3
|
+
import { recordSearchDiagnostics, runRgLines } from "./rg-process.ts";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { HashlineError } from "../core/errors.ts";
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
7
|
+
test("grep search exit status → accepts no matches and preserves failure diagnostics", () => {
|
|
8
|
+
for (const code of [0, 1]) {
|
|
9
|
+
const warnings: string[] = [];
|
|
10
|
+
recordSearchDiagnostics({ code, stderr: "", stopped: false }, warnings);
|
|
11
|
+
assert.deepEqual(warnings, []);
|
|
12
|
+
}
|
|
13
|
+
const warnings: string[] = [];
|
|
14
|
+
recordSearchDiagnostics({ code: 2, stderr: " regex parse error\n", stopped: false }, warnings);
|
|
15
|
+
recordSearchDiagnostics({ code: null, stderr: "", stopped: false }, warnings);
|
|
16
|
+
assert.equal(warnings.length, 2);
|
|
17
|
+
assert.equal(warnings[0], "regex parse error");
|
|
18
|
+
assert.match(warnings[1], /null/);
|
|
14
19
|
});
|
|
15
20
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
21
|
+
const listingFixture = fileURLToPath(
|
|
22
|
+
new URL("../testing/rg-line-listing.fixture.mjs", import.meta.url),
|
|
23
|
+
);
|
|
24
|
+
const parserTimeoutMs = 5_000;
|
|
25
|
+
|
|
26
|
+
async function parseListing(chunks: readonly string[], maxLines = 10, stop = false) {
|
|
27
|
+
const files: { path: string; lines: readonly number[] | undefined }[] = [];
|
|
28
|
+
const result = await runRgLines(
|
|
29
|
+
process.execPath,
|
|
30
|
+
[
|
|
31
|
+
listingFixture,
|
|
32
|
+
JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
|
|
33
|
+
...(stop ? ["wait"] : []),
|
|
34
|
+
],
|
|
35
|
+
AbortSignal.timeout(parserTimeoutMs),
|
|
36
|
+
maxLines,
|
|
37
|
+
(path, lines) => {
|
|
38
|
+
files.push({ path, lines });
|
|
39
|
+
return !stop;
|
|
28
40
|
},
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
assert.deepEqual(
|
|
44
|
-
args.flatMap((arg, index) => (args[index - 1] === "-e" ? [arg] : [])),
|
|
45
|
-
expectedPatterns,
|
|
46
|
-
);
|
|
47
|
-
return { code, stdout, stderr: "" };
|
|
48
|
-
};
|
|
49
|
-
assert.equal(
|
|
50
|
-
await resolveIgnoreCase("rg", patterns, modes, undefined, undefined, run),
|
|
51
|
-
expected,
|
|
52
|
-
);
|
|
53
|
-
assert.equal(calls, 1);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
41
|
+
);
|
|
42
|
+
return { files, result };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async () => {
|
|
46
|
+
const listing =
|
|
47
|
+
"dir\nfile.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n";
|
|
48
|
+
const { files, result } = await parseListing([...listing]);
|
|
49
|
+
assert.deepEqual(files, [
|
|
50
|
+
{ path: "dir\nfile.txt", lines: [1, 2, 10] },
|
|
51
|
+
{ path: "other.txt", lines: [3] },
|
|
52
|
+
]);
|
|
53
|
+
assert.equal(result.code, 0);
|
|
54
|
+
assert.equal(result.stopped, false);
|
|
56
55
|
});
|
|
57
56
|
|
|
58
|
-
test("
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
57
|
+
test("line listing exceeds maxLines → only the overflowing file requests all-line review", async () => {
|
|
58
|
+
for (const maxLines of [2, 3]) {
|
|
59
|
+
const { files } = await parseListing(
|
|
60
|
+
["many\0" + "1:x\n2:y\n3:z\n\nfew\0" + "1:\n\n"],
|
|
61
|
+
maxLines,
|
|
62
|
+
);
|
|
63
|
+
assert.deepEqual(files, [
|
|
64
|
+
{ path: "many", lines: maxLines === 2 ? undefined : [1, 2, 3] },
|
|
65
|
+
{ path: "few", lines: [1] },
|
|
66
|
+
]);
|
|
67
|
+
}
|
|
68
|
+
});
|
|
64
69
|
|
|
65
|
-
|
|
66
|
-
await
|
|
67
|
-
|
|
68
|
-
|
|
70
|
+
test("line consumer returns false → process stops before the next file", async () => {
|
|
71
|
+
const { files, result } = await parseListing(
|
|
72
|
+
["first\0" + "1:x\n\nsecond\0" + "2:y\n\n"],
|
|
73
|
+
10,
|
|
74
|
+
true,
|
|
69
75
|
);
|
|
76
|
+
assert.deepEqual(files, [{ path: "first", lines: [1] }]);
|
|
77
|
+
assert.equal(result.stopped, true);
|
|
70
78
|
});
|
|
71
79
|
|
|
72
|
-
test("
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
resolveIgnoreCase("rg", ["foo"], lineModes, undefined, controller.signal, run),
|
|
80
|
-
/Operation aborted/,
|
|
81
|
-
);
|
|
80
|
+
test("line listing ends with incomplete path or row → RIPGREP_FAILED", async () => {
|
|
81
|
+
for (const record of ["unfinished-path", "file\0" + "1:x", "file\0" + "1"]) {
|
|
82
|
+
await assert.rejects(
|
|
83
|
+
parseListing([record]),
|
|
84
|
+
(error: unknown) => error instanceof HashlineError && error.errorCode === "RIPGREP_FAILED",
|
|
85
|
+
);
|
|
86
|
+
}
|
|
82
87
|
});
|
|
83
88
|
|
|
84
|
-
test("
|
|
85
|
-
|
|
86
|
-
assert.
|
|
87
|
-
|
|
88
|
-
/^Error: regex parse error$/,
|
|
89
|
-
);
|
|
90
|
-
assert.throws(
|
|
91
|
-
() => assertRgSucceeded({ code: null, stderr: "" }),
|
|
92
|
-
/ripgrep exited with code null/,
|
|
93
|
-
);
|
|
89
|
+
test("line listing ends after a complete row → flush the final file without a separator", async () => {
|
|
90
|
+
const { files, result } = await parseListing(["final\0" + "1:x\n"]);
|
|
91
|
+
assert.deepEqual(files, [{ path: "final", lines: [1] }]);
|
|
92
|
+
assert.equal(result.code, 0);
|
|
94
93
|
});
|
package/src/pi/rg-process.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* ripgrep process layer: spawning and cancelling rg, bounded record and
|
|
3
|
-
* stderr reading, shared arguments,
|
|
4
|
-
*
|
|
3
|
+
* stderr reading, shared arguments, and the output protocols it parses.
|
|
4
|
+
* Knows nothing about candidate strategy, anchors, or output formatting.
|
|
5
5
|
*
|
|
6
6
|
* @module pi-hashline-edit/pi
|
|
7
7
|
*/
|
|
@@ -10,23 +10,37 @@ import { StringDecoder } from "node:string_decoder";
|
|
|
10
10
|
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
11
11
|
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
12
12
|
import type { Readable } from "node:stream";
|
|
13
|
-
import {
|
|
13
|
+
import { HashlineError } from "../core/errors.ts";
|
|
14
14
|
import { throwIfCancelled } from "./error-text.ts";
|
|
15
15
|
|
|
16
|
-
export const COMMON_RG_ARGS = ["--no-config", "--color=never"
|
|
16
|
+
export const COMMON_RG_ARGS = ["--no-config", "--color=never"];
|
|
17
17
|
export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
|
|
18
|
-
const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES / 1024 ** 2} MiB.`;
|
|
19
|
+
/**
|
|
20
|
+
* A ripgrep process or output-protocol failure. A finished run contributes its
|
|
21
|
+
* exit code and, as the cause, its stderr.
|
|
22
|
+
*/
|
|
23
|
+
export function ripgrepFailure(
|
|
24
|
+
message: string,
|
|
25
|
+
run?: { readonly code: number | null; readonly stderr: string } | { readonly error: unknown },
|
|
26
|
+
): HashlineError<"RIPGREP_FAILED"> {
|
|
27
|
+
if (run === undefined) return new HashlineError("RIPGREP_FAILED", message);
|
|
28
|
+
if ("error" in run) return new HashlineError("RIPGREP_FAILED", message, { cause: run.error });
|
|
29
|
+
const stderr = run.stderr.trim();
|
|
30
|
+
return new HashlineError("RIPGREP_FAILED", message, {
|
|
31
|
+
facts: { exitCode: run.code },
|
|
32
|
+
...(stderr ? { cause: stderr } : {}),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
23
35
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
multiline: boolean;
|
|
36
|
+
/** rg reported a path that is not valid UTF-8; tools cannot address it. */
|
|
37
|
+
function unsupportedPath(): HashlineError {
|
|
38
|
+
return new HashlineError("UNSUPPORTED_PATH", "Non-UTF-8 search paths are not supported.");
|
|
28
39
|
}
|
|
29
40
|
|
|
41
|
+
/** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
|
|
42
|
+
export const MAX_RG_STDERR_BYTES = 64 * 1024;
|
|
43
|
+
|
|
30
44
|
interface ExitResult {
|
|
31
45
|
code: number | null;
|
|
32
46
|
stderr: string;
|
|
@@ -45,6 +59,22 @@ export interface RgRunResult {
|
|
|
45
59
|
stopped: boolean;
|
|
46
60
|
}
|
|
47
61
|
|
|
62
|
+
/** @internal — injectable process boundary for deterministic tests. */
|
|
63
|
+
export interface GrepBackend {
|
|
64
|
+
runRgPaths: typeof runRgPaths;
|
|
65
|
+
runRgLines: typeof runRgLines;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Surface incomplete search diagnostics without discarding confirmed matches. */
|
|
69
|
+
export function recordSearchDiagnostics(result: RgRunResult, warnings: string[]): void {
|
|
70
|
+
const message =
|
|
71
|
+
result.stderr.trim() ||
|
|
72
|
+
(!result.stopped && result.code !== 0 && result.code !== 1
|
|
73
|
+
? `ripgrep exited with code ${result.code}.`
|
|
74
|
+
: "");
|
|
75
|
+
if (message) warnings.push(message);
|
|
76
|
+
}
|
|
77
|
+
|
|
48
78
|
function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal): RunningProcess {
|
|
49
79
|
throwIfCancelled(signal);
|
|
50
80
|
const env = { ...process.env };
|
|
@@ -94,7 +124,7 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
|
|
|
94
124
|
return { child, done, kill };
|
|
95
125
|
}
|
|
96
126
|
|
|
97
|
-
async function*
|
|
127
|
+
async function* nulDelimitedRecords(stream: Readable): AsyncGenerator<Buffer> {
|
|
98
128
|
let pending = Buffer.alloc(0);
|
|
99
129
|
for await (const value of stream) {
|
|
100
130
|
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
@@ -102,40 +132,32 @@ async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGene
|
|
|
102
132
|
let buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
103
133
|
pending = Buffer.alloc(0);
|
|
104
134
|
let at: number;
|
|
105
|
-
while ((at = buf.indexOf(
|
|
106
|
-
if (at > MAX_RG_RECORD_BYTES) throw
|
|
135
|
+
while ((at = buf.indexOf("\0")) !== -1) {
|
|
136
|
+
if (at > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
|
|
107
137
|
yield buf.subarray(0, at);
|
|
108
138
|
buf = buf.subarray(at + 1);
|
|
109
139
|
}
|
|
110
|
-
if (buf.length > MAX_RG_RECORD_BYTES) throw
|
|
140
|
+
if (buf.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
|
|
111
141
|
pending = buf;
|
|
112
142
|
}
|
|
113
143
|
if (pending.length) yield pending;
|
|
114
144
|
}
|
|
115
145
|
|
|
116
|
-
|
|
146
|
+
/** Run rg while read consumes its stdout; read returns false to stop rg early. */
|
|
147
|
+
async function runRg(
|
|
117
148
|
rgPath: string,
|
|
118
149
|
args: readonly string[],
|
|
119
|
-
input: Buffer | undefined,
|
|
120
|
-
delimiter: number,
|
|
121
150
|
signal: AbortSignal | undefined,
|
|
122
|
-
|
|
151
|
+
read: (stdout: Readable) => Promise<boolean>,
|
|
123
152
|
): Promise<RgRunResult> {
|
|
124
153
|
const process = startRg(rgPath, args, signal);
|
|
125
|
-
|
|
126
|
-
process.child.stdin.end(input);
|
|
154
|
+
process.child.stdin.end();
|
|
127
155
|
try {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (!(await onRecord(record))) {
|
|
131
|
-
stopped = true;
|
|
132
|
-
process.kill();
|
|
133
|
-
break;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
156
|
+
const stopped = !(await read(process.child.stdout));
|
|
157
|
+
if (stopped) process.kill();
|
|
136
158
|
const result = await process.done;
|
|
137
159
|
throwIfCancelled(signal);
|
|
138
|
-
if (result.error) throw
|
|
160
|
+
if (result.error) throw ripgrepFailure("Failed to run ripgrep.", { error: result.error });
|
|
139
161
|
return { code: result.code, stderr: result.stderr, stopped };
|
|
140
162
|
} finally {
|
|
141
163
|
process.kill();
|
|
@@ -143,18 +165,6 @@ async function runDelimited(
|
|
|
143
165
|
}
|
|
144
166
|
}
|
|
145
167
|
|
|
146
|
-
/** @internal — shared process boundary for JSONL searches. */
|
|
147
|
-
export function runRg(
|
|
148
|
-
rgPath: string,
|
|
149
|
-
args: string[],
|
|
150
|
-
signal: AbortSignal | undefined,
|
|
151
|
-
onLine: (line: string) => boolean | Promise<boolean>,
|
|
152
|
-
): Promise<RgRunResult> {
|
|
153
|
-
return runDelimited(rgPath, args, undefined, 10, signal, (record) =>
|
|
154
|
-
record.length === 0 ? true : onLine(record.toString("utf8")),
|
|
155
|
-
);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
168
|
/** @internal — read NUL-delimited UTF-8 paths from an owned rg process. */
|
|
159
169
|
export function runRgPaths(
|
|
160
170
|
rgPath: string,
|
|
@@ -162,145 +172,82 @@ export function runRgPaths(
|
|
|
162
172
|
signal: AbortSignal | undefined,
|
|
163
173
|
onPath: (path: string) => boolean | Promise<boolean>,
|
|
164
174
|
): Promise<RgRunResult> {
|
|
165
|
-
return
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
175
|
+
return runRg(rgPath, args, signal, async (stdout) => {
|
|
176
|
+
for await (const record of nulDelimitedRecords(stdout)) {
|
|
177
|
+
throwIfCancelled(signal);
|
|
178
|
+
if (!(await onPath(decodePath(record)))) return false;
|
|
179
|
+
}
|
|
180
|
+
return true;
|
|
170
181
|
});
|
|
171
182
|
}
|
|
172
183
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
}
|
|
184
|
+
function decodePath(record: Buffer): string {
|
|
185
|
+
const path = record.toString("utf8");
|
|
186
|
+
if (!Buffer.from(path, "utf8").equals(record)) throw unsupportedPath();
|
|
187
|
+
return path;
|
|
178
188
|
}
|
|
179
189
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
190
|
+
/** Arguments that make rg print, per file, its NUL-terminated path and matching line numbers. */
|
|
191
|
+
export const LINE_LISTING_ARGS = [
|
|
192
|
+
"--text",
|
|
193
|
+
"--null",
|
|
194
|
+
"--heading",
|
|
195
|
+
"--with-filename",
|
|
196
|
+
"--line-number",
|
|
197
|
+
"--max-columns=1",
|
|
198
|
+
];
|
|
185
199
|
|
|
186
|
-
|
|
200
|
+
/**
|
|
201
|
+
* @internal — read a {@link LINE_LISTING_ARGS} listing. Each file's group is a NUL-terminated
|
|
202
|
+
* path, then one `N:` record per matching line ending in a line feed (its content is at most
|
|
203
|
+
* one byte or an omission notice), then an empty line. onFile receives a file's ascending line
|
|
204
|
+
* numbers, or undefined once there are more than maxLines.
|
|
205
|
+
*/
|
|
206
|
+
export function runRgLines(
|
|
187
207
|
rgPath: string,
|
|
188
|
-
args:
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
) => Promise<
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
208
|
+
args: string[],
|
|
209
|
+
signal: AbortSignal | undefined,
|
|
210
|
+
maxLines: number,
|
|
211
|
+
onFile: (path: string, lines: readonly number[] | undefined) => boolean | Promise<boolean>,
|
|
212
|
+
): Promise<RgRunResult> {
|
|
213
|
+
return runRg(rgPath, args, signal, async (stdout) => {
|
|
214
|
+
let path: string | undefined;
|
|
215
|
+
let lines: number[] | undefined = [];
|
|
216
|
+
let pending: Buffer = Buffer.alloc(0);
|
|
217
|
+
const flush = () => {
|
|
218
|
+
const found = lines;
|
|
219
|
+
const file = path!;
|
|
220
|
+
path = undefined;
|
|
221
|
+
lines = [];
|
|
222
|
+
return onFile(file, found);
|
|
223
|
+
};
|
|
224
|
+
// Records are parsed synchronously; only a completed file waits for its consumer.
|
|
225
|
+
for await (const value of stdout) {
|
|
226
|
+
throwIfCancelled(signal);
|
|
227
|
+
const chunk = value as Buffer;
|
|
228
|
+
const buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
229
|
+
let at = 0;
|
|
230
|
+
for (;;) {
|
|
231
|
+
const end = buf.indexOf(path === undefined ? 0 : 10, at);
|
|
232
|
+
if (end === -1) break;
|
|
233
|
+
const record = buf.subarray(at, end);
|
|
234
|
+
at = end + 1;
|
|
235
|
+
if (path === undefined) path = decodePath(record);
|
|
236
|
+
else if (!record.length) {
|
|
237
|
+
if (!(await flush())) return false;
|
|
238
|
+
} else if (lines) {
|
|
239
|
+
const colon = record.indexOf(58);
|
|
240
|
+
const line = colon > 0 ? Number(record.subarray(0, colon).toString("latin1")) : NaN;
|
|
241
|
+
if (!Number.isSafeInteger(line) || line < 1)
|
|
242
|
+
throw ripgrepFailure("ripgrep printed an unexpected line record.");
|
|
243
|
+
if (lines.length < maxLines) lines.push(line);
|
|
244
|
+
else lines = undefined;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
pending = buf.subarray(at);
|
|
248
|
+
if (pending.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
|
|
249
|
+
}
|
|
250
|
+
if (pending.length) throw ripgrepFailure("ripgrep printed an incomplete line record.");
|
|
251
|
+
return path === undefined || flush();
|
|
201
252
|
});
|
|
202
|
-
process.child.stdin.end(input);
|
|
203
|
-
const result = await process.done;
|
|
204
|
-
throwIfCancelled(signal);
|
|
205
|
-
if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
|
|
206
|
-
if (bytes > MAX_RG_PROBE_OUTPUT_BYTES)
|
|
207
|
-
throw new Error("Unexpected ripgrep probe output overflow");
|
|
208
|
-
return {
|
|
209
|
-
code: result.code,
|
|
210
|
-
stderr: result.stderr,
|
|
211
|
-
stdout: Buffer.concat(chunks).toString("utf8"),
|
|
212
|
-
};
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
const DEFAULT_RG_MODE_ARGS = [...COMMON_RG_ARGS, "--engine=default"];
|
|
216
|
-
|
|
217
|
-
export function matcherArgs(modes: SearchModes): string[] {
|
|
218
|
-
return [
|
|
219
|
-
...DEFAULT_RG_MODE_ARGS,
|
|
220
|
-
modes.multiline ? "--multiline" : "--no-multiline",
|
|
221
|
-
modes.ignoreCase ? "--ignore-case" : "--case-sensitive",
|
|
222
|
-
...(modes.literal ? ["--fixed-strings"] : []),
|
|
223
|
-
];
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
/** Compile the patterns with rg's default engine against empty input; code 2 with a parse error means invalid regex. */
|
|
227
|
-
export async function probeRegex(
|
|
228
|
-
rgPath: string,
|
|
229
|
-
patterns: readonly string[],
|
|
230
|
-
multiline: boolean,
|
|
231
|
-
signal?: AbortSignal,
|
|
232
|
-
): Promise<Pick<TextRunResult, "code" | "stderr">> {
|
|
233
|
-
return runText(
|
|
234
|
-
rgPath,
|
|
235
|
-
[
|
|
236
|
-
...DEFAULT_RG_MODE_ARGS,
|
|
237
|
-
multiline ? "--multiline" : "--no-multiline",
|
|
238
|
-
"--quiet",
|
|
239
|
-
...patterns.flatMap((pattern) => ["-e", pattern]),
|
|
240
|
-
"--",
|
|
241
|
-
"-",
|
|
242
|
-
],
|
|
243
|
-
Buffer.alloc(0),
|
|
244
|
-
signal,
|
|
245
|
-
);
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
/** Resolve rg's query-level default case flag; inline regex flags still apply normally. */
|
|
249
|
-
export async function resolveIgnoreCase(
|
|
250
|
-
rgPath: string,
|
|
251
|
-
patterns: readonly string[],
|
|
252
|
-
modes: Pick<SearchModes, "literal" | "multiline">,
|
|
253
|
-
explicit: boolean | undefined,
|
|
254
|
-
signal?: AbortSignal,
|
|
255
|
-
run: RunText = runText,
|
|
256
|
-
): Promise<boolean> {
|
|
257
|
-
throwIfCancelled(signal);
|
|
258
|
-
if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
|
|
259
|
-
if (explicit !== undefined) return explicit;
|
|
260
|
-
|
|
261
|
-
const sources = patterns.map((pattern) => (modes.literal ? escapeRegex(pattern) : pattern));
|
|
262
|
-
const result = await run(
|
|
263
|
-
rgPath,
|
|
264
|
-
[
|
|
265
|
-
...DEFAULT_RG_MODE_ARGS,
|
|
266
|
-
modes.multiline ? "--multiline" : "--no-multiline",
|
|
267
|
-
"--smart-case",
|
|
268
|
-
"--encoding=none",
|
|
269
|
-
"--no-heading",
|
|
270
|
-
"--no-filename",
|
|
271
|
-
"--no-line-number",
|
|
272
|
-
"--only-matching",
|
|
273
|
-
"--replace",
|
|
274
|
-
"${1}",
|
|
275
|
-
"-e",
|
|
276
|
-
"(\\p{Lu})",
|
|
277
|
-
...sources.flatMap((pattern) => ["-e", pattern]),
|
|
278
|
-
"--",
|
|
279
|
-
"-",
|
|
280
|
-
],
|
|
281
|
-
Buffer.from("a\n"),
|
|
282
|
-
signal,
|
|
283
|
-
);
|
|
284
|
-
throwIfCancelled(signal);
|
|
285
|
-
assertRgSucceeded(result);
|
|
286
|
-
const lines = result.stdout.replace(/\r\n/g, "\n").split("\n");
|
|
287
|
-
if (lines.some((line) => line !== "" && line !== "a"))
|
|
288
|
-
throw new Error("Unexpected smart-case probe output");
|
|
289
|
-
return lines.includes("a");
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
interface RgString {
|
|
293
|
-
text?: string;
|
|
294
|
-
bytes?: string;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
export function rgBytes(value: RgString): Buffer {
|
|
298
|
-
if (typeof value.text === "string") return Buffer.from(value.text, "utf8");
|
|
299
|
-
if (typeof value.bytes === "string") return Buffer.from(value.bytes, "base64");
|
|
300
|
-
throw new Error("Invalid rg JSON string");
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
export function rgText(value: RgString): string {
|
|
304
|
-
if (typeof value.text === "string") return value.text;
|
|
305
|
-
throw new Error("Non-UTF-8 search paths are not supported");
|
|
306
253
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { lineCandidatePatterns } from "./rg-regex.ts";
|
|
4
|
+
|
|
5
|
+
// These expressions are the byte-level boundary contract, including deliberate widening.
|
|
6
|
+
for (const [pattern, flags, expected] of [
|
|
7
|
+
["a$", "", "a\\r?$"],
|
|
8
|
+
["[A-Z]{10,}", "m", "(?:[A-Z]){10,}"],
|
|
9
|
+
["(?m:^)b", "", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
|
|
10
|
+
["(\\w)\\1{4}", "m", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
|
|
11
|
+
] as const) {
|
|
12
|
+
test(`line candidates ${pattern} /${flags} → preserve required byte positions`, () => {
|
|
13
|
+
assert.deepEqual(
|
|
14
|
+
lineCandidatePatterns({ patterns: [pattern], literal: false, flags, multiline: false }),
|
|
15
|
+
[expected],
|
|
16
|
+
);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
for (const [pattern, expected] of [
|
|
21
|
+
["[[a-c]&&[b-d]]", "[b-c]"],
|
|
22
|
+
["[[a-c]--[b]]", "[ac]"],
|
|
23
|
+
["[\\p{ASCII}&&\\p{Letter}]", "[A-Za-z]"],
|
|
24
|
+
["[\\p{Letter}&&[a-c]]", "[a-c]"],
|
|
25
|
+
["[[a-c]--\\p{Uppercase_Letter}]", "[a-c]"],
|
|
26
|
+
["[a[bc]\\q{de|fg}]", "(?:[a-c]|(?:de|fg))"],
|
|
27
|
+
["[\\q{ab|cd}&&\\q{cd|ef}]", "cd"],
|
|
28
|
+
["[\\q{ab|cd}--\\q{cd}]", "ab"],
|
|
29
|
+
["[\\q{ab|}]", "(?:ab|)"],
|
|
30
|
+
["[[a]--[a]]", "[^\\x{0}-\\x{10ffff}]"],
|
|
31
|
+
] as const) {
|
|
32
|
+
test(`finite v class ${pattern} → narrow candidates without discarding strings`, () => {
|
|
33
|
+
assert.deepEqual(
|
|
34
|
+
lineCandidatePatterns({ patterns: [pattern], literal: false, flags: "v", multiline: false }),
|
|
35
|
+
[expected],
|
|
36
|
+
);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
test("capture disables i inside a caseless reference → retain the reference's case variants", () => {
|
|
41
|
+
assert.deepEqual(
|
|
42
|
+
lineCandidatePatterns({
|
|
43
|
+
patterns: ["((?-i:[[a]--[A]]))(?i:\\1)"],
|
|
44
|
+
literal: false,
|
|
45
|
+
flags: "v",
|
|
46
|
+
multiline: false,
|
|
47
|
+
}),
|
|
48
|
+
["a[Aa]"],
|
|
49
|
+
);
|
|
50
|
+
});
|