| 34 | argsSchema = GitDiffArgs; |
| 35 | |
| 36 | async execute(args: z.infer<typeof GitDiffArgs>, ctx: ToolContext): Promise<ToolResult> { |
| 37 | if (!await isGitRepo(ctx.cwd, ctx.signal)) { |
| 38 | return { content: '[NOT_A_GIT_REPO] Current directory is not inside a git working tree.', isError: true }; |
| 39 | } |
| 40 | if (args.scope === 'commit' && !args.ref) { |
| 41 | return { content: '[INVALID_ARGS] scope="commit" requires `ref` (commit SHA, branch, or HEAD~N).', isError: true }; |
| 42 | } |
| 43 | |
| 44 | const mode = args.mode ?? 'patch'; |
| 45 | const maxBytes = args.max_bytes ?? 80_000; |
| 46 | |
| 47 | let gitArgs: string[]; |
| 48 | if (args.scope === 'commit') { |
| 49 | gitArgs = ['show', '--format=', args.ref!]; |
| 50 | } else if (args.scope === 'staged') { |
| 51 | gitArgs = ['diff', '--cached']; |
| 52 | } else if (args.scope === 'all') { |
| 53 | gitArgs = ['diff', 'HEAD']; |
| 54 | } else { |
| 55 | gitArgs = ['diff']; |
| 56 | } |
| 57 | |
| 58 | if (mode === 'stat') gitArgs.push('--stat'); |
| 59 | else if (mode === 'name-only') gitArgs.push('--name-only'); |
| 60 | |
| 61 | if (args.paths && args.paths.length > 0) { |
| 62 | gitArgs.push('--'); |
| 63 | gitArgs.push(...args.paths); |
| 64 | } |
| 65 | |
| 66 | const r = await git(gitArgs, { cwd: ctx.cwd, signal: ctx.signal }); |
| 67 | if (r.exitCode !== 0) { |
| 68 | return { content: `[ERROR] ${r.stderr.trim() || r.stdout.trim()}`, isError: true }; |
| 69 | } |
| 70 | |
| 71 | let out = r.stdout; |
| 72 | if (out.trim() === '') { |
| 73 | return { content: `[NO_CHANGES] No diff for scope=${args.scope}${args.ref ? ` ref=${args.ref}` : ''}.` }; |
| 74 | } |
| 75 | |
| 76 | let truncatedNote = ''; |
| 77 | if (out.length > maxBytes) { |
| 78 | out = out.slice(0, maxBytes); |
| 79 | const lastNewline = out.lastIndexOf('\n'); |
| 80 | if (lastNewline > 0) out = out.slice(0, lastNewline); |
| 81 | truncatedNote = `\n\n[...truncated at ${maxBytes} bytes. Re-run with smaller --paths to see the rest of a specific file.]`; |
| 82 | } |
| 83 | |
| 84 | return { |
| 85 | content: out + truncatedNote, |
| 86 | metadata: { scope: args.scope, mode, bytes: r.stdout.length, truncated: truncatedNote !== '' }, |
| 87 | }; |
| 88 | } |
| 89 | } |