pi-worktrees/.pi/extensions/pi-worktree-parser.ts
David Kong fc19b36cd8 fix: address all code review findings for issue-3
Critical fixes:
- Normalize path comparison with path.resolve() (Task 001)
- Add validation guards for malformed lines in parser (Task 002)

Major fixes:
- Extract tool definitions to factory functions (Task 003)
- Use WorktreeListResult interface with enriched metadata (Tasks 004, 010)
- Add unit tests for parseWorktreeList — 12 tests covering edge cases (Task 005)
- Return warning message when zero worktrees found (Task 006)

Minor fixes:
- Apply consistent JSDoc to all functions including factories (Task 007)
- Replace em-dash with ASCII separator for encoding safety (Task 008)
- Add section comments between tool factories and command registration (Task 009)

Suggestions implemented:
- Export parseWorktreeList in separate testable module (Task 011)
2026-07-24 23:01:40 +10:00

69 lines
2.4 KiB
TypeScript

/**
* Git worktree list parser — pure functions, no pi SDK dependencies.
*
* Parses raw `git worktree list` output into structured entries.
*/
import path from "path";
// ─── Type Definitions ──────────────────────────────────────────────
/** A single worktree entry parsed from `git worktree list`. */
export 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;
}
// ─── Parser ────────────────────────────────────────────────────────
/**
* 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
*/
export 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+/);
// Guard against malformed lines — need at least 3 tokens (path, commit, branch/HEAD)
if (parts.length < 3) {
return null;
}
const worktreePath = parts[0];
const commitHash = parts[1];
const branchRaw = parts.slice(2).join(" ");
// Validate: branch must be in brackets [name] or HEAD for detached
if (!branchRaw.match(/^\[.+\]$/) && !branchRaw.match(/^HEAD$/)) {
return null;
}
// 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: path.resolve(worktreePath) === path.resolve(currentDir),
};
}).filter((entry): entry is WorktreeEntry => entry !== null);
}