Refactor code to use our custom Git class

This commit is contained in:
Alex Gleason committed 2025-09-14 16:26:37 -05:00
1 parent 55120452c7
commit 772a2f424b
9 files changed
+93 -123

No files matched your search

+2 -2
View File
@@ -36,9 +36,9 @@ import { AppSettingsDialog } from '@/components/AppSettingsDialog';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
import { useGit } from '@/hooks/useGit';
import { useFS } from '@/hooks/useFS'; import { useFS } from '@/hooks/useFS';
import JSZip from 'jszip'; import JSZip from 'jszip';
import git from 'isomorphic-git';
interface ActionsMenuProps { interface ActionsMenuProps {
projectId: string; projectId: string;
@@ -75,6 +75,7 @@ export function ActionsMenu({
const navigate = useNavigate(); const navigate = useNavigate();
const projectsManager = useProjectsManager(); const projectsManager = useProjectsManager();
const { toast } = useToast(); const { toast } = useToast();
const git = useGit();
const { fs } = useFS(); const { fs } = useFS();
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting; const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
@@ -156,7 +157,6 @@ export function ActionsMenu({
try { try {
// Get the current commit hash // Get the current commit hash
const commits = await git.log({ const commits = await git.log({
fs,
dir: projectPath, dir: projectPath,
depth: 1, depth: 1,
}); });
+2 -11
View File
@@ -37,14 +37,11 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSettings } from '@/hooks/useGitSettings'; import { useGitSettings } from '@/hooks/useGitSettings';
import { useFS } from '@/hooks/useFS'; import { useGit } from '@/hooks/useGit';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials';
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
interface GitDialogProps { interface GitDialogProps {
projectId: string; projectId: string;
children?: React.ReactNode; children?: React.ReactNode;
@@ -61,7 +58,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
const { settings } = useGitSettings(); const { settings } = useGitSettings();
const { fs } = useFS(); const git = useGit();
const { toast } = useToast(); const { toast } = useToast();
const projectPath = `/projects/${projectId}`; const projectPath = `/projects/${projectId}`;
@@ -118,12 +115,9 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
} : {}; } : {};
await git.push({ await git.push({
fs,
http,
dir: projectPath, dir: projectPath,
remote: remote.name, remote: remote.name,
ref: gitStatus.currentBranch, ref: gitStatus.currentBranch,
corsProxy: 'https://cors.isomorphic-git.org',
...authOptions, ...authOptions,
}); });
@@ -182,12 +176,9 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
} : {}; } : {};
await git.pull({ await git.pull({
fs,
http,
dir: projectPath, dir: projectPath,
ref: gitStatus.currentBranch, ref: gitStatus.currentBranch,
singleBranch: true, singleBranch: true,
corsProxy: 'https://cors.isomorphic-git.org',
author: { author: {
name: 'shakespeare.diy', name: 'shakespeare.diy',
email: '[email protected]', email: '[email protected]',
+19 -18
View File
@@ -3,21 +3,22 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp'; import { TestApp } from '@/test/TestApp';
import { GitHistoryDialog } from './GitHistoryDialog'; import { GitHistoryDialog } from './GitHistoryDialog';
// Mock isomorphic-git // Mock the useGit hook
vi.mock('isomorphic-git', () => ({ const mockGit = {
default: { log: vi.fn(),
log: vi.fn(), resolveRef: vi.fn(),
resolveRef: vi.fn(), readCommit: vi.fn(),
readCommit: vi.fn(), listFiles: vi.fn(),
listFiles: vi.fn(), readBlob: vi.fn(),
readBlob: vi.fn(), add: vi.fn(),
add: vi.fn(), remove: vi.fn(),
remove: vi.fn(), commit: vi.fn(),
commit: vi.fn(), findRoot: vi.fn(),
}, };
}));
// Mock the useFS hook vi.mock('@/hooks/useGit', () => ({
useGit: () => mockGit,
}));
vi.mock('@/hooks/useFS', () => ({ vi.mock('@/hooks/useFS', () => ({
useFS: () => ({ useFS: () => ({
fs: { fs: {
@@ -107,8 +108,8 @@ describe('GitHistoryDialog', () => {
}, },
]; ];
const git = await import('isomorphic-git'); mockGit.findRoot.mockResolvedValue('/projects/test-project/.git');
vi.mocked(git.default.log).mockResolvedValue(mockCommits); mockGit.log.mockResolvedValue(mockCommits);
render( render(
<TestApp> <TestApp>
@@ -144,8 +145,8 @@ describe('GitHistoryDialog', () => {
}, },
]; ];
const git = await import('isomorphic-git'); mockGit.findRoot.mockResolvedValue('/projects/test-project/.git');
vi.mocked(git.default.log).mockResolvedValue(mockCommits); mockGit.log.mockResolvedValue(mockCommits);
render( render(
<TestApp> <TestApp>
+5 -15
View File
@@ -5,9 +5,9 @@ import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react'; import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react';
import { useGit } from '@/hooks/useGit';
import { useFS } from '@/hooks/useFS'; import { useFS } from '@/hooks/useFS';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
import git from 'isomorphic-git';
interface GitCommit { interface GitCommit {
oid: string; oid: string;
@@ -43,12 +43,11 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
const setIsOpen = onOpenChange || setInternalOpen; const setIsOpen = onOpenChange || setInternalOpen;
const [isRollingBack, setIsRollingBack] = useState<string | null>(null); const [isRollingBack, setIsRollingBack] = useState<string | null>(null);
const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set()); const [expandedCommits, setExpandedCommits] = useState<Set<string>>(new Set());
const git = useGit();
const { fs } = useFS(); const { fs } = useFS();
const { toast } = useToast(); const { toast } = useToast();
const loadGitHistory = useCallback(async () => { const loadGitHistory = useCallback(async () => {
if (!fs) return;
setIsLoading(true); setIsLoading(true);
setError(null); setError(null);
@@ -57,7 +56,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
// Check if git repository exists // Check if git repository exists
try { try {
await fs.stat(`${projectPath}/.git`); await git.findRoot({ filepath: projectPath });
} catch { } catch {
setError('No git repository found in this project'); setError('No git repository found in this project');
return; return;
@@ -65,7 +64,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
// Get git log // Get git log
const gitLog = await git.log({ const gitLog = await git.log({
fs,
dir: projectPath, dir: projectPath,
depth: 50, // Limit to last 50 commits depth: 50, // Limit to last 50 commits
}); });
@@ -77,7 +75,7 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}, [fs, projectId]); }, [git, projectId]);
const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => { const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => {
if (!fs) return; if (!fs) return;
@@ -89,7 +87,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
// Get the current HEAD commit // Get the current HEAD commit
const currentCommit = await git.resolveRef({ const currentCommit = await git.resolveRef({
fs,
dir: projectPath, dir: projectPath,
ref: 'HEAD', ref: 'HEAD',
}); });
@@ -105,7 +102,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
// Get all commits between the target commit and HEAD // Get all commits between the target commit and HEAD
const allCommits = await git.log({ const allCommits = await git.log({
fs,
dir: projectPath, dir: projectPath,
depth: 1000, depth: 1000,
}); });
@@ -138,14 +134,12 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
// Get all files from the target commit // Get all files from the target commit
const targetFiles = await git.listFiles({ const targetFiles = await git.listFiles({
fs,
dir: projectPath, dir: projectPath,
ref: targetCommit.oid, ref: targetCommit.oid,
}); });
// Get current files to know what to remove // Get current files to know what to remove
const currentFiles = await git.listFiles({ const currentFiles = await git.listFiles({
fs,
dir: projectPath, dir: projectPath,
ref: 'HEAD', ref: 'HEAD',
}); });
@@ -156,7 +150,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
try { try {
await fs.unlink(`${projectPath}/${filepath}`); await fs.unlink(`${projectPath}/${filepath}`);
await git.remove({ await git.remove({
fs,
dir: projectPath, dir: projectPath,
filepath, filepath,
}); });
@@ -171,7 +164,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
for (const filepath of targetFiles) { for (const filepath of targetFiles) {
try { try {
const { blob } = await git.readBlob({ const { blob } = await git.readBlob({
fs,
dir: projectPath, dir: projectPath,
oid: targetCommit.oid, oid: targetCommit.oid,
filepath, filepath,
@@ -188,7 +180,6 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
// Stage the file // Stage the file
await git.add({ await git.add({
fs,
dir: projectPath, dir: projectPath,
filepath, filepath,
}); });
@@ -210,7 +201,6 @@ ${commitsToRevert.map(c => {
}).join('\n')}`; }).join('\n')}`;
await git.commit({ await git.commit({
fs,
dir: projectPath, dir: projectPath,
message: revertMessage, message: revertMessage,
author: { author: {
@@ -237,7 +227,7 @@ ${commitsToRevert.map(c => {
} finally { } finally {
setIsRollingBack(null); setIsRollingBack(null);
} }
}, [fs, projectId, toast, loadGitHistory]); }, [git, fs, projectId, toast, loadGitHistory]);
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
+17
View File
@@ -0,0 +1,17 @@
import { useMemo } from 'react';
import { Git } from '@/lib/git';
import { useFS } from '@/hooks/useFS';
/**
* Hook that provides a Git instance configured with the virtual filesystem
* and appropriate CORS proxy for GitHub/GitLab repositories.
*/
export function useGit() {
const { fs } = useFS();
const git = useMemo(() => {
return new Git(fs, 'https://cors.isomorphic-git.org');
}, [fs]);
return git;
}
+3 -14
View File
@@ -1,6 +1,5 @@
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import git from 'isomorphic-git'; import { useGit } from './useGit';
import { useFS } from './useFS';
interface GitFileChange { interface GitFileChange {
filepath: string; filepath: string;
@@ -41,7 +40,7 @@ interface GitStatus {
} }
export function useGitStatus(projectId: string | null) { export function useGitStatus(projectId: string | null) {
const { fs } = useFS(); const git = useGit();
return useQuery({ return useQuery({
queryKey: ['git-status', projectId], queryKey: ['git-status', projectId],
@@ -66,7 +65,7 @@ export function useGitStatus(projectId: string | null) {
// Check if we're in a git repository // Check if we're in a git repository
try { try {
await fs.stat(`${cwd}/.git`); await git.findRoot({ filepath: cwd });
} catch { } catch {
return { return {
hasUncommittedChanges: false, hasUncommittedChanges: false,
@@ -86,7 +85,6 @@ export function useGitStatus(projectId: string | null) {
let currentBranch: string | null = null; let currentBranch: string | null = null;
try { try {
const branch = await git.currentBranch({ const branch = await git.currentBranch({
fs,
dir: cwd, dir: cwd,
fullname: false, fullname: false,
}); });
@@ -99,7 +97,6 @@ export function useGitStatus(projectId: string | null) {
const branches: string[] = []; const branches: string[] = [];
try { try {
const allBranches = await git.listBranches({ const allBranches = await git.listBranches({
fs,
dir: cwd, dir: cwd,
}); });
branches.push(...allBranches); branches.push(...allBranches);
@@ -112,7 +109,6 @@ export function useGitStatus(projectId: string | null) {
let totalCommits = 0; let totalCommits = 0;
try { try {
const commits = await git.log({ const commits = await git.log({
fs,
dir: cwd, dir: cwd,
depth: 1, depth: 1,
}); });
@@ -137,7 +133,6 @@ export function useGitStatus(projectId: string | null) {
// Get total commit count // Get total commit count
const allCommits = await git.log({ const allCommits = await git.log({
fs,
dir: cwd, dir: cwd,
}); });
totalCommits = allCommits.length; totalCommits = allCommits.length;
@@ -149,7 +144,6 @@ export function useGitStatus(projectId: string | null) {
const remotes: GitRemote[] = []; const remotes: GitRemote[] = [];
try { try {
const remoteNames = await git.listRemotes({ const remoteNames = await git.listRemotes({
fs,
dir: cwd, dir: cwd,
}); });
@@ -165,7 +159,6 @@ export function useGitStatus(projectId: string | null) {
// Get git status to see what files have changed // Get git status to see what files have changed
const statusMatrix = await git.statusMatrix({ const statusMatrix = await git.statusMatrix({
fs,
dir: cwd, dir: cwd,
}); });
@@ -207,13 +200,11 @@ export function useGitStatus(projectId: string | null) {
try { try {
// Try to get the remote branch reference // Try to get the remote branch reference
const remoteRef = await git.resolveRef({ const remoteRef = await git.resolveRef({
fs,
dir: cwd, dir: cwd,
ref: remoteBranchName, ref: remoteBranchName,
}); });
const localRef = await git.resolveRef({ const localRef = await git.resolveRef({
fs,
dir: cwd, dir: cwd,
ref: currentBranch, ref: currentBranch,
}); });
@@ -221,13 +212,11 @@ export function useGitStatus(projectId: string | null) {
if (remoteRef && localRef && remoteRef !== localRef) { if (remoteRef && localRef && remoteRef !== localRef) {
// Get commits between local and remote // Get commits between local and remote
const localCommits = await git.log({ const localCommits = await git.log({
fs,
dir: cwd, dir: cwd,
ref: currentBranch, ref: currentBranch,
}); });
const remoteCommits = await git.log({ const remoteCommits = await git.log({
fs,
dir: cwd, dir: cwd,
ref: remoteBranchName, ref: remoteBranchName,
}); });
+8 -19
View File
@@ -1,6 +1,5 @@
import git from 'isomorphic-git';
import http from 'isomorphic-git/http/web';
import { Buffer } from 'buffer'; import { Buffer } from 'buffer';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime'; import type { JSRuntimeFS } from '@/lib/JSRuntime';
@@ -21,10 +20,12 @@ export interface Project {
export class ProjectsManager { export class ProjectsManager {
fs: JSRuntimeFS; fs: JSRuntimeFS;
git: Git;
dir: string; dir: string;
constructor(fs: JSRuntimeFS) { constructor(fs: JSRuntimeFS) {
this.fs = fs; this.fs = fs;
this.git = new Git(fs, 'https://cors.isomorphic-git.org');
this.dir = '/projects'; this.dir = '/projects';
} }
@@ -60,8 +61,7 @@ export class ProjectsManager {
} }
// Initialize new git repository // Initialize new git repository
await git.init({ await this.git.init({
fs: this.fs,
dir: project.path, dir: project.path,
defaultBranch: 'main', defaultBranch: 'main',
}); });
@@ -71,8 +71,7 @@ export class ProjectsManager {
for (const file of files) { for (const file of files) {
// Skip .git directory and other hidden files we don't want to track // Skip .git directory and other hidden files we don't want to track
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await git.add({ await this.git.add({
fs: this.fs,
dir: project.path, dir: project.path,
filepath: file, filepath: file,
}); });
@@ -80,8 +79,7 @@ export class ProjectsManager {
} }
// Make initial commit // Make initial commit
await git.commit({ await this.git.commit({
fs: this.fs,
dir: project.path, dir: project.path,
message: 'New project created with Shakespeare', message: 'New project created with Shakespeare',
author: { author: {
@@ -94,7 +92,6 @@ export class ProjectsManager {
} }
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> { async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
const url = new URL(repoUrl);
const id = customId || await this.generateUniqueProjectId(name); const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID // Check if project with this ID already exists when using custom ID
@@ -107,18 +104,11 @@ export class ProjectsManager {
await this.fs.mkdir(projectPath); await this.fs.mkdir(projectPath);
// Clone the repository // Clone the repository
await git.clone({ await this.git.clone({
fs: this.fs,
http,
dir: projectPath, dir: projectPath,
url: repoUrl, url: repoUrl,
singleBranch: true, singleBranch: true,
depth: options?.depth, // Use depth if provided, otherwise clone full history depth: options?.depth, // Use depth if provided, otherwise clone full history
// Use the CORS proxy only for GitHub and GitLab URLs
// More info: https://github.com/isomorphic-git/isomorphic-git#cors-support
corsProxy: url.hostname === 'github.com' || url.hostname === 'gitlab.com'
? 'https://cors.isomorphic-git.org'
: undefined,
}); });
// Get filesystem stats for timestamps // Get filesystem stats for timestamps
@@ -319,8 +309,7 @@ export class ProjectsManager {
async getNostrRepoAddress(projectId: string): Promise<string | null> { async getNostrRepoAddress(projectId: string): Promise<string | null> {
try { try {
const projectPath = `${this.dir}/${projectId}`; const projectPath = `${this.dir}/${projectId}`;
const config = await git.getConfig({ const config = await this.git.getConfig({
fs: this.fs,
dir: projectPath, dir: projectPath,
path: 'nostr.repo', path: 'nostr.repo',
}); });
+27 -29
View File
@@ -2,19 +2,19 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GitCommitTool } from './GitCommitTool'; import { GitCommitTool } from './GitCommitTool';
import type { JSRuntimeFS } from '../JSRuntime'; import type { JSRuntimeFS } from '../JSRuntime';
// Mock isomorphic-git // Mock the Git class
vi.mock('isomorphic-git', () => ({ const mockGitInstance = {
default: { statusMatrix: vi.fn(),
statusMatrix: vi.fn(), add: vi.fn(),
add: vi.fn(), remove: vi.fn(),
remove: vi.fn(), commit: vi.fn(),
commit: vi.fn(), currentBranch: vi.fn(),
currentBranch: vi.fn(), getConfig: vi.fn(),
getConfig: vi.fn(), };
},
}));
import git from 'isomorphic-git'; vi.mock('../git', () => ({
Git: vi.fn().mockImplementation(() => mockGitInstance),
}));
// Mock filesystem // Mock filesystem
const mockFS: JSRuntimeFS = { const mockFS: JSRuntimeFS = {
@@ -39,14 +39,15 @@ describe('GitCommitTool', () => {
tool = new GitCommitTool(mockFS, '/test/project'); tool = new GitCommitTool(mockFS, '/test/project');
// Setup default mocks // Setup default mocks
vi.mocked(git.statusMatrix).mockResolvedValue([ mockGitInstance.statusMatrix.mockResolvedValue([
['src/file1.ts', 1, 1, 0], // Modified file (present in head and workdir, but not staged) ['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) ['src/file2.ts', 0, 1, 0], // New file (absent in head, present in workdir, not staged)
]); ]);
vi.mocked(git.add).mockResolvedValue(); mockGitInstance.add.mockResolvedValue(undefined);
vi.mocked(git.commit).mockResolvedValue('abcd1234567890abcdef1234567890abcdef12'); mockGitInstance.remove.mockResolvedValue(undefined);
vi.mocked(git.currentBranch).mockResolvedValue('main'); mockGitInstance.commit.mockResolvedValue('abcd1234567890abcdef1234567890abcdef12');
vi.mocked(git.getConfig).mockRejectedValue(new Error('Config not found')); mockGitInstance.currentBranch.mockResolvedValue('main');
mockGitInstance.getConfig.mockRejectedValue(new Error('Config not found'));
}); });
it('should have correct description and inputSchema', () => { it('should have correct description and inputSchema', () => {
@@ -64,13 +65,11 @@ describe('GitCommitTool', () => {
const result = await tool.execute({ message: 'Add new feature' }); const result = await tool.execute({ message: 'Add new feature' });
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git'); expect(mockFS.stat).toHaveBeenCalledWith('/test/project/.git');
expect(git.statusMatrix).toHaveBeenCalledWith({ expect(mockGitInstance.statusMatrix).toHaveBeenCalledWith({
fs: mockFS,
dir: '/test/project', dir: '/test/project',
}); });
expect(git.add).toHaveBeenCalled(); expect(mockGitInstance.add).toHaveBeenCalled();
expect(git.commit).toHaveBeenCalledWith({ expect(mockGitInstance.commit).toHaveBeenCalledWith({
fs: mockFS,
dir: '/test/project', dir: '/test/project',
message: 'Add new feature', message: 'Add new feature',
author: { author: {
@@ -124,7 +123,7 @@ describe('GitCommitTool', () => {
const specialMessage = 'Fix: handle "quotes" and \'apostrophes\' in commit message'; const specialMessage = 'Fix: handle "quotes" and \'apostrophes\' in commit message';
const result = await tool.execute({ message: specialMessage }); const result = await tool.execute({ message: specialMessage });
expect(git.commit).toHaveBeenCalledWith(expect.objectContaining({ expect(mockGitInstance.commit).toHaveBeenCalledWith(expect.objectContaining({
message: specialMessage, message: specialMessage,
})); }));
expect(result).toContain('✅ Successfully committed'); expect(result).toContain('✅ Successfully committed');
@@ -141,7 +140,7 @@ describe('GitCommitTool', () => {
const multilineMessage = 'Add new feature\n\nThis commit adds a new feature that allows users to do something amazing.\n\nCloses #123'; 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 }); const result = await tool.execute({ message: multilineMessage });
expect(git.commit).toHaveBeenCalled(); expect(mockGitInstance.commit).toHaveBeenCalled();
expect(result).toContain('✅ Successfully committed'); expect(result).toContain('✅ Successfully committed');
expect(result).toContain('Add new feature'); expect(result).toContain('Add new feature');
}); });
@@ -154,12 +153,12 @@ describe('GitCommitTool', () => {
}); });
// Mock no changes in status matrix // Mock no changes in status matrix
vi.mocked(git.statusMatrix).mockResolvedValue([]); vi.mocked(mockGitInstance.statusMatrix).mockResolvedValue([]);
const result = await tool.execute({ message: 'Update documentation' }); const result = await tool.execute({ message: 'Update documentation' });
expect(result).toContain('ℹ️ No changes to commit. Working tree is clean.'); expect(result).toContain('ℹ️ No changes to commit. Working tree is clean.');
expect(git.commit).not.toHaveBeenCalled(); expect(mockGitInstance.commit).not.toHaveBeenCalled();
}); });
it('should provide detailed commit information', async () => { it('should provide detailed commit information', async () => {
@@ -185,14 +184,13 @@ describe('GitCommitTool', () => {
}); });
// Mock git config // Mock git config
vi.mocked(git.getConfig) vi.mocked(mockGitInstance.getConfig)
.mockResolvedValueOnce('John Doe') // user.name .mockResolvedValueOnce('John Doe') // user.name
.mockResolvedValueOnce('[email protected]'); // user.email .mockResolvedValueOnce('[email protected]'); // user.email
const result = await tool.execute({ message: 'Test commit' }); const result = await tool.execute({ message: 'Test commit' });
expect(git.commit).toHaveBeenCalledWith({ expect(mockGitInstance.commit).toHaveBeenCalledWith({
fs: mockFS,
dir: '/test/project', dir: '/test/project',
message: 'Test commit', message: 'Test commit',
author: { author: {
+10 -15
View File
@@ -1,5 +1,5 @@
import { z } from "zod"; import { z } from "zod";
import git from 'isomorphic-git'; import { Git } from "../git";
import type { Tool } from "./Tool"; import type { Tool } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime"; import type { JSRuntimeFS } from "../JSRuntime";
@@ -10,6 +10,7 @@ interface GitCommitParams {
export class GitCommitTool implements Tool<GitCommitParams> { export class GitCommitTool implements Tool<GitCommitParams> {
private fs: JSRuntimeFS; private fs: JSRuntimeFS;
private git: Git;
private cwd: string; private cwd: string;
readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files."; readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files.";
@@ -20,6 +21,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
constructor(fs: JSRuntimeFS, cwd: string) { constructor(fs: JSRuntimeFS, cwd: string) {
this.fs = fs; this.fs = fs;
this.git = new Git(fs);
this.cwd = cwd; this.cwd = cwd;
} }
@@ -40,8 +42,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
} }
// Get git status to see what files have changed // Get git status to see what files have changed
const statusMatrix = await git.statusMatrix({ const statusMatrix = await this.git.statusMatrix({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
}); });
@@ -60,16 +61,14 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Add all changed files to staging // Add all changed files to staging
for (const [filepath] of changedFiles) { for (const [filepath] of changedFiles) {
try { try {
await git.add({ await this.git.add({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
filepath, filepath,
}); });
} catch { } catch {
// If file was deleted, use git.remove instead // If file was deleted, use git.remove instead
try { try {
await git.remove({ await this.git.remove({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
filepath, filepath,
}); });
@@ -83,8 +82,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Get current branch name // Get current branch name
let currentBranch = 'main'; let currentBranch = 'main';
try { try {
currentBranch = await git.currentBranch({ currentBranch = await this.git.currentBranch({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
}) || 'main'; }) || 'main';
} catch { } catch {
@@ -99,13 +97,11 @@ export class GitCommitTool implements Tool<GitCommitParams> {
// Try to get configured author from git config // Try to get configured author from git config
try { try {
const configName = await git.getConfig({ const configName = await this.git.getConfig({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
path: 'user.name', path: 'user.name',
}); });
const configEmail = await git.getConfig({ const configEmail = await this.git.getConfig({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
path: 'user.email', path: 'user.email',
}); });
@@ -116,8 +112,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
} }
// Commit the changes // Commit the changes
const commitSha = await git.commit({ const commitSha = await this.git.commit({
fs: this.fs,
dir: this.cwd, dir: this.cwd,
message: message.trim(), message: message.trim(),
author, author,