import { useState, useEffect, useCallback } from 'react'; import { useNavigate } from 'react-router-dom'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; 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 { useGit } from '@/hooks/useGit'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useFS } from '@/hooks/useFS'; import { useToast } from '@/hooks/useToast'; import { useGitStatus } from '@/hooks/useGitStatus'; import { formatRelativeTime } from '@/lib/utils'; interface GitCommit { oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number; }; committer: { name: string; email: string; timestamp: number; }; }; } interface GitHistoryDialogProps { projectId: string; open?: boolean; onOpenChange?: (open: boolean) => void; } export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange }: GitHistoryDialogProps) { const [commits, setCommits] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [internalOpen, setInternalOpen] = useState(false); // Use controlled or internal state const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen; const setIsOpen = onOpenChange || setInternalOpen; const [isRollingBack, setIsRollingBack] = useState(null); const [expandedCommits, setExpandedCommits] = useState>(new Set()); const { fs } = useFS(); const { projectsPath } = useFSPaths(); const { git } = useGit(); const { toast } = useToast(); const navigate = useNavigate(); const { data: gitStatus } = useGitStatus(projectId); const loadGitHistory = useCallback(async () => { setIsLoading(true); setError(null); try { const projectPath = `${projectsPath}/${projectId}`; // Check if git repository exists try { await git.findRoot({ filepath: projectPath }); } catch { setError('No git repository found in this project'); return; } // Get git log const gitLog = await git.log({ dir: projectPath, depth: 50, // Limit to last 50 commits }); setCommits(gitLog); } catch (err) { console.error('Failed to load git history:', err); setError(err instanceof Error ? err.message : 'Failed to load git history'); } finally { setIsLoading(false); } }, [git, projectId, projectsPath]); const rollbackToCommit = useCallback(async (targetCommit: GitCommit) => { if (!fs) return; setIsRollingBack(targetCommit.oid); try { const projectPath = `${projectsPath}/${projectId}`; // Get the current HEAD commit const currentCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); // If we're already at this commit, no need to rollback if (currentCommit === targetCommit.oid) { toast({ title: "Already at this commit", description: "The codebase is already at this commit.", }); return; } // Get all commits between the target commit and HEAD const allCommits = await git.log({ dir: projectPath, depth: 1000, }); // Find the index of target commit and current HEAD const targetIndex = allCommits.findIndex(c => c.oid === targetCommit.oid); const currentIndex = allCommits.findIndex(c => c.oid === currentCommit); if (targetIndex === -1) { throw new Error('Target commit not found in history'); } if (currentIndex === -1) { throw new Error('Current commit not found in history'); } // Get commits to revert (from current back to target, exclusive) const commitsToRevert = allCommits.slice(currentIndex, targetIndex); if (commitsToRevert.length === 0) { toast({ title: "No commits to revert", description: "The target commit is ahead of the current commit.", }); return; } // Simple approach: checkout the target commit's tree and create a new commit // This effectively "reverts" to that state without complex merge logic // Get all files from the target commit const targetFiles = await git.listFiles({ dir: projectPath, ref: targetCommit.oid, }); // Get current files to know what to remove const currentFiles = await git.listFiles({ dir: projectPath, ref: 'HEAD', }); // Remove files that don't exist in target commit for (const filepath of currentFiles) { if (!targetFiles.includes(filepath)) { try { await fs.unlink(`${projectPath}/${filepath}`); await git.remove({ dir: projectPath, filepath, }); } catch (err) { // File might not exist, continue console.warn(`Could not remove ${filepath}:`, err); } } } // Restore all files from target commit for (const filepath of targetFiles) { try { const { blob } = await git.readBlob({ dir: projectPath, oid: targetCommit.oid, filepath, }); // Ensure directory exists const dirPath = filepath.split('/').slice(0, -1).join('/'); if (dirPath) { await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true }); } // Write the file await fs.writeFile(`${projectPath}/${filepath}`, blob); // Stage the file await git.add({ dir: projectPath, filepath, }); } catch (err) { console.error(`Failed to restore ${filepath}:`, err); } } // Create a revert commit const targetFirstLine = getCommitMessageLines(targetCommit.commit.message).firstLine; const revertMessage = `Revert to ${targetCommit.oid.substring(0, 7)}: ${targetFirstLine} This reverts the codebase back to the state at commit ${targetCommit.oid.substring(0, 7)}. Reverted ${commitsToRevert.length} commit(s): ${commitsToRevert.map(c => { const commitFirstLine = getCommitMessageLines(c.commit.message).firstLine; return `- ${c.oid.substring(0, 7)}: ${commitFirstLine}`; }).join('\n')}`; await git.commit({ dir: projectPath, message: revertMessage, }); toast({ title: "Rollback successful", description: `Reverted ${commitsToRevert.length} commit(s) back to ${targetCommit.oid.substring(0, 7)}`, }); // Close the dialog and navigate to project page with build query parameter setIsOpen(false); navigate(`/project/${projectId}?build`); } catch (err) { console.error('Failed to rollback:', err); toast({ title: "Rollback failed", description: err instanceof Error ? err.message : 'Failed to rollback to this commit', variant: "destructive", }); } finally { setIsRollingBack(null); } }, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]); const resetToHead = useCallback(async () => { if (!fs) return; setIsRollingBack('HEAD'); try { const projectPath = `${projectsPath}/${projectId}`; // Get the current HEAD commit const headCommit = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); // Get all files from HEAD const headFiles = await git.listFiles({ dir: projectPath, ref: 'HEAD', }); // Get current files in working directory const currentFiles = await git.listFiles({ dir: projectPath, }); // Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files) for (const filepath of currentFiles) { if (!headFiles.includes(filepath)) { try { await fs.unlink(`${projectPath}/${filepath}`); } catch (err) { console.warn(`Could not remove ${filepath}:`, err); } } } // Reset all files to HEAD state (equivalent to git reset --hard HEAD) for (const filepath of headFiles) { try { const { blob } = await git.readBlob({ dir: projectPath, oid: headCommit, filepath, }); // Ensure directory exists const dirPath = filepath.split('/').slice(0, -1).join('/'); if (dirPath) { await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true }); } // Write the file await fs.writeFile(`${projectPath}/${filepath}`, blob); } catch (err) { console.error(`Failed to reset ${filepath}:`, err); } } // Remove untracked files and directories (equivalent to git clean -fd) // Get git status to find untracked files const status = await git.statusMatrix({ dir: projectPath, }); const untrackedFiles = status .filter(([, headStatus, workdirStatus, stageStatus]) => headStatus === 0 && workdirStatus === 1 && stageStatus === 0 ) .map(([filepath]) => filepath); for (const filepath of untrackedFiles) { try { await fs.unlink(`${projectPath}/${filepath}`); } catch (err) { console.warn(`Could not remove untracked file ${filepath}:`, err); } } toast({ title: "Reset successful", description: "All changes have been discarded and working directory reset to HEAD", }); // Close the dialog and navigate to project page with build query parameter setIsOpen(false); navigate(`/project/${projectId}?build`); } catch (err) { console.error('Failed to reset:', err); toast({ title: "Reset failed", description: err instanceof Error ? err.message : 'Failed to reset to HEAD', variant: "destructive", }); } finally { setIsRollingBack(null); } }, [git, fs, projectId, toast, navigate, setIsOpen, projectsPath]); useEffect(() => { if (isOpen) { loadGitHistory(); } }, [isOpen, loadGitHistory]); const getCommitMessageLines = (message: string) => { const lines = message.split('\n').filter(line => line.trim() !== ''); return { firstLine: lines[0] || '', hasMoreLines: lines.length > 1, fullMessage: message, }; }; const toggleCommitExpansion = (commitOid: string) => { setExpandedCommits(prev => { const newSet = new Set(prev); if (newSet.has(commitOid)) { newSet.delete(commitOid); } else { newSet.add(commitOid); } return newSet; }); }; return ( {/* Only show trigger if not controlled externally */} {controlledOpen === undefined && ( )} Rollback Revert to an older commit
{isLoading ? (
Loading git history...
) : error ? (

Error loading git history

{error}

) : !commits || commits.length === 0 ? (

No commits found

This project doesn't have any git commits yet

) : (
{commits.map((commit, index) => { const { firstLine, hasMoreLines, fullMessage } = getCommitMessageLines(commit.commit.message); const isExpanded = expandedCommits.has(commit.oid); return (

{firstLine}

{hasMoreLines && ( )}
{isExpanded && hasMoreLines && (
{fullMessage.split('\n').slice(1).join('\n').trim()}
)}
{commit.commit.author.name} committed {formatRelativeTime(commit.commit.author.timestamp)}
{index === 0 ? ( // Show "Current" or "Rollback" for the most recent commit gitStatus?.hasUncommittedChanges ? ( Discard All Changes

This will discard all unstaged changes and reset your working directory to the current commit:

{firstLine}
{commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)}

This action cannot be undone.

Cancel {isRollingBack === 'HEAD' ? ( <>
Discarding... ) : ( <> Discard Changes )} ) : ( ) ) : ( // Show rollback button for older commits Confirm Rollback

This will create a new commit that reverts the codebase back to:

{firstLine}
{commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)}

This action will revert {index} commit(s) and cannot be undone easily. A new commit will be created with the reverted changes.

Cancel rollbackToCommit(commit)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={isRollingBack !== null} > {isRollingBack === commit.oid ? ( <>
Rolling back... ) : ( <> Rollback )} )}
); })}
)}
); }