@criogaid/pi-hashline-edit 0.1.0 → 0.1.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@criogaid/pi-hashline-edit",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "description": "Hashline-style file editing for pi — line-anchored edits verified by content hash, replacing oldText/newText matching",
6
6
  "homepage": "https://github.com/Criogaid/pi-hashline-edit#readme",
@@ -251,6 +251,33 @@ test("noIgnore searches ignored files while explicit excluding globs still apply
251
251
  }
252
252
  });
253
253
 
254
+ test("explicit file paths obey ordered glob filters without inheriting ignore rules", async () => {
255
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-file-glob-"));
256
+ try {
257
+ const kept = join(directory, "keep.ts");
258
+ const excluded = join(directory, "drop.test.ts");
259
+ const ignored = join(directory, "ignored.ts");
260
+ await writeFile(join(directory, ".ignore"), "ignored.ts\n");
261
+ await Promise.all([kept, excluded, ignored].map((path) => writeFile(path, "needle\n")));
262
+ const tool = makeGrepOverrideWithBackend(directory, {});
263
+ const result: any = await tool.execute("0", {
264
+ pattern: "needle",
265
+ path: [kept, excluded, ignored],
266
+ glob: ["*.ts", "!**/*.test.ts"],
267
+ outputMode: "files",
268
+ }, undefined, undefined);
269
+ const files = new Set(result.content[0].text.split("\n"));
270
+ assert.deepEqual(files, new Set(["keep.ts", "ignored.ts"]));
271
+
272
+ const none: any = await tool.execute("0", {
273
+ pattern: "needle", path: excluded, glob: "!**/*.test.ts",
274
+ }, undefined, undefined);
275
+ assert.equal(none.content[0].text, "No matches found");
276
+ } finally {
277
+ await rm(directory, { recursive: true, force: true });
278
+ }
279
+ });
280
+
254
281
  test("follow returns a resolved target path that edit can update without replacing the link", async (t) => {
255
282
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-follow-"));
256
283
  try {
@@ -34,7 +34,7 @@ import { rgPath as bundledRgPath } from "@vscode/ripgrep";
34
34
  import { Type } from "typebox";
35
35
  import { Text } from "@earendil-works/pi-tui";
36
36
  import { readFile, realpath, stat } from "node:fs/promises";
37
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
37
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
38
38
  import { hashFileLines } from "../core/hash.ts";
39
39
  import { splitLines } from "../core/lines.ts";
40
40
  import { getState } from "./state.ts";
@@ -219,6 +219,50 @@ function scopeArgs(scope: SearchScope): string[] {
219
219
  ];
220
220
  }
221
221
 
222
+ interface SearchPathInfo {
223
+ path: string;
224
+ isFile: boolean;
225
+ }
226
+
227
+ function fileKey(path: string): string {
228
+ const absolute = resolve(path);
229
+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;
230
+ }
231
+
232
+ async function filterExplicitFilesByGlob(
233
+ backend: GrepBackend,
234
+ rgPath: string,
235
+ scope: SearchScope,
236
+ paths: readonly SearchPathInfo[],
237
+ signal: AbortSignal | undefined,
238
+ ): Promise<string[]> {
239
+ const explicitFiles = paths.filter(({ isFile }) => isFile);
240
+ if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
241
+
242
+ const parents = [...new Set(explicitFiles.map(({ path }) => dirname(path)))];
243
+ const allowed = new Set<string>();
244
+ // Direct file arguments bypass ignore and symlink traversal; let only the ordered globs decide admission.
245
+ const args = [
246
+ ...COMMON_RG_ARGS,
247
+ ...scopeArgs({ ...scope, noIgnore: true, follow: true }),
248
+ "--files",
249
+ "--null",
250
+ "--max-depth=1",
251
+ "--",
252
+ ...parents,
253
+ ];
254
+ const listed = await backend.runRgPaths(rgPath, args, signal, async (path) => {
255
+ allowed.add(fileKey(path));
256
+ return true;
257
+ });
258
+ if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
259
+ throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
260
+ }
261
+ return paths
262
+ .filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
263
+ .map(({ path }) => path);
264
+ }
265
+
222
266
  async function fileIdentity(path: string): Promise<FileIdentity> {
223
267
  const value = await stat(path);
224
268
  if (!value.isFile()) throw new Error(`Search target is not a regular file: ${path}`);
@@ -414,6 +458,10 @@ function countLeading(s: string): number {
414
458
  function toDisplayLines(raw: string, theme: any): string[] {
415
459
  const out: string[] = [];
416
460
  const lines = raw.split("\n");
461
+ const lineNoWidth = lines.reduce(
462
+ (width, line) => Math.max(width, parseHashline(line)?.lineNo.length ?? 0),
463
+ 0,
464
+ );
417
465
  let i = 0;
418
466
  while (i < lines.length) {
419
467
  const line = lines[i];
@@ -434,7 +482,7 @@ function toDisplayLines(raw: string, theme: any): string[] {
434
482
  const marker = base > 0 ? theme.fg("dim", "›") + " " : "";
435
483
  for (const g of group) {
436
484
  const body = g.content.slice(base);
437
- out.push(theme.fg("dim", ` ${g.lineNo}: `) + marker + theme.fg("toolOutput", body));
485
+ out.push(theme.fg("dim", ` ${g.lineNo.padStart(lineNoWidth)}: `) + marker + theme.fg("toolOutput", body));
438
486
  }
439
487
  i = j;
440
488
  continue;
@@ -574,7 +622,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
574
622
  const values = toArray(params.path);
575
623
  return (values.length ? values : ["."]).map((path) => canonicalPath(cwd, path));
576
624
  })();
577
- const scope: SearchScope = {
625
+ let scope: SearchScope = {
578
626
  globs,
579
627
  noIgnore: params.noIgnore === true,
580
628
  follow: params.follow === true,
@@ -582,10 +630,15 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
582
630
  };
583
631
  const hashLen = state.config.hashLen;
584
632
 
633
+ const pathInfo: SearchPathInfo[] = [];
585
634
  for (const searchPath of searchPaths) {
586
- try { await stat(searchPath); }
635
+ try { pathInfo.push({ path: searchPath, isFile: (await stat(searchPath)).isFile() }); }
587
636
  catch { throw new Error(`Path not found: ${searchPath}`); }
588
637
  }
638
+ scope = {
639
+ ...scope,
640
+ searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal),
641
+ };
589
642
  if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
590
643
  throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
591
644
  }
@@ -597,7 +650,10 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
597
650
  let strictIdentities: Map<string, FileIdentity> | undefined;
598
651
  let linesTruncated = false;
599
652
 
600
- if (complex) {
653
+ if (scope.searchPaths.length === 0) {
654
+ raw = [];
655
+ matchLimitReached = false;
656
+ } else if (complex) {
601
657
  await backend.validatePatterns(rgPath, patterns, modes, !!wordMatch, signal);
602
658
  await backend.validatePatterns(rgPath, excludes, modes, false, signal);
603
659
  const result = await complexSearch({
@@ -618,7 +674,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
618
674
  ...scopeArgs(scope),
619
675
  ];
620
676
  for (const pattern of matchMode === "all" ? patterns.slice(0, 1) : patterns) args.push("-e", pattern);
621
- args.push("--", ...searchPaths);
677
+ args.push("--", ...scope.searchPaths);
622
678
 
623
679
  const andPredicates = matchMode === "all"
624
680
  ? patterns.slice(1).map((pattern) => backend.createLinePredicate(rgPath, [pattern], modes, !!wordMatch, signal))
@@ -22,6 +22,7 @@ type FakeOptions = {
22
22
  error?: Error;
23
23
  onRun?: () => void;
24
24
  smartCase?: boolean;
25
+ paths?: string[];
25
26
  };
26
27
 
27
28
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
@@ -82,8 +83,11 @@ function fakeBackend(options: FakeOptions = {}) {
82
83
  stopped: false,
83
84
  };
84
85
  },
85
- async runRgPaths() {
86
- return { code: 1, stderr: "", stopped: false };
86
+ async runRgPaths(_path, _args, _signal, onPath) {
87
+ for (const path of options.paths ?? []) {
88
+ if (!await onPath(path)) return { code: null, stderr: "", stopped: true };
89
+ }
90
+ return { code: options.paths?.length ? 0 : 1, stderr: "", stopped: false };
87
91
  },
88
92
  async resolveIgnoreCase(_path, patterns, modes, explicit) {
89
93
  modeCalls.push({ patterns, literal: modes.literal, explicit });
@@ -230,7 +234,10 @@ test("passes output flags and formats files and counts", async () => {
230
234
  const b = join(dir, "b.ts");
231
235
  await writeFile(a, "Foo a.b\n");
232
236
  await writeFile(b, "foo a.b\n");
233
- const fake = fakeBackend({ lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")] });
237
+ const fake = fakeBackend({
238
+ lines: [rgMatch(a, 1, "Foo a.b\n"), rgMatch(b, 1, "foo a.b\n")],
239
+ paths: [a, b],
240
+ });
234
241
 
235
242
  const files = await call(makeGrepOverrideWithBackend(dir, fake.backend), {
236
243
  pattern: ["Foo", "a.b"],
@@ -276,6 +283,26 @@ test("passes output flags and formats files and counts", async () => {
276
283
  );
277
284
  });
278
285
 
286
+ test("aligns TUI line numbers across files to the widest result", () => {
287
+ const tool = makeGrepOverrideWithBackend(process.cwd(), fakeBackend().backend);
288
+ const raw = [
289
+ "a.ts · 2 matches",
290
+ "99#ABCD│ alpha",
291
+ "100#ABCD│ beta",
292
+ "b.ts · 1 match",
293
+ "7#ABCD│gamma",
294
+ ].join("\n");
295
+ const theme = { fg: (_color: string, value: string) => value };
296
+ const rendered = tool.renderResult!(
297
+ { content: [{ type: "text", text: raw }] },
298
+ { isPartial: false, expanded: true },
299
+ theme,
300
+ {},
301
+ ).render(80).map((line: string) => line.trimEnd());
302
+ const rows = rendered.filter((line: string) => /^\s+\d+:/.test(line));
303
+ assert.deepEqual(rows.map((line: string) => line.indexOf(":")), [6, 6, 6]);
304
+ });
305
+
279
306
  test("counts only surviving matches toward the limit and stops the fake runner", async () => {
280
307
  await withDir(async (dir) =>
281
308
  withEnabled(true, async () => {