repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(shame): infer review targets

b68005857f40581a758bae507bb0198fa8bd7d41

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

extensions/shame/__tests__/harness.test.ts

Modified
1 +import { execFileSync } from "node:child_process";
2 +import { mkdirSync, writeFileSync } from "node:fs";
3 +import path from "node:path";
1 4 import { afterEach, describe, expect, it } from "vitest";
2 5 import { createTestSession, type TestSession } from "../../../test/harness";
3 6 import shameExtension, { __test } from "../index";
9 12 t = undefined;
15 +function git(...args: string[]): string {
16 + if (!t) throw new Error("missing session");
17 + return execFileSync("git", args, { cwd: t.cwd, encoding: "utf8" }).trim();
20 +function realExec() {
21 + return {
22 + exec: async (command: string, args: string[]) => {
23 + try {
24 + return {
25 + code: 0,
26 + stdout: execFileSync(command, args, {
27 + cwd: t?.cwd,
28 + encoding: "utf8",
29 + stdio: ["ignore", "pipe", "pipe"],
30 + }),
31 + stderr: "",
32 + };
33 + } catch (error) {
34 + const result = error as { stdout?: string; stderr?: string; status?: number };
35 + return {
36 + code: result.status ?? 1,
37 + stdout: result.stdout ?? "",
38 + stderr: result.stderr ?? "",
39 + };
40 + }
41 + },
42 + } as never;
45 +async function repository(): Promise<void> {
46 + t = await createTestSession({ extensionFactories: [shameExtension] });
47 + git("init", "-b", "trunk");
48 + git("config", "user.email", "test@example.com");
49 + git("config", "user.name", "Test");
50 + mkdirSync(path.join(t.cwd, "src"));
51 + mkdirSync(path.join(t.cwd, "test"));
52 + writeFileSync(path.join(t.cwd, "src/index.ts"), "export {};\n");
53 + git("add", ".");
54 + git("commit", "-m", "initial");
55 + git("branch", "feature");
12 58 describe("shame extension", () => {
13 59 it("loads in real Pi extension runtime", async () => {
14 60 t = await createTestSession({ extensionFactories: [shameExtension] });
16 62 expect(t.session.extensionRunner.extensions).toHaveLength(1);
63 + expect(
64 + t.session.extensionRunner.extensions[0].commands.has("shame"),
65 + ).toBe(true);
19 - it("parses quoted extra review focus", () => {
68 + it("parses paths and quoted extra review focus", () => {
20 69 expect(
21 - __test.parseReviewArgs('branch trunk --extra "focus auth regressions"'),
22 - ).toMatchObject({
23 - target: { type: "branch", branch: "trunk" },
70 + __test.parseInput('@src @test --extra "focus auth regressions"'),
71 + ).toEqual({
72 + tokens: ["@src", "@test"],
24 73 extra: "focus auth regressions",
28 - it("parses direct review targets", () => {
29 - expect(__test.parseReviewArgs("uncommitted").target).toEqual({
30 - type: "uncommitted",
77 + it("recognizes PR shorthand and URLs", () => {
78 + 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");
82 + expect(__test.pullRequestRef("#nope")).toBeNull();
83 + });
85 + it("uses the smart default without a target", async () => {
86 + await repository();
88 + await expect(
89 + __test.resolveTarget(realExec(), t?.cwd ?? "", []),
90 + ).resolves.toEqual({ target: { type: "commit", sha: "HEAD" } });
91 + });
93 + it("resolves @ paths, multiple paths, and plain paths", async () => {
94 + await repository();
96 + await expect(
97 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["@src", "@test"]),
98 + ).resolves.toEqual({
99 + target: { type: "folder", paths: ["src", "test"] },
32 - expect(__test.parseReviewArgs("folder src docs").target).toEqual({
33 - type: "folder",
34 - paths: ["src", "docs"],
101 + await expect(
102 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["src"]),
103 + ).resolves.toEqual({ target: { type: "folder", paths: ["src"] } });
104 + });
106 + it("resolves PRs, branches, and commits", async () => {
107 + await repository();
108 + const sha = git("rev-parse", "HEAD");
110 + await expect(
111 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["#7"]),
112 + ).resolves.toEqual({ target: { type: "pr", ref: "7" } });
113 + await expect(
114 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["feature"]),
115 + ).resolves.toEqual({
116 + target: { type: "branch", branch: "feature" },
36 - expect(__test.parseReviewArgs("pr 123").target).toEqual({
37 - type: "pr",
38 - ref: "123",
118 + await expect(
119 + __test.resolveTarget(realExec(), t?.cwd ?? "", [sha]),
120 + ).resolves.toEqual({ target: { type: "commit", sha } });
121 + });
123 + it("rejects missing and mixed targets", async () => {
124 + await repository();
126 + await expect(
127 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["@missing"]),
128 + ).resolves.toEqual({ error: "Path not found: missing" });
129 + await expect(
130 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["@src", "feature"]),
131 + ).resolves.toEqual({ error: "Cannot mix paths and Git refs in one review" });
132 + await expect(
133 + __test.resolveTarget(realExec(), t?.cwd ?? "", ["super"]),
134 + ).resolves.toEqual({
135 + error:
136 + 'Cannot resolve "super". Try /shame @<path>, #123, a PR URL, branch, or commit',

extensions/shame/index.ts

Modified
12 12 | { type: "folder"; paths: string[] }
13 13 | { type: "pr"; ref: string };
15 -type ParsedReviewArgs = {
16 - target: ReviewTarget | null;
15 +type ParsedInput = {
16 + tokens: string[];
17 17 extra?: string;
18 18 error?: string;
84 84 return tokens;
87 -function parseReviewArgs(args: string): ParsedReviewArgs {
87 +function parseInput(args: string): ParsedInput {
88 88 const raw = tokenizeArgs(args.trim());
89 - const parts: string[] = [];
89 + const tokens: string[] = [];
90 90 let extra: string | undefined;
92 92 for (let i = 0; i < raw.length; i++) {
93 93 const token = raw[i];
94 94 if (token === "--extra" || token === "-e") {
95 95 extra = raw[++i];
96 - if (!extra)
97 - return { target: null, error: `Expected text after ${token}` };
96 + if (!extra) return { tokens, error: `Expected text after ${token}` };
98 97 continue;
100 - parts.push(token);
99 + tokens.push(token);
103 - if (parts.length === 0) return { target: null, extra };
104 - const [kind, ...rest] = parts;
102 + return { tokens, extra };
106 - if (kind === "uncommitted") return { target: { type: "uncommitted" }, extra };
107 - if (kind === "branch") {
108 - const branch = rest[0];
109 - return branch
110 - ? { target: { type: "branch", branch }, extra }
111 - : { target: null, error: "Usage: /review branch <base>" };
112 - }
113 - if (kind === "commit") {
114 - const sha = rest[0];
115 - return sha
116 - ? { target: { type: "commit", sha }, extra }
117 - : { target: null, error: "Usage: /review commit <sha>" };
118 - }
119 - if (kind === "folder") {
120 - return rest.length > 0
121 - ? { target: { type: "folder", paths: rest }, extra }
122 - : { target: null, error: "Usage: /review folder <path> [path...]" };
123 - }
124 - if (kind === "pr") {
125 - const ref = rest[0];
126 - return ref
127 - ? { target: { type: "pr", ref }, extra }
128 - : { target: null, error: "Usage: /review pr <number-or-url>" };
129 - }
131 - return { target: null, error: `Unknown review target: ${kind}` };
105 +function pullRequestRef(token: string): string | null {
106 + if (/^#\d+$/.test(token)) return token.slice(1);
107 + return /^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+\/?$/.test(token)
108 + ? token
109 + : null;
134 112 async function execText(pi: ExtensionAPI, command: string, args: string[]) {
136 114 return result.code === 0 ? result.stdout.trim() : "";
117 +async function execOk(
118 + pi: ExtensionAPI,
119 + command: string,
120 + args: string[],
121 +): Promise<boolean> {
122 + return (await pi.exec(command, args)).code === 0;
125 +async function isBranch(pi: ExtensionAPI, ref: string): Promise<boolean> {
126 + return (
127 + (await execOk(pi, "git", ["show-ref", "--verify", `refs/heads/${ref}`])) ||
128 + (await execOk(pi, "git", ["show-ref", "--verify", `refs/remotes/${ref}`]))
129 + );
132 +async function isCommit(pi: ExtensionAPI, ref: string): Promise<boolean> {
133 + return await execOk(pi, "git", ["rev-parse", "--verify", `${ref}^{commit}`]);
136 +async function resolveTarget(
137 + pi: ExtensionAPI,
138 + cwd: string,
139 + tokens: string[],
140 +): Promise<{ target?: ReviewTarget; error?: string }> {
141 + if (tokens.length === 0) return { target: await smartTarget(pi) };
143 + const paths = tokens.map((token) => token.replace(/^@/, ""));
144 + const resolved = paths.map((candidate) => path.resolve(cwd, candidate));
145 + const inside = resolved.map(
146 + (candidate) => candidate === cwd || candidate.startsWith(`${cwd}${path.sep}`),
147 + );
148 + const exists = await Promise.all(
149 + resolved.map((candidate) => fs.stat(candidate).then(() => true).catch(() => false)),
150 + );
151 + const pathIntent = tokens.some((token) => token.startsWith("@"));
153 + if (pathIntent || exists.some(Boolean)) {
154 + if (inside.some((value) => !value))
155 + return { error: "Review paths must stay inside the project" };
156 + for (let i = 0; i < tokens.length; i++) {
157 + if (exists[i]) continue;
158 + if (!tokens[i].startsWith("@") && (await isBranch(pi, tokens[i])))
159 + return { error: "Cannot mix paths and Git refs in one review" };
160 + return { error: `Path not found: ${paths[i]}` };
162 + return {
163 + target: {
164 + type: "folder",
165 + paths: resolved.map((candidate) => path.relative(cwd, candidate)),
166 + },
167 + };
170 + if (tokens.length > 1)
171 + return { error: "Cannot mix paths and Git refs in one review" };
172 + const [token] = tokens;
173 + const pr = pullRequestRef(token);
174 + if (pr) return { target: { type: "pr", ref: pr } };
175 + if (await isBranch(pi, token))
176 + return { target: { type: "branch", branch: token } };
177 + if (await isCommit(pi, token))
178 + return { target: { type: "commit", sha: token } };
179 + return {
180 + error: `Cannot resolve "${token}". Try /shame @<path>, #123, a PR URL, branch, or commit`,
181 + };
139 184 async function currentBranch(pi: ExtensionAPI): Promise<string> {
140 185 return await execText(pi, "git", ["branch", "--show-current"]);
151 196 "branch",
152 197 "--format=%(refname:short)",
154 - if (branches.split(/\r?\n/).includes("main")) return "main";
155 - if (branches.split(/\r?\n/).includes("master")) return "master";
156 - return "main";
199 + for (const candidate of ["trunk", "main", "master"]) {
200 + if (branches.split(/\r?\n/).includes(candidate)) return candidate;
202 + return "trunk";
159 205 async function hasChanges(pi: ExtensionAPI): Promise<boolean> {
255 -export const __test = { parseReviewArgs, tokenizeArgs, targetLabel };
301 +export const __test = {
302 + parseInput,
303 + pullRequestRef,
304 + resolveTarget,
305 + tokenizeArgs,
306 + targetLabel,
257 309 export default function shameExtension(pi: ExtensionAPI) {
258 310 pi.registerCommand("shame", {
260 312 "Shame code. Usage: /shame [@path ...|#pr|pr-url|git-ref] [--extra <focus>]",
261 313 handler: async (args, ctx) => {
262 314 await ctx.waitForIdle();
263 - const parsed = parseReviewArgs(args);
315 + const parsed = parseInput(args);
264 316 if (parsed.error) {
265 317 ctx.ui.notify(parsed.error, "error");
266 318 return;
268 - const target = parsed.target ?? (await smartTarget(pi));
320 + const resolved = await resolveTarget(pi, ctx.cwd, parsed.tokens);
321 + if (!resolved.target) {
322 + ctx.ui.notify(resolved.error ?? "Cannot resolve review target", "error");
323 + return;
325 + const target = resolved.target;
269 326 ctx.ui.notify(`Starting review: ${targetLabel(target)}`, "info");
270 327 pi.sendUserMessage(await buildPrompt(pi, ctx, target, parsed.extra));