import { useState } from 'react'; import { useNavigate } from 'react-router-dom'; 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 { Alert, AlertDescription } from '@/components/ui/alert'; import { GitBranch, Upload, Download, Loader2, CheckCircle, AlertCircle, Clock, FileIcon, Plus, Minus, Edit, RefreshCw, Settings, AlertTriangle, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; 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 navigate = useNavigate(); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); const { git } = useGit(); 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({ dir: projectPath, remote: remote.name, ref: gitStatus.currentBranch, onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); 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({ dir: projectPath, ref: gitStatus.currentBranch, singleBranch: true, author: { name: 'shakespeare.diy', email: 'assistant@shakespeare.diy', }, onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); 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

)}
{/* Credentials Status */} {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && ( Authentication Credentials for push/pull operations {gitStatus.remotes.map((remote) => { const credentials = findCredentialsForRepo(remote.url, settings.credentials); const originDisplayName = getOriginDisplayName(remote.url); return (
{remote.name} {originDisplayName}
{credentials ? (
Configured
) : (
No credentials
)}
{!credentials && ( No credentials configured for {originDisplayName}. Push/pull operations may fail for private repositories.{' '} )}
); })}
)} {/* 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

)}
); }