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";
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() {
22 + exec:
async (command
: string, args
: string[])
=> {
26 + stdout:
execFileSync(command, args, {
29 + stdio: [
"ignore",
"pipe",
"pipe"],
34 + const result
= error
as { stdout
?: string; stderr
?: string; status
?: number };
36 + code: result.
status ?? 1,
37 + stdout: result.stdout
?? "",
38 + stderr: result.stderr
?? "",
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");
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);
64 + t.session.extensionRunner.extensions[
0].commands.
has(
"shame"),
19 - it(
"parses quoted extra review focus", ()
=> {
68 + it(
"parses paths and quoted extra review focus", ()
=> {
21 - __test.
parseReviewArgs(
'branch trunk --extra "focus auth regressions"'),
23 - target: { type:
"branch", branch:
"trunk" },
70 + __test.
parseInput(
'@src @test --extra "focus auth regressions"'),
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");
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();
85 + it(
"uses the smart default without a target",
async ()
=> {
89 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", []),
90 + ).resolves.
toEqual({ target: { type:
"commit", sha:
"HEAD" } });
93 + it(
"resolves @ paths, multiple paths, and plain paths",
async ()
=> {
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({
34 - paths: [
"src",
"docs"],
102 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [
"src"]),
103 + ).resolves.
toEqual({ target: { type:
"folder", paths: [
"src"] } });
106 + it(
"resolves PRs, branches, and commits",
async ()
=> {
107 + await repository();
108 + const sha
= git(
"rev-parse",
"HEAD");
111 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [
"#7"]),
112 + ).resolves.
toEqual({ target: { type:
"pr", ref:
"7" } });
114 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [
"feature"]),
115 + ).resolves.
toEqual({
116 + target: { type:
"branch", branch:
"feature" },
36 - expect(__test.
parseReviewArgs(
"pr 123").
target).
toEqual({
119 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [sha]),
120 + ).resolves.
toEqual({ target: { type:
"commit", sha } });
123 + it(
"rejects missing and mixed targets",
async ()
=> {
124 + await repository();
127 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [
"@missing"]),
128 + ).resolves.
toEqual({ error:
"Path not found: missing" });
130 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [
"@src",
"feature"]),
131 + ).resolves.
toEqual({ error:
"Cannot mix paths and Git refs in one review" });
133 + __test.
resolveTarget(
realExec(), t?.cwd
?? "", [
"super"]),
134 + ).resolves.
toEqual({
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;
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") {
97 - return { target:
null, error:
`Expected text after ${token}` };
96 + if (
!extra)
return { tokens, error:
`Expected text after ${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];
110 - ? { target: { type:
"branch", branch }, extra }
111 - : { target:
null, error:
"Usage: /review branch <base>" };
113 - if (kind
=== "commit") {
114 - const sha
= rest[
0];
116 - ? { target: { type:
"commit", sha }, extra }
117 - : { target:
null, error:
"Usage: /review commit <sha>" };
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...]" };
124 - if (kind
=== "pr") {
125 - const ref
= rest[
0];
127 - ? { target: { type:
"pr", ref }, extra }
128 - : { target:
null, error:
"Usage: /review pr <number-or-url>" };
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)
134 112 async function execText(pi
: ExtensionAPI, command
: string, args
: string[]) {
136 114 return result.
code === 0 ? result.stdout.
trim()
: "";
117 +async function execOk(
121 +)
: Promise<
boolean> {
122 + return (
await pi.
exec(command, args)).
code === 0;
125 +async function isBranch(pi
: ExtensionAPI, ref
: string)
: Promise<
boolean> {
127 + (
await execOk(pi,
"git", [
"show-ref",
"--verify",
`refs/heads/${ref}`]))
|| 128 + (
await execOk(pi,
"git", [
"show-ref",
"--verify",
`refs/remotes/${ref}`]))
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(
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}`),
148 + const exists
= await Promise.
all(
149 + resolved.
map((candidate)
=> fs.
stat(candidate).
then(()
=> true).
catch(()
=> false)),
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]}` };
165 + paths: resolved.
map((candidate)
=> path.
relative(cwd, candidate)),
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 } };
180 + error:
`Cannot resolve "${token}". Try /shame @<path>, #123, a PR URL, branch, or commit`,
139 184 async function currentBranch(pi
: ExtensionAPI)
: Promise<
string> {
140 185 return await execText(pi,
"git", [
"branch",
"--show-current"]);
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";
199 + for (
const candidate
of [
"trunk",
"main",
"master"]) {
200 + if (branches.
split(
/\r?\n/).
includes(candidate))
return candidate;
159 205 async function hasChanges(pi
: ExtensionAPI)
: Promise<
boolean> {
255 -export const __test
= { parseReviewArgs, tokenizeArgs, targetLabel };
301 +export const __test
= {
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");
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");
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));