diff --git a/package-lock.json b/package-lock.json index 0b3bdaf8..856c6143 100644 --- a/package-lock.json +++ b/package-lock.json @@ -66,6 +66,7 @@ "nostr-tools": "^2.15.2", "openai": "^5.15.0", "path-browserify": "^1.0.1", + "prismjs": "^1.30.0", "qrcode": "^1.5.4", "react": "^18.3.1", "react-day-picker": "^8.10.1", @@ -99,6 +100,7 @@ "@types/jszip": "^3.4.0", "@types/node": "^22.5.5", "@types/path-browserify": "^1.0.3", + "@types/prismjs": "^1.26.5", "@types/qrcode": "^1.5.5", "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", @@ -3804,6 +3806,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/prismjs": { + "version": "1.26.5", + "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz", + "integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/prop-types": { "version": "15.7.14", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz", @@ -8864,6 +8873,15 @@ "license": "MIT", "peer": true }, + "node_modules/prismjs": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz", + "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", diff --git a/package.json b/package.json index 20cf933c..640f2719 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "nostr-tools": "^2.15.2", "openai": "^5.15.0", "path-browserify": "^1.0.1", + "prismjs": "^1.30.0", "qrcode": "^1.5.4", "react": "^18.3.1", "react-day-picker": "^8.10.1", @@ -102,6 +103,7 @@ "@types/jszip": "^3.4.0", "@types/node": "^22.5.5", "@types/path-browserify": "^1.0.3", + "@types/prismjs": "^1.26.5", "@types/qrcode": "^1.5.5", "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 08f76ce4..1e4f4df9 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -1,9 +1,10 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useCallback } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, + DialogDescription, DialogHeader, DialogTitle, DialogTrigger, @@ -20,6 +21,13 @@ import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; import { GitBranch, Upload, @@ -35,6 +43,7 @@ import { AlertTriangle, Zap, Save, + Settings2, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; @@ -46,6 +55,9 @@ import { useNostrPublish } from '@/hooks/useNostrPublish'; import { cn } from '@/lib/utils'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; +import { GitManagementDialog } from '@/components/git/GitManagementDialog'; +import { MergeDialog } from '@/components/git/MergeDialog'; +import { PullRequestDialog } from '@/components/git/PullRequestDialog'; const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"]; @@ -65,6 +77,14 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const [searchParams, setSearchParams] = useSearchParams(); const navigate = useNavigate(); + // Branch management state + const [branches, setBranches] = useState([]); + const [isLoadingBranches, setIsLoadingBranches] = useState(false); + const [isSwitchingBranch, setIsSwitchingBranch] = useState(false); + const [isCreatingBranch, setIsCreatingBranch] = useState(false); + const [newBranchName, setNewBranchName] = useState(''); + const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false); + const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); const { git } = useGit(); @@ -83,6 +103,111 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } }, [gitStatus?.remotes]); + const loadBranches = useCallback(async () => { + setIsLoadingBranches(true); + try { + const localBranches = await git.listBranches({ dir: projectPath }); + setBranches(localBranches); + } catch (error) { + console.error('Failed to load branches:', error); + } finally { + setIsLoadingBranches(false); + } + }, [git, projectPath]); + + // Load branches when dialog opens + useEffect(() => { + if (open && gitStatus?.isGitRepo) { + loadBranches(); + } + }, [open, gitStatus?.isGitRepo, loadBranches]); + + const handleSwitchBranch = async (branchName: string) => { + setIsSwitchingBranch(true); + try { + await git.checkout({ + dir: projectPath, + ref: branchName, + }); + + toast({ + title: 'Branch switched', + description: `Switched to branch "${branchName}"`, + }); + + await refetchGitStatus(); + + // Trigger rebuild + const newSearchParams = new URLSearchParams(searchParams); + newSearchParams.set('build', ''); + setSearchParams(newSearchParams); + } catch (error) { + toast({ + title: 'Failed to switch branch', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setIsSwitchingBranch(false); + } + }; + + const handleCreateBranch = async () => { + if (!newBranchName.trim()) { + toast({ + title: 'Invalid branch name', + description: 'Please enter a branch name', + variant: 'destructive', + }); + return; + } + + // Validate branch name + const invalidChars = /[~^: \\?*[\]]/; + if (invalidChars.test(newBranchName)) { + toast({ + title: 'Invalid branch name', + description: 'Branch name contains invalid characters', + variant: 'destructive', + }); + return; + } + + setIsCreatingBranch(true); + try { + // Get current HEAD to base the new branch on + const currentRef = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + + // Create the new branch + await git.branch({ + dir: projectPath, + ref: newBranchName.trim(), + object: currentRef, + }); + + toast({ + title: 'Branch created', + description: `Created branch "${newBranchName}"`, + }); + + setNewBranchName(''); + setIsCreateBranchDialogOpen(false); + await loadBranches(); + await refetchGitStatus(); + } catch (error) { + toast({ + title: 'Failed to create branch', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setIsCreatingBranch(false); + } + }; + const handleSaveOrigin = async () => { if (!gitStatus?.isGitRepo) { toast({ @@ -550,256 +675,420 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const syncStatus = getSyncStatus(); + const [isGitManagementOpen, setIsGitManagementOpen] = useState(false); + return ( - - {children && {children}} - e.preventDefault()}> - - - - Repository - - - - {/* URL Configuration */} - {gitStatus?.isGitRepo && ( - - - Git URL - - -
-
- - setOriginUrl(e.target.value)} - disabled={isSavingOrigin} - /> -
+ <> + + {children && {children}} + e.preventDefault()}> + +
+ + + Repository + + {gitStatus?.isGitRepo && ( -
- - {/* Credentials Warning */} - {gitStatus.remotes.length > 0 && ( - (() => { - const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials)); - if (!remoteWithoutCredentials) return null; - - let protocol = ''; - let hostname = 'the remote host'; - try { - const url = new URL(remoteWithoutCredentials.url); - protocol = url.protocol; - hostname = url.hostname; - } catch { - // Invalid URL - return ( - - - - Invalid URL format. Enter an https URL. - - - ); - } - - // Check for unsupported protocols - if (protocol !== 'https:' && protocol !== 'nostr:') { - return ( - - - - The {protocol.replace(':', '')} URL type is not supported. Enter an https URL. - - - ); - } - - // For nostr protocol, only show warning if user is not logged in - if (protocol === 'nostr:' && !user) { - return ( - - - - You are not logged into Nostr. Push & pull might not work unless you{' '} - . - - - ); - } - - // For https protocol, show warning if no credentials - if (protocol === 'https:') { - return ( - - - - You are not logged into {hostname}. Push & pull might not work unless you{' '} - . - - - ); - } - - return null; - })() )} - - - )} +
+ - -
- - {/* Sync Status */} - {gitStatus?.isGitRepo && ( - - - Sync Status - - -
- - - {syncStatus.text} - -
- - {gitStatus.remotes.length > 0 && ( -
- - - -
- )} - - {/* Push to Nostr button when no remote is configured and user is logged in */} - {gitStatus.remotes.length === 0 && user && ( -
- -
- )} - - -
-
- )} - - {/* 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} - - + +
+ {/* URL Configuration */} + {gitStatus?.isGitRepo && ( + + + Git URL + + +
+
+ + setOriginUrl(e.target.value)} + disabled={isSavingOrigin} + /> +
+
- ))} -
- - - )} - {/* Clean Working Directory */} - {gitStatus?.isGitRepo && gitStatus.changedFiles.length === 0 && ( - - -
- -

Working directory is clean

-

No uncommitted changes

-
-
-
+ {/* Credentials Warning */} + {gitStatus.remotes.length > 0 && ( + (() => { + const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials)); + if (!remoteWithoutCredentials) return null; + + let protocol = ''; + let hostname = 'the remote host'; + try { + const url = new URL(remoteWithoutCredentials.url); + protocol = url.protocol; + hostname = url.hostname; + } catch { + // Invalid URL + return ( + + + + Invalid URL format. Enter an https URL. + + + ); + } + + // Check for unsupported protocols + if (protocol !== 'https:' && protocol !== 'nostr:') { + return ( + + + + The {protocol.replace(':', '')} URL type is not supported. Enter an https URL. + + + ); + } + + // For nostr protocol, only show warning if user is not logged in + if (protocol === 'nostr:' && !user) { + return ( + + + + You are not logged into Nostr. Push & pull might not work unless you{' '} + . + + + ); + } + + // For https protocol, show warning if no credentials + if (protocol === 'https:') { + return ( + + + + You are not logged into {hostname}. Push & pull might not work unless you{' '} + . + + + ); + } + + return null; + })() + )} + + + )} + + {/* Branch Selector */} + {gitStatus?.isGitRepo && gitStatus.currentBranch && ( + + + Current Branch + + +
+ + +
+
+
+ )} + + {/* Sync Status */} + {gitStatus?.isGitRepo && ( + + + Sync Status + + +
+ + + {syncStatus.text} + +
+ + {gitStatus.remotes.length > 0 && ( +
+ + + +
+ )} + + {/* Push to Nostr button when no remote is configured and user is logged in */} + {gitStatus.remotes.length === 0 && user && ( +
+ +
+ )} +
+
+ )} + + {/* Branch Operations */} + {gitStatus?.isGitRepo && gitStatus.currentBranch && ( + + + Branch Operations + + + refetchGitStatus()} + /> + {gitStatus.remotes.length > 0 && originUrl && ( + + )} + + + )} + + {/* 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

+
+
+
+ )} +
+ +
+ +
+ + {/* Advanced Git Management Dialog */} + + + {/* Create Branch Dialog */} + + + + Create New Branch + + Create a new branch from {gitStatus?.currentBranch || 'current HEAD'} + + +
+
+ + setNewBranchName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && !isCreatingBranch) { + handleCreateBranch(); + } + }} + autoFocus + /> +
+ {gitStatus?.currentBranch && ( +
+ Creating from: {gitStatus.currentBranch} +
)}
- -
-
+
+ + +
+ + + ); } \ No newline at end of file diff --git a/src/components/git/BranchManager.tsx b/src/components/git/BranchManager.tsx new file mode 100644 index 00000000..42e8b42e --- /dev/null +++ b/src/components/git/BranchManager.tsx @@ -0,0 +1,510 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog'; +import { Badge } from '@/components/ui/badge'; +import { + GitBranch, + Plus, + Trash2, + Check, + Loader2, + ArrowUpRight, +} from 'lucide-react'; +import { useGit } from '@/hooks/useGit'; +import { useToast } from '@/hooks/useToast'; +import { cn } from '@/lib/utils'; + +interface BranchInfo { + name: string; + isCurrent: boolean; + isRemote: boolean; + remoteName?: string; + commitId?: string; + ahead?: number; + behind?: number; +} + +interface BranchManagerProps { + projectId: string; + currentBranch: string | null; + onBranchChange?: () => void; +} + +export function BranchManager({ projectId, currentBranch, onBranchChange }: BranchManagerProps) { + const [branches, setBranches] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [newBranchName, setNewBranchName] = useState(''); + const [isCreating, setIsCreating] = useState(false); + const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false); + const [deletingBranch, setDeletingBranch] = useState(null); + const [switchingToBranch, setSwitchingToBranch] = useState(null); + + const { git } = useGit(); + const { toast } = useToast(); + const projectPath = `/projects/${projectId}`; + + const loadBranches = useCallback(async () => { + setIsLoading(true); + try { + // Get local branches + const localBranches = await git.listBranches({ + dir: projectPath, + }); + + // Get remote branches + let remoteBranches: string[] = []; + try { + remoteBranches = await git.listBranches({ + dir: projectPath, + remote: 'origin', + }); + } catch { + // No remote or error fetching remote branches + } + + // Get current branch + const current = await git.currentBranch({ dir: projectPath }).catch(() => null); + + // Build branch info + const branchInfos: BranchInfo[] = []; + + // Add local branches + for (const branch of localBranches) { + const isCurrent = branch === current; + let commitId: string | undefined; + try { + commitId = await git.resolveRef({ + dir: projectPath, + ref: `refs/heads/${branch}`, + }); + } catch { + // Skip branches we can't resolve + } + + branchInfos.push({ + name: branch, + isCurrent, + isRemote: false, + commitId, + }); + } + + // Add remote branches + for (const branch of remoteBranches) { + // Skip if we already have this as a local branch + if (localBranches.includes(branch)) continue; + + let commitId: string | undefined; + try { + commitId = await git.resolveRef({ + dir: projectPath, + ref: `refs/remotes/origin/${branch}`, + }); + } catch { + // Skip branches we can't resolve + } + + branchInfos.push({ + name: branch, + isCurrent: false, + isRemote: true, + remoteName: 'origin', + commitId, + }); + } + + setBranches(branchInfos); + } catch (error) { + console.error('Failed to load branches:', error); + toast({ + title: 'Failed to load branches', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setIsLoading(false); + } + }, [git, projectPath, toast]); + + useEffect(() => { + loadBranches(); + }, [projectId, currentBranch, loadBranches]); + + const handleCreateBranch = async () => { + if (!newBranchName.trim()) { + toast({ + title: 'Invalid branch name', + description: 'Please enter a branch name', + variant: 'destructive', + }); + return; + } + + // Validate branch name + const invalidChars = /[~^: \\?*[\]]/; + if (invalidChars.test(newBranchName)) { + toast({ + title: 'Invalid branch name', + description: 'Branch name contains invalid characters', + variant: 'destructive', + }); + return; + } + + setIsCreating(true); + try { + // Get current HEAD to base the new branch on + const currentRef = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + + // Create the new branch + await git.branch({ + dir: projectPath, + ref: newBranchName.trim(), + object: currentRef, + }); + + toast({ + title: 'Branch created', + description: `Created branch "${newBranchName}"`, + }); + + setNewBranchName(''); + setIsCreateDialogOpen(false); + await loadBranches(); + onBranchChange?.(); + } catch (error) { + toast({ + title: 'Failed to create branch', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setIsCreating(false); + } + }; + + const handleSwitchBranch = async (branchName: string) => { + setSwitchingToBranch(branchName); + try { + await git.checkout({ + dir: projectPath, + ref: branchName, + }); + + toast({ + title: 'Branch switched', + description: `Switched to branch "${branchName}"`, + }); + + await loadBranches(); + onBranchChange?.(); + } catch (error) { + toast({ + title: 'Failed to switch branch', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setSwitchingToBranch(null); + } + }; + + const handleDeleteBranch = async (branchName: string) => { + setDeletingBranch(branchName); + try { + await git.deleteBranch({ + dir: projectPath, + ref: branchName, + }); + + toast({ + title: 'Branch deleted', + description: `Deleted branch "${branchName}"`, + }); + + await loadBranches(); + onBranchChange?.(); + } catch (error) { + toast({ + title: 'Failed to delete branch', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setDeletingBranch(null); + } + }; + + const localBranches = branches.filter(b => !b.isRemote); + const remoteBranches = branches.filter(b => b.isRemote); + + return ( +
+ {/* Header with create button */} +
+

Branches

+ + + + + + + Create New Branch + + Create a new branch from the current HEAD + + +
+
+ + setNewBranchName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && !isCreating) { + handleCreateBranch(); + } + }} + autoFocus + /> +
+ {currentBranch && ( +
+ Creating from: {currentBranch} +
+ )} +
+
+ + +
+
+
+
+ + {isLoading ? ( +
+ +
+ ) : ( +
+ {/* Local Branches */} + {localBranches.length > 0 && ( +
+
+ Local Branches +
+
+ {localBranches.map((branch) => ( + + ))} +
+
+ )} + + {/* Remote Branches */} + {remoteBranches.length > 0 && ( +
+
+ Remote Branches +
+
+ {remoteBranches.map((branch) => ( + + ))} +
+
+ )} + + {/* Empty state */} + {localBranches.length === 0 && remoteBranches.length === 0 && ( +
+ +

No branches found

+
+ )} +
+ )} +
+ ); +} + +interface BranchItemProps { + branch: BranchInfo; + onSwitch: (name: string) => void; + onDelete: (name: string) => void; + isSwitching: boolean; + isDeleting: boolean; +} + +function BranchItem({ branch, onSwitch, onDelete, isSwitching, isDeleting }: BranchItemProps) { + const [showDeleteDialog, setShowDeleteDialog] = useState(false); + + return ( + <> +
+ {/* Branch icon and name */} +
+ {branch.isCurrent ? ( + + ) : ( + + )} +
+
+ + {branch.name} + + {branch.isRemote && ( + + )} +
+ {branch.commitId && ( +
+ {branch.commitId.substring(0, 7)} +
+ )} +
+
+ + {/* Current badge */} + {branch.isCurrent && ( + + Current + + )} + + {/* Actions */} + {!branch.isCurrent && !branch.isRemote && ( +
+ + +
+ )} +
+ + {/* Delete confirmation dialog */} + + + + Delete Branch + + Are you sure you want to delete the branch {branch.name}? + This action cannot be undone. + + + + Cancel + { + onDelete(branch.name); + setShowDeleteDialog(false); + }} + className="bg-destructive text-destructive-foreground hover:bg-destructive/90" + > + Delete Branch + + + + + + ); +} diff --git a/src/components/git/CompareView.tsx b/src/components/git/CompareView.tsx new file mode 100644 index 00000000..169008cf --- /dev/null +++ b/src/components/git/CompareView.tsx @@ -0,0 +1,350 @@ +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 */} + + + + + + + +
+ )} +
+ ); +} diff --git a/src/components/git/DiffViewer.tsx b/src/components/git/DiffViewer.tsx new file mode 100644 index 00000000..5f540035 --- /dev/null +++ b/src/components/git/DiffViewer.tsx @@ -0,0 +1,556 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Button } from '@/components/ui/button'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { Badge } from '@/components/ui/badge'; +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { + FileIcon, + Plus, + Minus, + Edit, + Loader2, + SplitSquareHorizontal, + ListTree, + Copy, + Check, +} from 'lucide-react'; +import { useGit } from '@/hooks/useGit'; +import { useFS } from '@/hooks/useFS'; +import { useToast } from '@/hooks/useToast'; +import { cn } from '@/lib/utils'; + +interface DiffHunk { + oldStart: number; + oldLines: number; + newStart: number; + newLines: number; + lines: DiffLine[]; +} + +interface DiffLine { + type: 'add' | 'delete' | 'context'; + content: string; + oldLineNumber?: number; + newLineNumber?: number; +} + +interface FileDiff { + filepath: string; + status: 'modified' | 'added' | 'deleted'; + hunks: DiffHunk[]; + oldContent?: string; + newContent?: string; +} + +interface DiffViewerProps { + projectId: string; + compareFrom?: string; // commit, branch, or 'HEAD' + compareTo?: string; // commit, branch, or working directory + filepath?: string; // If provided, show only this file +} + +export function DiffViewer({ projectId, compareFrom = 'HEAD', compareTo, filepath }: DiffViewerProps) { + const [diffs, setDiffs] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [selectedFile, setSelectedFile] = useState(null); + const [viewMode, setViewMode] = useState<'unified' | 'split'>('split'); + const [copiedHunk, setCopiedHunk] = useState(null); + + const { git } = useGit(); + const { fs } = useFS(); + const { toast } = useToast(); + const projectPath = `/projects/${projectId}`; + + const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise => { + // Get list of files from both refs and find differences + const filesFrom = await git.listFiles({ dir: projectPath, ref: from }); + const filesTo = await git.listFiles({ dir: projectPath, ref: to }); + + const changedFiles = new Set(); + + // Check files that exist in 'to' + for (const file of filesTo) { + try { + const blobFrom = await git.readBlob({ dir: projectPath, oid: from, filepath: file }); + const blobTo = await git.readBlob({ dir: projectPath, oid: to, filepath: file }); + + // Compare content + if (Buffer.from(blobFrom.blob).toString() !== Buffer.from(blobTo.blob).toString()) { + changedFiles.add(file); + } + } catch { + // File exists in one but not the other + changedFiles.add(file); + } + } + + // Check files that were deleted + for (const file of filesFrom) { + if (!filesTo.includes(file)) { + changedFiles.add(file); + } + } + + return Array.from(changedFiles); + }, [git, projectPath]); + + const generateFileDiff = useCallback(async ( + file: string, + from: string, + to?: string + ): Promise => { + try { + let oldContent = ''; + let newContent = ''; + let status: 'modified' | 'added' | 'deleted' = 'modified'; + + // Get old content + try { + const blob = await git.readBlob({ dir: projectPath, oid: from, filepath: file }); + oldContent = Buffer.from(blob.blob).toString('utf-8'); + } catch { + // File didn't exist in old version + status = 'added'; + } + + // Get new content + try { + if (to) { + const blob = await git.readBlob({ dir: projectPath, oid: to, filepath: file }); + newContent = Buffer.from(blob.blob).toString('utf-8'); + } else { + // Working directory + const content = await fs.readFile(`${projectPath}/${file}`, { encoding: 'utf8' }); + newContent = content; + } + } catch { + // File doesn't exist in new version + if (status !== 'added') { + status = 'deleted'; + } + } + + // Generate hunks + const hunks = generateDiffHunks(oldContent, newContent); + + return { + filepath: file, + status, + hunks, + oldContent, + newContent, + }; + } catch (error) { + console.error(`Error generating diff for ${file}:`, error); + return null; + } + }, [git, projectPath, fs]); + + const generateDiffHunks = (oldContent: string, newContent: string): DiffHunk[] => { + const oldLines = oldContent.split('\n'); + const newLines = newContent.split('\n'); + + // Simple line-by-line diff + const hunks: DiffHunk[] = []; + let currentHunk: DiffHunk | null = null; + + let oldIndex = 0; + let newIndex = 0; + + while (oldIndex < oldLines.length || newIndex < newLines.length) { + const oldLine = oldLines[oldIndex]; + const newLine = newLines[newIndex]; + + if (oldLine === newLine) { + // Context line + if (currentHunk) { + currentHunk.lines.push({ + type: 'context', + content: oldLine || '', + oldLineNumber: oldIndex + 1, + newLineNumber: newIndex + 1, + }); + } + oldIndex++; + newIndex++; + } else { + // Start a new hunk if needed + if (!currentHunk) { + currentHunk = { + oldStart: oldIndex + 1, + oldLines: 0, + newStart: newIndex + 1, + newLines: 0, + lines: [], + }; + + // Add context before the change + const contextStart = Math.max(0, oldIndex - 3); + for (let i = contextStart; i < oldIndex; i++) { + currentHunk.lines.push({ + type: 'context', + content: oldLines[i] || '', + oldLineNumber: i + 1, + newLineNumber: i + 1, + }); + } + } + + // Determine if this is an addition, deletion, or modification + if (oldIndex >= oldLines.length) { + // Addition + currentHunk.lines.push({ + type: 'add', + content: newLine || '', + newLineNumber: newIndex + 1, + }); + currentHunk.newLines++; + newIndex++; + } else if (newIndex >= newLines.length) { + // Deletion + currentHunk.lines.push({ + type: 'delete', + content: oldLine || '', + oldLineNumber: oldIndex + 1, + }); + currentHunk.oldLines++; + oldIndex++; + } else { + // Changed line - show as delete + add + currentHunk.lines.push({ + type: 'delete', + content: oldLine || '', + oldLineNumber: oldIndex + 1, + }); + currentHunk.lines.push({ + type: 'add', + content: newLine || '', + newLineNumber: newIndex + 1, + }); + currentHunk.oldLines++; + currentHunk.newLines++; + oldIndex++; + newIndex++; + } + + // Check if we should close this hunk + const contextAfter = 3; + let contextCount = 0; + let tempOldIndex = oldIndex; + let tempNewIndex = newIndex; + + while ( + contextCount < contextAfter && + tempOldIndex < oldLines.length && + tempNewIndex < newLines.length + ) { + if (oldLines[tempOldIndex] === newLines[tempNewIndex]) { + currentHunk.lines.push({ + type: 'context', + content: oldLines[tempOldIndex] || '', + oldLineNumber: tempOldIndex + 1, + newLineNumber: tempNewIndex + 1, + }); + contextCount++; + tempOldIndex++; + tempNewIndex++; + } else { + break; + } + } + + if (contextCount >= contextAfter || tempOldIndex >= oldLines.length) { + hunks.push(currentHunk); + currentHunk = null; + oldIndex = tempOldIndex; + newIndex = tempNewIndex; + } + } + } + + // Close any remaining hunk + if (currentHunk) { + hunks.push(currentHunk); + } + + return hunks; + }; + + const loadDiffs = useCallback(async () => { + setIsLoading(true); + try { + let files: string[] = []; + + if (filepath) { + files = [filepath]; + } else if (compareTo) { + // Compare two commits/branches + files = await getChangedFilesBetweenRefs(compareFrom, compareTo); + } else { + // Compare against working directory + const statusMatrix = await git.statusMatrix({ dir: projectPath }); + files = statusMatrix + .filter(([, head, workdir]) => head !== workdir) + .map(([file]) => file); + } + + const fileDiffs: FileDiff[] = []; + + for (const file of files) { + try { + const diff = await generateFileDiff(file, compareFrom, compareTo); + if (diff) { + fileDiffs.push(diff); + } + } catch (error) { + console.warn(`Failed to generate diff for ${file}:`, error); + } + } + + setDiffs(fileDiffs); + if (fileDiffs.length > 0 && !selectedFile) { + setSelectedFile(fileDiffs[0].filepath); + } + } catch (error) { + console.error('Failed to load diffs:', error); + toast({ + title: 'Failed to load diffs', + description: error instanceof Error ? error.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setIsLoading(false); + } + }, [compareFrom, compareTo, filepath, git, projectPath, selectedFile, toast, getChangedFilesBetweenRefs, generateFileDiff]); + + useEffect(() => { + loadDiffs(); + }, [projectId, compareFrom, compareTo, filepath, loadDiffs]); + + const copyHunkToClipboard = async (hunk: DiffHunk, index: number) => { + const hunkText = hunk.lines.map(line => line.content).join('\n'); + await navigator.clipboard.writeText(hunkText); + setCopiedHunk(index); + setTimeout(() => setCopiedHunk(null), 2000); + }; + + const selectedDiff = diffs.find(d => d.filepath === selectedFile); + + if (isLoading) { + return ( +
+ +
+ ); + } + + if (diffs.length === 0) { + return ( +
+ +

No changes to display

+
+ ); + } + + return ( +
+ {/* File list sidebar */} +
+
+

Changed Files

+

+ {diffs.length} file{diffs.length !== 1 ? 's' : ''} changed +

+
+ +
+ {diffs.map((diff) => ( + + ))} +
+
+
+ + {/* Diff content */} +
+ {selectedDiff && ( + <> + {/* Header */} +
+
+

{selectedDiff.filepath}

+ + {selectedDiff.status} + +
+ setViewMode(v as 'unified' | 'split')}> + + + + Split + + + + Unified + + + +
+ + {/* Diff content */} + +
+ {selectedDiff.hunks.map((hunk, hunkIndex) => ( +
+ {/* Hunk header */} +
+ + @@ -{hunk.oldStart},{hunk.oldLines} +{hunk.newStart},{hunk.newLines} @@ + + +
+ + {/* Hunk lines */} + {viewMode === 'split' ? ( + + ) : ( + + )} +
+ ))} +
+
+ + )} +
+
+ ); +} + +function SplitDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) { + return ( +
+ {/* Old (left) side */} +
+ {hunk.lines.map((line, i) => ( + line.type !== 'add' && ( +
+ + {line.oldLineNumber} + +
+                
+              
+
+ ) + ))} +
+ + {/* New (right) side */} +
+ {hunk.lines.map((line, i) => ( + line.type !== 'delete' && ( +
+ + {line.newLineNumber} + +
+                
+              
+
+ ) + ))} +
+
+ ); +} + +function UnifiedDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) { + return ( +
+ {hunk.lines.map((line, i) => ( +
+ + {line.oldLineNumber || line.newLineNumber} + + + {line.type === 'add' ? '+' : line.type === 'delete' ? '-' : ' '} + +
+            
+          
+
+ ))} +
+ ); +} diff --git a/src/components/git/GitManagementDialog.tsx b/src/components/git/GitManagementDialog.tsx new file mode 100644 index 00000000..a5848d3f --- /dev/null +++ b/src/components/git/GitManagementDialog.tsx @@ -0,0 +1,123 @@ +import { useState } from 'react'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { + GitBranch, + GitCompare, + Settings, +} from 'lucide-react'; +import { BranchManager } from './BranchManager'; +import { CompareView } from './CompareView'; +import { DiffViewer } from './DiffViewer'; +import { useGitStatus } from '@/hooks/useGitStatus'; + +interface GitManagementDialogProps { + projectId: string; + children?: React.ReactNode; + open?: boolean; + onOpenChange?: (open: boolean) => void; + defaultTab?: string; +} + +export function GitManagementDialog({ + projectId, + children, + open, + onOpenChange, + defaultTab = 'branches', +}: GitManagementDialogProps) { + const [activeTab, setActiveTab] = useState(defaultTab); + + const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); + + const handleBranchChange = () => { + // Refetch git status when branches change + refetchGitStatus(); + }; + + return ( + <> + + {children && {children}} + + {/* Fixed Header */} + + + + Git Management + + + + {/* Tabs Container - takes remaining space */} +
+ + {/* Fixed Tab List */} +
+ + + + Branches + + + + Changes + + + + Compare + + +
+ + {/* Scrollable Tab Content */} + + +
+ +
+
+
+ + +
+ +
+
+ + + +
+ +
+
+
+
+
+
+
+ + ); +} diff --git a/src/components/git/MergeDialog.tsx b/src/components/git/MergeDialog.tsx new file mode 100644 index 00000000..466b32cc --- /dev/null +++ b/src/components/git/MergeDialog.tsx @@ -0,0 +1,574 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, + DialogFooter, +} from '@/components/ui/dialog'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { Badge } from '@/components/ui/badge'; +import { Card, CardContent } from '@/components/ui/card'; +import { + GitMerge, + Loader2, + AlertCircle, + CheckCircle, + GitCommit, + AlertTriangle, +} from 'lucide-react'; +import { useGit } from '@/hooks/useGit'; +import { useToast } from '@/hooks/useToast'; +import { useSearchParams } from 'react-router-dom'; + +interface MergeDialogProps { + projectId: string; + currentBranch: string | null; + open?: boolean; + onOpenChange?: (open: boolean) => void; + onMergeComplete?: () => void; +} + +interface MergePreview { + sourceBranch: string; + targetBranch: string; + commitsToMerge: Array<{ + oid: string; + message: string; + author: string; + timestamp: number; + }>; + filesChanged: string[]; + canFastForward: boolean; + hasConflicts: boolean; + conflictingFiles: string[]; +} + +export function MergeDialog({ + projectId, + currentBranch, + open, + onOpenChange, + onMergeComplete, +}: MergeDialogProps) { + const [isOpen, setIsOpen] = useState(open ?? false); + const [branches, setBranches] = useState([]); + const [sourceBranch, setSourceBranch] = useState(''); + const [isLoadingBranches, setIsLoadingBranches] = useState(false); + const [isLoadingPreview, setIsLoadingPreview] = useState(false); + const [isMerging, setIsMerging] = useState(false); + const [mergePreview, setMergePreview] = useState(null); + const [error, setError] = useState(null); + const [mergeComplete, setMergeComplete] = useState(false); + + const { git } = useGit(); + const { toast } = useToast(); + const [searchParams, setSearchParams] = useSearchParams(); + const projectPath = `/projects/${projectId}`; + + useEffect(() => { + if (open !== undefined) { + setIsOpen(open); + } + }, [open]); + + const loadBranches = useCallback(async () => { + setIsLoadingBranches(true); + try { + const localBranches = await git.listBranches({ dir: projectPath }); + // Filter out current branch from source options + const availableBranches = localBranches.filter(b => b !== currentBranch); + setBranches(availableBranches); + + // Set default source branch + if (availableBranches.length > 0) { + setSourceBranch(availableBranches[0]); + } + } catch (err) { + console.error('Failed to load branches:', err); + toast({ + title: 'Failed to load branches', + description: err instanceof Error ? err.message : 'Unknown error', + variant: 'destructive', + }); + } finally { + setIsLoadingBranches(false); + } + }, [git, projectPath, currentBranch, toast]); + + const loadMergePreview = useCallback(async () => { + if (!sourceBranch || !currentBranch) return; + + setIsLoadingPreview(true); + setError(null); + + try { + // Get commits that will be merged + const sourceCommits = await git.log({ dir: projectPath, ref: sourceBranch, depth: 50 }); + const targetCommits = await git.log({ dir: projectPath, ref: currentBranch, depth: 50 }); + + const targetCommitIds = new Set(targetCommits.map(c => c.oid)); + const commitsToMerge = sourceCommits.filter(c => !targetCommitIds.has(c.oid)); + + // Get changed files + const sourceFiles = await git.listFiles({ dir: projectPath, ref: sourceBranch }); + const targetFiles = await git.listFiles({ dir: projectPath, ref: currentBranch }); + + const changedFiles = new Set(); + for (const file of [...sourceFiles, ...targetFiles]) { + try { + const sourceBlob = await git.readBlob({ + dir: projectPath, + oid: sourceBranch, + filepath: file, + }).catch(() => null); + + const targetBlob = await git.readBlob({ + dir: projectPath, + oid: currentBranch, + filepath: file, + }).catch(() => null); + + if (!sourceBlob || !targetBlob || + Buffer.from(sourceBlob.blob).toString() !== Buffer.from(targetBlob.blob).toString()) { + changedFiles.add(file); + } + } catch { + changedFiles.add(file); + } + } + + // Check if can fast-forward + const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch }); + const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch }); + + const canFastForward = await git.isDescendent({ + dir: projectPath, + oid: sourceOid, + ancestor: targetOid, + }).catch(() => false); + + // Try to detect conflicts (simplified - real detection happens during merge) + const conflictingFiles: string[] = []; + // For now, we'll set this during actual merge + + setMergePreview({ + sourceBranch, + targetBranch: currentBranch, + commitsToMerge: commitsToMerge.map(c => ({ + oid: c.oid, + message: c.commit.message, + author: c.commit.author.name, + timestamp: c.commit.author.timestamp, + })), + filesChanged: Array.from(changedFiles), + canFastForward, + hasConflicts: false, + conflictingFiles, + }); + } catch (err) { + console.error('Failed to load merge preview:', err); + setError(err instanceof Error ? err.message : 'Unknown error'); + } finally { + setIsLoadingPreview(false); + } + }, [sourceBranch, currentBranch, git, projectPath]); + + useEffect(() => { + if (isOpen) { + loadBranches(); + } + }, [isOpen, loadBranches]); + + useEffect(() => { + if (sourceBranch && currentBranch && sourceBranch !== currentBranch) { + loadMergePreview(); + } else { + setMergePreview(null); + } + }, [sourceBranch, currentBranch, loadMergePreview]); + + const performMerge = async () => { + if (!sourceBranch || !currentBranch) return; + + setIsMerging(true); + setError(null); + + try { + // Check if can fast-forward + const sourceOid = await git.resolveRef({ dir: projectPath, ref: sourceBranch }); + const targetOid = await git.resolveRef({ dir: projectPath, ref: currentBranch }); + + const canFastForward = await git.isDescendent({ + dir: projectPath, + oid: sourceOid, + ancestor: targetOid, + }).catch(() => false); + + if (canFastForward) { + // Fast-forward merge: update the current branch to point to source branch commit + await git.writeRef({ + dir: projectPath, + ref: `refs/heads/${currentBranch}`, + value: sourceOid, + force: true, + }); + + // Update working directory to match the new HEAD + await git.checkout({ + dir: projectPath, + ref: currentBranch, + force: true, + }); + + toast({ + title: 'Fast-forward merge successful', + description: `Successfully fast-forwarded ${currentBranch} to ${sourceBranch}`, + }); + } else { + // Three-way merge + const result = await git.merge({ + dir: projectPath, + ours: currentBranch, + theirs: sourceBranch, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + message: `Merge branch '${sourceBranch}' into ${currentBranch}`, + }); + + if (result.alreadyMerged) { + toast({ + title: 'Already merged', + description: 'The branches are already merged', + }); + setMergeComplete(true); + onMergeComplete?.(); + return; + } + + // The merge result contains the new tree OID + // We need to create a commit with this tree + const mergeCommitOid = await git.commit({ + dir: projectPath, + message: `Merge branch '${sourceBranch}' into ${currentBranch}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + parent: [targetOid, sourceOid], // Two parents for merge commit + tree: result.tree, + }); + + console.log('Created merge commit:', mergeCommitOid); + + // Update working directory to match the merge + await git.checkout({ + dir: projectPath, + ref: currentBranch, + force: true, + }); + + toast({ + title: 'Merge successful', + description: `Successfully merged ${sourceBranch} into ${currentBranch}`, + }); + } + + setMergeComplete(true); + + // Trigger rebuild + setTimeout(() => { + const newSearchParams = new URLSearchParams(searchParams); + newSearchParams.set('build', ''); + setSearchParams(newSearchParams); + }, 500); + + onMergeComplete?.(); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Unknown error'; + + if (errorMessage.includes('conflict') || errorMessage.includes('CONFLICT')) { + setError('Merge conflicts detected. Please resolve conflicts manually using the terminal.'); + } else { + setError(errorMessage); + } + + toast({ + title: 'Merge failed', + description: errorMessage, + variant: 'destructive', + duration: Infinity, + }); + } finally { + setIsMerging(false); + } + }; + + 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(); + } + }; + + const handleOpenChange = (newOpen: boolean) => { + setIsOpen(newOpen); + onOpenChange?.(newOpen); + + if (!newOpen) { + setSourceBranch(''); + setMergePreview(null); + setError(null); + setMergeComplete(false); + } + }; + + if (!currentBranch) { + return null; + } + + return ( + + + + + + + + + Merge Branch + + + Merge changes from another branch into {currentBranch} + + + + {mergeComplete ? ( + // Success state +
+ +
+

Merge Complete!

+

+ Successfully merged {sourceBranch} into {currentBranch} +

+
+ +
+ ) : ( + +
+ {/* Source branch selection */} +
+ + +

+ The branch to merge into {currentBranch} +

+
+ + {/* Merge direction visualization */} + {sourceBranch && ( +
+
+ + {sourceBranch} + + + + {currentBranch} + +
+
+ )} + + {/* Error alert */} + {error && ( + + + {error} + + )} + + {/* Loading preview */} + {isLoadingPreview && ( +
+ + Loading merge preview... +
+ )} + + {/* Merge preview */} + {mergePreview && !isLoadingPreview && ( +
+ {/* Stats */} +
+ + +
+ {mergePreview.commitsToMerge.length} +
+
+ Commits to Merge +
+
+
+ + +
+ {mergePreview.filesChanged.length} +
+
+ Files Changed +
+
+
+
+ + {/* Fast-forward badge */} + {mergePreview.canFastForward && ( + + + + This merge can be fast-forwarded (no merge commit needed) + + + )} + + {/* Commits to merge */} + {mergePreview.commitsToMerge.length > 0 && ( +
+

Commits to be merged:

+
+ {mergePreview.commitsToMerge.slice(0, 10).map((commit) => ( +
+ +
+

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

+
+ {commit.author} + • + {formatDate(commit.timestamp)} +
+
+
+ ))} + {mergePreview.commitsToMerge.length > 10 && ( +

+ + {mergePreview.commitsToMerge.length - 10} more commits +

+ )} +
+
+ )} + + {/* No changes */} + {mergePreview.commitsToMerge.length === 0 && ( + + + + No new commits to merge. The branches are already in sync. + + + )} + + {/* Warning about conflicts */} + {mergePreview.hasConflicts && ( + + + + Conflicts detected in {mergePreview.conflictingFiles.length} file(s). + You may need to resolve conflicts manually. + + + )} +
+ )} +
+
+ )} + + {!mergeComplete && ( + + + + + )} +
+
+ ); +} diff --git a/src/components/git/PullRequestDialog.tsx b/src/components/git/PullRequestDialog.tsx new file mode 100644 index 00000000..1997fb40 --- /dev/null +++ b/src/components/git/PullRequestDialog.tsx @@ -0,0 +1,549 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Textarea } from '@/components/ui/textarea'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DialogTrigger, + DialogFooter, +} from '@/components/ui/dialog'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { Badge } from '@/components/ui/badge'; +import { + GitPullRequest, + Loader2, + AlertCircle, + CheckCircle, + ExternalLink, + GitCompare, +} from 'lucide-react'; +import { useGit } from '@/hooks/useGit'; +import { useGitSettings } from '@/hooks/useGitSettings'; +import { useToast } from '@/hooks/useToast'; +import { findCredentialsForRepo } from '@/lib/gitCredentials'; + +interface PullRequestDialogProps { + projectId: string; + currentBranch: string | null; + remoteUrl?: string; + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +interface RemoteInfo { + owner: string; + repo: string; + platform: 'github' | 'gitlab'; + apiUrl: string; +} + +export function PullRequestDialog({ + projectId, + currentBranch, + remoteUrl, + open, + onOpenChange, +}: PullRequestDialogProps) { + const [isOpen, setIsOpen] = useState(open ?? false); + const [title, setTitle] = useState(''); + const [description, setDescription] = useState(''); + const [targetBranch, setTargetBranch] = useState('main'); + const [remoteBranches, setRemoteBranches] = useState([]); + const [isLoadingBranches, setIsLoadingBranches] = useState(false); + const [isCreating, setIsCreating] = useState(false); + const [remoteInfo, setRemoteInfo] = useState(null); + const [createdPrUrl, setCreatedPrUrl] = useState(null); + const [error, setError] = useState(null); + + const { git } = useGit(); + const { settings } = useGitSettings(); + const { toast } = useToast(); + const projectPath = `/projects/${projectId}`; + + useEffect(() => { + if (open !== undefined) { + setIsOpen(open); + } + }, [open]); + + const loadRemoteBranches = useCallback(async () => { + setIsLoadingBranches(true); + try { + const branches = await git.listBranches({ + dir: projectPath, + remote: 'origin', + }); + setRemoteBranches(branches); + + // Set default target branch + if (branches.includes('main')) { + setTargetBranch('main'); + } else if (branches.includes('master')) { + setTargetBranch('master'); + } else if (branches.length > 0) { + setTargetBranch(branches[0]); + } + } catch (err) { + console.warn('Failed to load remote branches:', err); + // Set default branches if we can't fetch + setRemoteBranches(['main', 'master', 'develop']); + } finally { + setIsLoadingBranches(false); + } + }, [git, projectPath]); + + useEffect(() => { + if (isOpen && remoteUrl) { + parseRemoteUrl(remoteUrl); + loadRemoteBranches(); + } + }, [isOpen, remoteUrl, loadRemoteBranches]); + + const parseRemoteUrl = (url: string) => { + setError(null); + try { + // Parse GitHub/GitLab URLs + let match; + let owner = ''; + let repo = ''; + let platform: 'github' | 'gitlab' = 'github'; + let apiUrl = ''; + + console.log('Parsing remote URL:', url); + + // Normalize URL - remove .git suffix if present + const normalizedUrl = url.replace(/\.git$/, ''); + + // GitHub SSH: git@github.com:owner/repo + match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/); + if (match) { + owner = match[1]; + repo = match[2]; + platform = 'github'; + apiUrl = 'https://api.github.com'; + console.log('Detected GitHub SSH:', { owner, repo }); + } + + // GitHub HTTPS: https://github.com/owner/repo + if (!match) { + match = normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/); + if (match) { + owner = match[1]; + repo = match[2]; + platform = 'github'; + apiUrl = 'https://api.github.com'; + console.log('Detected GitHub HTTPS:', { owner, repo }); + } + } + + // GitLab SSH: git@gitlab.com:owner/repo + if (!match) { + match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/); + if (match) { + owner = match[1]; + repo = match[2]; + platform = 'gitlab'; + apiUrl = 'https://gitlab.com/api/v4'; + console.log('Detected GitLab SSH:', { owner, repo }); + } + } + + // GitLab HTTPS: https://gitlab.com/owner/repo + if (!match) { + match = normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/); + if (match) { + owner = match[1]; + repo = match[2]; + platform = 'gitlab'; + apiUrl = 'https://gitlab.com/api/v4'; + console.log('Detected GitLab HTTPS:', { owner, repo }); + } + } + + if (owner && repo) { + console.log('Remote info set:', { owner, repo, platform, apiUrl }); + setRemoteInfo({ owner, repo, platform, apiUrl }); + } else { + console.error('Failed to parse URL - no owner/repo found:', url); + setError('Unsupported remote URL format. Only GitHub and GitLab URLs are supported (e.g., https://github.com/user/repo.git)'); + } + } catch (err) { + console.error('Error parsing remote URL:', err); + setError('Failed to parse remote URL: ' + (err instanceof Error ? err.message : 'Unknown error')); + } + }; + + const createPullRequest = async () => { + if (!remoteInfo || !currentBranch) return; + + if (!title.trim()) { + toast({ + title: 'Title required', + description: 'Please enter a title for the pull request', + variant: 'destructive', + }); + return; + } + + setIsCreating(true); + setError(null); + + try { + console.log('Creating PR for:', remoteInfo); + console.log('Remote URL:', remoteUrl); + + // Get credentials + const credentials = findCredentialsForRepo(remoteUrl || '', settings.credentials); + console.log('Found credentials:', credentials ? 'Yes' : 'No'); + console.log('Available credential origins:', Object.keys(settings.credentials)); + + if (credentials) { + console.log('Credential username:', credentials.username); + console.log('Credential password length:', credentials.password?.length || 0); + } + + if (!credentials) { + throw new Error( + `No credentials found for ${remoteInfo.platform === 'github' ? 'GitHub' : 'GitLab'}. Please add credentials in Settings > Git for ${remoteUrl}` + ); + } + + if (!credentials.password || credentials.password.trim() === '') { + throw new Error( + `Credentials found but token is empty. Please check your ${remoteInfo.platform === 'github' ? 'GitHub' : 'GitLab'} token in Settings > Git` + ); + } + + // Create PR based on platform + console.log(`Creating ${remoteInfo.platform} PR...`); + if (remoteInfo.platform === 'github') { + const prUrl = await createGitHubPR(remoteInfo, credentials.password); + setCreatedPrUrl(prUrl); + } else if (remoteInfo.platform === 'gitlab') { + const prUrl = await createGitLabMR(remoteInfo, credentials.password); + setCreatedPrUrl(prUrl); + } + + toast({ + title: 'Pull request created', + description: 'Successfully created pull request', + }); + } catch (err) { + const errorMessage = err instanceof Error ? err.message : 'Unknown error'; + setError(errorMessage); + toast({ + title: 'Failed to create pull request', + description: errorMessage, + variant: 'destructive', + }); + } finally { + setIsCreating(false); + } + }; + + const createGitHubPR = async (info: RemoteInfo, token: string): Promise => { + const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls`; + console.log('GitHub PR URL:', url); + console.log('GitHub PR data:', { title, body: description, head: currentBranch, base: targetBranch }); + + const response = await fetch(url, { + method: 'POST', + headers: { + 'Authorization': `token ${token}`, + 'Content-Type': 'application/json', + 'Accept': 'application/vnd.github.v3+json', + }, + body: JSON.stringify({ + title, + body: description, + head: currentBranch, + base: targetBranch, + }), + }); + + console.log('GitHub response status:', response.status); + + if (!response.ok) { + const errorText = await response.text(); + console.error('GitHub API error response:', errorText); + + let error; + try { + error = JSON.parse(errorText); + } catch { + error = { message: errorText || 'Unknown error' }; + } + + throw new Error(error.message || `GitHub API error: ${response.status} - ${response.statusText}`); + } + + const data = await response.json(); + console.log('GitHub PR created:', data.html_url); + return data.html_url; + }; + + const createGitLabMR = async (info: RemoteInfo, token: string): Promise => { + // Get project ID first + const projectUrl = `${info.apiUrl}/projects/${encodeURIComponent(`${info.owner}/${info.repo}`)}`; + console.log('GitLab project URL:', projectUrl); + console.log('Using token (first 10 chars):', token.substring(0, 10) + '...'); + + const projectResponse = await fetch(projectUrl, { + headers: { + 'PRIVATE-TOKEN': token, + 'Content-Type': 'application/json', + }, + }); + + console.log('GitLab project response status:', projectResponse.status); + + if (!projectResponse.ok) { + const errorText = await projectResponse.text(); + console.error('GitLab project error response:', errorText); + throw new Error(`Failed to get GitLab project: ${projectResponse.status} - ${errorText}`); + } + + const project = await projectResponse.json(); + console.log('GitLab project ID:', project.id); + + // Create merge request + const mrUrl = `${info.apiUrl}/projects/${project.id}/merge_requests`; + console.log('GitLab MR URL:', mrUrl); + console.log('GitLab MR data:', { source_branch: currentBranch, target_branch: targetBranch, title, description }); + + const response = await fetch(mrUrl, { + method: 'POST', + headers: { + 'PRIVATE-TOKEN': token, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + source_branch: currentBranch, + target_branch: targetBranch, + title, + description, + }), + }); + + console.log('GitLab MR response status:', response.status); + + if (!response.ok) { + const errorText = await response.text(); + console.error('GitLab MR error response:', errorText); + + let error; + try { + error = JSON.parse(errorText); + } catch { + error = { message: errorText || 'Unknown error' }; + } + + throw new Error(error.message || `GitLab API error: ${response.status} - ${response.statusText}`); + } + + const data = await response.json(); + console.log('GitLab MR created:', data.web_url); + return data.web_url; + }; + + const handleOpenChange = (newOpen: boolean) => { + setIsOpen(newOpen); + onOpenChange?.(newOpen); + + // Reset form when closing + if (!newOpen) { + setTitle(''); + setDescription(''); + setCreatedPrUrl(null); + setError(null); + } + }; + + if (!remoteUrl) { + return null; + } + + return ( + + + + + + + + + Create Pull Request + + + Create a pull request to merge your changes + + + + {createdPrUrl ? ( + // Success state +
+ +
+

Pull Request Created!

+

+ Your pull request has been created successfully +

+
+ +
+ ) : ( + // Form + +
+ {/* Branch comparison */} + {currentBranch && ( +
+
+ + {targetBranch} + + + + {currentBranch} + +
+

+ Merge {currentBranch} into {targetBranch} +

+
+ )} + + {/* Error alert */} + {error && ( + + + {error} + + )} + + {/* Target branch selection */} +
+ + +

+ The branch you want to merge your changes into +

+
+ + {/* Title */} +
+ + setTitle(e.target.value)} + disabled={isCreating} + /> +
+ + {/* Description */} +
+ +