| 33 | argsSchema = GitStatusArgs; |
| 34 | |
| 35 | async execute(args: z.infer<typeof GitStatusArgs>, ctx: ToolContext): Promise<ToolResult> { |
| 36 | if (!await isGitRepo(ctx.cwd, ctx.signal)) { |
| 37 | return { content: '[NOT_A_GIT_REPO] Current directory is not inside a git working tree.', isError: true }; |
| 38 | } |
| 39 | const showUntracked = args.show_untracked ?? true; |
| 40 | const flags = ['status', '--porcelain=v2', '--branch']; |
| 41 | if (!showUntracked) flags.push('--untracked-files=no'); |
| 42 | |
| 43 | const r = await git(flags, { cwd: ctx.cwd, signal: ctx.signal }); |
| 44 | if (r.exitCode !== 0) { |
| 45 | return { content: `[ERROR] ${r.stderr.trim() || r.stdout.trim()}`, isError: true }; |
| 46 | } |
| 47 | |
| 48 | let branch = '(detached)'; |
| 49 | let upstream: string | null = null; |
| 50 | let ahead = 0; |
| 51 | let behind = 0; |
| 52 | const staged: string[] = []; |
| 53 | const unstaged: string[] = []; |
| 54 | const untracked: string[] = []; |
| 55 | const unmerged: string[] = []; |
| 56 | |
| 57 | for (const raw of r.stdout.split('\n')) { |
| 58 | if (!raw) continue; |
| 59 | // # branch.head <name> |
| 60 | if (raw.startsWith('# branch.head ')) { |
| 61 | branch = raw.slice('# branch.head '.length).trim(); |
| 62 | continue; |
| 63 | } |
| 64 | // # branch.upstream <name> |
| 65 | if (raw.startsWith('# branch.upstream ')) { |
| 66 | upstream = raw.slice('# branch.upstream '.length).trim(); |
| 67 | continue; |
| 68 | } |
| 69 | // # branch.ab +<ahead> -<behind> |
| 70 | if (raw.startsWith('# branch.ab ')) { |
| 71 | const parts = raw.slice('# branch.ab '.length).split(' '); |
| 72 | ahead = Math.abs(parseInt(parts[0] ?? '0', 10) || 0); |
| 73 | behind = Math.abs(parseInt(parts[1] ?? '0', 10) || 0); |
| 74 | continue; |
| 75 | } |
| 76 | // "1 XY ..." = changed; "2 XY ..." = renamed/copied; "u XY ..." = unmerged; "? path" = untracked |
| 77 | const kind = raw[0]; |
| 78 | if (kind === '?') { |
| 79 | untracked.push(`?? ${raw.slice(2)}`); |
| 80 | continue; |
| 81 | } |
| 82 | if (kind === '!') continue; // ignored |
| 83 | if (kind === '1' || kind === '2') { |
| 84 | // Format: 1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path> |
| 85 | const segs = raw.split(' '); |
| 86 | const xy = segs[1] ?? '..'; |
| 87 | const x = xy[0]!; |
| 88 | const y = xy[1]!; |
| 89 | // For rename/copy, path is the last two-space-separated fields joined by tab |
| 90 | const path = kind === '2' ? (segs[9] ?? '') : (segs[8] ?? ''); |
| 91 | if (x !== '.') staged.push(`${x} ${path}`); |
| 92 | if (y !== '.') unstaged.push(`${y} ${path}`); |