From 227b0fab7691a6e50ab74c172be117673811ea8f Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 12 Sep 2025 17:21:24 -0500 Subject: [PATCH] Add GitDialog --- src/components/ActionsMenu.tsx | 18 ++ src/components/GitDialog.test.tsx | 134 +++++++++ src/components/GitDialog.tsx | 458 ++++++++++++++++++++++++++++++ src/hooks/useGitStatus.ts | 62 +++- 4 files changed, 663 insertions(+), 9 deletions(-) create mode 100644 src/components/GitDialog.test.tsx create mode 100644 src/components/GitDialog.tsx diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 7ae9e73a..77aa1650 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -28,8 +28,10 @@ import { Download, Trash2, Settings, + GitMerge, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; +import { GitDialog } from '@/components/GitDialog'; import { AppSettingsDialog } from '@/components/AppSettingsDialog'; import { useNavigate } from 'react-router-dom'; import { useProjectsManager } from '@/hooks/useProjectsManager'; @@ -66,6 +68,7 @@ export function ActionsMenu({ onProjectDeleted }: ActionsMenuProps) { const [gitHistoryOpen, setGitHistoryOpen] = useState(false); + const [gitDialogOpen, setGitDialogOpen] = useState(false); const [isDeleting, setIsDeleting] = useState(false); const [isExporting, setIsExporting] = useState(false); @@ -213,6 +216,15 @@ export function ActionsMenu({ New Chat + setGitDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Git Status + + setGitHistoryOpen(true)} disabled={isAnyLoading} @@ -320,6 +332,12 @@ export function ActionsMenu({ {/* Dialogs */} + + ({ + useGitStatus: () => mockUseGitStatus(), +})); + +vi.mock('@/hooks/useFS', () => ({ + useFS: vi.fn(() => ({ + fs: {}, + })), +})); + +vi.mock('@/hooks/useToast', () => ({ + useToast: vi.fn(() => ({ + toast: vi.fn(), + })), +})); + +describe('GitDialog', () => { + beforeEach(() => { + mockUseGitStatus.mockReturnValue({ + data: baseGitStatus, + refetch: mockRefetch, + }); + }); + + it('renders git repository information', () => { + render( + + {}}> + + + + ); + + expect(screen.getByText('Git Repository Status')).toBeInTheDocument(); + expect(screen.getByText('Repository Information')).toBeInTheDocument(); + expect(screen.getByText('main')).toBeInTheDocument(); + expect(screen.getByText('5')).toBeInTheDocument(); + expect(screen.getByText('origin')).toBeInTheDocument(); + }); + + it('shows sync status', () => { + render( + + {}}> + + + + ); + + expect(screen.getByText('Sync Status')).toBeInTheDocument(); + expect(screen.getByText('Up to date')).toBeInTheDocument(); + expect(screen.getByText('Pull')).toBeInTheDocument(); + expect(screen.getByText('Push')).toBeInTheDocument(); + }); + + it('shows clean working directory when no changes', () => { + render( + + {}}> + + + + ); + + expect(screen.getByText('Working directory is clean')).toBeInTheDocument(); + expect(screen.getByText('No uncommitted changes')).toBeInTheDocument(); + }); + + it('enables push button when there are commits ahead', () => { + // Mock git status with commits ahead + mockUseGitStatus.mockReturnValue({ + data: { + ...baseGitStatus, + ahead: 2, + }, + refetch: mockRefetch, + }); + + render( + + {}}> + + + + ); + + const pushButton = screen.getByText('Push'); + expect(pushButton).toBeInTheDocument(); + expect(pushButton.closest('button')).not.toBeDisabled(); + }); + + it('disables push button when no commits ahead', () => { + render( + + {}}> + + + + ); + + const pushButton = screen.getByText('Push'); + expect(pushButton).toBeInTheDocument(); + expect(pushButton.closest('button')).toBeDisabled(); + }); +}); \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx new file mode 100644 index 00000000..2eb1c637 --- /dev/null +++ b/src/components/GitDialog.tsx @@ -0,0 +1,458 @@ +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { + GitBranch, + Upload, + Download, + Loader2, + CheckCircle, + AlertCircle, + Clock, + FileIcon, + Plus, + Minus, + Edit, + RefreshCw, +} from 'lucide-react'; +import { useGitStatus } from '@/hooks/useGitStatus'; +import { useFS } from '@/hooks/useFS'; +import { useToast } from '@/hooks/useToast'; +import { cn } from '@/lib/utils'; +import git from 'isomorphic-git'; +import http from 'isomorphic-git/http/web'; + +interface GitDialogProps { + projectId: string; + children?: React.ReactNode; + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) { + const [isPushing, setIsPushing] = useState(false); + const [isPulling, setIsPulling] = useState(false); + const [pushResult, setPushResult] = useState(null); + const [pullResult, setPullResult] = useState(null); + + const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); + const { fs } = useFS(); + const { toast } = useToast(); + + const projectPath = `/projects/${projectId}`; + + const handlePush = async () => { + if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { + toast({ + title: "Cannot push", + description: "Not a git repository or no current branch", + variant: "destructive", + }); + return; + } + + if (gitStatus.remotes.length === 0) { + toast({ + title: "Cannot push", + description: "No remote repositories configured", + variant: "destructive", + }); + return; + } + + if (gitStatus.ahead === 0) { + toast({ + title: "Nothing to push", + description: "No commits ahead of remote. Commit your changes first.", + variant: "destructive", + }); + return; + } + + setIsPushing(true); + setPushResult(null); + + try { + const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') + + await git.push({ + fs, + http, + dir: projectPath, + remote: remote.name, + ref: gitStatus.currentBranch, + corsProxy: 'https://cors.isomorphic-git.org', + }); + + setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`); + toast({ + title: "Push successful", + description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`, + }); + + // Refresh git status after push + await refetchGitStatus(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + setPushResult(`❌ Push failed: ${errorMessage}`); + toast({ + title: "Push failed", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsPushing(false); + } + }; + + const handlePull = async () => { + if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { + toast({ + title: "Cannot pull", + description: "Not a git repository or no current branch", + variant: "destructive", + }); + return; + } + + if (gitStatus.remotes.length === 0) { + toast({ + title: "Cannot pull", + description: "No remote repositories configured", + variant: "destructive", + }); + return; + } + + setIsPulling(true); + setPullResult(null); + + try { + const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') + + await git.pull({ + fs, + http, + dir: projectPath, + ref: gitStatus.currentBranch, + singleBranch: true, + corsProxy: 'https://cors.isomorphic-git.org', + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + + setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`); + toast({ + title: "Pull successful", + description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`, + }); + + // Refresh git status after pull + await refetchGitStatus(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + setPullResult(`❌ Pull failed: ${errorMessage}`); + toast({ + title: "Pull failed", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsPulling(false); + } + }; + + const handleRefresh = async () => { + await refetchGitStatus(); + setPushResult(null); + setPullResult(null); + }; + + const getFileStatusIcon = (status: string) => { + switch (status) { + case 'added': + return ; + case 'deleted': + return ; + case 'modified': + return ; + case 'staged': + return ; + case 'untracked': + return ; + default: + return ; + } + }; + + const getFileStatusColor = (status: string) => { + switch (status) { + case 'added': + return 'bg-green-100 text-green-800 border-green-200'; + case 'deleted': + return 'bg-red-100 text-red-800 border-red-200'; + case 'modified': + return 'bg-blue-100 text-blue-800 border-blue-200'; + case 'staged': + return 'bg-green-100 text-green-800 border-green-200'; + case 'untracked': + return 'bg-gray-100 text-gray-800 border-gray-200'; + default: + return 'bg-gray-100 text-gray-800 border-gray-200'; + } + }; + + const getSyncStatus = () => { + if (!gitStatus?.isGitRepo) { + return { status: 'not-repo', text: 'Not a Git repository', icon: AlertCircle, color: 'text-gray-500' }; + } + + if (gitStatus.remotes.length === 0) { + return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' }; + } + + if (gitStatus.ahead > 0 && gitStatus.behind > 0) { + return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' }; + } + + if (gitStatus.ahead > 0) { + return { status: 'ahead', text: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead`, icon: Upload, color: 'text-blue-600' }; + } + + // Show uncommitted changes but with different styling since they can't be pushed directly + if (gitStatus.hasUncommittedChanges) { + return { status: 'uncommitted', text: `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`, icon: Clock, color: 'text-yellow-600' }; + } + + if (gitStatus.behind > 0) { + return { status: 'behind', text: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind`, icon: Download, color: 'text-orange-600' }; + } + + return { status: 'synced', text: 'Up to date', icon: CheckCircle, color: 'text-green-600' }; + }; + + const syncStatus = getSyncStatus(); + + return ( + + {children && {children}} + + + + + Git Repository Status + + + View repository status and sync with remote repositories + + + + +
+ {/* Repository Info */} + + + + Repository Information + + + + + {gitStatus?.isGitRepo ? ( + <> +
+ Current Branch: + + {gitStatus.currentBranch || 'unknown'} + +
+ +
+ Total Commits: + {gitStatus.totalCommits} +
+ + {gitStatus.latestCommit && ( +
+ Latest Commit: +
+
+ {gitStatus.latestCommit.oid.substring(0, 7)} +
+
{gitStatus.latestCommit.message}
+
+ + {new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()} +
+
+
+ )} + + {gitStatus.remotes.length > 0 && ( +
+ Remotes: + {gitStatus.remotes.map((remote) => ( +
+
+ {remote.name} + + {remote.url} + +
+
+ ))} +
+ )} + + ) : ( +
+ +

Not a Git repository

+
+ )} +
+
+ + {/* Sync Status */} + {gitStatus?.isGitRepo && ( + + + Sync Status + + +
+ + + {syncStatus.text} + +
+ + {gitStatus.remotes.length > 0 && ( +
+ + + +
+ )} + + {/* Operation Results */} + {(pushResult || pullResult) && ( +
+ {pushResult && ( +
+ {pushResult} +
+ )} + {pullResult && ( +
+ {pullResult} +
+ )} +
+ )} +
+
+ )} + + {/* Working Directory Changes */} + {gitStatus?.isGitRepo && gitStatus.changedFiles.length > 0 && ( + + + Working Directory Changes + + {gitStatus.changedFiles.length} file{gitStatus.changedFiles.length !== 1 ? 's' : ''} with changes + + + +
+ {gitStatus.changedFiles.map((file, index) => ( +
+ {getFileStatusIcon(file.status)} + + {file.filepath} + + + {file.status} + +
+ ))} +
+
+
+ )} + + {/* Clean Working Directory */} + {gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && ( + + +
+ +

Working directory is clean

+

No uncommitted changes

+
+
+
+ )} +
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/hooks/useGitStatus.ts b/src/hooks/useGitStatus.ts index a4cea527..b789019f 100644 --- a/src/hooks/useGitStatus.ts +++ b/src/hooks/useGitStatus.ts @@ -196,18 +196,62 @@ export function useGitStatus(projectId: string | null) { }); } - // Calculate ahead/behind (simplified - would need remote tracking branch info) - const ahead = 0; - const behind = 0; + // Calculate ahead/behind + let ahead = 0; + let behind = 0; try { - // This is a simplified calculation - in a real implementation, - // you'd compare with the remote tracking branch if (currentBranch && remotes.length > 0) { - // For now, we'll leave these as 0 since calculating ahead/behind - // requires more complex remote branch comparison + const remote = remotes[0]; // Use first remote (usually 'origin') + const remoteBranchName = `${remote.name}/${currentBranch}`; + + try { + // Try to get the remote branch reference + const remoteRef = await git.resolveRef({ + fs, + dir: cwd, + ref: remoteBranchName, + }); + + const localRef = await git.resolveRef({ + fs, + dir: cwd, + ref: currentBranch, + }); + + if (remoteRef && localRef && remoteRef !== localRef) { + // Get commits between local and remote + const localCommits = await git.log({ + fs, + dir: cwd, + ref: currentBranch, + }); + + const remoteCommits = await git.log({ + fs, + dir: cwd, + ref: remoteBranchName, + }); + + // Find commits that are in local but not in remote (ahead) + const remoteCommitOids = new Set(remoteCommits.map(c => c.oid)); + const localOnlyCommits = localCommits.filter(c => !remoteCommitOids.has(c.oid)); + ahead = localOnlyCommits.length; + + // Find commits that are in remote but not in local (behind) + const localCommitOids = new Set(localCommits.map(c => c.oid)); + const remoteOnlyCommits = remoteCommits.filter(c => !localCommitOids.has(c.oid)); + behind = remoteOnlyCommits.length; + } + } catch { + // Remote branch might not exist or other issues + // If we can't find remote branch, assume we're ahead if we have commits + if (totalCommits > 0) { + ahead = totalCommits; + } + } } - } catch (error) { - console.warn('Could not calculate ahead/behind:', error); + } catch (err) { + console.warn('Could not calculate ahead/behind:', err); } return {