pi-worktrees/.pi/extensions/pi-worktree.ts
David Kong fd607f511e 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
2026-07-24 22:53:04 +10:00

213 lines
7.5 KiB
TypeScript

/**
* pi-worktree Extension
*
* Manages git worktrees through tool commands and an interactive `/worktree` command.
*
* Tools:
* - git_worktree_create — Create a linked worktree for a branch
* - git_worktree_list — List all linked worktrees
* - git_worktree_switch — Switch working directory to a worktree
* - git_worktree_remove — Remove a linked worktree
*
* Command:
* - /worktree — Interactive picker to switch between worktrees
*/
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import { defineTool } from "@earendil-works/pi-coding-agent";
import { Type } from "@earendil-works/pi-ai";
// ─── Type Definitions ──────────────────────────────────────────────
/** A single worktree entry parsed from `git worktree list`. */
interface WorktreeEntry {
/** Full path to the worktree directory. */
path: string;
/** Short commit hash checked out in this worktree. */
commit: string;
/** Branch name, or "(detached)" for detached HEAD. */
branch: string;
/** Whether this worktree is the current working directory. */
isCurrent: boolean;
}
/** Result of listing all worktrees. Count available via `worktrees.length`. */
interface WorktreeListResult {
/** All worktrees in the repository. */
worktrees: WorktreeEntry[];
}
/** Error returned when a worktree operation fails. */
interface WorktreeError {
/** Human-readable error message from git or validation. */
message: string;
/** Suggested fix for the user. */
suggestion?: string;
}
// ─── Tool Parameter Schemas ────────────────────────────────────────
const createWorktreeParams = Type.Object({
path: Type.String({ description: "Path for the new worktree (relative or absolute)" }),
branch: Type.Optional(Type.String({ description: "Branch name to check out. Defaults to 'main'." })),
create_branch: Type.Optional(
Type.Boolean({
description: "If true and branch doesn't exist, create it. Defaults to false.",
}),
),
});
const listWorktreeParams = Type.Object({});
const switchWorktreeParams = Type.Object({
target: Type.String({ description: "Path or branch name of the target worktree to switch to." }),
});
const removeWorktreeParams = Type.Object({
path: Type.String({ description: "Path of the worktree to remove." }),
});
// ─── Helper Functions (stubs) ──────────────────────────────────────
/**
* 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 currentDir - Current working directory for comparison
* @returns Array of parsed worktree entries
*/
function parseWorktreeList(rawOutput: string, currentDir: string): WorktreeEntry[] {
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,
};
});
}
/**
* Check if the target path exists.
* @param path - Path to check
* @param ctx - Extension context for file system access
* @returns True if the path exists
*/
async function pathExists(path: string, ctx: ExtensionContext): Promise<boolean> {
throw new Error("not implemented");
}
/**
* Resolve a worktree target (path or branch name) to its full path.
* @param target - Path or branch name to resolve
* @param worktrees - List of all worktrees
* @returns The resolved path, or undefined if not found
*/
function resolveWorktreeTarget(target: string, worktrees: WorktreeEntry[]): string | undefined {
throw new Error("not implemented");
}
// ─── Extension Entry Point ────────────────────────────────────────
export default function (pi: ExtensionAPI) {
// 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",
label: "Git Worktree Create",
description: "Create a linked worktree for a branch in the current repo.",
parameters: createWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
return {
content: [{ type: "text", text: "Error: git_worktree_create is not yet implemented. Suggestion: Use `git worktree add` manually until this tool is complete." }],
isError: true,
};
},
}));
/** List all linked worktrees in the current repo. */
pi.registerTool(defineTool({
name: "git_worktree_list",
label: "Git Worktree List",
description: "List all linked worktrees in the current repo.",
parameters: listWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
const result = await pi.exec("git", ["worktree", "list"], { cwd: ctx.cwd });
if (result.exitCode !== 0) {
return {
content: [{ type: "text", text: `Error listing worktrees: ${result.stderr}. Suggestion: Ensure you are inside a git repository.` }],
isError: true,
};
}
const worktreeEntries = parseWorktreeList(result.stdout, ctx.cwd);
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",
label: "Git Worktree Switch",
description: "Switch pi's working directory to a linked worktree.",
parameters: switchWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
return {
content: [{ type: "text", text: "Error: git_worktree_switch is not yet implemented. Suggestion: Use the `/worktree` command or `git worktree` manually until this tool is complete." }],
isError: true,
};
},
}));
/** Remove a linked worktree. */
pi.registerTool(defineTool({
name: "git_worktree_remove",
label: "Git Worktree Remove",
description: "Remove a linked worktree.",
parameters: removeWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
return {
content: [{ type: "text", text: "Error: git_worktree_remove is not yet implemented. Suggestion: Use `git worktree remove` manually until this tool is complete." }],
isError: true,
};
},
}));
// Register /worktree command
pi.registerCommand("worktree", {
description: "Interactive picker to switch between linked worktrees.",
handler: async (_args, _ctx) => {
return {
content: [{ type: "text", text: "Error: /worktree command is not yet implemented. Suggestion: Use `git worktree list` and navigate manually until this command is complete." }],
isError: true,
};
},
});
}