diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 1bb84a91..5b0b20bd 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -16,6 +16,7 @@ import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool'; import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool'; import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool'; +import { GitCommitTool } from '@/lib/tools/GitCommitTool'; interface ChatPaneProps { projectId: string; @@ -189,6 +190,7 @@ BASE_DOMAIN=nostrdeploy.com`); addMessages(stepResult.response.messages); }, tools: { + git_commit: new GitCommitTool(browserFS, cwd), text_editor_view: new TextEditorViewTool(browserFS, cwd), text_editor_write: new TextEditorWriteTool(browserFS, cwd), text_editor_str_replace: new TextEditorStrReplaceTool(browserFS, cwd), @@ -206,6 +208,7 @@ Key capabilities: - Search through files - Add and remove npm packages - Install dependencies and dev dependencies +- Commit changes to git with automatic staging Guidelines: - Always check if files exist before writing to avoid overwriting diff --git a/src/lib/tools/GitCommitTool.test.ts b/src/lib/tools/GitCommitTool.test.ts new file mode 100644 index 00000000..7121ede7 --- /dev/null +++ b/src/lib/tools/GitCommitTool.test.ts @@ -0,0 +1,238 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { GitCommitTool } from './GitCommitTool'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock isomorphic-git +vi.mock('isomorphic-git', () => ({ + default: { + statusMatrix: vi.fn(), + add: vi.fn(), + remove: vi.fn(), + commit: vi.fn(), + currentBranch: vi.fn(), + getConfig: vi.fn(), + }, +})); + +import git from 'isomorphic-git'; + +// Mock filesystem +const mockFS: JSRuntimeFS = { + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}; + +describe('GitCommitTool', () => { + let tool: GitCommitTool; + + beforeEach(() => { + vi.clearAllMocks(); + tool = new GitCommitTool(mockFS, '/test/project'); + + // Setup default mocks + vi.mocked(git.statusMatrix).mockResolvedValue([ + ['src/file1.ts', 1, 1, 0], // Modified file (present in head and workdir, but not staged) + ['src/file2.ts', 0, 1, 0], // New file (absent in head, present in workdir, not staged) + ]); + vi.mocked(git.add).mockResolvedValue(); + vi.mocked(git.commit).mockResolvedValue('abcd1234567890abcdef1234567890abcdef12'); + vi.mocked(git.currentBranch).mockResolvedValue('main'); + vi.mocked(git.getConfig).mockRejectedValue(new Error('Config not found')); + }); + + it('should have correct description and parameters', () => { + expect(tool.description).toBe('Commit changes to git with a commit message. Automatically adds all unstaged files.'); + expect(tool.parameters).toBeDefined(); + }); + + it('should successfully commit changes', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await tool.execute({ message: 'Add new feature' }); + + expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git'); + expect(git.statusMatrix).toHaveBeenCalledWith({ + fs: mockFS, + dir: '/test/project', + }); + expect(git.add).toHaveBeenCalled(); + expect(git.commit).toHaveBeenCalledWith({ + fs: mockFS, + dir: '/test/project', + message: 'Add new feature', + author: { + name: 'Shakespeare User', + email: 'user@shakespeare.dev', + }, + committer: { + name: 'Shakespeare User', + email: 'user@shakespeare.dev', + }, + }); + expect(result.isError).toBe(false); + expect(result.content[0].text).toContain('✅ Successfully committed 2 files (abcd123)'); + expect(result.content[0].text).toContain('Add new feature'); + }); + + it('should handle empty commit message', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await tool.execute({ message: '' }); + + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain('❌ Commit message cannot be empty'); + }); + + it('should handle whitespace-only commit message', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await tool.execute({ message: ' ' }); + + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain('❌ Commit message cannot be empty'); + }); + + it('should handle not being in a git repository', async () => { + // Mock .git directory does not exist + vi.mocked(mockFS.stat).mockRejectedValue(new Error('File not found')); + + const result = await tool.execute({ message: 'Test commit' }); + + expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git'); + expect(result.isError).toBe(true); + expect(result.content[0].text).toContain('❌ Not a git repository'); + expect(result.content[0].text).toContain('git init'); + }); + + it('should handle commit with special characters in message', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const specialMessage = 'Fix: handle "quotes" and \'apostrophes\' in commit message'; + const result = await tool.execute({ message: specialMessage }); + + expect(git.commit).toHaveBeenCalledWith(expect.objectContaining({ + message: specialMessage, + })); + expect(result.isError).toBe(false); + expect(result.content[0].text).toContain('✅ Successfully committed'); + expect(result.content[0].text).toContain(specialMessage); + }); + + it('should handle multiline commit message', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const multilineMessage = 'Add new feature\n\nThis commit adds a new feature that allows users to do something amazing.\n\nCloses #123'; + const result = await tool.execute({ message: multilineMessage }); + + expect(git.commit).toHaveBeenCalled(); + expect(result.isError).toBe(false); + expect(result.content[0].text).toContain('✅ Successfully committed'); + expect(result.content[0].text).toContain('Add new feature'); + }); + + it('should handle no changes to commit', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + // Mock no changes in status matrix + vi.mocked(git.statusMatrix).mockResolvedValue([]); + + const result = await tool.execute({ message: 'Update documentation' }); + + expect(result.isError).toBe(false); + expect(result.content[0].text).toContain('ℹ️ No changes to commit. Working tree is clean.'); + expect(git.commit).not.toHaveBeenCalled(); + }); + + it('should provide detailed commit information', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await tool.execute({ message: 'Update documentation' }); + + expect(result.isError).toBe(false); + expect(result.content[0].text).toContain('📝 Commit: "Update documentation"'); + expect(result.content[0].text).toContain('🔗 Hash:'); + expect(result.content[0].text).toContain('🌿 Branch:'); + expect(result.content[0].text).toContain('📊 Changes:'); + }); + + it('should use git config when available', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + // Mock git config + vi.mocked(git.getConfig) + .mockResolvedValueOnce('John Doe') // user.name + .mockResolvedValueOnce('john@example.com'); // user.email + + const result = await tool.execute({ message: 'Test commit' }); + + expect(git.commit).toHaveBeenCalledWith({ + fs: mockFS, + dir: '/test/project', + message: 'Test commit', + author: { + name: 'John Doe', + email: 'john@example.com', + }, + committer: { + name: 'John Doe', + email: 'john@example.com', + }, + }); + expect(result.isError).toBe(false); + }); + + it('should handle very long commit message', async () => { + // Mock .git directory exists + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const longMessage = 'A'.repeat(1000); // Very long commit message + const result = await tool.execute({ message: longMessage }); + + expect(result.isError).toBe(false); + expect(result.content[0].text).toContain('✅ Successfully committed'); + }); +}); \ No newline at end of file diff --git a/src/lib/tools/GitCommitTool.ts b/src/lib/tools/GitCommitTool.ts new file mode 100644 index 00000000..c33f5586 --- /dev/null +++ b/src/lib/tools/GitCommitTool.ts @@ -0,0 +1,190 @@ +import { z } from "zod"; +import git from 'isomorphic-git'; + +import type { Tool, CallToolResult } from "./Tool"; +import type { JSRuntimeFS } from "../JSRuntime"; + +interface GitCommitParams { + message: string; +} + +export class GitCommitTool implements Tool { + private fs: JSRuntimeFS; + private cwd: string; + + readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files."; + + readonly parameters = z.object({ + message: z.string().describe('Commit message text'), + }); + + constructor(fs: JSRuntimeFS, cwd: string) { + this.fs = fs; + this.cwd = cwd; + } + + async execute(args: GitCommitParams): Promise { + const { message } = args; + + try { + // Check if we're in a git repository + try { + await this.fs.stat(`${this.cwd}/.git`); + } catch { + return { + content: [{ + type: "text", + text: `❌ Not a git repository. Initialize git first with 'git init'.`, + }], + isError: true, + }; + } + + // Validate commit message + if (!message.trim()) { + return { + content: [{ + type: "text", + text: `❌ Commit message cannot be empty.`, + }], + isError: true, + }; + } + + // Get git status to see what files have changed + const statusMatrix = await git.statusMatrix({ + fs: this.fs, + dir: this.cwd, + }); + + // Filter for files that have changes (not committed) + const changedFiles = statusMatrix.filter(([_filepath, headStatus, workdirStatus, stageStatus]) => { + // File has changes if: + // - workdir differs from head (modified/new/deleted) + // - stage differs from workdir (unstaged changes) + return headStatus !== workdirStatus || workdirStatus !== stageStatus; + }); + + if (changedFiles.length === 0) { + return { + content: [{ + type: "text", + text: `ℹ️ No changes to commit. Working tree is clean.`, + }], + isError: false, + }; + } + + // Add all changed files to staging + for (const [filepath] of changedFiles) { + try { + await git.add({ + fs: this.fs, + dir: this.cwd, + filepath, + }); + } catch { + // If file was deleted, use git.remove instead + try { + await git.remove({ + fs: this.fs, + dir: this.cwd, + filepath, + }); + } catch { + // If both add and remove fail, skip this file + console.warn(`Failed to stage file: ${filepath}`); + } + } + } + + // Get current branch name + let currentBranch = 'main'; + try { + currentBranch = await git.currentBranch({ + fs: this.fs, + dir: this.cwd, + }) || 'main'; + } catch { + // Default to 'main' if we can't get the current branch + } + + // Get author info (use default if not configured) + const author = { + name: 'Shakespeare User', + email: 'user@shakespeare.dev', + }; + + // Try to get configured author from git config + try { + const configName = await git.getConfig({ + fs: this.fs, + dir: this.cwd, + path: 'user.name', + }); + const configEmail = await git.getConfig({ + fs: this.fs, + dir: this.cwd, + path: 'user.email', + }); + if (configName) author.name = configName; + if (configEmail) author.email = configEmail; + } catch { + // Use defaults if config is not set + } + + // Commit the changes + const commitSha = await git.commit({ + fs: this.fs, + dir: this.cwd, + message: message.trim(), + author, + committer: author, + }); + + // Get short hash (first 7 characters) + const shortHash = commitSha.substring(0, 7); + + // Analyze the changes for summary + const addedFiles = changedFiles.filter(([, headStatus, workdirStatus]) => + headStatus === 0 && workdirStatus === 1 + ).length; + + const modifiedFiles = changedFiles.filter(([, headStatus, workdirStatus]) => + headStatus === 1 && workdirStatus === 1 + ).length; + + const deletedFiles = changedFiles.filter(([, headStatus, workdirStatus]) => + headStatus === 1 && workdirStatus === 0 + ).length; + + const totalFiles = changedFiles.length; + + const summary = `✅ Successfully committed ${totalFiles} file${totalFiles !== 1 ? 's' : ''} (${shortHash})`; + + let details = `📝 Commit: "${message.trim()}"\n`; + details += `🔗 Hash: ${shortHash}\n`; + details += `🌿 Branch: ${currentBranch}\n`; + details += `📊 Changes:\n`; + if (addedFiles > 0) details += ` • ${addedFiles} file${addedFiles !== 1 ? 's' : ''} added\n`; + if (modifiedFiles > 0) details += ` • ${modifiedFiles} file${modifiedFiles !== 1 ? 's' : ''} modified\n`; + if (deletedFiles > 0) details += ` • ${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} deleted\n`; + + return { + content: [{ + type: "text", + text: `${summary}\n\n${details}`, + }], + isError: false, + }; + } catch (error) { + return { + content: [{ + type: "text", + text: `❌ Error committing changes: ${String(error)}`, + }], + isError: true, + }; + } + } +} \ No newline at end of file