mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Remove all the git menus
This commit is contained in:
24 files changed
-9650
No files matched your search
@@ -8,7 +8,6 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
GitBranch,
|
||||
MoreHorizontal,
|
||||
MessageSquarePlus,
|
||||
History,
|
||||
@@ -17,7 +16,6 @@ import {
|
||||
Copy,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog';
|
||||
|
||||
@@ -44,7 +42,6 @@ export function ActionsMenu({
|
||||
}: ActionsMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
|
||||
|
||||
@@ -85,15 +82,6 @@ export function ActionsMenu({
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Repository
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeployDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
@@ -126,12 +114,6 @@ export function ActionsMenu({
|
||||
</DropdownMenu>
|
||||
|
||||
{/* Dialogs */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
|
||||
<GitHistoryDialog
|
||||
projectId={projectId}
|
||||
open={gitHistoryOpen}
|
||||
|
||||
@@ -1,248 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { GitDialog } from './GitDialog';
|
||||
|
||||
// Mock the hooks
|
||||
const mockRefetch = vi.fn();
|
||||
const mockUseGitStatus = vi.fn();
|
||||
|
||||
const baseGitStatus = {
|
||||
isGitRepo: true,
|
||||
currentBranch: 'main',
|
||||
hasUncommittedChanges: false,
|
||||
changedFiles: [],
|
||||
totalCommits: 5,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
latestCommit: {
|
||||
oid: 'abc123def456',
|
||||
message: 'Initial commit',
|
||||
author: {
|
||||
name: 'Test User',
|
||||
email: '[email protected]',
|
||||
timestamp: Date.now() / 1000,
|
||||
},
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
useGitStatus: () => mockUseGitStatus(),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useFS', () => ({
|
||||
useFS: vi.fn(() => ({
|
||||
fs: {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useToast', () => ({
|
||||
useToast: vi.fn(() => ({
|
||||
toast: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockUseGitSettings = vi.fn();
|
||||
|
||||
vi.mock('@/hooks/useGitSettings', () => ({
|
||||
useGitSettings: () => mockUseGitSettings(),
|
||||
}));
|
||||
|
||||
describe('GitDialog', () => {
|
||||
beforeEach(() => {
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: baseGitStatus,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: [
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
name: 'GitHub',
|
||||
origin: 'https://github.com',
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders git dialog without repository information section', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Repository')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status when branch is published', () => {
|
||||
// Mock git status with published branch
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead and branch is published', () => {
|
||||
// Mock git status with published branch and no commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables push and disables pull when branch is not published', () => {
|
||||
// Mock git status with unpublished branch (has commits but no remote branch)
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: false,
|
||||
totalCommits: 5,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Branch not published')).toBeInTheDocument();
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
|
||||
const pullButton = screen.getByText('Pull');
|
||||
expect(pullButton).toBeInTheDocument();
|
||||
expect(pullButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should not show warning when credentials are configured
|
||||
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows credentials warning when no credentials are configured', () => {
|
||||
// Mock git settings with no credentials and mock git status with an https remote
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: [],
|
||||
},
|
||||
});
|
||||
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show warning when credentials are missing
|
||||
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
|
||||
expect(screen.getByText('log in')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,6 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
GitBranch,
|
||||
MessageSquarePlus,
|
||||
History,
|
||||
Folder,
|
||||
@@ -21,7 +20,6 @@ interface ProjectTitleMenuProps {
|
||||
projectName: string;
|
||||
onNewChat: () => void;
|
||||
onGitHistory: () => void;
|
||||
onGitDialog: () => void;
|
||||
onDeploy: () => void;
|
||||
onDuplicate: () => void;
|
||||
onProjectDetails: () => void;
|
||||
@@ -34,7 +32,6 @@ export function ProjectTitleMenu({
|
||||
projectName,
|
||||
onNewChat,
|
||||
onGitHistory,
|
||||
onGitDialog,
|
||||
onDeploy,
|
||||
onDuplicate,
|
||||
onProjectDetails,
|
||||
@@ -74,15 +71,6 @@ export function ProjectTitleMenu({
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onGitDialog}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Repository
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onDeploy}
|
||||
disabled={isAnyLoading}
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
describe('AnnounceRepositoryDialog - NIP-34 Tag Structure', () => {
|
||||
it('should create tags with multiple values in single tag per NIP-34', () => {
|
||||
// Test the tag structure that would be created
|
||||
const webUrls = ['https://example.com/browse', 'https://mirror.example.com'];
|
||||
const cloneUrls = [
|
||||
'https://git.shakespeare.diy/npub1.../repo.git',
|
||||
'https://relay.ngit.dev/npub1.../repo.git',
|
||||
];
|
||||
const relays = ['wss://git.shakespeare.diy', 'wss://relay.ngit.dev'];
|
||||
|
||||
const tags: string[][] = [['d', 'test-repo']];
|
||||
|
||||
// Simulate the tag creation logic from AnnounceRepositoryDialog
|
||||
if (webUrls.length > 0) {
|
||||
const trimmedUrls = webUrls.map((url) => url.trim()).filter((url) => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['web', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
if (cloneUrls.length > 0) {
|
||||
const trimmedUrls = cloneUrls.map((url) => url.trim()).filter((url) => url);
|
||||
if (trimmedUrls.length > 0) {
|
||||
tags.push(['clone', ...trimmedUrls]);
|
||||
}
|
||||
}
|
||||
|
||||
if (relays.length > 0) {
|
||||
const trimmedRelays = relays.map((relay) => relay.trim()).filter((relay) => relay);
|
||||
if (trimmedRelays.length > 0) {
|
||||
tags.push(['relays', ...trimmedRelays]);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the structure matches NIP-34 spec
|
||||
expect(tags).toEqual([
|
||||
['d', 'test-repo'],
|
||||
['web', 'https://example.com/browse', 'https://mirror.example.com'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../repo.git',
|
||||
'https://relay.ngit.dev/npub1.../repo.git',
|
||||
],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
|
||||
]);
|
||||
|
||||
// Verify we have single tags with multiple values, not multiple tags
|
||||
const cloneTags = tags.filter((t) => t[0] === 'clone');
|
||||
expect(cloneTags.length).toBe(1);
|
||||
expect(cloneTags[0].length).toBe(3); // ['clone', url1, url2]
|
||||
|
||||
const relayTags = tags.filter((t) => t[0] === 'relays');
|
||||
expect(relayTags.length).toBe(1);
|
||||
expect(relayTags[0].length).toBe(3); // ['relays', relay1, relay2]
|
||||
});
|
||||
|
||||
it('should handle reading relays from single tag with multiple values', () => {
|
||||
// Simulate the event structure from Nostr
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev'],
|
||||
],
|
||||
};
|
||||
|
||||
// Simulate the reading logic from PullRequestDialog
|
||||
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
|
||||
let publishRelays: string[] = [];
|
||||
|
||||
if (relayTag && relayTag.length > 1) {
|
||||
publishRelays = relayTag.slice(1);
|
||||
}
|
||||
|
||||
// Verify we extracted all relay URLs correctly
|
||||
expect(publishRelays).toEqual(['wss://git.shakespeare.diy', 'wss://relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should handle reading clone URLs from single tag with multiple values', () => {
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
[
|
||||
'clone',
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
],
|
||||
],
|
||||
};
|
||||
|
||||
const cloneTag = repoEvent.tags.find((t: string[]) => t[0] === 'clone');
|
||||
let cloneUrls: string[] = [];
|
||||
|
||||
if (cloneTag && cloneTag.length > 1) {
|
||||
cloneUrls = cloneTag.slice(1);
|
||||
}
|
||||
|
||||
expect(cloneUrls).toEqual([
|
||||
'https://git.shakespeare.diy/npub1.../hello-shakespeare.git',
|
||||
'https://relay.ngit.dev/npub1.../hello-shakespeare.git',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should handle reading maintainers from single tag with multiple values', () => {
|
||||
const repoEvent = {
|
||||
tags: [
|
||||
['d', 'hello-shakespeare'],
|
||||
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
|
||||
],
|
||||
};
|
||||
|
||||
// Simulate the reading logic from NostrGitProvider
|
||||
const maintainerTag = repoEvent.tags.find((t: string[]) => t[0] === 'maintainers');
|
||||
const maintainers = maintainerTag ? maintainerTag.slice(1) : [];
|
||||
|
||||
expect(maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
|
||||
});
|
||||
});
|
||||
@@ -1,746 +0,0 @@
|
||||
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 { TagInput } from '@/components/ui/tag-input';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import {
|
||||
GitBranch,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
Plus,
|
||||
X,
|
||||
Settings,
|
||||
ChevronDown,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import {
|
||||
createRepositoryAnnouncementEvent,
|
||||
createRepositoryNaddr,
|
||||
validateRepositoryAnnouncementData,
|
||||
validateRepositoryId,
|
||||
parseRepositoryAnnouncement,
|
||||
} from '@/lib/announceRepository';
|
||||
|
||||
export interface AnnounceRepositoryResult {
|
||||
repoId: string;
|
||||
cloneUrls: string[];
|
||||
relays: string[];
|
||||
naddr: string;
|
||||
}
|
||||
|
||||
interface AnnounceRepositoryDialogProps {
|
||||
projectId: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
onSuccess?: (result: AnnounceRepositoryResult) => void;
|
||||
/** Repository naddr to edit (if editing existing repo) */
|
||||
editNaddr?: string;
|
||||
}
|
||||
|
||||
export function AnnounceRepositoryDialog({
|
||||
projectId,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
editNaddr,
|
||||
}: AnnounceRepositoryDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(open ?? false);
|
||||
const [isPrepopulated, setIsPrepopulated] = useState(false);
|
||||
const [repoId, setRepoId] = useState('');
|
||||
const [repoIdError, setRepoIdError] = useState<string | null>(null);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [webUrls, setWebUrls] = useState<string[]>([]);
|
||||
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
|
||||
const [relays, setRelays] = useState<string[]>([]);
|
||||
const [tTags, setTTags] = useState<string[]>([]);
|
||||
const [earliestCommit, setEarliestCommit] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [newWebUrl, setNewWebUrl] = useState('');
|
||||
const [newCloneUrl, setNewCloneUrl] = useState('');
|
||||
const [newRelay, setNewRelay] = useState('');
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
const { config } = useAppContext();
|
||||
const { fs } = useFS();
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (open !== undefined) {
|
||||
setIsOpen(open);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Convert projectId to kebab-case for repo ID
|
||||
const toKebabCase = (str: string): string => {
|
||||
return str
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
};
|
||||
|
||||
// Validate repository ID on change
|
||||
const handleRepoIdChange = (value: string) => {
|
||||
setRepoId(value);
|
||||
try {
|
||||
validateRepositoryId(value);
|
||||
setRepoIdError(null);
|
||||
} catch (err) {
|
||||
setRepoIdError(err instanceof Error ? err.message : 'Invalid repository ID');
|
||||
}
|
||||
};
|
||||
|
||||
const getEarliestCommit = useCallback(async () => {
|
||||
try {
|
||||
const commits = await git.log({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
if (commits.length > 0) {
|
||||
// Get the earliest commit (last in the log)
|
||||
const earliest = commits[commits.length - 1];
|
||||
setEarliestCommit(earliest.oid);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to get earliest commit:', err);
|
||||
}
|
||||
}, [git, projectPath]);
|
||||
|
||||
const prepopulateFields = useCallback(async () => {
|
||||
// Set default repo ID from project ID (kebab-case)
|
||||
const defaultRepoId = toKebabCase(projectId);
|
||||
setRepoId(defaultRepoId);
|
||||
|
||||
// Set default name from project ID (title case)
|
||||
const defaultName = projectId
|
||||
.split(/[-_]/)
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
setName(defaultName);
|
||||
|
||||
// Prepopulate clone URLs and relays from grasp servers (matching original handlePushToNostr)
|
||||
if (user?.pubkey && config.graspMetadata.relays && config.graspMetadata.relays.length > 0) {
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
|
||||
// Clone URLs: https://{hostname}/{npub}/{repo-id}.git
|
||||
const cloneUrls = config.graspMetadata.relays.map(relay => {
|
||||
try {
|
||||
const url = new URL(relay.url);
|
||||
return `https://${url.hostname}/${npub}/${defaultRepoId}.git`;
|
||||
} catch {
|
||||
// Fallback: extract hostname from URL string
|
||||
const hostname = relay.url.replace(/^wss?:\/\//, '').replace(/\/.*$/, '');
|
||||
return `https://${hostname}/${npub}/${defaultRepoId}.git`;
|
||||
}
|
||||
});
|
||||
setCloneUrls(cloneUrls);
|
||||
|
||||
// Relay URLs from grasp metadata
|
||||
const relayUrls = config.graspMetadata.relays.map(r => r.url);
|
||||
setRelays(relayUrls);
|
||||
} else {
|
||||
// Fallback to write relays if no grasp servers configured
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
|
||||
}
|
||||
|
||||
// Prepopulate t-tags
|
||||
const defaultTTags: string[] = ['shakespeare'];
|
||||
|
||||
// Try to read template.json to get template name
|
||||
try {
|
||||
const dotAI = new DotAI(fs, projectPath);
|
||||
const template = await dotAI.readTemplate();
|
||||
if (template?.name) {
|
||||
// Convert template name to lowercase and add as t-tag
|
||||
const templateTag = template.name.toLowerCase();
|
||||
if (!defaultTTags.includes(templateTag)) {
|
||||
defaultTTags.push(templateTag);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read template for t-tags:', error);
|
||||
}
|
||||
|
||||
setTTags(defaultTTags);
|
||||
|
||||
// Get earliest commit
|
||||
await getEarliestCommit();
|
||||
}, [projectId, projectPath, fs, config.relayMetadata, config.graspMetadata.relays, user?.pubkey, getEarliestCommit]);
|
||||
|
||||
// Load existing repository data if editing, or prepopulate fields for new repos
|
||||
useEffect(() => {
|
||||
// Only run when dialog opens
|
||||
if (!isOpen || isPrepopulated) return;
|
||||
|
||||
const loadExistingRepo = async () => {
|
||||
if (!editNaddr) return;
|
||||
|
||||
try {
|
||||
// Decode the naddr to get repository coordinates
|
||||
const decoded = nip19.decode(editNaddr);
|
||||
if (decoded.type !== 'naddr') {
|
||||
throw new Error('Invalid repository identifier');
|
||||
}
|
||||
|
||||
const { identifier, pubkey, kind, relays: naddrRelays } = decoded.data;
|
||||
|
||||
// Query for the repository announcement event
|
||||
const filter = {
|
||||
kinds: [kind],
|
||||
authors: [pubkey],
|
||||
'#d': [identifier],
|
||||
};
|
||||
|
||||
const signal = AbortSignal.timeout(3000);
|
||||
const readRelays = config.relayMetadata.relays
|
||||
.filter(r => r.read)
|
||||
.map(r => r.url);
|
||||
const events = await nostr.query([filter], {
|
||||
signal,
|
||||
relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : readRelays
|
||||
});
|
||||
|
||||
if (events.length === 0) {
|
||||
throw new Error('Repository announcement not found');
|
||||
}
|
||||
|
||||
// Use the most recent event
|
||||
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
setRepoId(parsed.identifier);
|
||||
setName(parsed.name || '');
|
||||
setDescription(parsed.description || '');
|
||||
setWebUrls(parsed.webUrls);
|
||||
setCloneUrls(parsed.httpsCloneUrls);
|
||||
setRelays(parsed.relays);
|
||||
setEarliestCommit(parsed.earliestCommit || '');
|
||||
|
||||
// Extract t-tags from the event
|
||||
const extractedTTags = parsed.event.tags
|
||||
.filter(([name]) => name === 't')
|
||||
.map(([, value]) => value)
|
||||
.filter((value): value is string => !!value);
|
||||
setTTags(extractedTTags);
|
||||
|
||||
setIsPrepopulated(true);
|
||||
} catch (error) {
|
||||
console.error('Failed to load repository data:', error);
|
||||
toast({
|
||||
title: 'Failed to load repository',
|
||||
description: error instanceof Error ? error.message : 'Unknown error',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (editNaddr) {
|
||||
loadExistingRepo();
|
||||
} else {
|
||||
prepopulateFields();
|
||||
setIsPrepopulated(true);
|
||||
}
|
||||
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
|
||||
|
||||
const addWebUrl = () => {
|
||||
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
|
||||
setWebUrls([...webUrls, newWebUrl.trim()]);
|
||||
setNewWebUrl('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeWebUrl = (index: number) => {
|
||||
setWebUrls(webUrls.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const addCloneUrl = () => {
|
||||
const trimmedUrl = newCloneUrl.trim();
|
||||
|
||||
// Prevent nostr:// URLs in clone URLs
|
||||
if (trimmedUrl.startsWith('nostr://')) {
|
||||
toast({
|
||||
title: 'Invalid clone URL',
|
||||
description: 'Clone URLs must be HTTPS URLs, not nostr:// URLs',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (trimmedUrl && !cloneUrls.includes(trimmedUrl)) {
|
||||
setCloneUrls([...cloneUrls, trimmedUrl]);
|
||||
setNewCloneUrl('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeCloneUrl = (index: number) => {
|
||||
setCloneUrls(cloneUrls.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const addRelay = () => {
|
||||
if (newRelay.trim() && !relays.includes(newRelay.trim())) {
|
||||
setRelays([...relays, newRelay.trim()]);
|
||||
setNewRelay('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeRelay = (index: number) => {
|
||||
setRelays(relays.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const announceRepository = async () => {
|
||||
if (!user || !user.signer) {
|
||||
toast({
|
||||
title: 'Authentication required',
|
||||
description: 'Please log in with Nostr to announce repositories',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Validate data
|
||||
validateRepositoryAnnouncementData({
|
||||
repoId,
|
||||
cloneUrls,
|
||||
});
|
||||
|
||||
// Create repository announcement event using shared utility
|
||||
const repoEvent = createRepositoryAnnouncementEvent({
|
||||
repoId,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
cloneUrls,
|
||||
relays,
|
||||
tTags,
|
||||
earliestCommit,
|
||||
});
|
||||
|
||||
console.log('=== ANNOUNCING REPOSITORY ===');
|
||||
console.log('Repository ID:', repoId.trim());
|
||||
console.log('Owner pubkey:', user.pubkey);
|
||||
console.log('Creating repository announcement event:', repoEvent);
|
||||
|
||||
// Sign the event
|
||||
const signedEvent = await user.signer.signEvent(repoEvent);
|
||||
|
||||
console.log('Signed repository announcement:', signedEvent);
|
||||
console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`);
|
||||
|
||||
// Publish to Nostr relays
|
||||
// Repository announcements go to: write relays + relays specified in the announcement
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
const publishRelays = [...new Set([...writeRelays, ...relays])];
|
||||
console.log('Publishing repository announcement to relays:', publishRelays);
|
||||
|
||||
await nostr.event(signedEvent, { relays: publishRelays });
|
||||
|
||||
console.log('Published repository announcement to Nostr relays');
|
||||
console.log('To verify: Query for kind 30617 with authors=[' + user.pubkey + '] and #d=[' + repoId.trim() + ']');
|
||||
|
||||
// Create naddr for the repository using shared utility
|
||||
const naddr = createRepositoryNaddr(repoId, user.pubkey, relays);
|
||||
|
||||
toast({
|
||||
title: 'Published Nostr announcement',
|
||||
description: 'Configuring repository...',
|
||||
});
|
||||
|
||||
// Close the dialog
|
||||
handleOpenChange(false);
|
||||
|
||||
// Call success callback with the data needed for Git operations
|
||||
onSuccess?.({
|
||||
repoId: repoId.trim(),
|
||||
cloneUrls,
|
||||
relays,
|
||||
naddr,
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to announce repository',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenChange = (newOpen: boolean) => {
|
||||
setIsOpen(newOpen);
|
||||
onOpenChange?.(newOpen);
|
||||
|
||||
// Reset form when closing
|
||||
if (!newOpen) {
|
||||
setIsPrepopulated(false);
|
||||
setRepoId('');
|
||||
setName('');
|
||||
setDescription('');
|
||||
setWebUrls([]);
|
||||
setCloneUrls([]);
|
||||
setRelays(['wss://relay.nostr.band']);
|
||||
setTTags([]);
|
||||
setEarliestCommit('');
|
||||
setError(null);
|
||||
setNewWebUrl('');
|
||||
setNewCloneUrl('');
|
||||
setNewRelay('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
{editNaddr ? 'Edit' : ''} Nostr Repository Settings
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{editNaddr
|
||||
? 'Update your repository announcement (NIP-34) for Nostr git clients'
|
||||
: 'Configure your repository announcement (NIP-34) for Nostr git clients'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 p-1 pr-4">
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Repository ID */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-id">Repository ID *</Label>
|
||||
<Input
|
||||
id="repo-id"
|
||||
placeholder="e.g., my-project"
|
||||
value={repoId}
|
||||
onChange={(e) => handleRepoIdChange(e.target.value)}
|
||||
disabled={isCreating}
|
||||
className={repoIdError ? 'border-destructive' : ''}
|
||||
/>
|
||||
{repoIdError ? (
|
||||
<p className="text-xs text-destructive">{repoIdError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Kebab-case short name (e.g., "my-project", "awesome-app")
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-name">Name</Label>
|
||||
<Input
|
||||
id="repo-name"
|
||||
placeholder="Human-readable project name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Display name for your repository
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-description">Description</Label>
|
||||
<Textarea
|
||||
id="repo-description"
|
||||
placeholder="Brief description of your project"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={3}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Advanced Settings */}
|
||||
<Collapsible open={showAdvanced} onOpenChange={setShowAdvanced}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="w-full justify-between p-0 hover:bg-transparent"
|
||||
>
|
||||
<span className="text-sm font-medium">Advanced Settings</span>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${
|
||||
showAdvanced ? 'rotate-180' : ''
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="space-y-6 pt-4">
|
||||
{/* Web URLs */}
|
||||
<div className="space-y-2">
|
||||
<Label>Web URLs (Optional)</Label>
|
||||
<div className="space-y-2">
|
||||
{webUrls.map((url, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
const newUrls = [...webUrls];
|
||||
newUrls[index] = e.target.value;
|
||||
setWebUrls(newUrls);
|
||||
}}
|
||||
className="flex-1"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => removeWebUrl(index)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="https://example.com/browse"
|
||||
value={newWebUrl}
|
||||
onChange={(e) => setNewWebUrl(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === 'Enter' && (e.preventDefault(), addWebUrl())
|
||||
}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={addWebUrl}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
URLs where the repository can be browsed online
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Clone URLs */}
|
||||
<div className="space-y-2">
|
||||
<Label>Git Server Clone URLs</Label>
|
||||
<div className="space-y-2">
|
||||
{cloneUrls.map((url, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
const newUrls = [...cloneUrls];
|
||||
newUrls[index] = e.target.value;
|
||||
setCloneUrls(newUrls);
|
||||
}}
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => removeCloneUrl(index)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="https://gitnostr.com/..."
|
||||
value={newCloneUrl}
|
||||
onChange={(e) => setNewCloneUrl(e.target.value)}
|
||||
onKeyDown={(e) =>
|
||||
e.key === 'Enter' && (e.preventDefault(), addCloneUrl())
|
||||
}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={addCloneUrl}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
HTTPS URLs for cloning the repository (nostr:// URLs not allowed)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Relays */}
|
||||
<div className="space-y-2">
|
||||
<Label>Git Nostr Relays</Label>
|
||||
<div className="space-y-2">
|
||||
{relays.map((relay, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={relay}
|
||||
onChange={(e) => {
|
||||
const newRelays = [...relays];
|
||||
newRelays[index] = e.target.value;
|
||||
setRelays(newRelays);
|
||||
}}
|
||||
className="flex-1 font-mono text-sm"
|
||||
disabled={isCreating}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => removeRelay(index)}
|
||||
disabled={isCreating || relays.length === 1}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="wss://relay.example.com"
|
||||
value={newRelay}
|
||||
onChange={(e) => setNewRelay(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addRelay())}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={addRelay}
|
||||
disabled={isCreating}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Nostr relays where patches and issues will be published and monitored
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Category Tags (t-tags) */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="category-tags">Category Tags</Label>
|
||||
<TagInput
|
||||
id="category-tags"
|
||||
value={tTags}
|
||||
onChange={setTTags}
|
||||
placeholder="e.g., nostr, social, web"
|
||||
disabled={isCreating}
|
||||
transformTag={(tag) => tag.trim().toLowerCase()}
|
||||
allowDuplicates={false}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tags for categorizing your repository. Press space or comma to add a tag.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Earliest Commit */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
|
||||
<Input
|
||||
id="earliest-commit"
|
||||
placeholder="Commit hash"
|
||||
value={earliestCommit}
|
||||
onChange={(e) => setEarliestCommit(e.target.value)}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The root commit of your repository (auto-detected)
|
||||
</p>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={announceRepository}
|
||||
disabled={isCreating || !!repoIdError || !repoId.trim()}
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{editNaddr ? 'Updating...' : 'Publishing...'}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-2" />
|
||||
{editNaddr ? 'Update on Nostr' : 'Publish to Nostr'}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,522 +0,0 @@
|
||||
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 { useFSPaths } from '@/hooks/useFSPaths';
|
||||
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<BranchInfo[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
|
||||
const [deletingBranch, setDeletingBranch] = useState<string | null>(null);
|
||||
const [switchingToBranch, setSwitchingToBranch] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${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,
|
||||
});
|
||||
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
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 (
|
||||
<div className="space-y-4">
|
||||
{/* Header with create button */}
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-medium">Branches</h3>
|
||||
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-8 gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
New Branch
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Create New Branch</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new branch from the current HEAD
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="branch-name">Branch Name</Label>
|
||||
<Input
|
||||
id="branch-name"
|
||||
placeholder="feature/my-new-feature"
|
||||
value={newBranchName}
|
||||
onChange={(e) => setNewBranchName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !isCreating) {
|
||||
handleCreateBranch();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
{currentBranch && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Creating from: <span className="font-medium">{currentBranch}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setIsCreateDialogOpen(false)}
|
||||
disabled={isCreating}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleCreateBranch} disabled={isCreating}>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Create Branch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Local Branches */}
|
||||
{localBranches.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Local Branches
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{localBranches.map((branch) => (
|
||||
<BranchItem
|
||||
key={branch.name}
|
||||
branch={branch}
|
||||
onSwitch={handleSwitchBranch}
|
||||
onDelete={handleDeleteBranch}
|
||||
isSwitching={switchingToBranch === branch.name}
|
||||
isDeleting={deletingBranch === branch.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Remote Branches */}
|
||||
{remoteBranches.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||||
Remote Branches
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{remoteBranches.map((branch) => (
|
||||
<BranchItem
|
||||
key={`remote-${branch.name}`}
|
||||
branch={branch}
|
||||
onSwitch={handleSwitchBranch}
|
||||
onDelete={handleDeleteBranch}
|
||||
isSwitching={switchingToBranch === branch.name}
|
||||
isDeleting={deletingBranch === branch.name}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty state */}
|
||||
{localBranches.length === 0 && remoteBranches.length === 0 && (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<GitBranch className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">No branches found</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-3 p-3 rounded-lg border transition-colors group',
|
||||
branch.isCurrent
|
||||
? 'bg-primary/5 border-primary/20'
|
||||
: 'hover:bg-muted/50 border-transparent'
|
||||
)}
|
||||
>
|
||||
{/* Branch icon and name */}
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
{branch.isCurrent ? (
|
||||
<Check className="h-4 w-4 text-primary shrink-0" />
|
||||
) : (
|
||||
<GitBranch className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
'font-mono text-sm truncate',
|
||||
branch.isCurrent && 'font-semibold text-primary'
|
||||
)}
|
||||
>
|
||||
{branch.name}
|
||||
</span>
|
||||
{branch.isRemote && (
|
||||
<ArrowUpRight className="h-3 w-3 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
{branch.commitId && (
|
||||
<div className="text-xs text-muted-foreground font-mono">
|
||||
{branch.commitId.substring(0, 7)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Current badge */}
|
||||
{branch.isCurrent && (
|
||||
<Badge variant="secondary" className="shrink-0">
|
||||
Current
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
{!branch.isCurrent && !branch.isRemote && (
|
||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2"
|
||||
onClick={() => onSwitch(branch.name)}
|
||||
disabled={isSwitching || isDeleting}
|
||||
>
|
||||
{isSwitching ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<GitBranch className="h-4 w-4 mr-1" />
|
||||
Switch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setShowDeleteDialog(true)}
|
||||
disabled={isSwitching || isDeleting}
|
||||
>
|
||||
{isDeleting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Delete confirmation dialog */}
|
||||
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Branch</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete the branch <strong>{branch.name}</strong>?
|
||||
This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
onDelete(branch.name);
|
||||
setShowDeleteDialog(false);
|
||||
}}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete Branch
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
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 { useFSPaths } from '@/hooks/useFSPaths';
|
||||
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<string[]>([]);
|
||||
const [commits, setCommits] = useState<CommitInfo[]>([]);
|
||||
const [baseRef, setBaseRef] = useState<string>('');
|
||||
const [compareRef, setCompareRef] = useState<string>('');
|
||||
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 { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${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<string>();
|
||||
|
||||
// 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 (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Comparison selectors */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<GitCompare className="h-5 w-5" />
|
||||
Compare Branches
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Select two branches to compare changes
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex-1">
|
||||
<label className="text-sm font-medium mb-2 block">Base Branch</label>
|
||||
<Select value={baseRef} onValueChange={setBaseRef}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select base branch" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="pt-6">
|
||||
<GitCompare className="h-5 w-5 text-muted-foreground" />
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<label className="text-sm font-medium mb-2 block">Compare Branch</label>
|
||||
<Select value={compareRef} onValueChange={setCompareRef}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select compare branch" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comparison stats */}
|
||||
{comparisonStats && !isComparing && (
|
||||
<div className="mt-6 grid grid-cols-3 gap-4">
|
||||
<div className="bg-muted/30 rounded-lg p-4 text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{comparisonStats.ahead}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Commits Ahead
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-muted/30 rounded-lg p-4 text-center">
|
||||
<div className="text-2xl font-bold text-orange-600">
|
||||
{comparisonStats.behind}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Commits Behind
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-muted/30 rounded-lg p-4 text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{comparisonStats.filesChanged}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Files Changed
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isComparing && (
|
||||
<div className="mt-6 flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
|
||||
<span className="text-muted-foreground">Comparing branches...</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Comparison results */}
|
||||
{baseRef && compareRef && baseRef !== compareRef && !isComparing && (
|
||||
<Tabs defaultValue="commits" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="commits" className="gap-2">
|
||||
<GitCommit className="h-4 w-4" />
|
||||
Commits ({commits.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="files" className="gap-2">
|
||||
<FileIcon className="h-4 w-4" />
|
||||
Files ({comparisonStats?.filesChanged || 0})
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Commits tab */}
|
||||
<TabsContent value="commits" className="mt-6">
|
||||
{commits.length > 0 ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">
|
||||
Commits in {compareRef} not in {baseRef}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{commits.map((commit) => (
|
||||
<div
|
||||
key={commit.oid}
|
||||
className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<GitCommit className="h-5 w-5 text-muted-foreground shrink-0 mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm">
|
||||
{commit.message.split('\n')[0]}
|
||||
</p>
|
||||
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
|
||||
<span>{commit.author}</span>
|
||||
<span>•</span>
|
||||
<span>{formatDate(commit.timestamp)}</span>
|
||||
<span>•</span>
|
||||
<span className="font-mono">{commit.oid.substring(0, 7)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center">
|
||||
<GitCommit className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
|
||||
<p className="text-muted-foreground">
|
||||
No commits difference between branches
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* Files tab */}
|
||||
<TabsContent value="files" className="mt-6">
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<DiffViewer
|
||||
projectId={projectId}
|
||||
compareFrom={baseRef}
|
||||
compareTo={compareRef}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,558 +0,0 @@
|
||||
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 { useFSPaths } from '@/hooks/useFSPaths';
|
||||
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<FileDiff[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [viewMode, setViewMode] = useState<'unified' | 'split'>('split');
|
||||
const [copiedHunk, setCopiedHunk] = useState<number | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
const getChangedFilesBetweenRefs = useCallback(async (from: string, to: string): Promise<string[]> => {
|
||||
// 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<string>();
|
||||
|
||||
// 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<FileDiff | null> => {
|
||||
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 (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (diffs.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<FileIcon className="h-12 w-12 text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">No changes to display</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
{/* File list sidebar */}
|
||||
<div className="w-64 border-r">
|
||||
<div className="p-4 border-b">
|
||||
<h3 className="font-semibold text-sm">Changed Files</h3>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{diffs.length} file{diffs.length !== 1 ? 's' : ''} changed
|
||||
</p>
|
||||
</div>
|
||||
<ScrollArea className="h-[calc(100%-73px)]">
|
||||
<div className="p-2 space-y-1">
|
||||
{diffs.map((diff) => (
|
||||
<button
|
||||
key={diff.filepath}
|
||||
onClick={() => setSelectedFile(diff.filepath)}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-2 p-2 rounded-lg text-left transition-colors',
|
||||
selectedFile === diff.filepath
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'hover:bg-muted/50'
|
||||
)}
|
||||
>
|
||||
{diff.status === 'added' && <Plus className="h-4 w-4 text-green-600 shrink-0" />}
|
||||
{diff.status === 'deleted' && <Minus className="h-4 w-4 text-red-600 shrink-0" />}
|
||||
{diff.status === 'modified' && <Edit className="h-4 w-4 text-blue-600 shrink-0" />}
|
||||
<span className="font-mono text-sm truncate">{diff.filepath}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Diff content */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
{selectedDiff && (
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="p-4 border-b flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="font-mono text-sm font-medium">{selectedDiff.filepath}</h3>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
selectedDiff.status === 'added' && 'border-green-600 text-green-600',
|
||||
selectedDiff.status === 'deleted' && 'border-red-600 text-red-600',
|
||||
selectedDiff.status === 'modified' && 'border-blue-600 text-blue-600'
|
||||
)}
|
||||
>
|
||||
{selectedDiff.status}
|
||||
</Badge>
|
||||
</div>
|
||||
<Tabs value={viewMode} onValueChange={(v) => setViewMode(v as 'unified' | 'split')}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="split" className="gap-2">
|
||||
<SplitSquareHorizontal className="h-4 w-4" />
|
||||
Split
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="unified" className="gap-2">
|
||||
<ListTree className="h-4 w-4" />
|
||||
Unified
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* Diff content */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-4">
|
||||
{selectedDiff.hunks.map((hunk, hunkIndex) => (
|
||||
<div key={hunkIndex} className="mb-6 border rounded-lg overflow-hidden">
|
||||
{/* Hunk header */}
|
||||
<div className="bg-muted/50 px-4 py-2 flex items-center justify-between border-b">
|
||||
<span className="font-mono text-xs text-muted-foreground">
|
||||
@@ -{hunk.oldStart},{hunk.oldLines} +{hunk.newStart},{hunk.newLines} @@
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2"
|
||||
onClick={() => copyHunkToClipboard(hunk, hunkIndex)}
|
||||
>
|
||||
{copiedHunk === hunkIndex ? (
|
||||
<>
|
||||
<Check className="h-3 w-3 mr-1" />
|
||||
Copied
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-3 w-3 mr-1" />
|
||||
Copy
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Hunk lines */}
|
||||
{viewMode === 'split' ? (
|
||||
<SplitDiffView hunk={hunk} filepath={selectedDiff.filepath} />
|
||||
) : (
|
||||
<UnifiedDiffView hunk={hunk} filepath={selectedDiff.filepath} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SplitDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 divide-x font-mono text-sm">
|
||||
{/* Old (left) side */}
|
||||
<div>
|
||||
{hunk.lines.map((line, i) => (
|
||||
line.type !== 'add' && (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'flex',
|
||||
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
|
||||
)}
|
||||
>
|
||||
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
|
||||
{line.oldLineNumber}
|
||||
</span>
|
||||
<pre className="px-2 py-1 flex-1 overflow-x-auto">
|
||||
<code
|
||||
className={cn(line.type === 'delete' && 'text-red-700 dark:text-red-400')}
|
||||
dangerouslySetInnerHTML={{ __html: line.content }}
|
||||
/>
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New (right) side */}
|
||||
<div>
|
||||
{hunk.lines.map((line, i) => (
|
||||
line.type !== 'delete' && (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'flex',
|
||||
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20'
|
||||
)}
|
||||
>
|
||||
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
|
||||
{line.newLineNumber}
|
||||
</span>
|
||||
<pre className="px-2 py-1 flex-1 overflow-x-auto">
|
||||
<code
|
||||
className={cn(line.type === 'add' && 'text-green-700 dark:text-green-400')}
|
||||
dangerouslySetInnerHTML={{ __html: line.content }}
|
||||
/>
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UnifiedDiffView({ hunk }: { hunk: DiffHunk; filepath: string }) {
|
||||
return (
|
||||
<div className="font-mono text-sm">
|
||||
{hunk.lines.map((line, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
'flex',
|
||||
line.type === 'add' && 'bg-green-50 dark:bg-green-950/20',
|
||||
line.type === 'delete' && 'bg-red-50 dark:bg-red-950/20'
|
||||
)}
|
||||
>
|
||||
<span className="px-2 py-1 text-muted-foreground select-none w-12 text-right shrink-0">
|
||||
{line.oldLineNumber || line.newLineNumber}
|
||||
</span>
|
||||
<span className="px-2 py-1 select-none w-6 shrink-0">
|
||||
{line.type === 'add' ? '+' : line.type === 'delete' ? '-' : ' '}
|
||||
</span>
|
||||
<pre className="px-2 py-1 flex-1 overflow-x-auto">
|
||||
<code
|
||||
className={cn(
|
||||
line.type === 'add' && 'text-green-700 dark:text-green-400',
|
||||
line.type === 'delete' && 'text-red-700 dark:text-red-400'
|
||||
)}
|
||||
dangerouslySetInnerHTML={{ __html: line.content }}
|
||||
/>
|
||||
</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
import { useState, useEffect } 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,
|
||||
GitPullRequest,
|
||||
} from 'lucide-react';
|
||||
import { BranchManager } from './BranchManager';
|
||||
import { CompareView } from './CompareView';
|
||||
import { DiffViewer } from './DiffViewer';
|
||||
import { PullRequestForm } from './PullRequestForm';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
|
||||
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 [remoteUrl, setRemoteUrl] = useState<string | null>(null);
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
|
||||
useEffect(() => {
|
||||
const loadRemoteUrl = async () => {
|
||||
try {
|
||||
const url = await git.getRemoteURL(projectPath, 'origin');
|
||||
setRemoteUrl(url);
|
||||
} catch {
|
||||
setRemoteUrl(null);
|
||||
}
|
||||
};
|
||||
if (open) {
|
||||
loadRemoteUrl();
|
||||
}
|
||||
}, [open, git, projectPath]);
|
||||
|
||||
const handleBranchChange = () => {
|
||||
// Refetch git status when branches change
|
||||
refetchGitStatus();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-6xl h-[90vh] p-0 flex flex-col gap-0">
|
||||
{/* Fixed Header */}
|
||||
<DialogHeader className="px-6 pt-6 pb-4 border-b shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Git Management
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Tabs Container - takes remaining space */}
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col">
|
||||
{/* Fixed Tab List */}
|
||||
<div className="border-b px-6 shrink-0">
|
||||
<TabsList className="h-auto p-0 bg-transparent">
|
||||
<TabsTrigger
|
||||
value="branches"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Branches
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="changes"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<Settings className="h-4 w-4" />
|
||||
Changes
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="compare"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<GitCompare className="h-4 w-4" />
|
||||
Compare
|
||||
</TabsTrigger>
|
||||
{remoteUrl && (
|
||||
<TabsTrigger
|
||||
value="pr"
|
||||
className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-primary rounded-none"
|
||||
>
|
||||
<GitPullRequest className="h-4 w-4" />
|
||||
Pull Request
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
{/* Scrollable Tab Content */}
|
||||
<TabsContent value="branches" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-6">
|
||||
<BranchManager
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus?.currentBranch || null}
|
||||
onBranchChange={handleBranchChange}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="changes" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col min-h-0">
|
||||
<div className="flex-1 min-h-0">
|
||||
<DiffViewer
|
||||
projectId={projectId}
|
||||
compareFrom="HEAD"
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="compare" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-6">
|
||||
<CompareView projectId={projectId} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
{remoteUrl && (
|
||||
<TabsContent value="pr" className="flex-1 m-0 data-[state=active]:flex data-[state=active]:flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-6">
|
||||
<PullRequestForm
|
||||
projectId={projectId}
|
||||
currentBranch={gitStatus?.currentBranch || null}
|
||||
remoteUrl={remoteUrl}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
)}
|
||||
</Tabs>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,576 +0,0 @@
|
||||
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 { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
interface MergeDialogProps {
|
||||
projectId: string;
|
||||
currentBranch: string | null;
|
||||
sourceBranch?: string;
|
||||
targetBranch?: string;
|
||||
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,
|
||||
sourceBranch: initialSourceBranch,
|
||||
targetBranch: _initialTargetBranch,
|
||||
open,
|
||||
onOpenChange,
|
||||
onMergeComplete,
|
||||
}: MergeDialogProps) {
|
||||
const [isOpen, setIsOpen] = useState(open ?? false);
|
||||
const [branches, setBranches] = useState<string[]>([]);
|
||||
const [sourceBranch, setSourceBranch] = useState<string>(initialSourceBranch || '');
|
||||
const [isLoadingBranches, setIsLoadingBranches] = useState(false);
|
||||
const [isLoadingPreview, setIsLoadingPreview] = useState(false);
|
||||
const [isMerging, setIsMerging] = useState(false);
|
||||
const [mergePreview, setMergePreview] = useState<MergePreview | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [mergeComplete, setMergeComplete] = useState(false);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { toast } = useToast();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const projectPath = `${projectsPath}/${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<string>();
|
||||
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: '[email protected]',
|
||||
},
|
||||
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}`,
|
||||
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 (
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" className="gap-2">
|
||||
<GitMerge className="h-4 w-4" />
|
||||
Merge Branch
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitMerge className="h-5 w-5" />
|
||||
Merge Branch
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Merge changes from another branch into {currentBranch}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{mergeComplete ? (
|
||||
// Success state
|
||||
<div className="py-8 text-center space-y-4">
|
||||
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Merge Complete!</h3>
|
||||
<p className="text-muted-foreground">
|
||||
Successfully merged {sourceBranch} into {currentBranch}
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => handleOpenChange(false)}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 pr-4">
|
||||
{/* Source branch selection */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Source Branch</label>
|
||||
<Select
|
||||
value={sourceBranch}
|
||||
onValueChange={setSourceBranch}
|
||||
disabled={isLoadingBranches || isMerging}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select branch to merge from" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{branches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The branch to merge into {currentBranch}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Merge direction visualization */}
|
||||
{sourceBranch && (
|
||||
<div className="bg-muted/30 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 justify-center text-sm">
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{sourceBranch}
|
||||
</Badge>
|
||||
<GitMerge className="h-4 w-4 text-muted-foreground" />
|
||||
<Badge variant="default" className="font-mono">
|
||||
{currentBranch}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Loading preview */}
|
||||
{isLoadingPreview && (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mr-2" />
|
||||
<span className="text-muted-foreground">Loading merge preview...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Merge preview */}
|
||||
{mergePreview && !isLoadingPreview && (
|
||||
<div className="space-y-4">
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<div className="text-2xl font-bold text-green-600">
|
||||
{mergePreview.commitsToMerge.length}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Commits to Merge
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<div className="text-2xl font-bold text-blue-600">
|
||||
{mergePreview.filesChanged.length}
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-1">
|
||||
Files Changed
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Fast-forward badge */}
|
||||
{mergePreview.canFastForward && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
This merge can be fast-forwarded (no merge commit needed)
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Commits to merge */}
|
||||
{mergePreview.commitsToMerge.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-sm font-medium mb-3">Commits to be merged:</h4>
|
||||
<div className="space-y-2 max-h-60 overflow-y-auto">
|
||||
{mergePreview.commitsToMerge.slice(0, 10).map((commit) => (
|
||||
<div
|
||||
key={commit.oid}
|
||||
className="flex items-start gap-3 p-3 rounded-lg border bg-card"
|
||||
>
|
||||
<GitCommit className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">
|
||||
{commit.message.split('\n')[0]}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
|
||||
<span>{commit.author}</span>
|
||||
<span>•</span>
|
||||
<span>{formatDate(commit.timestamp)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{mergePreview.commitsToMerge.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground text-center py-2">
|
||||
+ {mergePreview.commitsToMerge.length - 10} more commits
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No changes */}
|
||||
{mergePreview.commitsToMerge.length === 0 && (
|
||||
<Alert>
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No new commits to merge. The branches are already in sync.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Warning about conflicts */}
|
||||
{mergePreview.hasConflicts && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Conflicts detected in {mergePreview.conflictingFiles.length} file(s).
|
||||
You may need to resolve conflicts manually.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)}
|
||||
|
||||
{!mergeComplete && (
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isMerging}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={performMerge}
|
||||
disabled={
|
||||
isMerging ||
|
||||
isLoadingPreview ||
|
||||
!mergePreview ||
|
||||
mergePreview.commitsToMerge.length === 0
|
||||
}
|
||||
>
|
||||
{isMerging ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Merging...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitMerge className="h-4 w-4 mr-2" />
|
||||
Merge Branch
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,565 +0,0 @@
|
||||
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 {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import {
|
||||
GitPullRequest,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
ExternalLink,
|
||||
GitCompare,
|
||||
GitFork,
|
||||
} from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
|
||||
interface PullRequestFormProps {
|
||||
projectId: string;
|
||||
currentBranch: string | null;
|
||||
remoteUrl: string;
|
||||
}
|
||||
|
||||
interface RemoteInfo {
|
||||
owner: string;
|
||||
repo: string;
|
||||
platform: 'github' | 'gitlab';
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
interface ForkInfo {
|
||||
needsFork: boolean;
|
||||
forkOwner?: string;
|
||||
forkRepo?: string;
|
||||
forkUrl?: string;
|
||||
}
|
||||
|
||||
export function PullRequestForm({ projectId, currentBranch, remoteUrl }: PullRequestFormProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [targetBranch, setTargetBranch] = useState('main');
|
||||
const [remoteBranches, setRemoteBranches] = useState<string[]>([]);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
const [remoteInfo, setRemoteInfo] = useState<RemoteInfo | null>(null);
|
||||
const [forkInfo, setForkInfo] = useState<ForkInfo>({ needsFork: false });
|
||||
const [isCheckingPermissions, setIsCheckingPermissions] = useState(false);
|
||||
const [createdPrUrl, setCreatedPrUrl] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
// All the helper functions from PullRequestDialog can be reused here
|
||||
// (parseRemoteUrl, checkPushPermissions, ensureFork, etc.)
|
||||
// For brevity, I'll import them or duplicate the core logic
|
||||
|
||||
const parseRemoteUrl = useCallback((url: string) => {
|
||||
// Same implementation as PullRequestDialog
|
||||
setError(null);
|
||||
try {
|
||||
let match;
|
||||
let owner = '';
|
||||
let repo = '';
|
||||
let platform: 'github' | 'gitlab' = 'github';
|
||||
let apiUrl = '';
|
||||
|
||||
const normalizedUrl = url.replace(/\.git$/, '');
|
||||
|
||||
// GitHub SSH/HTTPS
|
||||
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/) ||
|
||||
normalizedUrl.match(/https?:\/\/github\.com\/([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
owner = match[1];
|
||||
repo = match[2];
|
||||
platform = 'github';
|
||||
apiUrl = 'https://api.github.com';
|
||||
}
|
||||
|
||||
// GitLab SSH/HTTPS
|
||||
if (!match) {
|
||||
match = normalizedUrl.match(/git@gitlab\.com:([^/]+)\/(.+)$/) ||
|
||||
normalizedUrl.match(/https?:\/\/gitlab\.com\/([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
owner = match[1];
|
||||
repo = match[2];
|
||||
platform = 'gitlab';
|
||||
apiUrl = 'https://gitlab.com/api/v4';
|
||||
}
|
||||
}
|
||||
|
||||
if (owner && repo) {
|
||||
setRemoteInfo({ owner, repo, platform, apiUrl });
|
||||
} else {
|
||||
setError('Unsupported remote URL format');
|
||||
}
|
||||
} catch {
|
||||
setError('Failed to parse remote URL');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadRemoteBranches = useCallback(async () => {
|
||||
try {
|
||||
const branches = await git.listBranches({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
});
|
||||
setRemoteBranches(branches);
|
||||
|
||||
if (branches.includes('main')) {
|
||||
setTargetBranch('main');
|
||||
} else if (branches.includes('master')) {
|
||||
setTargetBranch('master');
|
||||
} else if (branches.length > 0) {
|
||||
setTargetBranch(branches[0]);
|
||||
}
|
||||
} catch {
|
||||
setRemoteBranches(['main', 'master', 'develop']);
|
||||
}
|
||||
}, [git, projectPath]);
|
||||
|
||||
const checkPermissionsAndFork = useCallback(async () => {
|
||||
if (!remoteInfo) return;
|
||||
|
||||
setIsCheckingPermissions(true);
|
||||
try {
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
if (!credentials) {
|
||||
setForkInfo({ needsFork: false });
|
||||
return;
|
||||
}
|
||||
|
||||
// Simplified permission check - assume fork needed if we get 403/404
|
||||
// Full implementation would use the helper functions from PullRequestDialog
|
||||
setForkInfo({ needsFork: false });
|
||||
} catch {
|
||||
setForkInfo({ needsFork: false });
|
||||
} finally {
|
||||
setIsCheckingPermissions(false);
|
||||
}
|
||||
}, [remoteInfo, remoteUrl, settings.credentials]);
|
||||
|
||||
useEffect(() => {
|
||||
if (remoteUrl) {
|
||||
parseRemoteUrl(remoteUrl);
|
||||
loadRemoteBranches();
|
||||
checkPermissionsAndFork();
|
||||
}
|
||||
}, [remoteUrl, parseRemoteUrl, loadRemoteBranches, checkPermissionsAndFork]);
|
||||
|
||||
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 {
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
if (!credentials) {
|
||||
throw new Error('No credentials found. Please add credentials in Settings > Git');
|
||||
}
|
||||
|
||||
// Check if user is on main/master - if so, create a feature branch
|
||||
let branchToUse = currentBranch;
|
||||
const isOnDefaultBranch = currentBranch === 'main' || currentBranch === 'master';
|
||||
|
||||
if (isOnDefaultBranch) {
|
||||
console.log(`User is on default branch '${currentBranch}', creating feature branch`);
|
||||
|
||||
// Generate branch name from PR title
|
||||
const sanitizedTitle = title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, '')
|
||||
.replace(/\s+/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.substring(0, 50);
|
||||
|
||||
const baseName = sanitizedTitle || 'feature';
|
||||
const featureBranchName = `${baseName}-${Date.now().toString(36).slice(-4)}`;
|
||||
console.log(`Creating feature branch: ${featureBranchName}`);
|
||||
|
||||
try {
|
||||
// Check for uncommitted changes BEFORE creating branch
|
||||
const statusMatrix = await git.statusMatrix({ dir: projectPath });
|
||||
const hasUncommittedChanges = statusMatrix.some(([, head, workdir]) => head !== workdir);
|
||||
|
||||
// Create and checkout branch first
|
||||
await git.branch({
|
||||
dir: projectPath,
|
||||
ref: featureBranchName,
|
||||
checkout: true,
|
||||
});
|
||||
|
||||
branchToUse = featureBranchName;
|
||||
console.log(`Successfully created and checked out branch: ${featureBranchName}`);
|
||||
|
||||
// If there were uncommitted changes, commit them to the new branch
|
||||
if (hasUncommittedChanges) {
|
||||
console.log('Committing changes to new branch');
|
||||
|
||||
for (const [filepath, , workdir] of statusMatrix) {
|
||||
if ((workdir as number) === 0) {
|
||||
await git.remove({ dir: projectPath, filepath });
|
||||
} else if ((workdir as number) !== 0) {
|
||||
await git.add({ dir: projectPath, filepath });
|
||||
}
|
||||
}
|
||||
|
||||
await git.commit({
|
||||
dir: projectPath,
|
||||
message: title,
|
||||
});
|
||||
|
||||
console.log('Committed changes to new branch');
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Feature branch created',
|
||||
description: `Created branch '${featureBranchName}' for your changes`,
|
||||
});
|
||||
} catch (branchError) {
|
||||
console.error('Failed to create feature branch:', branchError);
|
||||
throw new Error(
|
||||
`Cannot create PR from '${currentBranch}' branch.\n\n` +
|
||||
`Failed to create a feature branch automatically.\n` +
|
||||
`Please create a new branch manually in the Branches tab first.\n\n` +
|
||||
`Error: ${branchError instanceof Error ? branchError.message : 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If fork is needed, push the branch first
|
||||
const headRef = forkInfo.needsFork && forkInfo.forkOwner
|
||||
? `${forkInfo.forkOwner}:${branchToUse}`
|
||||
: branchToUse;
|
||||
|
||||
console.log('PR head ref will be:', headRef);
|
||||
console.log('PR base ref will be:', targetBranch);
|
||||
|
||||
if (forkInfo.needsFork && forkInfo.forkUrl) {
|
||||
console.log(`Pushing branch ${branchToUse} to fork ${forkInfo.forkUrl}`);
|
||||
|
||||
// Check current remotes
|
||||
const remotes = await git.listRemotes({ dir: projectPath });
|
||||
const originRemote = remotes.find(r => r.remote === 'origin');
|
||||
const forkRemote = remotes.find(r => r.url === forkInfo.forkUrl);
|
||||
|
||||
let pushRemote = 'origin';
|
||||
|
||||
if (originRemote?.url !== forkInfo.forkUrl) {
|
||||
if (forkRemote) {
|
||||
pushRemote = forkRemote.remote;
|
||||
} else {
|
||||
await git.addRemote({
|
||||
dir: projectPath,
|
||||
remote: 'fork',
|
||||
url: forkInfo.forkUrl,
|
||||
});
|
||||
pushRemote = 'fork';
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: pushRemote,
|
||||
ref: branchToUse,
|
||||
onAuth: () => credentials,
|
||||
});
|
||||
console.log('Successfully pushed to fork');
|
||||
} catch (pushError) {
|
||||
const errorMsg = pushError instanceof Error ? pushError.message : 'Unknown error';
|
||||
throw new Error(
|
||||
`Failed to push branch '${branchToUse}' to your fork.\n\n` +
|
||||
`This usually means:\n` +
|
||||
`1. The branch hasn't been committed yet\n` +
|
||||
`2. Network/authentication issues\n\n` +
|
||||
`Error: ${errorMsg}\n\n` +
|
||||
`Try committing and pushing manually first.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const url = `${remoteInfo.apiUrl}/repos/${remoteInfo.owner}/${remoteInfo.repo}/pulls`;
|
||||
|
||||
const prData = {
|
||||
title,
|
||||
body: description,
|
||||
head: headRef,
|
||||
base: targetBranch,
|
||||
maintainer_can_modify: true,
|
||||
};
|
||||
|
||||
console.log('Creating PR with data:', prData);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `token ${credentials.password}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(prData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error('PR creation failed:', errorText);
|
||||
|
||||
let error;
|
||||
try {
|
||||
error = JSON.parse(errorText);
|
||||
} catch {
|
||||
error = { message: errorText || 'Unknown error' };
|
||||
}
|
||||
|
||||
// Extract detailed error messages
|
||||
let errorMessage = error.message || `API error: ${response.status} - ${response.statusText}`;
|
||||
|
||||
if (error.errors && Array.isArray(error.errors)) {
|
||||
const errorDetails = error.errors.map((e: { message?: string; field?: string; code?: string }) => {
|
||||
if (e.message) return e.message;
|
||||
if (e.field && e.code) return `${e.field}: ${e.code}`;
|
||||
return JSON.stringify(e);
|
||||
}).join('; ');
|
||||
errorMessage = `${errorMessage}\n\nDetails: ${errorDetails}`;
|
||||
}
|
||||
|
||||
if (error.documentation_url) {
|
||||
errorMessage = `${errorMessage}\n\nSee: ${error.documentation_url}`;
|
||||
}
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setCreatedPrUrl(data.html_url);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
if (!currentBranch) {
|
||||
return (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
No branch selected. Please select or create a branch first.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (createdPrUrl) {
|
||||
return (
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-16 w-16 text-green-600 mx-auto" />
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Pull Request Created!</h3>
|
||||
<p className="text-muted-foreground">
|
||||
Your pull request has been created successfully
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => window.open(createdPrUrl, '_blank')}
|
||||
className="gap-2"
|
||||
>
|
||||
View Pull Request
|
||||
<ExternalLink className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setCreatedPrUrl(null);
|
||||
setTitle('');
|
||||
setDescription('');
|
||||
}}
|
||||
>
|
||||
Create Another
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Permission/Fork info */}
|
||||
{isCheckingPermissions && (
|
||||
<Alert>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<AlertDescription>Checking repository permissions...</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{forkInfo.needsFork && forkInfo.forkOwner && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
You don't have push access. Your changes will be pushed to your fork at <strong>{forkInfo.forkOwner}/{forkInfo.forkRepo}</strong>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Auto-branch creation notice */}
|
||||
{currentBranch && (currentBranch === 'main' || currentBranch === 'master') && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
You're on the <strong>{currentBranch}</strong> branch. A feature branch will be automatically created from your PR title for this contribution.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Branch comparison */}
|
||||
<div className="bg-muted/30 rounded-lg p-4">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{targetBranch}
|
||||
</Badge>
|
||||
<GitCompare className="h-4 w-4 text-muted-foreground" />
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{currentBranch}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-2">
|
||||
Merge {currentBranch} into {targetBranch}
|
||||
</p>
|
||||
{(currentBranch === 'main' || currentBranch === 'master') && (
|
||||
<p className="text-xs text-blue-600 dark:text-blue-400 mt-1">
|
||||
Note: A new branch will be created automatically
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="whitespace-pre-wrap">{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Target branch */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="target-branch">Target Branch</Label>
|
||||
<Select value={targetBranch} onValueChange={setTargetBranch} disabled={isCreating}>
|
||||
<SelectTrigger id="target-branch">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{remoteBranches.map((branch) => (
|
||||
<SelectItem key={branch} value={branch}>
|
||||
{branch}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-title">Title *</Label>
|
||||
<Input
|
||||
id="pr-title"
|
||||
placeholder="Brief description of your changes"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-description">Description</Label>
|
||||
<Textarea
|
||||
id="pr-description"
|
||||
placeholder="Provide more details about your changes (supports Markdown)"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={8}
|
||||
disabled={isCreating}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Create button */}
|
||||
<Button
|
||||
onClick={createPullRequest}
|
||||
disabled={isCreating || isCheckingPermissions}
|
||||
className="w-full"
|
||||
>
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{forkInfo.needsFork ? 'Creating fork & PR...' : 'Creating...'}
|
||||
</>
|
||||
) : forkInfo.needsFork ? (
|
||||
<>
|
||||
<GitFork className="h-4 w-4 mr-2" />
|
||||
Fork & Create PR
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GitPullRequest className="h-4 w-4 mr-2" />
|
||||
Create Pull Request
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Repository info */}
|
||||
{remoteInfo && (
|
||||
<div className="bg-muted/30 rounded-lg p-3">
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Repository:</span>
|
||||
<span className="font-medium">
|
||||
{remoteInfo.owner}/{remoteInfo.repo}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">Platform:</span>
|
||||
<Badge variant="outline" className="capitalize">
|
||||
{remoteInfo.platform}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export { AnnounceRepositoryDialog } from './AnnounceRepositoryDialog';
|
||||
export { BranchManager } from './BranchManager';
|
||||
export { CompareView } from './CompareView';
|
||||
export { DiffViewer } from './DiffViewer';
|
||||
export { GitManagementDialog } from './GitManagementDialog';
|
||||
export { MergeDialog } from './MergeDialog';
|
||||
export { PullRequestDialog } from './PullRequestDialog';
|
||||
@@ -1,720 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGitFetch } from './useGitFetch';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Create mocks that can be reconfigured per test
|
||||
const mockGit = {
|
||||
findRoot: vi.fn(),
|
||||
listRemotes: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
resolveRef: vi.fn(),
|
||||
fetch: vi.fn(),
|
||||
};
|
||||
|
||||
const mockToast = vi.fn();
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Mock the git operations
|
||||
vi.mock('./useGit', () => ({
|
||||
useGit: () => ({
|
||||
git: mockGit,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useGitSettings', () => ({
|
||||
useGitSettings: () => ({
|
||||
settings: {
|
||||
credentials: [],
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useFSPaths', () => ({
|
||||
useFSPaths: () => ({
|
||||
projectsPath: '/projects',
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: mockToast,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock QueryClient to track invalidateQueries calls
|
||||
vi.mock('@tanstack/react-query', async () => {
|
||||
const actual = await vi.importActual('@tanstack/react-query');
|
||||
return {
|
||||
...actual,
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('useGitFetch', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockToast.mockClear();
|
||||
mockInvalidateQueries.mockClear();
|
||||
});
|
||||
|
||||
it('returns null state when projectId is null', async () => {
|
||||
const { result } = renderHook(() => useGitFetch(null), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
// When projectId is null, the query is disabled and won't fetch
|
||||
// So we just check the initial state
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when default branch is checked out', async () => {
|
||||
// Setup mocks for default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'); // after current (same as default)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when non-default branch is checked out', async () => {
|
||||
// Setup mocks for non-default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default (main)
|
||||
.mockResolvedValueOnce('def456') // before current (feature-branch)
|
||||
.mockResolvedValueOnce('abc123') // after default (main)
|
||||
.mockResolvedValueOnce('def456'); // after current (feature-branch)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('detects changes on default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on non-default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on non-default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default (no change)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on current branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on both default and non-default branches', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('new111') // after default (changed!)
|
||||
.mockResolvedValueOnce('new222'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on both branches
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on default branch when non-default branch is checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('def456'); // after current (no change)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('can be manually refetched', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef for initial fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
const firstFetchTime = result.current.data?.fetchedAt;
|
||||
|
||||
// Setup mocks for refetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Manually trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
|
||||
});
|
||||
|
||||
// Verify fetch was called twice (initial + refetch)
|
||||
expect(mockGit.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
describe('Toast Notifications', () => {
|
||||
it('shows toast when default branch changes (on default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed!
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when non-default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on feature branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123') // main unchanged
|
||||
.mockResolvedValueOnce('xyz789'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for feature branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on main branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('xyz789') // main changed!
|
||||
.mockResolvedValueOnce('def456'); // feature-branch unchanged
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for main branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows two toasts when both branches change (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('new111') // main changed!
|
||||
.mockResolvedValueOnce('new222'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// Verify both toast messages
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated twice (once per toast)
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not show toast on initial load', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch with changes detected in the fetch itself
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed from before to after fetch
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Should report changes in data
|
||||
expect(result.current.data?.hasChanges).toBe(true);
|
||||
|
||||
// But no toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not show toast when no changes detected', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast should be shown
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Verify git status was not invalidated (filter out other queries like 'nostr')
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not show duplicate toast for same branch when default equals current', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with changes (both default and current are 'main')
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789')
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Should only show one toast (for default branch), not two
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Should only invalidate once
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,357 +0,0 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useToast } from './useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
interface FetchResult {
|
||||
defaultBranch: string | null;
|
||||
defaultBranchOid: string | null;
|
||||
defaultBranchChanged: boolean;
|
||||
currentBranch: string | null;
|
||||
currentBranchOid: string | null;
|
||||
currentBranchChanged: boolean;
|
||||
fetchedAt: number;
|
||||
hasChanges: boolean;
|
||||
remoteUrl: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch updates from remote repository and detect changes.
|
||||
* Polls every 60 seconds and shows toast notifications when changes are detected.
|
||||
*
|
||||
* @param projectId - The project ID to fetch for
|
||||
* @returns Query result with manual refetch capability
|
||||
*/
|
||||
export function useGitFetch(projectId: string | null) {
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Track which branches we've already notified about to avoid duplicate toasts
|
||||
const notifiedBranchesRef = useRef<Set<string>>(new Set());
|
||||
// Track if this is the first successful fetch to avoid showing toasts on initial load
|
||||
const isFirstFetchRef = useRef(true);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['git-fetch', projectId],
|
||||
queryFn: async (): Promise<FetchResult> => {
|
||||
console.log('=== GIT FETCH STARTING ===');
|
||||
console.log('Project ID:', projectId);
|
||||
|
||||
if (!projectId) {
|
||||
console.log('No project ID, returning empty result');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
defaultBranchChanged: false,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
currentBranchChanged: false,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
console.log('Working directory:', cwd);
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await git.findRoot({ filepath: cwd });
|
||||
console.log('Git repository found');
|
||||
} catch {
|
||||
console.log('Not a git repository');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
defaultBranchChanged: false,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
currentBranchChanged: false,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get remotes
|
||||
const remotes = await git.listRemotes({ dir: cwd });
|
||||
console.log('Remotes found:', remotes);
|
||||
|
||||
if (remotes.length === 0) {
|
||||
console.log('No remotes configured');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
defaultBranchChanged: false,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
currentBranchChanged: false,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
const remoteUrl = remote.url || null;
|
||||
console.log('Using remote:', remote.remote, 'URL:', remoteUrl);
|
||||
|
||||
if (!remoteUrl) {
|
||||
console.log('No remote URL found');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
defaultBranchChanged: false,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
currentBranchChanged: false,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get credentials for authentication
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
console.log('Credentials found:', !!credentials);
|
||||
|
||||
// Get current branch before fetch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
const branch = await git.currentBranch({
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
currentBranch = (branch && branch.trim() !== '') ? branch : null;
|
||||
console.log('Current branch:', currentBranch);
|
||||
} catch (error) {
|
||||
console.warn('Could not get current branch:', error);
|
||||
}
|
||||
|
||||
// Store OIDs before fetch
|
||||
let beforeDefaultOid: string | null = null;
|
||||
let beforeCurrentOid: string | null = null;
|
||||
|
||||
// Get default branch from local symbolic ref
|
||||
let defaultBranch: string | null = null;
|
||||
try {
|
||||
console.log('Reading default branch from local symbolic ref...');
|
||||
|
||||
// Read the symbolic ref file directly
|
||||
// The file contains something like: "ref: refs/remotes/origin/main"
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
} else {
|
||||
console.log('Could not get default branch from local symbolic ref value:', refValue);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
|
||||
// If we have a default branch, try to get its OID before fetch
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
beforeDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID before fetch:', beforeDefaultOid);
|
||||
} catch {
|
||||
console.log('Remote default branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not read default branch from local data:', error);
|
||||
}
|
||||
|
||||
// Get current branch OID before fetch
|
||||
if (currentBranch) {
|
||||
try {
|
||||
beforeCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID before fetch:', beforeCurrentOid);
|
||||
} catch {
|
||||
console.log('Remote current branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
|
||||
// Perform fetch
|
||||
try {
|
||||
console.log('Fetching from remote...');
|
||||
await git.fetch({
|
||||
dir: cwd,
|
||||
remote: remote.remote,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
console.log('Fetch completed successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Get OIDs after fetch
|
||||
let afterDefaultOid: string | null = null;
|
||||
let afterCurrentOid: string | null = null;
|
||||
|
||||
// Re-read default branch from symbolic ref in case it was just created by fetch
|
||||
if (!defaultBranch) {
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
afterDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID after fetch:', afterDefaultOid);
|
||||
} catch {
|
||||
console.log('Could not resolve default branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (currentBranch) {
|
||||
try {
|
||||
afterCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID after fetch:', afterCurrentOid);
|
||||
} catch {
|
||||
console.log('Could not resolve current branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
// Detect changes
|
||||
const defaultBranchChanged = beforeDefaultOid !== null &&
|
||||
afterDefaultOid !== null &&
|
||||
beforeDefaultOid !== afterDefaultOid;
|
||||
|
||||
const currentBranchChanged = beforeCurrentOid !== null &&
|
||||
afterCurrentOid !== null &&
|
||||
beforeCurrentOid !== afterCurrentOid &&
|
||||
currentBranch !== defaultBranch; // Don't double-report if they're the same
|
||||
|
||||
console.log('Changes detected:', {
|
||||
defaultBranchChanged,
|
||||
currentBranchChanged,
|
||||
});
|
||||
|
||||
const result = {
|
||||
defaultBranch,
|
||||
defaultBranchOid: afterDefaultOid,
|
||||
defaultBranchChanged,
|
||||
currentBranch,
|
||||
currentBranchOid: afterCurrentOid,
|
||||
currentBranchChanged,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: defaultBranchChanged || currentBranchChanged,
|
||||
remoteUrl,
|
||||
};
|
||||
|
||||
console.log('=== GIT FETCH COMPLETE ===');
|
||||
console.log('Result:', result);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Error fetching from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
enabled: !!projectId,
|
||||
refetchInterval: 60000, // Fetch every 60 seconds
|
||||
staleTime: 30000, // Consider data stale after 30 seconds
|
||||
retry: 1, // Only retry once on failure
|
||||
});
|
||||
|
||||
// Show toast notifications when changes are detected
|
||||
useEffect(() => {
|
||||
if (!query.data || !query.isSuccess) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip toasts on the first successful fetch (initial load)
|
||||
if (isFirstFetchRef.current) {
|
||||
isFirstFetchRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const { defaultBranch, defaultBranchChanged, currentBranch, currentBranchChanged, fetchedAt } = query.data;
|
||||
|
||||
// Create a unique key for this fetch's branch changes
|
||||
const defaultBranchKey = defaultBranch ? `${fetchedAt}-${defaultBranch}` : null;
|
||||
const currentBranchKey = currentBranch ? `${fetchedAt}-${currentBranch}` : null;
|
||||
|
||||
// Show toast for default branch changes
|
||||
if (defaultBranchChanged && defaultBranch && defaultBranchKey && !notifiedBranchesRef.current.has(defaultBranchKey)) {
|
||||
notifiedBranchesRef.current.add(defaultBranchKey);
|
||||
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${defaultBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Show toast for current branch changes (if different from default)
|
||||
if (currentBranchChanged && currentBranch && currentBranchKey && !notifiedBranchesRef.current.has(currentBranchKey)) {
|
||||
notifiedBranchesRef.current.add(currentBranchKey);
|
||||
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${currentBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
}, [query.data, query.isSuccess, toast, queryClient, projectId]);
|
||||
|
||||
return query;
|
||||
}
|
||||
@@ -1,456 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
export interface PullRequest {
|
||||
id: number | string;
|
||||
number: number | string;
|
||||
title: string;
|
||||
state: 'open' | 'closed' | 'merged';
|
||||
author: string;
|
||||
authorPubkey?: string; // For Nostr patches
|
||||
url: string;
|
||||
createdAt: string;
|
||||
sourceBranch: string;
|
||||
targetBranch: string;
|
||||
isOwner?: boolean; // Whether current user is the PR creator
|
||||
}
|
||||
|
||||
interface RemoteInfo {
|
||||
owner: string;
|
||||
repo: string;
|
||||
platform: 'github' | 'gitlab' | 'nostr';
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
function parseRemoteUrl(url: string): RemoteInfo | null {
|
||||
try {
|
||||
// Nostr git: nostr://<pubkey>/<repo-id>
|
||||
if (url.startsWith('nostr://')) {
|
||||
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
const pubkeyOrNpub = match[1];
|
||||
const repo = match[2];
|
||||
|
||||
// Convert npub to hex if needed
|
||||
let owner = pubkeyOrNpub;
|
||||
if (pubkeyOrNpub.startsWith('npub1')) {
|
||||
try {
|
||||
const decoded = nip19.decode(pubkeyOrNpub);
|
||||
if (decoded.type === 'npub') {
|
||||
owner = decoded.data; // hex pubkey
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to decode npub:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return { owner, repo, platform: 'nostr', apiUrl: '' };
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize URL - remove .git suffix if present
|
||||
const normalizedUrl = url.replace(/\.git$/, '');
|
||||
let match;
|
||||
let owner = '';
|
||||
let repo = '';
|
||||
let platform: 'github' | 'gitlab' = 'github';
|
||||
let apiUrl = '';
|
||||
|
||||
// GitHub SSH: [email protected]:owner/repo
|
||||
match = normalizedUrl.match(/git@github\.com:([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
owner = match[1];
|
||||
repo = match[2];
|
||||
platform = 'github';
|
||||
apiUrl = 'https://api.github.com';
|
||||
}
|
||||
|
||||
// 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';
|
||||
}
|
||||
}
|
||||
|
||||
// GitLab SSH: [email protected]: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';
|
||||
}
|
||||
}
|
||||
|
||||
// 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';
|
||||
}
|
||||
}
|
||||
|
||||
if (owner && repo) {
|
||||
return { owner, repo, platform, apiUrl };
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchGitHubPRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise<PullRequest[]> {
|
||||
const url = `${info.apiUrl}/repos/${info.owner}/${info.repo}/pulls?state=open`;
|
||||
const headers: Record<string, string> = {
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
};
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = `token ${token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(url, { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch GitHub PRs: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
interface GitHubPR {
|
||||
id: number;
|
||||
number: number;
|
||||
title: string;
|
||||
state: string;
|
||||
user: { login: string };
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
head: { ref: string };
|
||||
base: { ref: string };
|
||||
body?: string;
|
||||
}
|
||||
|
||||
const allPRs = data.map((pr: GitHubPR) => ({
|
||||
id: pr.id,
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
state: pr.state,
|
||||
author: pr.user.login,
|
||||
url: pr.html_url,
|
||||
createdAt: pr.created_at,
|
||||
sourceBranch: pr.head.ref,
|
||||
targetBranch: pr.base.ref,
|
||||
isOwner: pr.user.login === currentUsername,
|
||||
}));
|
||||
|
||||
// If repo owner, return all PRs. Otherwise, return only user's PRs
|
||||
if (isRepoOwner) {
|
||||
return allPRs;
|
||||
} else if (currentUsername) {
|
||||
return allPRs.filter((pr: PullRequest) => pr.author === currentUsername);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
async function fetchGitLabMRs(info: RemoteInfo, token?: string, currentUsername?: string, isRepoOwner?: boolean): Promise<PullRequest[]> {
|
||||
// Get project ID first
|
||||
const projectUrl = `${info.apiUrl}/projects/${encodeURIComponent(`${info.owner}/${info.repo}`)}`;
|
||||
const projectHeaders: Record<string, string> = {};
|
||||
|
||||
if (token) {
|
||||
projectHeaders['PRIVATE-TOKEN'] = token;
|
||||
}
|
||||
|
||||
const projectResponse = await fetch(projectUrl, { headers: projectHeaders });
|
||||
|
||||
if (!projectResponse.ok) {
|
||||
throw new Error(`Failed to fetch GitLab project: ${projectResponse.status}`);
|
||||
}
|
||||
|
||||
const project = await projectResponse.json();
|
||||
|
||||
// Fetch merge requests
|
||||
const mrUrl = `${info.apiUrl}/projects/${project.id}/merge_requests?state=opened`;
|
||||
const mrHeaders: Record<string, string> = {};
|
||||
|
||||
if (token) {
|
||||
mrHeaders['PRIVATE-TOKEN'] = token;
|
||||
}
|
||||
|
||||
const response = await fetch(mrUrl, { headers: mrHeaders });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch GitLab MRs: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
interface GitLabMR {
|
||||
id: number;
|
||||
iid: number;
|
||||
title: string;
|
||||
state: string;
|
||||
author: { username: string };
|
||||
web_url: string;
|
||||
created_at: string;
|
||||
source_branch: string;
|
||||
target_branch: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
const allMRs = data.map((mr: GitLabMR) => ({
|
||||
id: mr.id,
|
||||
number: mr.iid,
|
||||
title: mr.title,
|
||||
state: mr.state === 'opened' ? 'open' : mr.state,
|
||||
author: mr.author.username,
|
||||
url: mr.web_url,
|
||||
createdAt: mr.created_at,
|
||||
sourceBranch: mr.source_branch,
|
||||
targetBranch: mr.target_branch,
|
||||
isOwner: mr.author.username === currentUsername,
|
||||
}));
|
||||
|
||||
// If repo owner, return all MRs. Otherwise, return only user's MRs
|
||||
if (isRepoOwner) {
|
||||
return allMRs;
|
||||
} else if (currentUsername) {
|
||||
return allMRs.filter((mr: PullRequest) => mr.author === currentUsername);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
interface NostrInterface {
|
||||
query: (filters: unknown[], options?: { signal?: AbortSignal }) => Promise<unknown[]>;
|
||||
}
|
||||
|
||||
async function fetchNostrPatches(
|
||||
info: RemoteInfo,
|
||||
currentUserPubkey: string | undefined,
|
||||
nostr: NostrInterface,
|
||||
signal: AbortSignal,
|
||||
isRepoOwner?: boolean
|
||||
): Promise<PullRequest[]> {
|
||||
console.log('=== FETCHING NOSTR PATCHES ===');
|
||||
console.log('Repository:', `${info.owner}/${info.repo}`);
|
||||
console.log('Current user pubkey:', currentUserPubkey);
|
||||
console.log('Is repo owner:', isRepoOwner);
|
||||
|
||||
if (!currentUserPubkey && !isRepoOwner) {
|
||||
console.log('No current user, returning empty array');
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
// Build query filter based on whether user is repo owner or contributor
|
||||
interface PatchFilter {
|
||||
kinds: number[];
|
||||
'#a': string[];
|
||||
limit: number;
|
||||
authors?: string[];
|
||||
}
|
||||
|
||||
const filter: PatchFilter = {
|
||||
kinds: [1617],
|
||||
'#a': [`30617:${info.owner}:${info.repo}`],
|
||||
limit: 50,
|
||||
};
|
||||
|
||||
// If not repo owner, only fetch user's own patches
|
||||
if (!isRepoOwner && currentUserPubkey) {
|
||||
filter.authors = [currentUserPubkey];
|
||||
}
|
||||
|
||||
console.log('Querying patches with filter:', filter);
|
||||
|
||||
const patches = await nostr.query([filter], { signal });
|
||||
|
||||
console.log(`Found ${patches.length} patches`);
|
||||
|
||||
if (patches.length > 0) {
|
||||
console.log('Sample patch:', patches[0]);
|
||||
}
|
||||
|
||||
// Query for status events (kind 1630-1633) to determine patch state
|
||||
const patchIds = patches.map((p: NostrEvent) => p.id);
|
||||
let statusEvents: NostrEvent[] = [];
|
||||
|
||||
if (patchIds.length > 0) {
|
||||
const events = await nostr.query([
|
||||
{
|
||||
kinds: [1630, 1631, 1632, 1633], // Open, Applied/Merged, Closed, Draft
|
||||
'#e': patchIds,
|
||||
}
|
||||
], { signal });
|
||||
statusEvents = events as NostrEvent[];
|
||||
console.log(`Found ${statusEvents.length} status events`);
|
||||
}
|
||||
|
||||
// Build a map of patch ID to latest status
|
||||
const patchStatus = new Map<string, string>();
|
||||
statusEvents.forEach((statusEvent: NostrEvent) => {
|
||||
const patchId = statusEvent.tags.find(t => t[0] === 'e' && t[3] === 'root')?.[1];
|
||||
if (patchId) {
|
||||
// Status event kinds: 1630=Open, 1631=Applied/Merged, 1632=Closed, 1633=Draft
|
||||
const status = statusEvent.kind === 1631 ? 'merged' : statusEvent.kind === 1632 ? 'closed' : 'open';
|
||||
|
||||
// Only update if we don't have a status or this event is newer
|
||||
const existing = patchStatus.get(patchId);
|
||||
if (!existing || statusEvent.created_at > (statusEvents.find(e => e.tags.find(t => t[1] === patchId))?.created_at || 0)) {
|
||||
patchStatus.set(patchId, status);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Convert Nostr patches to PullRequest format
|
||||
const pullRequests: PullRequest[] = patches.map((patch: NostrEvent) => {
|
||||
const subject = patch.tags.find(t => t[0] === 'subject')?.[1] || 'Untitled patch';
|
||||
|
||||
// Get status from status events, default to 'open'
|
||||
const state = patchStatus.get(patch.id) || 'open';
|
||||
|
||||
// Extract source/target branches from content if available
|
||||
const contentLines = patch.content.split('\n');
|
||||
let sourceBranch = 'unknown';
|
||||
let targetBranch = 'main';
|
||||
|
||||
for (const line of contentLines) {
|
||||
if (line.startsWith('From:')) {
|
||||
sourceBranch = line.replace('From:', '').trim();
|
||||
}
|
||||
if (line.startsWith('To:')) {
|
||||
targetBranch = line.replace('To:', '').trim();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: patch.id,
|
||||
number: patch.id.slice(0, 8),
|
||||
title: subject,
|
||||
state: state as 'open' | 'closed' | 'merged',
|
||||
author: nip19.npubEncode(patch.pubkey),
|
||||
authorPubkey: patch.pubkey,
|
||||
url: `nostr:${patch.id}`,
|
||||
createdAt: new Date(patch.created_at * 1000).toISOString(),
|
||||
sourceBranch,
|
||||
targetBranch,
|
||||
isOwner: patch.pubkey === currentUserPubkey,
|
||||
};
|
||||
});
|
||||
|
||||
console.log('Converted patches to PRs:', pullRequests);
|
||||
|
||||
return pullRequests;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch Nostr patches:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function usePullRequests(remoteUrl?: string) {
|
||||
const { settings } = useGitSettings();
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['pull-requests', remoteUrl, user?.pubkey],
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!remoteUrl) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const remoteInfo = parseRemoteUrl(remoteUrl);
|
||||
if (!remoteInfo) {
|
||||
throw new Error('Invalid remote URL format');
|
||||
}
|
||||
|
||||
// Determine if current user is the repo owner
|
||||
let isRepoOwner = false;
|
||||
let currentUsername: string | undefined;
|
||||
|
||||
if (remoteInfo.platform === 'nostr') {
|
||||
// For Nostr, check if user's pubkey matches repo owner
|
||||
isRepoOwner = user?.pubkey === remoteInfo.owner;
|
||||
} else if (remoteInfo.platform === 'github') {
|
||||
// For GitHub, fetch current username
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
const token = credentials?.password;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, {
|
||||
headers: {
|
||||
'Authorization': `token ${token}`,
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
},
|
||||
});
|
||||
if (userResponse.ok) {
|
||||
const userData = await userResponse.json();
|
||||
currentUsername = userData.login;
|
||||
isRepoOwner = currentUsername === remoteInfo.owner;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch current GitHub user:', error);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// GitLab
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
const token = credentials?.password;
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const userResponse = await fetch(`${remoteInfo.apiUrl}/user`, {
|
||||
headers: {
|
||||
'PRIVATE-TOKEN': token,
|
||||
},
|
||||
});
|
||||
if (userResponse.ok) {
|
||||
const userData = await userResponse.json();
|
||||
currentUsername = userData.username;
|
||||
isRepoOwner = currentUsername === remoteInfo.owner;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to fetch current GitLab user:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Fetching PRs - isRepoOwner:', isRepoOwner, 'currentUser:', currentUsername || user?.pubkey);
|
||||
|
||||
// Fetch PRs based on platform
|
||||
if (remoteInfo.platform === 'nostr') {
|
||||
return await fetchNostrPatches(remoteInfo, user?.pubkey, nostr, signal, isRepoOwner);
|
||||
} else if (remoteInfo.platform === 'github') {
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
const token = credentials?.password;
|
||||
return await fetchGitHubPRs(remoteInfo, token, currentUsername, isRepoOwner);
|
||||
} else {
|
||||
// GitLab
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
const token = credentials?.password;
|
||||
return await fetchGitLabMRs(remoteInfo, token, currentUsername, isRepoOwner);
|
||||
}
|
||||
},
|
||||
enabled: !!remoteUrl,
|
||||
refetchInterval: 60000, // Refetch every minute
|
||||
staleTime: 30000, // Consider data stale after 30 seconds
|
||||
});
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
PullRequestCheck,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
} from './types';
|
||||
|
||||
interface GitHubPRResponse {
|
||||
id: number;
|
||||
number: number;
|
||||
state: string;
|
||||
title: string;
|
||||
body: string;
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: { login: string };
|
||||
head: { ref: string; repo: { full_name: string } };
|
||||
base: { ref: string; repo: { full_name: string } };
|
||||
mergeable?: boolean;
|
||||
merged?: boolean;
|
||||
}
|
||||
|
||||
export class GitHubProvider implements GitHostProvider {
|
||||
readonly name = 'GitHub';
|
||||
readonly apiBaseUrl = 'https://api.github.com';
|
||||
|
||||
private config: GitHostConfig;
|
||||
private corsProxy?: string;
|
||||
|
||||
constructor(config: GitHostConfig, corsProxy?: string) {
|
||||
this.config = config;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const url = `${this.apiBaseUrl}${path}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
...options,
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
'Authorization': `Bearer ${this.config.token}`,
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`GitHub API error (${response.status}): ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async getRepository(owner: string, repo: string): Promise<GitRepository> {
|
||||
interface GitHubRepo {
|
||||
owner: { login: string };
|
||||
name: string;
|
||||
full_name: string;
|
||||
default_branch: string;
|
||||
clone_url: string;
|
||||
html_url: string;
|
||||
description: string;
|
||||
private: boolean;
|
||||
}
|
||||
|
||||
const data = await this.fetch<GitHubRepo>(`/repos/${owner}/${repo}`);
|
||||
|
||||
return {
|
||||
owner: data.owner.login,
|
||||
name: data.name,
|
||||
fullName: data.full_name,
|
||||
defaultBranch: data.default_branch,
|
||||
cloneUrl: data.clone_url,
|
||||
webUrl: data.html_url,
|
||||
description: data.description,
|
||||
isPrivate: data.private,
|
||||
};
|
||||
}
|
||||
|
||||
async canUserPush(owner: string, repo: string): Promise<boolean> {
|
||||
try {
|
||||
interface GitHubRepoWithPermissions {
|
||||
permissions?: { push?: boolean; admin?: boolean };
|
||||
}
|
||||
|
||||
const data = await this.fetch<GitHubRepoWithPermissions>(`/repos/${owner}/${repo}`);
|
||||
return data.permissions?.push === true || data.permissions?.admin === true;
|
||||
} catch {
|
||||
// If we can't check permissions, assume no push access
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async createFork(owner: string, repo: string): Promise<GitFork> {
|
||||
interface GitHubFork {
|
||||
owner: { login: string };
|
||||
name: string;
|
||||
clone_url: string;
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
const data = await this.fetch<GitHubFork>(`/repos/${owner}/${repo}/forks`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
return {
|
||||
owner: data.owner.login,
|
||||
name: data.name,
|
||||
fullName: `${data.owner.login}/${data.name}`,
|
||||
cloneUrl: data.clone_url,
|
||||
webUrl: data.html_url,
|
||||
parentFullName: `${owner}/${repo}`,
|
||||
};
|
||||
}
|
||||
|
||||
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
|
||||
try {
|
||||
interface GitHubForkCheck {
|
||||
fork: boolean;
|
||||
owner: { login: string };
|
||||
name: string;
|
||||
full_name: string;
|
||||
clone_url: string;
|
||||
html_url: string;
|
||||
parent?: { full_name: string };
|
||||
}
|
||||
|
||||
// Check if the fork already exists
|
||||
const data = await this.fetch<GitHubForkCheck>(`/repos/${username}/${upstreamRepo}`);
|
||||
|
||||
// Verify it's actually a fork of the upstream repo
|
||||
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
|
||||
return {
|
||||
owner: data.owner.login,
|
||||
name: data.name,
|
||||
fullName: data.full_name,
|
||||
cloneUrl: data.clone_url,
|
||||
webUrl: data.html_url,
|
||||
parentFullName: data.parent.full_name,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async waitForFork(
|
||||
upstreamOwner: string,
|
||||
upstreamRepo: string,
|
||||
username: string,
|
||||
timeout = 30000
|
||||
): Promise<GitFork> {
|
||||
const startTime = Date.now();
|
||||
const pollInterval = 1000;
|
||||
|
||||
while (Date.now() - startTime < timeout) {
|
||||
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
|
||||
if (fork) {
|
||||
return fork;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
throw new Error('Timeout waiting for fork to be created');
|
||||
}
|
||||
|
||||
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
|
||||
const [baseOwner, baseRepo] = options.baseRepo.split('/');
|
||||
const [headOwner] = options.headRepo.split('/');
|
||||
|
||||
// Format head ref for cross-repo PR
|
||||
const head = headOwner !== baseOwner
|
||||
? `${headOwner}:${options.headBranch}`
|
||||
: options.headBranch;
|
||||
|
||||
const data = await this.fetch<GitHubPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: options.title,
|
||||
body: options.body || '',
|
||||
head,
|
||||
base: options.baseBranch,
|
||||
maintainer_can_modify: options.maintainerCanModify ?? true,
|
||||
}),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
|
||||
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async listPullRequests(
|
||||
owner: string,
|
||||
repo: string,
|
||||
state: 'open' | 'closed' | 'all' = 'open'
|
||||
): Promise<PullRequest[]> {
|
||||
const data = await this.fetch<GitHubPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
|
||||
return data.map(pr => this.transformPullRequest(pr));
|
||||
}
|
||||
|
||||
async updatePullRequest(
|
||||
owner: string,
|
||||
repo: string,
|
||||
number: number,
|
||||
options: { title?: string; body?: string }
|
||||
): Promise<PullRequest> {
|
||||
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(options),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
|
||||
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ state: 'closed' }),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<GitHostUser> {
|
||||
interface GitHubUser {
|
||||
login: string;
|
||||
name: string;
|
||||
email: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
|
||||
const data = await this.fetch<GitHubUser>('/user');
|
||||
|
||||
return {
|
||||
username: data.login,
|
||||
name: data.name,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatar_url,
|
||||
};
|
||||
}
|
||||
|
||||
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
|
||||
const [headOwner, headRepoName] = headRepo.split('/');
|
||||
return `https://github.com/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}?expand=1`;
|
||||
}
|
||||
|
||||
private transformPullRequest(data: {
|
||||
id: number;
|
||||
number: number;
|
||||
state: string;
|
||||
title: string;
|
||||
body: string;
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: { login: string };
|
||||
head: { ref: string; repo: { full_name: string } };
|
||||
base: { ref: string; repo: { full_name: string } };
|
||||
mergeable?: boolean;
|
||||
merged?: boolean;
|
||||
}): PullRequest {
|
||||
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
|
||||
|
||||
return {
|
||||
number: data.number,
|
||||
title: data.title,
|
||||
body: data.body,
|
||||
state,
|
||||
headBranch: data.head.ref,
|
||||
baseBranch: data.base.ref,
|
||||
headRepo: data.head.repo?.full_name || '',
|
||||
baseRepo: data.base.repo.full_name,
|
||||
url: data.html_url,
|
||||
createdAt: new Date(data.created_at),
|
||||
updatedAt: new Date(data.updated_at),
|
||||
author: data.user.login,
|
||||
mergeable: data.mergeable,
|
||||
checks: this.transformChecks(data),
|
||||
};
|
||||
}
|
||||
|
||||
private transformChecks(_data: unknown): PullRequestCheck[] | undefined {
|
||||
// GitHub's check runs are in a separate API call, so we don't have them here
|
||||
// This would need a separate API call to /repos/{owner}/{repo}/commits/{ref}/check-runs
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
PullRequestCheck,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
} from './types';
|
||||
|
||||
interface GitLabMRResponse {
|
||||
id: number;
|
||||
iid: number;
|
||||
state: string;
|
||||
title: string;
|
||||
description: string;
|
||||
web_url: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
author: { username: string };
|
||||
source_branch: string;
|
||||
target_branch: string;
|
||||
source_project_id: number;
|
||||
target_project_id: number;
|
||||
merge_status?: string;
|
||||
merged_at?: string;
|
||||
pipeline?: {
|
||||
status: string;
|
||||
web_url: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class GitLabProvider implements GitHostProvider {
|
||||
readonly name = 'GitLab';
|
||||
readonly apiBaseUrl = 'https://gitlab.com/api/v4';
|
||||
|
||||
private config: GitHostConfig;
|
||||
private corsProxy?: string;
|
||||
|
||||
constructor(config: GitHostConfig, corsProxy?: string) {
|
||||
this.config = config;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const url = `${this.apiBaseUrl}${path}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
...options,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.config.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`GitLab API error (${response.status}): ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
private encodeProjectPath(owner: string, repo: string): string {
|
||||
return encodeURIComponent(`${owner}/${repo}`);
|
||||
}
|
||||
|
||||
async getRepository(owner: string, repo: string): Promise<GitRepository> {
|
||||
interface GitLabProject {
|
||||
namespace: { path: string };
|
||||
path: string;
|
||||
path_with_namespace: string;
|
||||
default_branch: string;
|
||||
http_url_to_repo: string;
|
||||
web_url: string;
|
||||
description: string;
|
||||
visibility: string;
|
||||
}
|
||||
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<GitLabProject>(`/projects/${projectPath}`);
|
||||
|
||||
return {
|
||||
owner: data.namespace.path,
|
||||
name: data.path,
|
||||
fullName: data.path_with_namespace,
|
||||
defaultBranch: data.default_branch,
|
||||
cloneUrl: data.http_url_to_repo,
|
||||
webUrl: data.web_url,
|
||||
description: data.description,
|
||||
isPrivate: data.visibility === 'private',
|
||||
};
|
||||
}
|
||||
|
||||
async canUserPush(owner: string, repo: string): Promise<boolean> {
|
||||
try {
|
||||
interface GitLabProjectWithPermissions {
|
||||
permissions?: {
|
||||
project_access?: { access_level?: number };
|
||||
};
|
||||
}
|
||||
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<GitLabProjectWithPermissions>(`/projects/${projectPath}`);
|
||||
|
||||
// GitLab permissions are more granular
|
||||
// developer (30), maintainer (40), or owner (50) can push
|
||||
const accessLevel = data.permissions?.project_access?.access_level || 0;
|
||||
return accessLevel >= 30;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async createFork(owner: string, repo: string): Promise<GitFork> {
|
||||
interface GitLabFork {
|
||||
namespace: { path: string };
|
||||
path: string;
|
||||
path_with_namespace: string;
|
||||
http_url_to_repo: string;
|
||||
web_url: string;
|
||||
forked_from_project?: { path_with_namespace: string };
|
||||
}
|
||||
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<GitLabFork>(`/projects/${projectPath}/fork`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
return {
|
||||
owner: data.namespace.path,
|
||||
name: data.path,
|
||||
fullName: data.path_with_namespace,
|
||||
cloneUrl: data.http_url_to_repo,
|
||||
webUrl: data.web_url,
|
||||
parentFullName: data.forked_from_project?.path_with_namespace || `${owner}/${repo}`,
|
||||
};
|
||||
}
|
||||
|
||||
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
|
||||
try {
|
||||
interface GitLabForkCheck {
|
||||
namespace: { path: string };
|
||||
path: string;
|
||||
path_with_namespace: string;
|
||||
http_url_to_repo: string;
|
||||
web_url: string;
|
||||
forked_from_project?: { path_with_namespace: string };
|
||||
}
|
||||
|
||||
const forkPath = this.encodeProjectPath(username, upstreamRepo);
|
||||
const data = await this.fetch<GitLabForkCheck>(`/projects/${forkPath}`);
|
||||
|
||||
// Check if it's a fork of the upstream
|
||||
if (data.forked_from_project?.path_with_namespace === `${upstreamOwner}/${upstreamRepo}`) {
|
||||
return {
|
||||
owner: data.namespace.path,
|
||||
name: data.path,
|
||||
fullName: data.path_with_namespace,
|
||||
cloneUrl: data.http_url_to_repo,
|
||||
webUrl: data.web_url,
|
||||
parentFullName: data.forked_from_project.path_with_namespace,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async waitForFork(
|
||||
upstreamOwner: string,
|
||||
upstreamRepo: string,
|
||||
username: string,
|
||||
timeout = 30000
|
||||
): Promise<GitFork> {
|
||||
const startTime = Date.now();
|
||||
const pollInterval = 1000;
|
||||
|
||||
while (Date.now() - startTime < timeout) {
|
||||
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
|
||||
if (fork) {
|
||||
return fork;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
throw new Error('Timeout waiting for fork to be created');
|
||||
}
|
||||
|
||||
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
|
||||
// In GitLab, MRs are created on the source (fork) project
|
||||
const sourceProjectPath = this.encodeProjectPath(options.headRepo.split('/')[0], options.headRepo.split('/')[1]);
|
||||
const [targetOwner, targetRepo] = options.baseRepo.split('/');
|
||||
|
||||
const data = await this.fetch<GitLabMRResponse>(`/projects/${sourceProjectPath}/merge_requests`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
source_branch: options.headBranch,
|
||||
target_branch: options.baseBranch,
|
||||
target_project_id: this.encodeProjectPath(targetOwner, targetRepo),
|
||||
title: options.title,
|
||||
description: options.body || '',
|
||||
allow_collaboration: options.maintainerCanModify ?? true,
|
||||
}),
|
||||
});
|
||||
|
||||
return this.transformMergeRequest(data);
|
||||
}
|
||||
|
||||
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`);
|
||||
return this.transformMergeRequest(data);
|
||||
}
|
||||
|
||||
async listPullRequests(
|
||||
owner: string,
|
||||
repo: string,
|
||||
state: 'open' | 'closed' | 'all' = 'open'
|
||||
): Promise<PullRequest[]> {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const stateParam = state === 'all' ? 'all' : state === 'open' ? 'opened' : 'closed';
|
||||
const data = await this.fetch<GitLabMRResponse[]>(`/projects/${projectPath}/merge_requests?state=${stateParam}`);
|
||||
return data.map(mr => this.transformMergeRequest(mr));
|
||||
}
|
||||
|
||||
async updatePullRequest(
|
||||
owner: string,
|
||||
repo: string,
|
||||
number: number,
|
||||
options: { title?: string; body?: string }
|
||||
): Promise<PullRequest> {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
title: options.title,
|
||||
description: options.body,
|
||||
}),
|
||||
});
|
||||
|
||||
return this.transformMergeRequest(data);
|
||||
}
|
||||
|
||||
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
state_event: 'close',
|
||||
}),
|
||||
});
|
||||
|
||||
return this.transformMergeRequest(data);
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<GitHostUser> {
|
||||
interface GitLabUser {
|
||||
username: string;
|
||||
name: string;
|
||||
email: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
|
||||
const data = await this.fetch<GitLabUser>('/user');
|
||||
|
||||
return {
|
||||
username: data.username,
|
||||
name: data.name,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatar_url,
|
||||
};
|
||||
}
|
||||
|
||||
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
|
||||
const [headOwner, headRepoName] = headRepo.split('/');
|
||||
return `https://gitlab.com/${baseRepo}/-/merge_requests/new?merge_request[source_branch]=${headBranch}&merge_request[source_project]=${headOwner}/${headRepoName}&merge_request[target_branch]=${baseBranch}`;
|
||||
}
|
||||
|
||||
private transformMergeRequest(data: GitLabMRResponse): PullRequest {
|
||||
const state = data.state === 'merged' ? 'merged' : data.state === 'opened' ? 'open' : 'closed';
|
||||
|
||||
return {
|
||||
number: data.iid, // GitLab uses iid (internal id) for MRs
|
||||
title: data.title,
|
||||
body: data.description,
|
||||
state,
|
||||
headBranch: data.source_branch,
|
||||
baseBranch: data.target_branch,
|
||||
headRepo: data.source_project_id?.toString() || '',
|
||||
baseRepo: data.target_project_id?.toString() || '',
|
||||
url: data.web_url,
|
||||
createdAt: new Date(data.created_at),
|
||||
updatedAt: new Date(data.updated_at),
|
||||
author: data.author.username,
|
||||
mergeable: data.merge_status === 'can_be_merged',
|
||||
checks: this.transformPipeline(data),
|
||||
};
|
||||
}
|
||||
|
||||
private transformPipeline(data: GitLabMRResponse): PullRequestCheck[] | undefined {
|
||||
if (!data.pipeline) return undefined;
|
||||
|
||||
const mapConclusion = (status: string): PullRequestCheck['conclusion'] => {
|
||||
switch (status) {
|
||||
case 'success': return 'success';
|
||||
case 'failed': return 'failure';
|
||||
case 'canceled': return 'cancelled';
|
||||
case 'skipped': return 'skipped';
|
||||
default: return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
return [{
|
||||
name: 'Pipeline',
|
||||
status: data.pipeline.status === 'running' ? 'pending' :
|
||||
data.pipeline.status === 'success' ? 'success' : 'failure',
|
||||
conclusion: mapConclusion(data.pipeline.status),
|
||||
detailsUrl: data.pipeline.web_url,
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
} from './types';
|
||||
|
||||
interface GiteaPRResponse {
|
||||
id: number;
|
||||
number: number;
|
||||
state: string;
|
||||
title: string;
|
||||
body: string;
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: { login: string };
|
||||
head: { ref: string; repo: { full_name: string } };
|
||||
base: { ref: string; repo: { full_name: string } };
|
||||
mergeable?: boolean;
|
||||
merged?: boolean;
|
||||
}
|
||||
|
||||
export class GiteaProvider implements GitHostProvider {
|
||||
readonly name: string;
|
||||
readonly apiBaseUrl: string;
|
||||
|
||||
private config: GitHostConfig;
|
||||
private corsProxy?: string;
|
||||
|
||||
constructor(config: GitHostConfig, apiBaseUrl: string, name = 'Gitea', corsProxy?: string) {
|
||||
this.config = config;
|
||||
this.apiBaseUrl = apiBaseUrl;
|
||||
this.name = name;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const url = `${this.apiBaseUrl}${path}`;
|
||||
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
|
||||
|
||||
const response = await fetch(targetUrl, {
|
||||
...options,
|
||||
headers: {
|
||||
'Authorization': `token ${this.config.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`${this.name} API error (${response.status}): ${errorText}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async getRepository(owner: string, repo: string): Promise<GitRepository> {
|
||||
interface GiteaRepo {
|
||||
owner: { login: string };
|
||||
name: string;
|
||||
full_name: string;
|
||||
default_branch: string;
|
||||
clone_url: string;
|
||||
html_url: string;
|
||||
description: string;
|
||||
private: boolean;
|
||||
}
|
||||
|
||||
const data = await this.fetch<GiteaRepo>(`/repos/${owner}/${repo}`);
|
||||
|
||||
return {
|
||||
owner: data.owner.login,
|
||||
name: data.name,
|
||||
fullName: data.full_name,
|
||||
defaultBranch: data.default_branch,
|
||||
cloneUrl: data.clone_url,
|
||||
webUrl: data.html_url,
|
||||
description: data.description,
|
||||
isPrivate: data.private,
|
||||
};
|
||||
}
|
||||
|
||||
async canUserPush(owner: string, repo: string): Promise<boolean> {
|
||||
try {
|
||||
interface GiteaRepoWithPermissions {
|
||||
permissions?: { push?: boolean; admin?: boolean };
|
||||
}
|
||||
|
||||
const data = await this.fetch<GiteaRepoWithPermissions>(`/repos/${owner}/${repo}`);
|
||||
return data.permissions?.push === true || data.permissions?.admin === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async createFork(owner: string, repo: string): Promise<GitFork> {
|
||||
interface GiteaFork {
|
||||
owner: { login: string };
|
||||
name: string;
|
||||
full_name: string;
|
||||
clone_url: string;
|
||||
html_url: string;
|
||||
parent?: { full_name: string };
|
||||
}
|
||||
|
||||
const data = await this.fetch<GiteaFork>(`/repos/${owner}/${repo}/forks`, {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
return {
|
||||
owner: data.owner.login,
|
||||
name: data.name,
|
||||
fullName: data.full_name,
|
||||
cloneUrl: data.clone_url,
|
||||
webUrl: data.html_url,
|
||||
parentFullName: data.parent?.full_name || `${owner}/${repo}`,
|
||||
};
|
||||
}
|
||||
|
||||
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
|
||||
try {
|
||||
interface GiteaForkCheck {
|
||||
fork: boolean;
|
||||
owner: { login: string };
|
||||
name: string;
|
||||
full_name: string;
|
||||
clone_url: string;
|
||||
html_url: string;
|
||||
parent?: { full_name: string };
|
||||
}
|
||||
|
||||
const data = await this.fetch<GiteaForkCheck>(`/repos/${username}/${upstreamRepo}`);
|
||||
|
||||
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
|
||||
return {
|
||||
owner: data.owner.login,
|
||||
name: data.name,
|
||||
fullName: data.full_name,
|
||||
cloneUrl: data.clone_url,
|
||||
webUrl: data.html_url,
|
||||
parentFullName: data.parent.full_name,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async waitForFork(
|
||||
upstreamOwner: string,
|
||||
upstreamRepo: string,
|
||||
username: string,
|
||||
timeout = 30000
|
||||
): Promise<GitFork> {
|
||||
const startTime = Date.now();
|
||||
const pollInterval = 1000;
|
||||
|
||||
while (Date.now() - startTime < timeout) {
|
||||
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
|
||||
if (fork) {
|
||||
return fork;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, pollInterval));
|
||||
}
|
||||
|
||||
throw new Error('Timeout waiting for fork to be created');
|
||||
}
|
||||
|
||||
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
|
||||
const [baseOwner, baseRepo] = options.baseRepo.split('/');
|
||||
const [headOwner] = options.headRepo.split('/');
|
||||
|
||||
// Format head ref for cross-repo PR
|
||||
const head = headOwner !== baseOwner
|
||||
? `${headOwner}:${options.headBranch}`
|
||||
: options.headBranch;
|
||||
|
||||
const data = await this.fetch<GiteaPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
title: options.title,
|
||||
body: options.body || '',
|
||||
head,
|
||||
base: options.baseBranch,
|
||||
}),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
|
||||
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async listPullRequests(
|
||||
owner: string,
|
||||
repo: string,
|
||||
state: 'open' | 'closed' | 'all' = 'open'
|
||||
): Promise<PullRequest[]> {
|
||||
const data = await this.fetch<GiteaPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
|
||||
return data.map(pr => this.transformPullRequest(pr));
|
||||
}
|
||||
|
||||
async updatePullRequest(
|
||||
owner: string,
|
||||
repo: string,
|
||||
number: number,
|
||||
options: { title?: string; body?: string }
|
||||
): Promise<PullRequest> {
|
||||
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(options),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
|
||||
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ state: 'closed' }),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<GitHostUser> {
|
||||
interface GiteaUser {
|
||||
login: string;
|
||||
full_name: string;
|
||||
email: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
|
||||
const data = await this.fetch<GiteaUser>('/user');
|
||||
|
||||
return {
|
||||
username: data.login,
|
||||
name: data.full_name,
|
||||
email: data.email,
|
||||
avatarUrl: data.avatar_url,
|
||||
};
|
||||
}
|
||||
|
||||
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
|
||||
const baseUrl = this.apiBaseUrl.replace('/api/v1', '');
|
||||
const [headOwner, headRepoName] = headRepo.split('/');
|
||||
return `${baseUrl}/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}`;
|
||||
}
|
||||
|
||||
private transformPullRequest(data: {
|
||||
id: number;
|
||||
number: number;
|
||||
state: string;
|
||||
title: string;
|
||||
body: string;
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: { login: string };
|
||||
head: { ref: string; repo: { full_name: string } };
|
||||
base: { ref: string; repo: { full_name: string } };
|
||||
mergeable?: boolean;
|
||||
merged?: boolean;
|
||||
}): PullRequest {
|
||||
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
|
||||
|
||||
return {
|
||||
number: data.number,
|
||||
title: data.title,
|
||||
body: data.body,
|
||||
state,
|
||||
headBranch: data.head.ref,
|
||||
baseBranch: data.base.ref,
|
||||
headRepo: data.head.repo?.full_name || '',
|
||||
baseRepo: data.base.repo.full_name,
|
||||
url: data.html_url,
|
||||
createdAt: new Date(data.created_at),
|
||||
updatedAt: new Date(data.updated_at),
|
||||
author: data.user.login,
|
||||
mergeable: data.mergeable,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
import { NRelay1, type NostrEvent } from '@nostrify/nostrify';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
} from './types';
|
||||
|
||||
interface NostrSigner {
|
||||
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nostr Git provider implementing NIP-34 (git stuff)
|
||||
* Enables creating patches/PRs on Nostr git repositories
|
||||
*/
|
||||
export class NostrGitProvider implements GitHostProvider {
|
||||
readonly name = 'Nostr Git';
|
||||
readonly apiBaseUrl = ''; // Not applicable for Nostr
|
||||
|
||||
private relay: NRelay1;
|
||||
private signer: NostrSigner;
|
||||
private pubkey: string;
|
||||
private relayUrls: string[];
|
||||
|
||||
constructor(config: GitHostConfig & { signer: NostrSigner; pubkey: string; relayUrls: string[] }) {
|
||||
this.signer = config.signer;
|
||||
this.pubkey = config.pubkey;
|
||||
this.relayUrls = config.relayUrls;
|
||||
|
||||
// For Nostr git, we need to publish to the repository's designated relays
|
||||
// The relay will be set dynamically when we know which repo we're working with
|
||||
this.relay = new NRelay1('wss://relay.nostr.band'); // Default, will be changed
|
||||
}
|
||||
|
||||
private async queryRepo(owner: string, repo: string): Promise<NostrEvent> {
|
||||
// Query for repository announcement (kind 30617)
|
||||
// d tag is the repo-id (usually kebab-case short name)
|
||||
const events = await this.relay.query([
|
||||
{
|
||||
kinds: [30617],
|
||||
authors: [owner], // owner is the pubkey
|
||||
'#d': [repo], // repo is the d tag identifier
|
||||
limit: 1,
|
||||
}
|
||||
]) as NostrEvent[];
|
||||
|
||||
if (events.length === 0) {
|
||||
throw new Error(`Repository not found: ${owner}/${repo}`);
|
||||
}
|
||||
|
||||
return events[0];
|
||||
}
|
||||
|
||||
async getRepository(owner: string, repo: string): Promise<GitRepository> {
|
||||
const event = await this.queryRepo(owner, repo);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Update relay to use repository's designated relays
|
||||
if (repoAnn.relays.length > 0) {
|
||||
this.relayUrls = repoAnn.relays;
|
||||
this.relay = new NRelay1(repoAnn.relays[0]);
|
||||
}
|
||||
|
||||
return {
|
||||
owner,
|
||||
name: repoAnn.name || repo,
|
||||
fullName: `${owner}/${repo}`,
|
||||
defaultBranch: 'main', // Nostr git doesn't specify, assume main
|
||||
cloneUrl: repoAnn.httpsCloneUrls[0] || '',
|
||||
webUrl: repoAnn.webUrls[0] || '',
|
||||
description: repoAnn.description,
|
||||
isPrivate: false, // All Nostr repos are public
|
||||
};
|
||||
}
|
||||
|
||||
async canUserPush(owner: string, repo: string): Promise<boolean> {
|
||||
// In Nostr git, anyone can submit patches (kind 1617)
|
||||
// But only maintainers can apply them
|
||||
// Check if current user is listed as a maintainer
|
||||
const event = await this.queryRepo(owner, repo);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Repo owner is always a maintainer
|
||||
const isMaintainer = owner === this.pubkey || parsed.maintainers.includes(this.pubkey);
|
||||
return isMaintainer;
|
||||
}
|
||||
|
||||
async createFork(owner: string, repo: string): Promise<GitFork> {
|
||||
// In Nostr git, there's no explicit "fork" concept
|
||||
// Users submit patches to the original repo
|
||||
// For compatibility with the PR flow, we return a "virtual fork"
|
||||
const repoEvent = await this.queryRepo(owner, repo);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// The "fork" is actually just the user's local copy
|
||||
// We'll use this to track that patches come from the user
|
||||
return {
|
||||
owner: this.pubkey,
|
||||
name: repo,
|
||||
fullName: `${this.pubkey}/${repo}`,
|
||||
cloneUrl: parsed.httpsCloneUrls[0] || '',
|
||||
webUrl: parsed.webUrls[0] || '',
|
||||
parentFullName: `${owner}/${repo}`,
|
||||
};
|
||||
}
|
||||
|
||||
async getFork(_upstreamOwner: string, _upstreamRepo: string, _username: string): Promise<GitFork | null> {
|
||||
// Nostr git doesn't have forks - patches are submitted directly
|
||||
// Return null to indicate no fork exists
|
||||
return null;
|
||||
}
|
||||
|
||||
async waitForFork(upstreamOwner: string, upstreamRepo: string, _username: string, _timeout = 10000): Promise<GitFork> {
|
||||
// Create a virtual fork immediately
|
||||
return this.createFork(upstreamOwner, upstreamRepo);
|
||||
}
|
||||
|
||||
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
|
||||
// In Nostr git, a "pull request" is a patch event (kind 1617)
|
||||
// The patch content should be the output of `git format-patch`
|
||||
|
||||
const [owner, repo] = options.baseRepo.split('/');
|
||||
const repoEvent = await this.queryRepo(owner, repo);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get the earliest unique commit (euc) for the repository
|
||||
const euc = parsed.earliestCommit;
|
||||
|
||||
// Create patch content from the provided body or generate a simple patch description
|
||||
const patchContent = options.body ||
|
||||
`Patch proposal: ${options.title}\n\nFrom: ${options.headBranch}\nTo: ${options.baseBranch}`;
|
||||
|
||||
// Create patch event (kind 1617)
|
||||
const patchEvent = await this.signer.signEvent({
|
||||
kind: 1617,
|
||||
content: patchContent,
|
||||
tags: [
|
||||
['a', `30617:${owner}:${repo}`], // Reference to repository announcement
|
||||
['p', owner], // Repository owner
|
||||
['t', 'root'], // Root patch in series
|
||||
['t', 'root-revision'], // First patch in a revision
|
||||
['subject', options.title], // Use subject tag for title
|
||||
// Optional: Add r tag for euc if available
|
||||
...(euc ? [['r', euc]] : []),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Publish to repository's designated relays
|
||||
await this.relay.event(patchEvent);
|
||||
|
||||
// Return a PullRequest-compatible object
|
||||
return {
|
||||
number: parseInt(patchEvent.id.slice(0, 8), 16), // Use first 8 chars of event ID as number
|
||||
title: options.title,
|
||||
body: options.body,
|
||||
state: 'open',
|
||||
headBranch: options.headBranch,
|
||||
baseBranch: options.baseBranch,
|
||||
headRepo: options.headRepo,
|
||||
baseRepo: options.baseRepo,
|
||||
url: `nostr:${patchEvent.id}`, // Nostr event reference
|
||||
createdAt: new Date(patchEvent.created_at * 1000),
|
||||
updatedAt: new Date(patchEvent.created_at * 1000),
|
||||
author: this.pubkey,
|
||||
};
|
||||
}
|
||||
|
||||
async getPullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
|
||||
// Query for patch event by converting number back to event ID
|
||||
// This is a limitation - we'd need to store the mapping or query differently
|
||||
throw new Error('Getting specific patches by number is not yet implemented for Nostr git');
|
||||
}
|
||||
|
||||
async listPullRequests(owner: string, repo: string, _state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequest[]> {
|
||||
// Query for patch events (kind 1617) referencing this repository
|
||||
const events = await this.relay.query([
|
||||
{
|
||||
kinds: [1617],
|
||||
'#a': [`30617:${owner}:${repo}`],
|
||||
'#t': ['root'], // Only root patches, not replies
|
||||
limit: 50,
|
||||
}
|
||||
]);
|
||||
|
||||
// For state filtering, we'd need to check status events (kind 1630-1633)
|
||||
// For now, return all as 'open'
|
||||
return events.map(event => ({
|
||||
number: parseInt(event.id.slice(0, 8), 16),
|
||||
title: event.tags.find((t: string[]) => t[0] === 'subject')?.[1] || 'Untitled patch',
|
||||
body: event.content,
|
||||
state: 'open' as const,
|
||||
headBranch: 'unknown', // Not stored in NIP-34
|
||||
baseBranch: 'unknown', // Not stored in NIP-34
|
||||
headRepo: `${event.pubkey}/${repo}`,
|
||||
baseRepo: `${owner}/${repo}`,
|
||||
url: `nostr:${event.id}`,
|
||||
createdAt: new Date(event.created_at * 1000),
|
||||
updatedAt: new Date(event.created_at * 1000),
|
||||
author: event.pubkey,
|
||||
}));
|
||||
}
|
||||
|
||||
async updatePullRequest(_owner: string, _repo: string, _number: number, _options: { title?: string; body?: string }): Promise<PullRequest> {
|
||||
// In Nostr git, you can't edit events - you'd create a new revision
|
||||
throw new Error('Updating patches is not supported - create a new revision instead');
|
||||
}
|
||||
|
||||
async closePullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
|
||||
// To close a patch, publish a status event (kind 1632 - Closed)
|
||||
throw new Error('Closing patches via status events is not yet implemented');
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<GitHostUser> {
|
||||
// In Nostr, we can query the user's profile (kind 0)
|
||||
const profiles = await this.relay.query([
|
||||
{
|
||||
kinds: [0],
|
||||
authors: [this.pubkey],
|
||||
limit: 1,
|
||||
}
|
||||
]);
|
||||
|
||||
if (profiles.length > 0) {
|
||||
const profile = JSON.parse(profiles[0].content);
|
||||
return {
|
||||
username: profile.name || this.pubkey.slice(0, 8),
|
||||
name: profile.display_name || profile.name,
|
||||
email: profile.nip05,
|
||||
avatarUrl: profile.picture,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
username: this.pubkey.slice(0, 8),
|
||||
};
|
||||
}
|
||||
|
||||
getCompareUrl(_baseRepo: string, _baseBranch: string, _headRepo: string, _headBranch: string): string {
|
||||
// Nostr git doesn't have a web compare view
|
||||
// Could potentially link to a Nostr client that displays patches
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
export * from './types';
|
||||
export { GitHubProvider } from './GitHubProvider';
|
||||
export { GitLabProvider } from './GitLabProvider';
|
||||
export { GiteaProvider } from './GiteaProvider';
|
||||
export { NostrGitProvider } from './NostrGitProvider';
|
||||
|
||||
import { GitHubProvider } from './GitHubProvider';
|
||||
import { GitLabProvider } from './GitLabProvider';
|
||||
import { GiteaProvider } from './GiteaProvider';
|
||||
import { NostrGitProvider } from './NostrGitProvider';
|
||||
import { detectGitHost } from './types';
|
||||
import type { GitHostProvider, GitHostConfig } from './types';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Create a Git host provider instance based on the repository URL
|
||||
*/
|
||||
interface NostrSigner {
|
||||
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
|
||||
}
|
||||
|
||||
export function createGitHostProvider(
|
||||
url: string,
|
||||
config: GitHostConfig & { signer?: NostrSigner; pubkey?: string; relayUrls?: string[] },
|
||||
corsProxy?: string
|
||||
): GitHostProvider | null {
|
||||
const hostType = detectGitHost(url);
|
||||
|
||||
switch (hostType) {
|
||||
case 'github':
|
||||
return new GitHubProvider(config, corsProxy);
|
||||
|
||||
case 'gitlab':
|
||||
return new GitLabProvider(config, corsProxy);
|
||||
|
||||
case 'codeberg':
|
||||
return new GiteaProvider(config, 'https://codeberg.org/api/v1', 'Codeberg', corsProxy);
|
||||
|
||||
case 'gitea':
|
||||
// Extract API URL from repository URL
|
||||
try {
|
||||
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
|
||||
const apiUrl = `${parsed.protocol}//${parsed.hostname}/api/v1`;
|
||||
return new GiteaProvider(config, apiUrl, 'Gitea', corsProxy);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
case 'nostr':
|
||||
// Nostr git requires signer and pubkey
|
||||
if (!config.signer || !config.pubkey) {
|
||||
throw new Error('Nostr git requires signer and pubkey in config');
|
||||
}
|
||||
return new NostrGitProvider({
|
||||
token: config.token,
|
||||
signer: config.signer,
|
||||
pubkey: config.pubkey,
|
||||
relayUrls: config.relayUrls || ['wss://relay.nostr.band'],
|
||||
});
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
/**
|
||||
* Git host provider abstraction for PR/MR operations
|
||||
*/
|
||||
|
||||
export interface GitHostUser {
|
||||
username: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
export interface GitRepository {
|
||||
owner: string;
|
||||
name: string;
|
||||
fullName: string; // e.g. "owner/repo"
|
||||
defaultBranch: string;
|
||||
cloneUrl: string;
|
||||
webUrl: string;
|
||||
description?: string;
|
||||
isPrivate: boolean;
|
||||
}
|
||||
|
||||
export interface GitFork {
|
||||
owner: string;
|
||||
name: string;
|
||||
fullName: string;
|
||||
cloneUrl: string;
|
||||
webUrl: string;
|
||||
parentFullName: string; // The upstream repo
|
||||
}
|
||||
|
||||
export interface PullRequest {
|
||||
number: number;
|
||||
title: string;
|
||||
body?: string;
|
||||
state: 'open' | 'closed' | 'merged';
|
||||
headBranch: string;
|
||||
baseBranch: string;
|
||||
headRepo: string; // Full name of head repo (fork)
|
||||
baseRepo: string; // Full name of base repo (upstream)
|
||||
url: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
author: string;
|
||||
mergeable?: boolean;
|
||||
checks?: PullRequestCheck[];
|
||||
}
|
||||
|
||||
export interface PullRequestCheck {
|
||||
name: string;
|
||||
status: 'pending' | 'success' | 'failure' | 'cancelled';
|
||||
conclusion?: 'success' | 'failure' | 'neutral' | 'cancelled' | 'skipped' | 'timed_out' | 'action_required';
|
||||
detailsUrl?: string;
|
||||
}
|
||||
|
||||
export interface CreatePullRequestOptions {
|
||||
title: string;
|
||||
body?: string;
|
||||
headBranch: string;
|
||||
baseBranch: string;
|
||||
headRepo: string; // For cross-repo PRs (from fork)
|
||||
baseRepo: string; // The upstream repo
|
||||
maintainerCanModify?: boolean;
|
||||
}
|
||||
|
||||
export interface GitHostConfig {
|
||||
token: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract interface for Git hosting providers (GitHub, GitLab, Gitea, etc.)
|
||||
*/
|
||||
export interface GitHostProvider {
|
||||
readonly name: string;
|
||||
readonly apiBaseUrl: string;
|
||||
|
||||
// Repository operations
|
||||
getRepository(owner: string, repo: string): Promise<GitRepository>;
|
||||
canUserPush(owner: string, repo: string): Promise<boolean>;
|
||||
|
||||
// Fork operations
|
||||
createFork(owner: string, repo: string): Promise<GitFork>;
|
||||
getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null>;
|
||||
waitForFork(upstreamOwner: string, upstreamRepo: string, username: string, timeout?: number): Promise<GitFork>;
|
||||
|
||||
// Pull request operations
|
||||
createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest>;
|
||||
getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
|
||||
listPullRequests(owner: string, repo: string, state?: 'open' | 'closed' | 'all'): Promise<PullRequest[]>;
|
||||
updatePullRequest(owner: string, repo: string, number: number, options: { title?: string; body?: string }): Promise<PullRequest>;
|
||||
closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
|
||||
|
||||
// User operations
|
||||
getCurrentUser(): Promise<GitHostUser>;
|
||||
|
||||
// Utility
|
||||
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect Git host from repository URL
|
||||
*/
|
||||
export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'codeberg' | 'nostr' | 'unknown' {
|
||||
try {
|
||||
// Check for Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
|
||||
if (url.startsWith('nostr://')) {
|
||||
return 'nostr';
|
||||
}
|
||||
|
||||
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
|
||||
const hostname = parsed.hostname.toLowerCase();
|
||||
|
||||
if (hostname === 'github.com') return 'github';
|
||||
if (hostname === 'gitlab.com') return 'gitlab';
|
||||
if (hostname === 'codeberg.org') return 'codeberg';
|
||||
if (hostname.includes('gitea')) return 'gitea';
|
||||
|
||||
return 'unknown';
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse repository owner and name from URL
|
||||
*/
|
||||
export function parseRepoUrl(url: string): { owner: string; repo: string } | null {
|
||||
try {
|
||||
// Handle Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
|
||||
if (url.startsWith('nostr://')) {
|
||||
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
|
||||
if (match) {
|
||||
let owner = match[1]; // pubkey in hex or npub
|
||||
const repo = match[2]; // repo-id (d tag)
|
||||
|
||||
// Convert npub to hex if needed
|
||||
if (owner.startsWith('npub1')) {
|
||||
try {
|
||||
const decoded = nip19.decode(owner);
|
||||
if (decoded.type === 'npub') {
|
||||
owner = decoded.data;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to decode npub:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
owner, // pubkey in hex
|
||||
repo, // repo-id (d tag)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Handle git@ URLs
|
||||
const normalized = url.replace(/^git@([^:]+):/, 'https://$1/').replace(/\.git$/, '');
|
||||
const parsed = new URL(normalized);
|
||||
const parts = parsed.pathname.split('/').filter(Boolean);
|
||||
|
||||
if (parts.length >= 2) {
|
||||
return {
|
||||
owner: parts[0],
|
||||
repo: parts[1],
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format repository URL for display
|
||||
*/
|
||||
export function formatRepoUrl(url: string): string {
|
||||
const parsed = parseRepoUrl(url);
|
||||
if (parsed) {
|
||||
return `${parsed.owner}/${parsed.repo}`;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ProjectTitleMenu } from '@/components/ProjectTitleMenu';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
@@ -36,7 +35,6 @@ export function ProjectView() {
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
|
||||
|
||||
@@ -164,7 +162,6 @@ export function ProjectView() {
|
||||
projectName={project.name}
|
||||
onNewChat={handleNewChat}
|
||||
onGitHistory={() => setGitHistoryOpen(true)}
|
||||
onGitDialog={() => setGitDialogOpen(true)}
|
||||
onDeploy={() => setDeployDialogOpen(true)}
|
||||
onDuplicate={() => setDuplicateDialogOpen(true)}
|
||||
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
||||
@@ -309,11 +306,6 @@ export function ProjectView() {
|
||||
onOpenChange={setIsProjectDetailsOpen}
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
<GitDialog
|
||||
projectId={project.id}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
<GitHistoryDialog
|
||||
projectId={project.id}
|
||||
open={gitHistoryOpen}
|
||||
@@ -387,7 +379,6 @@ export function ProjectView() {
|
||||
projectName={project.name}
|
||||
onNewChat={handleNewChat}
|
||||
onGitHistory={() => setGitHistoryOpen(true)}
|
||||
onGitDialog={() => setGitDialogOpen(true)}
|
||||
onDeploy={() => setDeployDialogOpen(true)}
|
||||
onDuplicate={() => setDuplicateDialogOpen(true)}
|
||||
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
||||
@@ -478,11 +469,6 @@ export function ProjectView() {
|
||||
onOpenChange={setIsProjectDetailsOpen}
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
<GitDialog
|
||||
projectId={project.id}
|
||||
open={gitDialogOpen}
|
||||
onOpenChange={setGitDialogOpen}
|
||||
/>
|
||||
<GitHistoryDialog
|
||||
projectId={project.id}
|
||||
open={gitHistoryOpen}
|
||||
|
||||
Reference in new issue
Block a user