@criogaid/pi-hashline-edit 0.6.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -369
- package/README.zh-CN.md +162 -0
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +11 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +328 -161
- package/src/core/apply.ts +129 -95
- package/src/core/case-fold.test.ts +44 -0
- package/src/core/case-fold.ts +77 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +184 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/hash.test.ts +1 -25
- package/src/core/hash.ts +0 -5
- package/src/core/lines.ts +32 -7
- package/src/core/ranges.test.ts +41 -9
- package/src/core/ranges.ts +11 -4
- package/src/core/regex.ts +51 -0
- package/src/core/replace-schema.ts +41 -0
- package/src/core/replace.test.ts +90 -0
- package/src/core/replace.ts +40 -56
- package/src/core/search-analysis.test.ts +208 -0
- package/src/core/search-analysis.ts +379 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +20 -17
- package/src/index.ts +24 -16
- package/src/integration/config-registration.test.ts +42 -28
- package/src/integration/fusion-dispatch.test.ts +62 -127
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +273 -0
- package/src/integration/grep-js-completeness.test.ts +218 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-order.test.ts +78 -0
- package/src/integration/grep-path-matrix.test.ts +133 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +407 -0
- package/src/integration/grep-rg.test.ts +294 -436
- package/src/integration/grep-scan-budget.test.ts +111 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +56 -1
- package/src/integration/model-budget-lifecycle.test.ts +137 -0
- package/src/integration/mutation-file-types.test.ts +12 -26
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +97 -0
- package/src/integration/publication-read-changes.test.ts +376 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +36 -0
- package/src/integration/replace-worker-boundary.test.ts +117 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +54 -0
- package/src/pi/action-fusion.test.ts +256 -251
- package/src/pi/action-fusion.ts +121 -332
- package/src/pi/anchor-format.test.ts +16 -0
- package/src/pi/anchor-format.ts +16 -3
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +46 -0
- package/src/pi/argument-error.ts +76 -0
- package/src/pi/argument-format.test.ts +197 -0
- package/src/pi/argument-validation.test.ts +780 -49
- package/src/pi/argument-validation.ts +55 -58
- package/src/pi/budgets.ts +48 -21
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +29 -15
- package/src/pi/config.ts +27 -13
- package/src/pi/diagnostic-buffer.test.ts +51 -16
- package/src/pi/diagnostic-buffer.ts +13 -16
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +103 -99
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +407 -429
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +265 -88
- package/src/pi/failure-context.ts +165 -181
- package/src/pi/failure-path.test.ts +179 -117
- package/src/pi/file-commit.test.ts +90 -73
- package/src/pi/file-commit.ts +216 -178
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-revision.ts +25 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/fusion-card-interaction.test.ts +143 -0
- package/src/pi/fusion-card.test.ts +233 -51
- package/src/pi/fusion-card.ts +246 -142
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +191 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-order.test.ts +323 -0
- package/src/pi/grep-output.testing.ts +24 -0
- package/src/pi/grep-output.ts +187 -151
- package/src/pi/grep-render.ts +31 -25
- package/src/pi/grep-scope.ts +62 -54
- package/src/pi/grep-search.ts +327 -241
- package/src/pi/grep-tool.ts +126 -147
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +813 -713
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +6 -7
- package/src/pi/mutation-result.test.ts +45 -91
- package/src/pi/mutation-result.ts +86 -114
- package/src/pi/mutation-runner.ts +81 -81
- package/src/pi/output-budgets.test.ts +175 -0
- package/src/pi/path.ts +10 -1
- package/src/pi/pi.test.ts +4 -5
- package/src/pi/read-tool.ts +108 -142
- package/src/pi/read.test.ts +155 -96
- package/src/pi/regex-worker-contract.ts +55 -0
- package/src/pi/regex-worker.ts +95 -0
- package/src/pi/registration.test.ts +148 -124
- package/src/pi/render.test.ts +361 -84
- package/src/pi/render.ts +150 -32
- package/src/pi/replace-regex.ts +13 -48
- package/src/pi/replace-tool.ts +52 -158
- package/src/pi/replace-worker-contract.ts +10 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +191 -340
- package/src/pi/report-cause.ts +103 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +524 -0
- package/src/pi/report.test.ts +343 -0
- package/src/pi/report.ts +285 -0
- package/src/pi/result-safety.test.ts +216 -481
- package/src/pi/rg-process.test.ts +101 -76
- package/src/pi/rg-process.ts +130 -177
- package/src/pi/rg-regex.test.ts +67 -0
- package/src/pi/rg-regex.ts +715 -0
- package/src/pi/text-stream.test.ts +97 -69
- package/src/pi/text-stream.ts +97 -76
- package/src/pi/tool-call.testing.ts +20 -46
- package/src/pi/write-tool.ts +50 -41
- package/src/pi/write.test.ts +71 -95
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +324 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/integration/forget-grep.test.ts +0 -98
- package/src/pi/forget-tool.ts +0 -268
- package/src/pi/forget.test.ts +0 -343
- package/src/pi/forget.testing.ts +0 -273
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
|
@@ -1,94 +1,119 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import
|
|
3
|
+
import childProcess from "node:child_process";
|
|
4
|
+
import { syncBuiltinESMExports } from "node:module";
|
|
5
|
+
import { Readable } from "node:stream";
|
|
6
|
+
import { recordSearchDiagnostics, runRgLines } from "./rg-process.ts";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { HashlineError } from "../core/errors.ts";
|
|
4
9
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
}
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
10
|
+
test("grep search exit status → accepts no matches and preserves failure diagnostics", () => {
|
|
11
|
+
for (const code of [0, 1]) {
|
|
12
|
+
const warnings: string[] = [];
|
|
13
|
+
recordSearchDiagnostics({ code, stderr: "", stopped: false }, warnings);
|
|
14
|
+
assert.deepEqual(warnings, []);
|
|
15
|
+
}
|
|
16
|
+
const warnings: string[] = [];
|
|
17
|
+
recordSearchDiagnostics({ code: 2, stderr: " regex parse error\n", stopped: false }, warnings);
|
|
18
|
+
recordSearchDiagnostics({ code: null, stderr: "", stopped: false }, warnings);
|
|
19
|
+
assert.equal(warnings.length, 2);
|
|
20
|
+
assert.equal(warnings[0], "regex parse error");
|
|
21
|
+
assert.match(warnings[1], /null/);
|
|
14
22
|
});
|
|
15
23
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
24
|
+
const listingFixture = fileURLToPath(
|
|
25
|
+
new URL("../testing/rg-line-listing.fixture.mjs", import.meta.url),
|
|
26
|
+
);
|
|
27
|
+
const parserTimeoutMs = 5_000;
|
|
28
|
+
|
|
29
|
+
async function parseListing(chunks: readonly string[], maxLines = 10, stop = false) {
|
|
30
|
+
const files: { path: string; lines: readonly number[] | undefined }[] = [];
|
|
31
|
+
const result = await runRgLines(
|
|
32
|
+
process.execPath,
|
|
33
|
+
[
|
|
34
|
+
listingFixture,
|
|
35
|
+
JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
|
|
36
|
+
...(stop ? ["wait"] : []),
|
|
37
|
+
],
|
|
38
|
+
AbortSignal.timeout(parserTimeoutMs),
|
|
39
|
+
maxLines,
|
|
40
|
+
(path, lines) => {
|
|
41
|
+
files.push({ path, lines });
|
|
42
|
+
return !stop;
|
|
28
43
|
},
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
44
|
+
);
|
|
45
|
+
return { files, result };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async (t) => {
|
|
49
|
+
const listing = Buffer.from(
|
|
50
|
+
"dir\n文件.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n",
|
|
51
|
+
);
|
|
52
|
+
const spawn = childProcess.spawn;
|
|
53
|
+
let chunks: Buffer[] = [];
|
|
54
|
+
try {
|
|
55
|
+
t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
|
|
56
|
+
const child = spawn(...args);
|
|
57
|
+
assert.ok(child.stdout);
|
|
58
|
+
const stream = Readable.from(chunks);
|
|
59
|
+
t.mock.method(child.stdout, Symbol.asyncIterator, () => stream[Symbol.asyncIterator]());
|
|
60
|
+
return child;
|
|
61
|
+
});
|
|
62
|
+
syncBuiltinESMExports();
|
|
63
|
+
for (let split = 1; split < listing.length; split++) {
|
|
64
|
+
chunks = [listing.subarray(0, split), listing.subarray(split)];
|
|
65
|
+
const { files, result } = await parseListing([]);
|
|
66
|
+
assert.deepEqual(
|
|
67
|
+
files,
|
|
68
|
+
[
|
|
69
|
+
{ path: "dir\n文件.txt", lines: [1, 2, 10] },
|
|
70
|
+
{ path: "other.txt", lines: [3] },
|
|
71
|
+
],
|
|
72
|
+
`split=${split}`,
|
|
52
73
|
);
|
|
53
|
-
assert.equal(
|
|
74
|
+
assert.equal(result.code, 0);
|
|
75
|
+
assert.equal(result.stopped, false);
|
|
54
76
|
}
|
|
77
|
+
} finally {
|
|
78
|
+
t.mock.restoreAll();
|
|
79
|
+
syncBuiltinESMExports();
|
|
55
80
|
}
|
|
56
81
|
});
|
|
57
82
|
|
|
58
|
-
test("
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
83
|
+
test("line listing exceeds maxLines → only the overflowing file requests all-line review", async () => {
|
|
84
|
+
for (const maxLines of [2, 3]) {
|
|
85
|
+
const { files } = await parseListing(
|
|
86
|
+
["many\0" + "1:x\n2:y\n3:z\n\nfew\0" + "1:\n\n"],
|
|
87
|
+
maxLines,
|
|
88
|
+
);
|
|
89
|
+
assert.deepEqual(files, [
|
|
90
|
+
{ path: "many", lines: maxLines === 2 ? undefined : [1, 2, 3] },
|
|
91
|
+
{ path: "few", lines: [1] },
|
|
92
|
+
]);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
64
95
|
|
|
65
|
-
|
|
66
|
-
await
|
|
67
|
-
|
|
68
|
-
|
|
96
|
+
test("line consumer returns false → process stops before the next file", async () => {
|
|
97
|
+
const { files, result } = await parseListing(
|
|
98
|
+
["first\0" + "1:x\n\nsecond\0" + "2:y\n\n"],
|
|
99
|
+
10,
|
|
100
|
+
true,
|
|
69
101
|
);
|
|
102
|
+
assert.deepEqual(files, [{ path: "first", lines: [1] }]);
|
|
103
|
+
assert.equal(result.stopped, true);
|
|
70
104
|
});
|
|
71
105
|
|
|
72
|
-
test("
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
resolveIgnoreCase("rg", ["foo"], lineModes, undefined, controller.signal, run),
|
|
80
|
-
/Operation aborted/,
|
|
81
|
-
);
|
|
106
|
+
test("line listing ends with incomplete path or row → RIPGREP_FAILED", async () => {
|
|
107
|
+
for (const record of ["unfinished-path", "file\0" + "1:x", "file\0" + "1"]) {
|
|
108
|
+
await assert.rejects(
|
|
109
|
+
parseListing([record]),
|
|
110
|
+
(error: unknown) => error instanceof HashlineError && error.errorCode === "RIPGREP_FAILED",
|
|
111
|
+
);
|
|
112
|
+
}
|
|
82
113
|
});
|
|
83
114
|
|
|
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
|
-
);
|
|
115
|
+
test("line listing ends after a complete row → flush the final file without a separator", async () => {
|
|
116
|
+
const { files, result } = await parseListing(["final\0" + "1:x\n"]);
|
|
117
|
+
assert.deepEqual(files, [{ path: "final", lines: [1] }]);
|
|
118
|
+
assert.equal(result.code, 0);
|
|
94
119
|
});
|
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,43 @@ 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
|
+
import { formatByteSize } from "./budgets.ts";
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Every rg run visits input roots in caller order and sorts each directory's entries.
|
|
19
|
+
* This is deterministic traversal, not global full-path sorting. rg walks in one thread;
|
|
20
|
+
* matching stays parallel in grep-search's workers.
|
|
21
|
+
*/
|
|
22
|
+
export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--sort=path"];
|
|
17
23
|
export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
|
|
18
|
-
const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${MAX_RG_RECORD_BYTES
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${formatByteSize(MAX_RG_RECORD_BYTES)}.`;
|
|
25
|
+
/**
|
|
26
|
+
* A ripgrep process or output-protocol failure. A finished run contributes its
|
|
27
|
+
* exit code and, as the cause, its stderr.
|
|
28
|
+
*/
|
|
29
|
+
function ripgrepFailure(
|
|
30
|
+
message: string,
|
|
31
|
+
run?: { readonly code: number | null; readonly stderr: string } | { readonly error: unknown },
|
|
32
|
+
): HashlineError<"RIPGREP_FAILED"> {
|
|
33
|
+
if (run === undefined) return new HashlineError("RIPGREP_FAILED", message);
|
|
34
|
+
if ("error" in run) return new HashlineError("RIPGREP_FAILED", message, { cause: run.error });
|
|
35
|
+
const stderr = run.stderr.trim();
|
|
36
|
+
return new HashlineError("RIPGREP_FAILED", message, {
|
|
37
|
+
facts: { exitCode: run.code },
|
|
38
|
+
...(stderr ? { cause: stderr } : {}),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
23
41
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
multiline: boolean;
|
|
42
|
+
/** rg reported a path that is not valid UTF-8; tools cannot address it. */
|
|
43
|
+
function unsupportedPath(): HashlineError {
|
|
44
|
+
return new HashlineError("UNSUPPORTED_PATH", "Non-UTF-8 search paths are not supported.");
|
|
28
45
|
}
|
|
29
46
|
|
|
47
|
+
/** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
|
|
48
|
+
export const MAX_RG_STDERR_BYTES = 64 * 1024;
|
|
49
|
+
|
|
30
50
|
interface ExitResult {
|
|
31
51
|
code: number | null;
|
|
32
52
|
stderr: string;
|
|
@@ -45,6 +65,22 @@ export interface RgRunResult {
|
|
|
45
65
|
stopped: boolean;
|
|
46
66
|
}
|
|
47
67
|
|
|
68
|
+
/** @internal — injectable process boundary for deterministic tests. */
|
|
69
|
+
export interface GrepBackend {
|
|
70
|
+
runRgPaths: typeof runRgPaths;
|
|
71
|
+
runRgLines: typeof runRgLines;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Surface incomplete search diagnostics without discarding confirmed matches. */
|
|
75
|
+
export function recordSearchDiagnostics(result: RgRunResult, warnings: string[]): void {
|
|
76
|
+
const message =
|
|
77
|
+
result.stderr.trim() ||
|
|
78
|
+
(!result.stopped && result.code !== 0 && result.code !== 1
|
|
79
|
+
? `ripgrep exited with code ${result.code}.`
|
|
80
|
+
: "");
|
|
81
|
+
if (message) warnings.push(message);
|
|
82
|
+
}
|
|
83
|
+
|
|
48
84
|
function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal): RunningProcess {
|
|
49
85
|
throwIfCancelled(signal);
|
|
50
86
|
const env = { ...process.env };
|
|
@@ -94,7 +130,7 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
|
|
|
94
130
|
return { child, done, kill };
|
|
95
131
|
}
|
|
96
132
|
|
|
97
|
-
async function*
|
|
133
|
+
async function* nulDelimitedRecords(stream: Readable): AsyncGenerator<Buffer> {
|
|
98
134
|
let pending = Buffer.alloc(0);
|
|
99
135
|
for await (const value of stream) {
|
|
100
136
|
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
@@ -102,40 +138,32 @@ async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGene
|
|
|
102
138
|
let buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
103
139
|
pending = Buffer.alloc(0);
|
|
104
140
|
let at: number;
|
|
105
|
-
while ((at = buf.indexOf(
|
|
106
|
-
if (at > MAX_RG_RECORD_BYTES) throw
|
|
141
|
+
while ((at = buf.indexOf("\0")) !== -1) {
|
|
142
|
+
if (at > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
|
|
107
143
|
yield buf.subarray(0, at);
|
|
108
144
|
buf = buf.subarray(at + 1);
|
|
109
145
|
}
|
|
110
|
-
if (buf.length > MAX_RG_RECORD_BYTES) throw
|
|
146
|
+
if (buf.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
|
|
111
147
|
pending = buf;
|
|
112
148
|
}
|
|
113
149
|
if (pending.length) yield pending;
|
|
114
150
|
}
|
|
115
151
|
|
|
116
|
-
|
|
152
|
+
/** Run rg while read consumes its stdout; read returns false to stop rg early. */
|
|
153
|
+
async function runRg(
|
|
117
154
|
rgPath: string,
|
|
118
155
|
args: readonly string[],
|
|
119
|
-
input: Buffer | undefined,
|
|
120
|
-
delimiter: number,
|
|
121
156
|
signal: AbortSignal | undefined,
|
|
122
|
-
|
|
157
|
+
read: (stdout: Readable) => Promise<boolean>,
|
|
123
158
|
): Promise<RgRunResult> {
|
|
124
159
|
const process = startRg(rgPath, args, signal);
|
|
125
|
-
|
|
126
|
-
process.child.stdin.end(input);
|
|
160
|
+
process.child.stdin.end();
|
|
127
161
|
try {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (!(await onRecord(record))) {
|
|
131
|
-
stopped = true;
|
|
132
|
-
process.kill();
|
|
133
|
-
break;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
162
|
+
const stopped = !(await read(process.child.stdout));
|
|
163
|
+
if (stopped) process.kill();
|
|
136
164
|
const result = await process.done;
|
|
137
165
|
throwIfCancelled(signal);
|
|
138
|
-
if (result.error) throw
|
|
166
|
+
if (result.error) throw ripgrepFailure("Failed to run ripgrep.", { error: result.error });
|
|
139
167
|
return { code: result.code, stderr: result.stderr, stopped };
|
|
140
168
|
} finally {
|
|
141
169
|
process.kill();
|
|
@@ -143,18 +171,6 @@ async function runDelimited(
|
|
|
143
171
|
}
|
|
144
172
|
}
|
|
145
173
|
|
|
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
174
|
/** @internal — read NUL-delimited UTF-8 paths from an owned rg process. */
|
|
159
175
|
export function runRgPaths(
|
|
160
176
|
rgPath: string,
|
|
@@ -162,145 +178,82 @@ export function runRgPaths(
|
|
|
162
178
|
signal: AbortSignal | undefined,
|
|
163
179
|
onPath: (path: string) => boolean | Promise<boolean>,
|
|
164
180
|
): Promise<RgRunResult> {
|
|
165
|
-
return
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
181
|
+
return runRg(rgPath, args, signal, async (stdout) => {
|
|
182
|
+
for await (const record of nulDelimitedRecords(stdout)) {
|
|
183
|
+
throwIfCancelled(signal);
|
|
184
|
+
if (!(await onPath(decodePath(record)))) return false;
|
|
185
|
+
}
|
|
186
|
+
return true;
|
|
170
187
|
});
|
|
171
188
|
}
|
|
172
189
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
}
|
|
190
|
+
function decodePath(record: Buffer): string {
|
|
191
|
+
const path = record.toString("utf8");
|
|
192
|
+
if (!Buffer.from(path, "utf8").equals(record)) throw unsupportedPath();
|
|
193
|
+
return path;
|
|
178
194
|
}
|
|
179
195
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
196
|
+
/** Arguments that make rg print, per file, its NUL-terminated path and matching line numbers. */
|
|
197
|
+
export const LINE_LISTING_ARGS = [
|
|
198
|
+
"--text",
|
|
199
|
+
"--null",
|
|
200
|
+
"--heading",
|
|
201
|
+
"--with-filename",
|
|
202
|
+
"--line-number",
|
|
203
|
+
"--max-columns=1",
|
|
204
|
+
];
|
|
185
205
|
|
|
186
|
-
|
|
206
|
+
/**
|
|
207
|
+
* @internal — read a {@link LINE_LISTING_ARGS} listing. Each file's group is a NUL-terminated
|
|
208
|
+
* path, then one `N:` record per matching line ending in a line feed (its content is at most
|
|
209
|
+
* one byte or an omission notice), then an empty line. onFile receives a file's ascending line
|
|
210
|
+
* numbers, or undefined once there are more than maxLines.
|
|
211
|
+
*/
|
|
212
|
+
export function runRgLines(
|
|
187
213
|
rgPath: string,
|
|
188
|
-
args:
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
) => Promise<
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
214
|
+
args: string[],
|
|
215
|
+
signal: AbortSignal | undefined,
|
|
216
|
+
maxLines: number,
|
|
217
|
+
onFile: (path: string, lines: readonly number[] | undefined) => boolean | Promise<boolean>,
|
|
218
|
+
): Promise<RgRunResult> {
|
|
219
|
+
return runRg(rgPath, args, signal, async (stdout) => {
|
|
220
|
+
let path: string | undefined;
|
|
221
|
+
let lines: number[] | undefined = [];
|
|
222
|
+
let pending: Buffer = Buffer.alloc(0);
|
|
223
|
+
const flush = () => {
|
|
224
|
+
const found = lines;
|
|
225
|
+
const file = path!;
|
|
226
|
+
path = undefined;
|
|
227
|
+
lines = [];
|
|
228
|
+
return onFile(file, found);
|
|
229
|
+
};
|
|
230
|
+
// Records are parsed synchronously; only a completed file waits for its consumer.
|
|
231
|
+
for await (const value of stdout) {
|
|
232
|
+
throwIfCancelled(signal);
|
|
233
|
+
const chunk = value as Buffer;
|
|
234
|
+
const buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
235
|
+
let at = 0;
|
|
236
|
+
for (;;) {
|
|
237
|
+
const end = buf.indexOf(path === undefined ? 0 : 10, at);
|
|
238
|
+
if (end === -1) break;
|
|
239
|
+
const record = buf.subarray(at, end);
|
|
240
|
+
at = end + 1;
|
|
241
|
+
if (path === undefined) path = decodePath(record);
|
|
242
|
+
else if (!record.length) {
|
|
243
|
+
if (!(await flush())) return false;
|
|
244
|
+
} else if (lines) {
|
|
245
|
+
const colon = record.indexOf(58);
|
|
246
|
+
const line = colon > 0 ? Number(record.subarray(0, colon).toString("latin1")) : NaN;
|
|
247
|
+
if (!Number.isSafeInteger(line) || line < 1)
|
|
248
|
+
throw ripgrepFailure("ripgrep printed an unexpected line record.");
|
|
249
|
+
if (lines.length < maxLines) lines.push(line);
|
|
250
|
+
else lines = undefined;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
pending = buf.subarray(at);
|
|
254
|
+
if (pending.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
|
|
255
|
+
}
|
|
256
|
+
if (pending.length) throw ripgrepFailure("ripgrep printed an incomplete line record.");
|
|
257
|
+
return path === undefined || flush();
|
|
201
258
|
});
|
|
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
259
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
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
|
+
});
|
|
51
|
+
|
|
52
|
+
test("deeply nested pattern → line candidates retain the native match", () => {
|
|
53
|
+
for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
|
|
54
|
+
const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
|
|
55
|
+
assert.equal(new RegExp(pattern).test("A"), true);
|
|
56
|
+
const candidates = lineCandidatePatterns({
|
|
57
|
+
patterns: [pattern],
|
|
58
|
+
literal: false,
|
|
59
|
+
flags: "",
|
|
60
|
+
multiline: false,
|
|
61
|
+
});
|
|
62
|
+
// An unavailable line analysis delegates candidate discovery to the file prefilter.
|
|
63
|
+
assert.ok(
|
|
64
|
+
candidates === undefined || candidates.some((candidate) => new RegExp(candidate).test("A")),
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
});
|