@criogaid/pi-hashline-edit 0.8.0 → 0.10.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.
Files changed (118) hide show
  1. package/README.md +13 -10
  2. package/README.zh-CN.md +12 -9
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +118 -293
  7. package/src/core/apply.ts +63 -165
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.ts +4 -4
  10. package/src/core/errors.test.ts +23 -7
  11. package/src/core/errors.ts +32 -5
  12. package/src/core/hash.test.ts +8 -16
  13. package/src/core/hash.ts +3 -23
  14. package/src/core/lines.ts +2 -4
  15. package/src/core/ranges.test.ts +16 -8
  16. package/src/core/ranges.ts +10 -6
  17. package/src/core/regex.ts +3 -4
  18. package/src/core/replace.test.ts +47 -1
  19. package/src/core/replace.ts +19 -13
  20. package/src/core/search-analysis.test.ts +24 -27
  21. package/src/core/search-analysis.ts +34 -65
  22. package/src/core/search-matrix.testing.ts +0 -2
  23. package/src/core/search.ts +1 -1
  24. package/src/core/text.test.ts +5 -5
  25. package/src/core/text.ts +5 -12
  26. package/src/core/types.ts +7 -43
  27. package/src/integration/config-registration.test.ts +2 -2
  28. package/src/integration/fusion-dispatch.test.ts +2 -5
  29. package/src/integration/grep-flags.test.ts +0 -14
  30. package/src/integration/grep-js-completeness.test.ts +34 -8
  31. package/src/integration/grep-line-candidates.test.ts +4 -8
  32. package/src/integration/grep-matrix.test.ts +3 -7
  33. package/src/integration/grep-path-matrix.test.ts +5 -5
  34. package/src/integration/grep-prefilter-coverage.test.ts +3 -7
  35. package/src/integration/grep-process-limits.test.ts +78 -0
  36. package/src/integration/grep-rg.test.ts +123 -25
  37. package/src/integration/grep-scan-budget.test.ts +2 -2
  38. package/src/integration/grep-translation.test.ts +12 -27
  39. package/src/integration/large-text.test.ts +1 -47
  40. package/src/integration/model-budget-lifecycle.test.ts +13 -3
  41. package/src/integration/mutation-file-types.testing.ts +1 -1
  42. package/src/integration/npm-package.testing.ts +1 -1
  43. package/src/integration/publication-read-changes.test.ts +125 -47
  44. package/src/integration/replace-worker-boundary.test.ts +21 -11
  45. package/src/integration/report-replay.test.ts +21 -23
  46. package/src/integration/utf8-errors.test.ts +1 -1
  47. package/src/pi/AGENTS.md +16 -16
  48. package/src/pi/action-fusion.test.ts +168 -300
  49. package/src/pi/action-fusion.ts +148 -111
  50. package/src/pi/anchor-format.test.ts +9 -9
  51. package/src/pi/anchor-format.ts +6 -8
  52. package/src/pi/argument-diagnostics.ts +52 -207
  53. package/src/pi/argument-error.ts +2 -1
  54. package/src/pi/argument-format.test.ts +20 -22
  55. package/src/pi/argument-validation.test.ts +382 -418
  56. package/src/pi/argument-validation.ts +5 -8
  57. package/src/pi/budgets.ts +5 -4
  58. package/src/pi/config.test.ts +5 -2
  59. package/src/pi/config.ts +4 -6
  60. package/src/pi/diagnostic-buffer.test.ts +12 -1
  61. package/src/pi/diagnostic-buffer.ts +1 -2
  62. package/src/pi/directory-sync.test.ts +0 -1
  63. package/src/pi/edit-tool.ts +173 -226
  64. package/src/pi/error-text.ts +4 -8
  65. package/src/pi/execute.test.ts +165 -266
  66. package/src/pi/failure-context.test.ts +144 -126
  67. package/src/pi/failure-context.ts +45 -94
  68. package/src/pi/failure-path.test.ts +168 -141
  69. package/src/pi/file-commit.test.ts +110 -53
  70. package/src/pi/file-commit.ts +90 -137
  71. package/src/pi/file-snapshot.test.ts +3 -5
  72. package/src/pi/fusion-card.test.ts +4 -1
  73. package/src/pi/fusion-card.ts +16 -24
  74. package/src/pi/grep-candidates.test.ts +2 -101
  75. package/src/pi/grep-candidates.ts +23 -69
  76. package/src/pi/grep-matrix.test.ts +2 -2
  77. package/src/pi/grep-order.test.ts +4 -4
  78. package/src/pi/grep-output.ts +62 -96
  79. package/src/pi/grep-render.ts +1 -1
  80. package/src/pi/grep-reread.ts +92 -0
  81. package/src/pi/grep-scope.ts +40 -42
  82. package/src/pi/grep-search.ts +22 -31
  83. package/src/pi/grep-tool.ts +55 -82
  84. package/src/pi/grep.test.ts +81 -46
  85. package/src/pi/model-budgets.test.ts +25 -23
  86. package/src/pi/model-budgets.ts +6 -38
  87. package/src/pi/mutation-result.test.ts +44 -35
  88. package/src/pi/mutation-result.ts +51 -20
  89. package/src/pi/mutation-runner.ts +126 -70
  90. package/src/pi/output-budgets.test.ts +38 -16
  91. package/src/pi/path.ts +1 -1
  92. package/src/pi/pi.test.ts +3 -1
  93. package/src/pi/read-tool.ts +5 -5
  94. package/src/pi/regex-worker-contract.ts +3 -13
  95. package/src/pi/regex-worker.ts +1 -10
  96. package/src/pi/registration.test.ts +82 -20
  97. package/src/pi/render.test.ts +79 -42
  98. package/src/pi/render.ts +69 -63
  99. package/src/pi/replace-regex.ts +14 -2
  100. package/src/pi/replace-tool.ts +22 -83
  101. package/src/pi/replace-worker.ts +1 -1
  102. package/src/pi/replace.test.ts +9 -5
  103. package/src/pi/report-cause.ts +3 -8
  104. package/src/pi/report-failure.testing.ts +1 -2
  105. package/src/pi/report-schema.ts +65 -81
  106. package/src/pi/report.test.ts +171 -25
  107. package/src/pi/report.ts +33 -87
  108. package/src/pi/result-safety.test.ts +177 -189
  109. package/src/pi/rg-process.test.ts +77 -63
  110. package/src/pi/rg-process.ts +48 -64
  111. package/src/pi/rg-regex.ts +40 -400
  112. package/src/pi/schema.ts +12 -0
  113. package/src/pi/text-stream.test.ts +0 -21
  114. package/src/pi/text-stream.ts +14 -21
  115. package/src/pi/write-tool.ts +33 -62
  116. package/src/pi/write.test.ts +1 -3
  117. package/src/testing/regex-translation-corpus.ts +12 -12
  118. package/src/pi/replace-worker-contract.ts +0 -10
@@ -1,24 +1,28 @@
1
- import { test } from "node:test";
1
+ import { test, type TestContext } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import childProcess from "node:child_process";
4
4
  import { syncBuiltinESMExports } from "node:module";
5
5
  import { Readable } from "node:stream";
6
- import { recordSearchDiagnostics, runRgLines } from "./rg-process.ts";
6
+ import { searchDiagnostic, runRgLines } from "./rg-process.ts";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { HashlineError } from "../core/errors.ts";
9
9
 
10
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, []);
11
+ for (const [code, stopped, stderr, expected] of [
12
+ [0, false, "", undefined],
13
+ [1, false, "", undefined],
14
+ [2, false, " \n", "ripgrep exited with code 2."],
15
+ [null, false, "", "ripgrep exited with code null."],
16
+ [null, true, "", undefined],
17
+ [2, false, " regex parse error\n", "regex parse error"],
18
+ [null, true, " regex parse error\n", "regex parse error"],
19
+ ] as const) {
20
+ assert.equal(
21
+ searchDiagnostic({ code, stderr, stopped }),
22
+ expected,
23
+ JSON.stringify({ code, stderr, stopped }),
24
+ );
15
25
  }
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/);
22
26
  });
23
27
 
24
28
  const listingFixture = fileURLToPath(
@@ -26,63 +30,72 @@ const listingFixture = fileURLToPath(
26
30
  );
27
31
  const parserTimeoutMs = 5_000;
28
32
 
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;
43
- },
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
- );
33
+ async function parseListing(
34
+ t: TestContext,
35
+ chunks: readonly string[],
36
+ maxLines = 10,
37
+ stop = false,
38
+ splitChunks?: readonly Buffer[],
39
+ ) {
52
40
  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);
41
+ const mock = t.mock.method(childProcess, "spawn", (...args: Parameters<typeof spawn>) => {
42
+ const child = spawn(process.execPath, args[1] ?? [], args[2]);
43
+ if (splitChunks) {
57
44
  assert.ok(child.stdout);
58
- const stream = Readable.from(chunks);
45
+ const stream = Readable.from(splitChunks);
59
46
  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}`,
73
- );
74
- assert.equal(result.code, 0);
75
- assert.equal(result.stopped, false);
76
47
  }
48
+ return child;
49
+ });
50
+ syncBuiltinESMExports();
51
+ try {
52
+ const files: { path: string; lines: readonly number[] | undefined }[] = [];
53
+ const result = await runRgLines(
54
+ [
55
+ listingFixture,
56
+ JSON.stringify(chunks.map((chunk) => Buffer.from(chunk).toString("base64"))),
57
+ ...(stop ? ["wait"] : []),
58
+ ],
59
+ AbortSignal.timeout(parserTimeoutMs),
60
+ maxLines,
61
+ (path, lines) => {
62
+ files.push({ path, lines });
63
+ return !stop;
64
+ },
65
+ );
66
+ return { files, result };
77
67
  } finally {
78
- t.mock.restoreAll();
68
+ mock.mock.restore();
79
69
  syncBuiltinESMExports();
80
70
  }
71
+ }
72
+
73
+ test("line listing split at every byte → newline paths, empty rows, and grouped files survive", async (t) => {
74
+ const listing = Buffer.from(
75
+ "dir\n文件.txt\0" + "1:\n2:x\n10:[Omitted long matching line]\n\n" + "other.txt\0" + "3:y\n\n",
76
+ );
77
+ for (let split = 1; split < listing.length; split++) {
78
+ const { files, result } = await parseListing(t, [], 10, false, [
79
+ listing.subarray(0, split),
80
+ listing.subarray(split),
81
+ ]);
82
+ assert.deepEqual(
83
+ files,
84
+ [
85
+ { path: "dir\n文件.txt", lines: [1, 2, 10] },
86
+ { path: "other.txt", lines: [3] },
87
+ ],
88
+ `split=${split}`,
89
+ );
90
+ assert.equal(result.code, 0);
91
+ assert.equal(result.stopped, false);
92
+ }
81
93
  });
82
94
 
83
- test("line listing exceeds maxLines → only the overflowing file requests all-line review", async () => {
95
+ test("line listing exceeds maxLines → only the overflowing file requests all-line review", async (t) => {
84
96
  for (const maxLines of [2, 3]) {
85
97
  const { files } = await parseListing(
98
+ t,
86
99
  ["many\0" + "1:x\n2:y\n3:z\n\nfew\0" + "1:\n\n"],
87
100
  maxLines,
88
101
  );
@@ -93,8 +106,9 @@ test("line listing exceeds maxLines → only the overflowing file requests all-l
93
106
  }
94
107
  });
95
108
 
96
- test("line consumer returns false → process stops before the next file", async () => {
109
+ test("line consumer returns false → process stops before the next file", async (t) => {
97
110
  const { files, result } = await parseListing(
111
+ t,
98
112
  ["first\0" + "1:x\n\nsecond\0" + "2:y\n\n"],
99
113
  10,
100
114
  true,
@@ -103,17 +117,17 @@ test("line consumer returns false → process stops before the next file", async
103
117
  assert.equal(result.stopped, true);
104
118
  });
105
119
 
106
- test("line listing ends with incomplete path or row → RIPGREP_FAILED", async () => {
120
+ test("line listing ends with incomplete path or row → RIPGREP_FAILED", async (t) => {
107
121
  for (const record of ["unfinished-path", "file\0" + "1:x", "file\0" + "1"]) {
108
122
  await assert.rejects(
109
- parseListing([record]),
123
+ parseListing(t, [record]),
110
124
  (error: unknown) => error instanceof HashlineError && error.errorCode === "RIPGREP_FAILED",
111
125
  );
112
126
  }
113
127
  });
114
128
 
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"]);
129
+ test("line listing ends after a complete row → flush the final file without a separator", async (t) => {
130
+ const { files, result } = await parseListing(t, ["final\0" + "1:x\n"]);
117
131
  assert.deepEqual(files, [{ path: "final", lines: [1] }]);
118
132
  assert.equal(result.code, 0);
119
133
  });
@@ -7,8 +7,9 @@
7
7
  */
8
8
 
9
9
  import { StringDecoder } from "node:string_decoder";
10
+ import { rgPath } from "@vscode/ripgrep";
10
11
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
11
- import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
+ import { spawn, type ChildProcessByStdio } from "node:child_process";
12
13
  import type { Readable } from "node:stream";
13
14
  import { HashlineError } from "../core/errors.ts";
14
15
  import { throwIfCancelled } from "./error-text.ts";
@@ -20,29 +21,10 @@ import { formatByteSize } from "./budgets.ts";
20
21
  * matching stays parallel in grep-search's workers.
21
22
  */
22
23
  export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--sort=path"];
24
+ /** Leave room for rg's arguments and paths on hosts with small command-line limits. */
25
+ export const MAX_RG_PATTERN_UNITS = 24 * 1024;
23
26
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
24
27
  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
- }
41
-
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.");
45
- }
46
28
 
47
29
  /** Bounded ripgrep stderr retains the beginning and end with an omission notice. */
48
30
  export const MAX_RG_STDERR_BYTES = 64 * 1024;
@@ -54,7 +36,7 @@ interface ExitResult {
54
36
  }
55
37
 
56
38
  interface RunningProcess {
57
- child: ChildProcessWithoutNullStreams;
39
+ child: ChildProcessByStdio<null, Readable, Readable>;
58
40
  done: Promise<ExitResult>;
59
41
  kill(): void;
60
42
  }
@@ -71,25 +53,32 @@ export interface GrepBackend {
71
53
  runRgLines: typeof runRgLines;
72
54
  }
73
55
 
74
- /** Surface incomplete search diagnostics without discarding confirmed matches. */
75
- export function recordSearchDiagnostics(result: RgRunResult, warnings: string[]): void {
76
- const message =
56
+ /** An incomplete run's diagnostic, surfaced without discarding confirmed matches. */
57
+ export function searchDiagnostic(result: RgRunResult): string | undefined {
58
+ return (
77
59
  result.stderr.trim() ||
78
60
  (!result.stopped && result.code !== 0 && result.code !== 1
79
61
  ? `ripgrep exited with code ${result.code}.`
80
- : "");
81
- if (message) warnings.push(message);
62
+ : undefined)
63
+ );
64
+ }
65
+
66
+ /** spawn reports a failure to start by throwing or by an error event, depending on the errno. */
67
+ function startFailure(cause: unknown): HashlineError {
68
+ return new HashlineError("RIPGREP_FAILED", "Failed to run ripgrep.", { cause });
82
69
  }
83
70
 
84
- function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal): RunningProcess {
71
+ function startRg(args: readonly string[], signal?: AbortSignal): RunningProcess {
85
72
  throwIfCancelled(signal);
86
- const env = { ...process.env };
87
- delete env.RIPGREP_CONFIG_PATH;
88
- const child = spawn(rgPath, [...args], {
89
- stdio: ["pipe", "pipe", "pipe"],
90
- shell: false,
91
- env,
92
- });
73
+ let child: ChildProcessByStdio<null, Readable, Readable>;
74
+ try {
75
+ child = spawn(rgPath, [...args], {
76
+ stdio: ["ignore", "pipe", "pipe"],
77
+ shell: false,
78
+ });
79
+ } catch (cause) {
80
+ throw startFailure(cause);
81
+ }
93
82
  const stderr = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
94
83
  const stderrDecoder = new StringDecoder("utf8");
95
84
  let error: Error | undefined;
@@ -110,12 +99,6 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
110
99
  child.on("error", (cause) => {
111
100
  error = cause;
112
101
  });
113
- child.stdin.on("error", (cause: NodeJS.ErrnoException) => {
114
- if (cause.code !== "EPIPE") {
115
- error = cause;
116
- kill();
117
- }
118
- });
119
102
  const done = new Promise<ExitResult>((resolve) => {
120
103
  child.on("close", (code) => {
121
104
  closed = true;
@@ -126,24 +109,25 @@ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal):
126
109
  });
127
110
  });
128
111
  signal?.addEventListener("abort", kill, { once: true });
129
- if (signal?.aborted) kill();
130
112
  return { child, done, kill };
131
113
  }
132
114
 
133
115
  async function* nulDelimitedRecords(stream: Readable): AsyncGenerator<Buffer> {
134
- let pending = Buffer.alloc(0);
116
+ let pending: Buffer = Buffer.alloc(0);
135
117
  for await (const value of stream) {
136
- const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
118
+ const chunk = value as Buffer;
137
119
  // Fast path: no pending data — search the chunk directly.
138
120
  let buf = pending.length ? Buffer.concat([pending, chunk]) : chunk;
139
121
  pending = Buffer.alloc(0);
140
122
  let at: number;
141
123
  while ((at = buf.indexOf("\0")) !== -1) {
142
- if (at > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
124
+ if (at > MAX_RG_RECORD_BYTES)
125
+ throw new HashlineError("RIPGREP_FAILED", RG_RECORD_LIMIT_MESSAGE);
143
126
  yield buf.subarray(0, at);
144
127
  buf = buf.subarray(at + 1);
145
128
  }
146
- if (buf.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
129
+ if (buf.length > MAX_RG_RECORD_BYTES)
130
+ throw new HashlineError("RIPGREP_FAILED", RG_RECORD_LIMIT_MESSAGE);
147
131
  pending = buf;
148
132
  }
149
133
  if (pending.length) yield pending;
@@ -151,34 +135,31 @@ async function* nulDelimitedRecords(stream: Readable): AsyncGenerator<Buffer> {
151
135
 
152
136
  /** Run rg while read consumes its stdout; read returns false to stop rg early. */
153
137
  async function runRg(
154
- rgPath: string,
155
138
  args: readonly string[],
156
139
  signal: AbortSignal | undefined,
157
140
  read: (stdout: Readable) => Promise<boolean>,
158
141
  ): Promise<RgRunResult> {
159
- const process = startRg(rgPath, args, signal);
160
- process.child.stdin.end();
142
+ const rg = startRg(args, signal);
161
143
  try {
162
- const stopped = !(await read(process.child.stdout));
163
- if (stopped) process.kill();
164
- const result = await process.done;
144
+ const stopped = !(await read(rg.child.stdout));
145
+ if (stopped) rg.kill();
146
+ const result = await rg.done;
165
147
  throwIfCancelled(signal);
166
- if (result.error) throw ripgrepFailure("Failed to run ripgrep.", { error: result.error });
148
+ if (result.error) throw startFailure(result.error);
167
149
  return { code: result.code, stderr: result.stderr, stopped };
168
150
  } finally {
169
- process.kill();
170
- await process.done;
151
+ rg.kill();
152
+ await rg.done;
171
153
  }
172
154
  }
173
155
 
174
156
  /** @internal — read NUL-delimited UTF-8 paths from an owned rg process. */
175
157
  export function runRgPaths(
176
- rgPath: string,
177
158
  args: string[],
178
159
  signal: AbortSignal | undefined,
179
160
  onPath: (path: string) => boolean | Promise<boolean>,
180
161
  ): Promise<RgRunResult> {
181
- return runRg(rgPath, args, signal, async (stdout) => {
162
+ return runRg(args, signal, async (stdout) => {
182
163
  for await (const record of nulDelimitedRecords(stdout)) {
183
164
  throwIfCancelled(signal);
184
165
  if (!(await onPath(decodePath(record)))) return false;
@@ -187,9 +168,11 @@ export function runRgPaths(
187
168
  });
188
169
  }
189
170
 
171
+ /** A path rg reported; one that is not valid UTF-8 cannot be addressed by tools. */
190
172
  function decodePath(record: Buffer): string {
191
173
  const path = record.toString("utf8");
192
- if (!Buffer.from(path, "utf8").equals(record)) throw unsupportedPath();
174
+ if (!Buffer.from(path, "utf8").equals(record))
175
+ throw new HashlineError("UNSUPPORTED_PATH", "Non-UTF-8 search paths are not supported.");
193
176
  return path;
194
177
  }
195
178
 
@@ -210,13 +193,12 @@ export const LINE_LISTING_ARGS = [
210
193
  * numbers, or undefined once there are more than maxLines.
211
194
  */
212
195
  export function runRgLines(
213
- rgPath: string,
214
196
  args: string[],
215
197
  signal: AbortSignal | undefined,
216
198
  maxLines: number,
217
199
  onFile: (path: string, lines: readonly number[] | undefined) => boolean | Promise<boolean>,
218
200
  ): Promise<RgRunResult> {
219
- return runRg(rgPath, args, signal, async (stdout) => {
201
+ return runRg(args, signal, async (stdout) => {
220
202
  let path: string | undefined;
221
203
  let lines: number[] | undefined = [];
222
204
  let pending: Buffer = Buffer.alloc(0);
@@ -245,15 +227,17 @@ export function runRgLines(
245
227
  const colon = record.indexOf(58);
246
228
  const line = colon > 0 ? Number(record.subarray(0, colon).toString("latin1")) : NaN;
247
229
  if (!Number.isSafeInteger(line) || line < 1)
248
- throw ripgrepFailure("ripgrep printed an unexpected line record.");
230
+ throw new HashlineError("RIPGREP_FAILED", "ripgrep printed an unexpected line record.");
249
231
  if (lines.length < maxLines) lines.push(line);
250
232
  else lines = undefined;
251
233
  }
252
234
  }
253
235
  pending = buf.subarray(at);
254
- if (pending.length > MAX_RG_RECORD_BYTES) throw ripgrepFailure(RG_RECORD_LIMIT_MESSAGE);
236
+ if (pending.length > MAX_RG_RECORD_BYTES)
237
+ throw new HashlineError("RIPGREP_FAILED", RG_RECORD_LIMIT_MESSAGE);
255
238
  }
256
- if (pending.length) throw ripgrepFailure("ripgrep printed an incomplete line record.");
239
+ if (pending.length)
240
+ throw new HashlineError("RIPGREP_FAILED", "ripgrep printed an incomplete line record.");
257
241
  return path === undefined || flush();
258
242
  });
259
243
  }