repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(shame): complete paths and branches

a154d3b9188ac8647ffd5a86446304aad10fd6c3

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/shame/__tests__/harness.test.ts

Modified
31 31 stderr: "",
33 33 } catch (error) {
34 - const result = error as { stdout?: string; stderr?: string; status?: number };
34 + const result = error as {
35 + stdout?: string;
36 + stderr?: string;
37 + status?: number;
38 + };
35 39 return {
36 40 code: result.status ?? 1,
37 41 stdout: result.stdout ?? "",
60 64 t = await createTestSession({ extensionFactories: [shameExtension] });
62 66 expect(t.session.extensionRunner.extensions).toHaveLength(1);
63 - expect(
64 - t.session.extensionRunner.extensions[0].commands.has("shame"),
65 - ).toBe(true);
67 + expect(t.session.extensionRunner.extensions[0].commands.has("shame")).toBe(
68 + true,
69 + );
68 72 it("parses paths and quoted extra review focus", () => {
77 81 it("recognizes PR shorthand and URLs", () => {
78 82 expect(__test.pullRequestRef("#123")).toBe("123");
79 - expect(
80 - __test.pullRequestRef("https://github.com/acme/app/pull/42"),
81 - ).toBe("https://github.com/acme/app/pull/42");
83 + expect(__test.pullRequestRef("https://github.com/acme/app/pull/42")).toBe(
84 + "https://github.com/acme/app/pull/42",
85 + );
82 86 expect(__test.pullRequestRef("#nope")).toBeNull();
120 124 ).resolves.toEqual({ target: { type: "commit", sha } });
127 + it("completes @ paths, branches, and examples", async () => {
128 + await repository();
129 + const command =
130 + t?.session.extensionRunner.extensions[0].commands.get("shame");
132 + expect(command?.getArgumentCompletions?.("@sr")).toContainEqual({
133 + value: "@src/",
134 + label: "@src/",
135 + });
136 + expect(command?.getArgumentCompletions?.("@src/ @te")).toContainEqual({
137 + value: "@src/ @test/",
138 + label: "@test/",
139 + });
140 + expect(command?.getArgumentCompletions?.("fea")).toContainEqual({
141 + value: "feature",
142 + label: "feature",
143 + });
144 + expect(command?.getArgumentCompletions?.("")).toEqual(
145 + expect.arrayContaining([
146 + { value: "#123", label: "#123", description: "GitHub PR" },
148 + value: '--extra "focus"',
149 + label: "--extra",
150 + description: "extra review focus",
151 + },
152 + ]),
153 + );
154 + });
123 156 it("rejects missing and mixed targets", async () => {
124 157 await repository();
128 161 ).resolves.toEqual({ error: "Path not found: missing" });
129 162 await expect(
130 163 __test.resolveTarget(realExec(), t?.cwd ?? "", ["@src", "feature"]),
131 - ).resolves.toEqual({ error: "Cannot mix paths and Git refs in one review" });
164 + ).resolves.toEqual({
165 + error: "Cannot mix paths and Git refs in one review",
166 + });
132 167 await expect(
133 168 __test.resolveTarget(realExec(), t?.cwd ?? "", ["super"]),
134 169 ).resolves.toEqual({

extensions/shame/index.ts

Modified
1 -import { promises as fs } from "node:fs";
1 +import { execFileSync } from "node:child_process";
2 +import { promises as fs, readdirSync } from "node:fs";
2 3 import path from "node:path";
3 4 import type {
4 5 ExtensionAPI,
143 144 const paths = tokens.map((token) => token.replace(/^@/, ""));
144 145 const resolved = paths.map((candidate) => path.resolve(cwd, candidate));
145 146 const inside = resolved.map(
146 - (candidate) => candidate === cwd || candidate.startsWith(`${cwd}${path.sep}`),
147 + (candidate) =>
148 + candidate === cwd || candidate.startsWith(`${cwd}${path.sep}`),
148 150 const exists = await Promise.all(
149 - resolved.map((candidate) => fs.stat(candidate).then(() => true).catch(() => false)),
151 + resolved.map((candidate) =>
152 + fs
153 + .stat(candidate)
154 + .then(() => true)
155 + .catch(() => false),
156 + ),
151 158 const pathIntent = tokens.some((token) => token.startsWith("@"));
308 +type Completion = { value: string; label: string; description?: string };
310 +const safeCompletion = (value: string) => !/[\u0000-\u001f\u007f]/.test(value);
312 +function pathCompletions(
313 + cwd: string,
314 + before: string,
315 + active: string,
316 +): Completion[] {
317 + const raw = active.startsWith("@") ? active.slice(1) : "";
318 + const slash = raw.lastIndexOf("/");
319 + const directory = slash < 0 ? "" : raw.slice(0, slash + 1);
320 + const prefix = slash < 0 ? raw : raw.slice(slash + 1);
321 + const parent = path.resolve(cwd, directory);
322 + if (parent !== cwd && !parent.startsWith(`${cwd}${path.sep}`)) return [];
324 + try {
325 + return readdirSync(parent, { withFileTypes: true })
326 + .filter(
327 + (entry) => safeCompletion(entry.name) && entry.name.startsWith(prefix),
329 + .map((entry) => {
330 + const completion = `@${directory}${entry.name}${entry.isDirectory() ? "/" : ""}`;
331 + return { value: before + completion, label: completion };
332 + })
333 + .sort((a, b) => a.label.localeCompare(b.label));
334 + } catch {
335 + return [];
339 +function branchCompletions(
340 + cwd: string,
341 + before: string,
342 + active: string,
343 +): Completion[] {
344 + try {
345 + return execFileSync(
346 + "git",
348 + "for-each-ref",
349 + "--format=%(refname:short)",
350 + "refs/heads",
351 + "refs/remotes",
352 + ],
353 + { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
355 + .split(/\r?\n/)
356 + .filter((ref) => safeCompletion(ref) && ref.startsWith(active))
357 + .map((ref) => ({ value: before + ref, label: ref }));
358 + } catch {
359 + return [];
363 +function completeArguments(
364 + cwd: string,
365 + argumentText: string,
366 +): Completion[] | null {
367 + const match = argumentText.match(/^(.*\s)?(\S*)$/);
368 + const before = match?.[1] ?? "";
369 + const active = match?.[2] ?? argumentText;
370 + const items =
371 + active.startsWith("@") || active === ""
372 + ? pathCompletions(cwd, before, active)
373 + : branchCompletions(cwd, before, active);
375 + if ("#123".startsWith(active))
376 + items.push({
377 + value: `${before}#123`,
378 + label: "#123",
379 + description: "GitHub PR",
380 + });
381 + if ("--extra".startsWith(active))
382 + items.push({
383 + value: `${before}--extra "focus"`,
384 + label: "--extra",
385 + description: "extra review focus",
386 + });
387 + return items.length > 0 ? items : null;
301 390 export const __test = {
302 391 parseInput,
303 392 pullRequestRef,
309 398 export default function shameExtension(pi: ExtensionAPI) {
399 + let cwd = process.cwd();
400 + pi.on("session_start", (_event, ctx) => {
401 + cwd = ctx.cwd;
402 + });
310 404 pi.registerCommand("shame", {
311 405 description:
312 406 "Shame code. Usage: /shame [@path ...|#pr|pr-url|git-ref] [--extra <focus>]",
407 + getArgumentCompletions(argumentText) {
408 + return completeArguments(cwd, argumentText);
409 + },
313 410 handler: async (args, ctx) => {
314 411 await ctx.waitForIdle();
315 412 const parsed = parseInput(args);
320 417 const resolved = await resolveTarget(pi, ctx.cwd, parsed.tokens);
321 418 if (!resolved.target) {
322 - ctx.ui.notify(resolved.error ?? "Cannot resolve review target", "error");
419 + ctx.ui.notify(
420 + resolved.error ?? "Cannot resolve review target",
421 + "error",
422 + );
323 423 return;
325 425 const target = resolved.target;