import { useState, useEffect, useCallback } from 'react'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { GitCompare, Loader2, GitCommit, FileIcon } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; import { useToast } from '@/hooks/useToast'; import { DiffViewer } from './DiffViewer'; interface CompareViewProps { projectId: string; } interface CommitInfo { oid: string; message: string; author: string; timestamp: number; } export function CompareView({ projectId }: CompareViewProps) { const [branches, setBranches] = useState([]); const [commits, setCommits] = useState([]); const [baseRef, setBaseRef] = useState(''); const [compareRef, setCompareRef] = useState(''); const [isLoading, setIsLoading] = useState(true); const [isComparing, setIsComparing] = useState(false); const [comparisonStats, setComparisonStats] = useState<{ ahead: number; behind: number; filesChanged: number; } | null>(null); const { git } = useGit(); const { toast } = useToast(); const projectPath = `/projects/${projectId}`; const loadReferences = useCallback(async () => { setIsLoading(true); try { // Get all branches const localBranches = await git.listBranches({ dir: projectPath }); setBranches(localBranches); // Set defaults const currentBranch = await git.currentBranch({ dir: projectPath }).catch(() => null); if (currentBranch) { setCompareRef(currentBranch); } // Set base to main/master if available if (localBranches.includes('main')) { setBaseRef('main'); } else if (localBranches.includes('master')) { setBaseRef('master'); } else if (localBranches.length > 0) { setBaseRef(localBranches[0]); } } catch (error) { console.error('Failed to load references:', error); toast({ title: 'Failed to load branches', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setIsLoading(false); } }, [git, projectPath, toast]); const performComparison = useCallback(async () => { if (!baseRef || !compareRef) return; setIsComparing(true); try { // Get commits in compareRef that are not in baseRef const baseCommits = await git.log({ dir: projectPath, ref: baseRef, depth: 100 }); const compareCommits = await git.log({ dir: projectPath, ref: compareRef, depth: 100 }); const baseCommitIds = new Set(baseCommits.map(c => c.oid)); const compareCommitIds = new Set(compareCommits.map(c => c.oid)); // Commits ahead (in compare but not in base) const aheadCommits = compareCommits.filter(c => !baseCommitIds.has(c.oid)); // Commits behind (in base but not in compare) const behindCommits = baseCommits.filter(c => !compareCommitIds.has(c.oid)); // Get list of changed files const baseFiles = await git.listFiles({ dir: projectPath, ref: baseRef }); const compareFiles = await git.listFiles({ dir: projectPath, ref: compareRef }); const changedFiles = new Set(); // Check files in compare ref for (const file of compareFiles) { try { const baseBlob = await git.readBlob({ dir: projectPath, oid: baseRef, filepath: file }); const compareBlob = await git.readBlob({ dir: projectPath, oid: compareRef, filepath: file }); if (Buffer.from(baseBlob.blob).toString() !== Buffer.from(compareBlob.blob).toString()) { changedFiles.add(file); } } catch { // File exists in one but not the other changedFiles.add(file); } } // Check for deleted files for (const file of baseFiles) { if (!compareFiles.includes(file)) { changedFiles.add(file); } } setComparisonStats({ ahead: aheadCommits.length, behind: behindCommits.length, filesChanged: changedFiles.size, }); // Set commit info for display const commitInfos: CommitInfo[] = aheadCommits.map(c => ({ oid: c.oid, message: c.commit.message, author: c.commit.author.name, timestamp: c.commit.author.timestamp, })); setCommits(commitInfos); } catch (error) { console.error('Failed to compare:', error); toast({ title: 'Comparison failed', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setIsComparing(false); } }, [baseRef, compareRef, git, projectPath, toast]); useEffect(() => { loadReferences(); }, [projectId, loadReferences]); useEffect(() => { if (baseRef && compareRef && baseRef !== compareRef) { performComparison(); } }, [baseRef, compareRef, performComparison]); const formatDate = (timestamp: number) => { const date = new Date(timestamp * 1000); const now = new Date(); const diffMs = now.getTime() - date.getTime(); const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); if (diffDays === 0) { return 'today'; } else if (diffDays === 1) { return 'yesterday'; } else if (diffDays < 7) { return `${diffDays} days ago`; } else { return date.toLocaleDateString(); } }; if (isLoading) { return (
); } return (
{/* Comparison selectors */} Compare Branches Select two branches to compare changes
{/* Comparison stats */} {comparisonStats && !isComparing && (
{comparisonStats.ahead}
Commits Ahead
{comparisonStats.behind}
Commits Behind
{comparisonStats.filesChanged}
Files Changed
)} {isComparing && (
Comparing branches...
)}
{/* Comparison results */} {baseRef && compareRef && baseRef !== compareRef && !isComparing && ( Commits ({commits.length}) Files ({comparisonStats?.filesChanged || 0}) {/* Commits tab */} {commits.length > 0 ? ( Commits in {compareRef} not in {baseRef} {commits.map((commit) => (

{commit.message.split('\n')[0]}

{commit.author} • {formatDate(commit.timestamp)} • {commit.oid.substring(0, 7)}
))}
) : (

No commits difference between branches

)}
{/* Files tab */}
)}
); }