feat: implement git_worktree_list tool

- Implement parseWorktreeList() to parse /home/david/Projects/extensions/pi-worktrees         e597520 [issue-1-tmp]
/home/david/Projects/extensions/pi-worktrees/issue-3 dd2202f [issue-3]
/home/david/Projects/extensions/pi-worktrees/main    dd2202f [main] output
  into structured WorktreeEntry[] with path, commit, branch, isCurrent
- Handle detached HEAD (no brackets → '(detached)')
- Wire the parser into git_worktree_list execute function
- Return formatted display text + structured details for downstream use
- Move tool definitions inside extension factory to capture  closure
- Add error handling with clear message when not in a git repo
This commit is contained in:
David Kong 2026-07-24 22:53:04 +10:00
parent dd2202f54c
commit fd607f511e

View file

@ -71,12 +71,37 @@ const removeWorktreeParams = Type.Object({
/** /**
* Parse raw `git worktree list` output into structured entries. * Parse raw `git worktree list` output into structured entries.
*
* Expected format (whitespace-separated):
* /path/to/repo abc1234 [main]
* /tmp/feature-x def5678 [feature-x]
* /tmp/detached fedcba HEAD
*
* @param rawOutput - Raw stdout from `git worktree list` * @param rawOutput - Raw stdout from `git worktree list`
* @param currentDir - Current working directory for comparison * @param currentDir - Current working directory for comparison
* @returns Array of parsed worktree entries * @returns Array of parsed worktree entries
*/ */
function parseWorktreeList(rawOutput: string, currentDir: string): WorktreeEntry[] { function parseWorktreeList(rawOutput: string, currentDir: string): WorktreeEntry[] {
throw new Error("not implemented"); const lines = rawOutput.trim().split("\n").filter((line) => line.trim());
return lines.map((line) => {
// Split on whitespace: path, commit_hash, [branch] or HEAD
const parts = line.trim().split(/\s+/);
const worktreePath = parts[0];
const commitHash = parts[1];
const branchRaw = parts.slice(2).join(" ");
// Extract branch name from brackets, or mark as detached
const bracketMatch = branchRaw.match(/^\[(.+)\]$/);
const branchName = bracketMatch ? bracketMatch[1] : "(detached)";
return {
path: worktreePath,
commit: commitHash,
branch: branchName,
isCurrent: worktreePath === currentDir,
};
});
} }
/** /**
@ -99,10 +124,13 @@ function resolveWorktreeTarget(target: string, worktrees: WorktreeEntry[]): stri
throw new Error("not implemented"); throw new Error("not implemented");
} }
// ─── Tool Definitions ────────────────────────────────────────────── // ─── Extension Entry Point ────────────────────────────────────────
/** Create a linked worktree for a branch in the current repo. */ export default function (pi: ExtensionAPI) {
const gitWorktreeCreateTool = defineTool({ // Register tools (defined here to capture `pi` via closure)
/** Create a linked worktree for a branch in the current repo. */
pi.registerTool(defineTool({
name: "git_worktree_create", name: "git_worktree_create",
label: "Git Worktree Create", label: "Git Worktree Create",
description: "Create a linked worktree for a branch in the current repo.", description: "Create a linked worktree for a branch in the current repo.",
@ -113,24 +141,39 @@ const gitWorktreeCreateTool = defineTool({
isError: true, isError: true,
}; };
}, },
}); }));
/** List all linked worktrees in the current repo. */ /** List all linked worktrees in the current repo. */
const gitWorktreeListTool = defineTool({ pi.registerTool(defineTool({
name: "git_worktree_list", name: "git_worktree_list",
label: "Git Worktree List", label: "Git Worktree List",
description: "List all linked worktrees in the current repo.", description: "List all linked worktrees in the current repo.",
parameters: listWorktreeParams, parameters: listWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) { async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
const result = await pi.exec("git", ["worktree", "list"], { cwd: ctx.cwd });
if (result.exitCode !== 0) {
return { return {
content: [{ type: "text", text: "Error: git_worktree_list is not yet implemented. Suggestion: Use `git worktree list` manually until this tool is complete." }], content: [{ type: "text", text: `Error listing worktrees: ${result.stderr}. Suggestion: Ensure you are inside a git repository.` }],
isError: true, isError: true,
}; };
}, }
});
/** Switch pi's working directory to a linked worktree. */ const worktreeEntries = parseWorktreeList(result.stdout, ctx.cwd);
const gitWorktreeSwitchTool = defineTool({
const displayLines = worktreeEntries.map(
(entry) => `${entry.branch}${entry.path}${entry.isCurrent ? " (current)" : ""}`,
);
return {
content: [{ type: "text", text: displayLines.join("\n") }],
details: { worktrees: worktreeEntries },
};
},
}));
/** Switch pi's working directory to a linked worktree. */
pi.registerTool(defineTool({
name: "git_worktree_switch", name: "git_worktree_switch",
label: "Git Worktree Switch", label: "Git Worktree Switch",
description: "Switch pi's working directory to a linked worktree.", description: "Switch pi's working directory to a linked worktree.",
@ -141,10 +184,10 @@ const gitWorktreeSwitchTool = defineTool({
isError: true, isError: true,
}; };
}, },
}); }));
/** Remove a linked worktree. */ /** Remove a linked worktree. */
const gitWorktreeRemoveTool = defineTool({ pi.registerTool(defineTool({
name: "git_worktree_remove", name: "git_worktree_remove",
label: "Git Worktree Remove", label: "Git Worktree Remove",
description: "Remove a linked worktree.", description: "Remove a linked worktree.",
@ -155,16 +198,7 @@ const gitWorktreeRemoveTool = defineTool({
isError: true, isError: true,
}; };
}, },
}); }));
// ─── Extension Entry Point ────────────────────────────────────────
export default function (pi: ExtensionAPI) {
// Register tools
pi.registerTool(gitWorktreeCreateTool);
pi.registerTool(gitWorktreeListTool);
pi.registerTool(gitWorktreeSwitchTool);
pi.registerTool(gitWorktreeRemoveTool);
// Register /worktree command // Register /worktree command
pi.registerCommand("worktree", { pi.registerCommand("worktree", {