mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add upstream PR contribution system
Implements a complete workflow for non-technical users to contribute to open source projects: **New Features:** - ContributeButton component shows "Propose Changes" when project has upstream remote - ContributeWizard guides users through 5-step contribution process - PRStatusBadge shows existing PR status for current branch - Automatic forking when user lacks push permissions - OAuth and PAT authentication for GitHub, GitLab, Gitea/Codeberg - Pre-submission validation (type check + build) - Automatic remote configuration (upstream/origin) - PR creation and updates via Git host APIs **Git Host Abstraction:** - GitHostProvider interface for platform-agnostic operations - GitHubProvider with GitHub REST API v3 - GitLabProvider with GitLab REST API v4 - GiteaProvider for Gitea/Forgejo/Codeberg instances - Auto-detection of Git host from repository URL **Components:** - components/contribute/ContributeButton.tsx - Entry point button - components/contribute/ContributeWizard.tsx - Multi-step wizard UI - components/contribute/AuthStep.tsx - Authentication flow - components/contribute/DiffView.tsx - Changed files review - components/contribute/PRStatusBadge.tsx - PR status display **Hooks:** - hooks/useContribute.ts - Main contribution workflow orchestration **Context Updates:** - Extended GitSettings to include hostTokens for API authentication - Updated GitHubOAuth to save tokens in both formats **Integration:** - Added to ProjectView header (mobile and desktop) - Integrated with existing Git workflow - Works with existing OAuth callback system **Documentation:** - CONTRIBUTING_GUIDE.md with user guide and developer docs The system handles the entire fork → branch → commit → push → PR flow transparently, making open source contribution accessible to users without Git knowledge.
This commit is contained in:
1 parent
4226159f5d
commit
add685257b
18 files changed
+2670
-5
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
|
||||
|
||||
@@ -9,6 +9,7 @@ interface GitSettingsProviderProps {
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
@@ -85,6 +86,39 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
}));
|
||||
};
|
||||
|
||||
const addHostToken = (host: string, token: GitHostToken) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: token,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeHostToken = (host: string) => {
|
||||
setSettings(prev => {
|
||||
const { [host]: removed, ...rest } = prev.hostTokens;
|
||||
return {
|
||||
...prev,
|
||||
hostTokens: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
hostTokens: {
|
||||
...prev.hostTokens,
|
||||
[host]: {
|
||||
...prev.hostTokens[host],
|
||||
...token,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.credentials).length > 0;
|
||||
|
||||
const contextValue: GitSettingsContextType = {
|
||||
@@ -93,6 +127,9 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
addCredential,
|
||||
removeCredential,
|
||||
updateCredential,
|
||||
addHostToken,
|
||||
removeHostToken,
|
||||
updateHostToken,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
|
||||
import { InfoIcon, KeyRound, ExternalLink } from 'lucide-react';
|
||||
|
||||
interface AuthStepProps {
|
||||
host: string;
|
||||
onComplete: (host: string, token: string, username?: string) => void;
|
||||
}
|
||||
|
||||
export function AuthStep({ host, onComplete }: AuthStepProps) {
|
||||
const { isOAuthConfigured, initiateOAuth } = useGitHubOAuth();
|
||||
const [token, setToken] = useState('');
|
||||
const [username, setUsername] = useState('');
|
||||
|
||||
const handleTokenSubmit = () => {
|
||||
if (!token.trim()) return;
|
||||
onComplete(host, token.trim(), username.trim() || undefined);
|
||||
};
|
||||
|
||||
const getTokenInstructions = () => {
|
||||
switch (host) {
|
||||
case 'github.com':
|
||||
return {
|
||||
url: 'https://github.com/settings/tokens/new',
|
||||
scopes: 'public_repo (for public repositories)',
|
||||
steps: [
|
||||
'Click "Generate new token (classic)"',
|
||||
'Set a descriptive note like "Shakespeare Contributions"',
|
||||
'Select the "public_repo" scope',
|
||||
'Click "Generate token" at the bottom',
|
||||
'Copy the token and paste it below',
|
||||
],
|
||||
};
|
||||
case 'gitlab.com':
|
||||
return {
|
||||
url: 'https://gitlab.com/-/profile/personal_access_tokens',
|
||||
scopes: 'api or write_repository',
|
||||
steps: [
|
||||
'Enter a token name like "Shakespeare"',
|
||||
'Select the "api" or "write_repository" scope',
|
||||
'Click "Create personal access token"',
|
||||
'Copy the token and paste it below',
|
||||
],
|
||||
};
|
||||
case 'codeberg.org':
|
||||
return {
|
||||
url: 'https://codeberg.org/user/settings/applications',
|
||||
scopes: 'repo',
|
||||
steps: [
|
||||
'Go to Applications > Access Tokens',
|
||||
'Click "Generate New Token"',
|
||||
'Enter a description like "Shakespeare"',
|
||||
'Select the "repo" permission',
|
||||
'Click "Generate Token"',
|
||||
'Copy the token and paste it below',
|
||||
],
|
||||
};
|
||||
default:
|
||||
return {
|
||||
url: `https://${host}/user/settings/applications`,
|
||||
scopes: 'repo or write access',
|
||||
steps: [
|
||||
'Navigate to your user settings',
|
||||
'Find the access tokens or applications section',
|
||||
'Create a new token with repository write permissions',
|
||||
'Copy the token and paste it below',
|
||||
],
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const instructions = getTokenInstructions();
|
||||
const showOAuth = host === 'github.com' && isOAuthConfigured;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Connect to {host}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
To propose changes, you need to authenticate with {host}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue={showOAuth ? 'oauth' : 'token'}>
|
||||
{showOAuth && (
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="oauth">Quick Connect</TabsTrigger>
|
||||
<TabsTrigger value="token">Access Token</TabsTrigger>
|
||||
</TabsList>
|
||||
)}
|
||||
|
||||
{showOAuth && (
|
||||
<TabsContent value="oauth" className="space-y-4 mt-4">
|
||||
<Alert>
|
||||
<InfoIcon className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
The fastest way to connect. You'll be redirected to {host} to authorize Shakespeare.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Button onClick={initiateOAuth} className="w-full">
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Connect with {host === 'github.com' ? 'GitHub' : host}
|
||||
</Button>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
<TabsContent value="token" className="space-y-4 mt-4">
|
||||
<Alert>
|
||||
<InfoIcon className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Create a personal access token on {host} with the following scope: <strong>{instructions.scopes}</strong>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="space-y-3 p-4 bg-muted rounded-lg">
|
||||
<p className="text-sm font-medium">How to create a token:</p>
|
||||
<ol className="text-sm space-y-2 list-decimal list-inside">
|
||||
{instructions.steps.map((step, index) => (
|
||||
<li key={index}>{step}</li>
|
||||
))}
|
||||
</ol>
|
||||
<a
|
||||
href={instructions.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-primary hover:underline inline-flex items-center gap-1"
|
||||
>
|
||||
Open {host} token settings
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Username (optional)</Label>
|
||||
<Input
|
||||
id="username"
|
||||
placeholder="your-username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your username on {host} (helpful but not required)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="token">Personal Access Token</Label>
|
||||
<Input
|
||||
id="token"
|
||||
type="password"
|
||||
placeholder="ghp_xxxxxxxxxxxx"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<KeyRound className="inline h-3 w-3 mr-1" />
|
||||
Your token is stored locally and never sent to Shakespeare servers
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button onClick={handleTokenSubmit} disabled={!token.trim()} className="w-full">
|
||||
Connect
|
||||
</Button>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ContributeWizard } from './ContributeWizard';
|
||||
import { GitPullRequest } from 'lucide-react';
|
||||
import { detectGitHost } from '@/lib/git-hosts';
|
||||
|
||||
interface ContributeButtonProps {
|
||||
projectDir: string;
|
||||
variant?: 'default' | 'outline' | 'ghost';
|
||||
size?: 'default' | 'sm' | 'lg' | 'icon';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ContributeButton({ projectDir, variant = 'outline', size = 'default', className }: ContributeButtonProps) {
|
||||
const { git } = useGit();
|
||||
const [showWizard, setShowWizard] = useState(false);
|
||||
const [canContribute, setCanContribute] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const checkContributeAvailable = async () => {
|
||||
try {
|
||||
// Check if there's a remote with a supported host
|
||||
const upstreamUrl = await git.getRemoteURL(projectDir, 'upstream');
|
||||
const originUrl = await git.getRemoteURL(projectDir, 'origin');
|
||||
const remoteUrl = upstreamUrl || originUrl;
|
||||
|
||||
if (remoteUrl) {
|
||||
const hostType = detectGitHost(remoteUrl);
|
||||
setCanContribute(hostType !== 'unknown');
|
||||
} else {
|
||||
setCanContribute(false);
|
||||
}
|
||||
} catch {
|
||||
setCanContribute(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkContributeAvailable();
|
||||
}, [git, projectDir]);
|
||||
|
||||
if (!canContribute) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant={variant}
|
||||
size={size}
|
||||
onClick={() => setShowWizard(true)}
|
||||
className={className}
|
||||
>
|
||||
<GitPullRequest className="h-4 w-4 mr-2" />
|
||||
Propose Changes
|
||||
</Button>
|
||||
|
||||
<ContributeWizard
|
||||
projectDir={projectDir}
|
||||
open={showWizard}
|
||||
onOpenChange={setShowWizard}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useContribute } from '@/hooks/useContribute';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { AuthStep } from './AuthStep';
|
||||
import { DiffView } from './DiffView';
|
||||
import { AlertCircle, CheckCircle2, Loader2, GitFork, Upload, GitPullRequest } from 'lucide-react';
|
||||
import type { PullRequest } from '@/lib/git-hosts';
|
||||
|
||||
interface ContributeWizardProps {
|
||||
projectDir: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onComplete?: (pr: PullRequest) => void;
|
||||
}
|
||||
|
||||
export function ContributeWizard({ projectDir, open, onOpenChange, onComplete }: ContributeWizardProps) {
|
||||
const { git } = useGit();
|
||||
const { mutateAsync: buildProject } = useBuildProject();
|
||||
const { needsAuth, authenticate, contribute, isLoading, error, step, message, pr } = useContribute();
|
||||
|
||||
const [wizardStep, setWizardStep] = useState<'auth' | 'review' | 'branch' | 'checks' | 'result'>('auth');
|
||||
const [authStatus, setAuthStatus] = useState<{ needsAuth: boolean; host?: string; url?: string } | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
branchName: '',
|
||||
commitMessage: '',
|
||||
prTitle: '',
|
||||
prBody: '',
|
||||
maintainerCanModify: true,
|
||||
});
|
||||
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
|
||||
const [buildPassed, setBuildPassed] = useState(false);
|
||||
const [checkingBuild, setCheckingBuild] = useState(false);
|
||||
|
||||
// Check auth status when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
needsAuth(projectDir).then(status => {
|
||||
setAuthStatus(status);
|
||||
if (!status.needsAuth) {
|
||||
setWizardStep('review');
|
||||
} else {
|
||||
setWizardStep('auth');
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [open, projectDir, needsAuth]);
|
||||
|
||||
// Reset state when dialog closes
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setWizardStep('auth');
|
||||
setFormData({
|
||||
branchName: '',
|
||||
commitMessage: '',
|
||||
prTitle: '',
|
||||
prBody: '',
|
||||
maintainerCanModify: true,
|
||||
});
|
||||
setValidationErrors({});
|
||||
setBuildPassed(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const handleAuthComplete = (host: string, token: string, username?: string) => {
|
||||
authenticate(host, token, username);
|
||||
setWizardStep('review');
|
||||
};
|
||||
|
||||
const handleReviewNext = () => {
|
||||
setWizardStep('branch');
|
||||
};
|
||||
|
||||
const validateBranchForm = () => {
|
||||
const errors: Record<string, string> = {};
|
||||
|
||||
if (!formData.branchName.trim()) {
|
||||
errors.branchName = 'Branch name is required';
|
||||
} else if (!/^[a-zA-Z0-9._\/-]+$/.test(formData.branchName)) {
|
||||
errors.branchName = 'Invalid branch name. Use only letters, numbers, dots, dashes, and slashes.';
|
||||
}
|
||||
|
||||
if (!formData.commitMessage.trim()) {
|
||||
errors.commitMessage = 'Commit message is required';
|
||||
}
|
||||
|
||||
if (!formData.prTitle.trim()) {
|
||||
errors.prTitle = 'Pull request title is required';
|
||||
}
|
||||
|
||||
setValidationErrors(errors);
|
||||
return Object.keys(errors).length === 0;
|
||||
};
|
||||
|
||||
const handleBranchNext = async () => {
|
||||
if (!validateBranchForm()) return;
|
||||
|
||||
setWizardStep('checks');
|
||||
|
||||
// Run build check
|
||||
setCheckingBuild(true);
|
||||
try {
|
||||
await buildProject(projectDir);
|
||||
setBuildPassed(true);
|
||||
} catch (error) {
|
||||
setBuildPassed(false);
|
||||
setValidationErrors(prev => ({
|
||||
...prev,
|
||||
build: 'Build failed. Please fix errors before submitting.',
|
||||
}));
|
||||
} finally {
|
||||
setCheckingBuild(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!buildPassed) {
|
||||
setValidationErrors(prev => ({
|
||||
...prev,
|
||||
build: 'Build must pass before submitting',
|
||||
}));
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await contribute({
|
||||
projectDir,
|
||||
branchName: formData.branchName,
|
||||
commitMessage: formData.commitMessage,
|
||||
prTitle: formData.prTitle,
|
||||
prBody: formData.prBody,
|
||||
maintainerCanModify: formData.maintainerCanModify,
|
||||
});
|
||||
|
||||
if (result) {
|
||||
setWizardStep('result');
|
||||
onComplete?.(result);
|
||||
}
|
||||
};
|
||||
|
||||
const getProgress = () => {
|
||||
switch (wizardStep) {
|
||||
case 'auth': return 20;
|
||||
case 'review': return 40;
|
||||
case 'branch': return 60;
|
||||
case 'checks': return 80;
|
||||
case 'result': return 100;
|
||||
default: return 0;
|
||||
}
|
||||
};
|
||||
|
||||
const getStepIcon = () => {
|
||||
if (step === 'fork') return <GitFork className="h-5 w-5" />;
|
||||
if (step === 'push') return <Upload className="h-5 w-5" />;
|
||||
if (step === 'pr') return <GitPullRequest className="h-5 w-5" />;
|
||||
if (step === 'complete') return <CheckCircle2 className="h-5 w-5" />;
|
||||
return <Loader2 className="h-5 w-5 animate-spin" />;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Propose Changes</DialogTitle>
|
||||
<DialogDescription>
|
||||
Submit your changes to the original project
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Progress value={getProgress()} className="mb-4" />
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{wizardStep === 'auth' && authStatus && (
|
||||
<AuthStep
|
||||
host={authStatus.host!}
|
||||
onComplete={handleAuthComplete}
|
||||
/>
|
||||
)}
|
||||
|
||||
{wizardStep === 'review' && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Review Your Changes</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Review the changes you're proposing to submit
|
||||
</p>
|
||||
</div>
|
||||
<DiffView projectDir={projectDir} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{wizardStep === 'branch' && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Branch & Commit Details</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Describe your changes and create a branch
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="branch-name">Branch Name</Label>
|
||||
<Input
|
||||
id="branch-name"
|
||||
placeholder="my-feature-branch"
|
||||
value={formData.branchName}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, branchName: e.target.value }))}
|
||||
/>
|
||||
{validationErrors.branchName && (
|
||||
<p className="text-sm text-destructive">{validationErrors.branchName}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="commit-message">Commit Message</Label>
|
||||
<Input
|
||||
id="commit-message"
|
||||
placeholder="Brief description of your changes"
|
||||
value={formData.commitMessage}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, commitMessage: e.target.value }))}
|
||||
/>
|
||||
{validationErrors.commitMessage && (
|
||||
<p className="text-sm text-destructive">{validationErrors.commitMessage}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-title">Pull Request Title</Label>
|
||||
<Input
|
||||
id="pr-title"
|
||||
placeholder="Summary of your contribution"
|
||||
value={formData.prTitle}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, prTitle: e.target.value }))}
|
||||
/>
|
||||
{validationErrors.prTitle && (
|
||||
<p className="text-sm text-destructive">{validationErrors.prTitle}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pr-body">Description (optional)</Label>
|
||||
<Textarea
|
||||
id="pr-body"
|
||||
placeholder="Detailed description of what changed and why..."
|
||||
value={formData.prBody}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, prBody: e.target.value }))}
|
||||
rows={5}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="maintainer-edit"
|
||||
checked={formData.maintainerCanModify}
|
||||
onCheckedChange={(checked) =>
|
||||
setFormData(prev => ({ ...prev, maintainerCanModify: checked === true }))
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="maintainer-edit" className="text-sm font-normal cursor-pointer">
|
||||
Allow maintainers to edit your changes
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{wizardStep === 'checks' && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2">Pre-submission Checks</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Validating your changes before submission
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<span className="text-sm">Type Check & Build</span>
|
||||
{checkingBuild ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||
) : buildPassed ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<AlertCircle className="h-4 w-4 text-destructive" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{validationErrors.build && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{validationErrors.build}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{wizardStep === 'result' && pr && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2 text-green-600">
|
||||
<CheckCircle2 className="h-6 w-6" />
|
||||
<h3 className="text-lg font-semibold">Pull Request Created!</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 p-4 bg-muted rounded-lg">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">PR #{pr.number}:</span> {pr.title}
|
||||
</p>
|
||||
<a
|
||||
href={pr.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-primary hover:underline"
|
||||
>
|
||||
View Pull Request →
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && message && (
|
||||
<div className="flex items-center gap-2 p-3 bg-muted rounded-lg">
|
||||
{getStepIcon()}
|
||||
<span className="text-sm">{message}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{wizardStep === 'auth' && authStatus?.needsAuth && (
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{wizardStep === 'review' && (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleReviewNext}>
|
||||
Continue
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{wizardStep === 'branch' && (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setWizardStep('review')}>
|
||||
Back
|
||||
</Button>
|
||||
<Button onClick={handleBranchNext}>
|
||||
Run Checks
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{wizardStep === 'checks' && (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setWizardStep('branch')}>
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={!buildPassed || isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Submitting...
|
||||
</>
|
||||
) : (
|
||||
'Submit Pull Request'
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{wizardStep === 'result' && (
|
||||
<Button onClick={() => onOpenChange(false)}>
|
||||
Done
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { FileIcon, FilePlusIcon, FileMinusIcon, FileEditIcon } from 'lucide-react';
|
||||
|
||||
interface DiffViewProps {
|
||||
projectDir: string;
|
||||
}
|
||||
|
||||
interface FileChange {
|
||||
filepath: string;
|
||||
type: 'added' | 'modified' | 'deleted' | 'untracked';
|
||||
}
|
||||
|
||||
export function DiffView({ projectDir }: DiffViewProps) {
|
||||
const { git } = useGit();
|
||||
const [changes, setChanges] = useState<FileChange[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const loadChanges = async () => {
|
||||
try {
|
||||
const statusMatrix = await git.statusMatrix({ dir: projectDir });
|
||||
|
||||
const fileChanges: FileChange[] = statusMatrix
|
||||
.filter(([, head, workdir, stage]) => {
|
||||
// Show files that are different between HEAD and workdir
|
||||
return head !== workdir || stage !== head;
|
||||
})
|
||||
.map(([filepath, head, workdir, stage]) => {
|
||||
let type: FileChange['type'] = 'modified';
|
||||
|
||||
if (head === 0 && workdir !== 0) {
|
||||
type = stage === 0 ? 'untracked' : 'added';
|
||||
} else if (head !== 0 && workdir === 0) {
|
||||
type = 'deleted';
|
||||
} else if (head !== workdir) {
|
||||
type = 'modified';
|
||||
}
|
||||
|
||||
return { filepath, type };
|
||||
});
|
||||
|
||||
setChanges(fileChanges);
|
||||
} catch (error) {
|
||||
console.error('Failed to load changes:', error);
|
||||
setChanges([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadChanges();
|
||||
}, [git, projectDir]);
|
||||
|
||||
const getFileIcon = (type: FileChange['type']) => {
|
||||
switch (type) {
|
||||
case 'added':
|
||||
case 'untracked':
|
||||
return <FilePlusIcon className="h-4 w-4 text-green-600" />;
|
||||
case 'deleted':
|
||||
return <FileMinusIcon className="h-4 w-4 text-red-600" />;
|
||||
case 'modified':
|
||||
return <FileEditIcon className="h-4 w-4 text-blue-600" />;
|
||||
default:
|
||||
return <FileIcon className="h-4 w-4" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getTypeBadge = (type: FileChange['type']) => {
|
||||
const variants = {
|
||||
added: 'default',
|
||||
untracked: 'secondary',
|
||||
modified: 'secondary',
|
||||
deleted: 'destructive',
|
||||
} as const;
|
||||
|
||||
return (
|
||||
<Badge variant={variants[type]} className="text-xs">
|
||||
{type}
|
||||
</Badge>
|
||||
);
|
||||
};
|
||||
|
||||
const stats = {
|
||||
added: changes.filter(c => c.type === 'added' || c.type === 'untracked').length,
|
||||
modified: changes.filter(c => c.type === 'modified').length,
|
||||
deleted: changes.filter(c => c.type === 'deleted').length,
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8 text-sm text-muted-foreground">
|
||||
Loading changes...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (changes.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8 text-sm text-muted-foreground">
|
||||
No changes to review
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<span className="text-muted-foreground">Changes:</span>
|
||||
{stats.added > 0 && (
|
||||
<span className="text-green-600">+{stats.added} added</span>
|
||||
)}
|
||||
{stats.modified > 0 && (
|
||||
<span className="text-blue-600">~{stats.modified} modified</span>
|
||||
)}
|
||||
{stats.deleted > 0 && (
|
||||
<span className="text-red-600">-{stats.deleted} deleted</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-64 border rounded-lg">
|
||||
<div className="p-2 space-y-1">
|
||||
{changes.map((change) => (
|
||||
<div
|
||||
key={change.filepath}
|
||||
className="flex items-center justify-between p-2 rounded-md hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||
{getFileIcon(change.type)}
|
||||
<span className="text-sm font-mono truncate">{change.filepath}</span>
|
||||
</div>
|
||||
{getTypeBadge(change.type)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { createGitHostProvider, parseRepoUrl } from '@/lib/git-hosts';
|
||||
import { ExternalLink, GitPullRequest, CheckCircle2, XCircle, GitMerge } from 'lucide-react';
|
||||
import type { PullRequest } from '@/lib/git-hosts';
|
||||
|
||||
interface PRStatusBadgeProps {
|
||||
projectDir: string;
|
||||
}
|
||||
|
||||
export function PRStatusBadge({ projectDir }: PRStatusBadgeProps) {
|
||||
const { git } = useGit();
|
||||
const { settings } = useGitSettings();
|
||||
const { config } = useAppContext();
|
||||
const [prs, setPrs] = useState<PullRequest[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const loadPRs = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// Get the current branch
|
||||
const currentBranch = await git.currentBranch({ dir: projectDir });
|
||||
if (!currentBranch) return;
|
||||
|
||||
// Get remote URL
|
||||
const upstreamUrl = await git.getRemoteURL(projectDir, 'upstream');
|
||||
const originUrl = await git.getRemoteURL(projectDir, 'origin');
|
||||
const remoteUrl = upstreamUrl || originUrl;
|
||||
|
||||
if (!remoteUrl) return;
|
||||
|
||||
const parsed = parseRepoUrl(remoteUrl);
|
||||
if (!parsed) return;
|
||||
|
||||
const hostname = new URL(remoteUrl.replace(/^git@/, 'https://').replace(/\.git$/, '')).hostname;
|
||||
const hostToken = settings.hostTokens[hostname];
|
||||
|
||||
if (!hostToken) return;
|
||||
|
||||
const provider = createGitHostProvider(remoteUrl, { token: hostToken.token }, config.corsProxy);
|
||||
if (!provider) return;
|
||||
|
||||
// List open PRs for this repo
|
||||
const allPrs = await provider.listPullRequests(parsed.owner, parsed.repo, 'open');
|
||||
|
||||
// Filter PRs that match the current branch
|
||||
const relevantPrs = allPrs.filter(pr => pr.headBranch === currentBranch);
|
||||
setPrs(relevantPrs);
|
||||
} catch (error) {
|
||||
console.error('Failed to load PRs:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadPRs();
|
||||
}, [git, projectDir, settings.hostTokens, config.corsProxy]);
|
||||
|
||||
if (loading || prs.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pr = prs[0]; // Show the first matching PR
|
||||
|
||||
const getStateIcon = () => {
|
||||
switch (pr.state) {
|
||||
case 'open':
|
||||
return <GitPullRequest className="h-3 w-3" />;
|
||||
case 'merged':
|
||||
return <GitMerge className="h-3 w-3" />;
|
||||
case 'closed':
|
||||
return <XCircle className="h-3 w-3" />;
|
||||
default:
|
||||
return <GitPullRequest className="h-3 w-3" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStateColor = () => {
|
||||
switch (pr.state) {
|
||||
case 'open':
|
||||
return 'default';
|
||||
case 'merged':
|
||||
return 'secondary';
|
||||
case 'closed':
|
||||
return 'destructive';
|
||||
default:
|
||||
return 'secondary';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Badge variant={getStateColor()} className="cursor-pointer gap-1">
|
||||
{getStateIcon()}
|
||||
PR #{pr.number}
|
||||
</Badge>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-80" align="end">
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h4 className="font-medium text-sm leading-tight">{pr.title}</h4>
|
||||
<Badge variant={getStateColor()} className="shrink-0">
|
||||
{pr.state}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
#{pr.number} opened by {pr.author}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{pr.body && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-3">
|
||||
{pr.body}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{pr.checks && pr.checks.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium">Checks</p>
|
||||
{pr.checks.map((check, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-xs">
|
||||
{check.status === 'success' ? (
|
||||
<CheckCircle2 className="h-3 w-3 text-green-600" />
|
||||
) : check.status === 'failure' ? (
|
||||
<XCircle className="h-3 w-3 text-red-600" />
|
||||
) : (
|
||||
<div className="h-3 w-3 rounded-full border-2 border-muted-foreground animate-spin" />
|
||||
)}
|
||||
<span>{check.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button variant="outline" size="sm" className="w-full" asChild>
|
||||
<a href={pr.url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="h-3 w-3 mr-2" />
|
||||
View Pull Request
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { ContributeButton } from './ContributeButton';
|
||||
export { ContributeWizard } from './ContributeWizard';
|
||||
export { PRStatusBadge } from './PRStatusBadge';
|
||||
export { AuthStep } from './AuthStep';
|
||||
export { DiffView } from './DiffView';
|
||||
@@ -5,8 +5,16 @@ export interface GitCredential {
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface GitHostToken {
|
||||
token: string;
|
||||
username?: string;
|
||||
scopes?: string[];
|
||||
createdAt?: number;
|
||||
}
|
||||
|
||||
export interface GitSettings {
|
||||
credentials: Record<string, GitCredential>; // keyed by origin
|
||||
hostTokens: Record<string, GitHostToken>; // keyed by host domain (e.g., 'github.com')
|
||||
name?: string;
|
||||
email?: string;
|
||||
coAuthorEnabled?: boolean;
|
||||
@@ -18,6 +26,9 @@ export interface GitSettingsContextType {
|
||||
addCredential: (origin: string, credential: GitCredential) => void;
|
||||
removeCredential: (origin: string) => void;
|
||||
updateCredential: (origin: string, credential: Partial<GitCredential>) => void;
|
||||
addHostToken: (host: string, token: GitHostToken) => void;
|
||||
removeHostToken: (host: string) => void;
|
||||
updateHostToken: (host: string, token: Partial<GitHostToken>) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useFS } from './useFS';
|
||||
import { useGit } from './useGit';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { createGitHostProvider, parseRepoUrl, detectGitHost } from '@/lib/git-hosts';
|
||||
import type { PullRequest } from '@/lib/git-hosts';
|
||||
|
||||
export interface ContributeState {
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
step: 'idle' | 'auth' | 'prepare' | 'fork' | 'push' | 'pr' | 'complete';
|
||||
message?: string;
|
||||
pr?: PullRequest;
|
||||
}
|
||||
|
||||
export interface ContributeOptions {
|
||||
projectDir: string;
|
||||
branchName: string;
|
||||
commitMessage: string;
|
||||
prTitle: string;
|
||||
prBody?: string;
|
||||
maintainerCanModify?: boolean;
|
||||
}
|
||||
|
||||
export function useContribute() {
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { settings, addHostToken } = useGitSettings();
|
||||
const { config } = useAppContext();
|
||||
|
||||
const [state, setState] = useState<ContributeState>({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
step: 'idle',
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the current repository's upstream URL
|
||||
*/
|
||||
const getUpstreamUrl = useCallback(async (projectDir: string): Promise<string | null> => {
|
||||
try {
|
||||
// Try to get upstream remote first
|
||||
const upstreamUrl = await git.getRemoteURL(projectDir, 'upstream');
|
||||
if (upstreamUrl) return upstreamUrl;
|
||||
|
||||
// Fall back to origin
|
||||
const originUrl = await git.getRemoteURL(projectDir, 'origin');
|
||||
return originUrl;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [git]);
|
||||
|
||||
/**
|
||||
* Check if user needs to authenticate with the Git host
|
||||
*/
|
||||
const needsAuth = useCallback(async (projectDir: string): Promise<{ needsAuth: boolean; host?: string; url?: string }> => {
|
||||
const url = await getUpstreamUrl(projectDir);
|
||||
if (!url) {
|
||||
return { needsAuth: false };
|
||||
}
|
||||
|
||||
const hostType = detectGitHost(url);
|
||||
if (hostType === 'unknown') {
|
||||
return { needsAuth: false };
|
||||
}
|
||||
|
||||
// Extract hostname
|
||||
const hostname = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, '')).hostname;
|
||||
|
||||
// Check if we have a token for this host
|
||||
const hasToken = !!settings.hostTokens[hostname];
|
||||
|
||||
return {
|
||||
needsAuth: !hasToken,
|
||||
host: hostname,
|
||||
url,
|
||||
};
|
||||
}, [getUpstreamUrl, settings.hostTokens]);
|
||||
|
||||
/**
|
||||
* Add authentication token for a Git host
|
||||
*/
|
||||
const authenticate = useCallback((host: string, token: string, username?: string) => {
|
||||
addHostToken(host, {
|
||||
token,
|
||||
username,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
}, [addHostToken]);
|
||||
|
||||
/**
|
||||
* Execute the complete contribution workflow
|
||||
*/
|
||||
const contribute = useCallback(async (options: ContributeOptions): Promise<PullRequest | null> => {
|
||||
setState({ isLoading: true, error: null, step: 'prepare' });
|
||||
|
||||
try {
|
||||
// 1. Get upstream repository info
|
||||
const upstreamUrl = await getUpstreamUrl(options.projectDir);
|
||||
if (!upstreamUrl) {
|
||||
throw new Error('No remote repository found. This project must be cloned from a Git repository.');
|
||||
}
|
||||
|
||||
const parsed = parseRepoUrl(upstreamUrl);
|
||||
if (!parsed) {
|
||||
throw new Error('Invalid repository URL format');
|
||||
}
|
||||
|
||||
const hostname = new URL(upstreamUrl.replace(/^git@/, 'https://').replace(/\.git$/, '')).hostname;
|
||||
const hostToken = settings.hostTokens[hostname];
|
||||
|
||||
if (!hostToken) {
|
||||
throw new Error(`Not authenticated with ${hostname}. Please connect your account first.`);
|
||||
}
|
||||
|
||||
// Create Git host provider
|
||||
const provider = createGitHostProvider(upstreamUrl, { token: hostToken.token }, config.corsProxy);
|
||||
if (!provider) {
|
||||
throw new Error('Unsupported Git hosting provider');
|
||||
}
|
||||
|
||||
setState(prev => ({ ...prev, step: 'auth', message: 'Checking permissions...' }));
|
||||
|
||||
// 2. Get repository and check permissions
|
||||
const repo = await provider.getRepository(parsed.owner, parsed.repo);
|
||||
const canPush = await provider.canUserPush(parsed.owner, parsed.repo);
|
||||
const currentUser = await provider.getCurrentUser();
|
||||
|
||||
let forkUrl: string | null = null;
|
||||
let forkFullName: string | null = null;
|
||||
|
||||
// 3. Fork if necessary
|
||||
if (!canPush) {
|
||||
setState(prev => ({ ...prev, step: 'fork', message: 'Creating your copy of the project...' }));
|
||||
|
||||
// Check if fork already exists
|
||||
let fork = await provider.getFork(parsed.owner, parsed.repo, currentUser.username);
|
||||
|
||||
if (!fork) {
|
||||
// Create fork
|
||||
fork = await provider.createFork(parsed.owner, parsed.repo);
|
||||
|
||||
// Wait for fork to be ready
|
||||
fork = await provider.waitForFork(parsed.owner, parsed.repo, currentUser.username, 30000);
|
||||
}
|
||||
|
||||
forkUrl = fork.cloneUrl;
|
||||
forkFullName = fork.fullName;
|
||||
|
||||
// Configure remotes: upstream = original, origin = fork
|
||||
try {
|
||||
await git.addRemote({
|
||||
dir: options.projectDir,
|
||||
remote: 'upstream',
|
||||
url: upstreamUrl,
|
||||
});
|
||||
} catch {
|
||||
// upstream might already exist, update it
|
||||
await git.deleteRemote({ dir: options.projectDir, remote: 'upstream' });
|
||||
await git.addRemote({
|
||||
dir: options.projectDir,
|
||||
remote: 'upstream',
|
||||
url: upstreamUrl,
|
||||
});
|
||||
}
|
||||
|
||||
// Update origin to point to fork
|
||||
await git.deleteRemote({ dir: options.projectDir, remote: 'origin' });
|
||||
await git.addRemote({
|
||||
dir: options.projectDir,
|
||||
remote: 'origin',
|
||||
url: forkUrl,
|
||||
});
|
||||
} else {
|
||||
forkFullName = `${parsed.owner}/${parsed.repo}`;
|
||||
}
|
||||
|
||||
// 4. Create and switch to feature branch
|
||||
setState(prev => ({ ...prev, step: 'prepare', message: 'Preparing changes...' }));
|
||||
|
||||
const currentBranch = await git.currentBranch({ dir: options.projectDir });
|
||||
|
||||
// If we're already on the feature branch, that's fine
|
||||
if (currentBranch !== options.branchName) {
|
||||
// Create branch from current HEAD
|
||||
await git.branch({
|
||||
dir: options.projectDir,
|
||||
ref: options.branchName,
|
||||
checkout: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Commit all changes
|
||||
const statusMatrix = await git.statusMatrix({ dir: options.projectDir });
|
||||
const hasChanges = statusMatrix.some(([, head, workdir]) => head !== workdir);
|
||||
|
||||
if (hasChanges) {
|
||||
// Stage all changes
|
||||
for (const [filepath, , workdir] of statusMatrix) {
|
||||
if (workdir === 0) {
|
||||
// File deleted
|
||||
await git.remove({ dir: options.projectDir, filepath });
|
||||
} else {
|
||||
// File added or modified
|
||||
await git.add({ dir: options.projectDir, filepath });
|
||||
}
|
||||
}
|
||||
|
||||
// Commit
|
||||
await git.commit({
|
||||
dir: options.projectDir,
|
||||
message: options.commitMessage,
|
||||
});
|
||||
}
|
||||
|
||||
// 6. Push to remote
|
||||
setState(prev => ({ ...prev, step: 'push', message: 'Uploading your changes...' }));
|
||||
|
||||
const credentials = settings.credentials[forkUrl || upstreamUrl] ||
|
||||
settings.credentials[`https://${hostname}`] ||
|
||||
{ username: hostToken.username || currentUser.username, password: hostToken.token };
|
||||
|
||||
await git.push({
|
||||
dir: options.projectDir,
|
||||
remote: 'origin',
|
||||
ref: options.branchName,
|
||||
onAuth: () => credentials,
|
||||
});
|
||||
|
||||
// 7. Create pull request
|
||||
setState(prev => ({ ...prev, step: 'pr', message: 'Creating pull request...' }));
|
||||
|
||||
const pr = await provider.createPullRequest({
|
||||
title: options.prTitle,
|
||||
body: options.prBody,
|
||||
headBranch: options.branchName,
|
||||
baseBranch: repo.defaultBranch,
|
||||
headRepo: forkFullName!,
|
||||
baseRepo: `${parsed.owner}/${parsed.repo}`,
|
||||
maintainerCanModify: options.maintainerCanModify ?? true,
|
||||
});
|
||||
|
||||
setState({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
step: 'complete',
|
||||
message: 'Pull request created successfully!',
|
||||
pr,
|
||||
});
|
||||
|
||||
return pr;
|
||||
} catch (error) {
|
||||
console.error('Contribution error:', error);
|
||||
setState({
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to create pull request',
|
||||
step: 'idle',
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}, [getUpstreamUrl, settings, config.corsProxy, git, addHostToken]);
|
||||
|
||||
/**
|
||||
* Update an existing pull request by pushing new commits
|
||||
*/
|
||||
const updatePR = useCallback(async (
|
||||
projectDir: string,
|
||||
branchName: string,
|
||||
commitMessage: string
|
||||
): Promise<boolean> => {
|
||||
setState({ isLoading: true, error: null, step: 'prepare' });
|
||||
|
||||
try {
|
||||
// Get current branch
|
||||
const currentBranch = await git.currentBranch({ dir: projectDir });
|
||||
|
||||
if (currentBranch !== branchName) {
|
||||
// Checkout the PR branch
|
||||
await git.checkout({
|
||||
dir: projectDir,
|
||||
ref: branchName,
|
||||
});
|
||||
}
|
||||
|
||||
// Commit changes
|
||||
const statusMatrix = await git.statusMatrix({ dir: projectDir });
|
||||
const hasChanges = statusMatrix.some(([, head, workdir]) => head !== workdir);
|
||||
|
||||
if (!hasChanges) {
|
||||
setState({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
step: 'complete',
|
||||
message: 'No changes to commit',
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stage all changes
|
||||
for (const [filepath, , workdir] of statusMatrix) {
|
||||
if (workdir === 0) {
|
||||
await git.remove({ dir: projectDir, filepath });
|
||||
} else {
|
||||
await git.add({ dir: projectDir, filepath });
|
||||
}
|
||||
}
|
||||
|
||||
await git.commit({
|
||||
dir: projectDir,
|
||||
message: commitMessage,
|
||||
});
|
||||
|
||||
// Push to remote
|
||||
setState(prev => ({ ...prev, step: 'push', message: 'Uploading updates...' }));
|
||||
|
||||
const originUrl = await git.getRemoteURL(projectDir, 'origin');
|
||||
if (!originUrl) {
|
||||
throw new Error('No origin remote found');
|
||||
}
|
||||
|
||||
const hostname = new URL(originUrl.replace(/^git@/, 'https://').replace(/\.git$/, '')).hostname;
|
||||
const hostToken = settings.hostTokens[hostname];
|
||||
|
||||
if (!hostToken) {
|
||||
throw new Error(`Not authenticated with ${hostname}`);
|
||||
}
|
||||
|
||||
const credentials = settings.credentials[originUrl] ||
|
||||
settings.credentials[`https://${hostname}`] ||
|
||||
{ username: hostToken.username || 'git', password: hostToken.token };
|
||||
|
||||
await git.push({
|
||||
dir: projectDir,
|
||||
remote: 'origin',
|
||||
ref: branchName,
|
||||
onAuth: () => credentials,
|
||||
});
|
||||
|
||||
setState({
|
||||
isLoading: false,
|
||||
error: null,
|
||||
step: 'complete',
|
||||
message: 'Pull request updated successfully!',
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Update PR error:', error);
|
||||
setState({
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to update pull request',
|
||||
step: 'idle',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}, [git, settings]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
needsAuth,
|
||||
authenticate,
|
||||
contribute,
|
||||
updatePR,
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useState, useCallback } from 'react';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
import type { GitHostToken } from '@/contexts/GitSettingsContext';
|
||||
|
||||
interface GitHubOAuthState {
|
||||
isLoading: boolean;
|
||||
@@ -19,7 +20,7 @@ export function useGitHubOAuth() {
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { addCredential } = useGitSettings();
|
||||
const { addCredential, addHostToken } = useGitSettings();
|
||||
const { config } = useAppContext();
|
||||
const { corsProxy } = config;
|
||||
|
||||
@@ -161,12 +162,21 @@ export function useGitHubOAuth() {
|
||||
|
||||
const userData = await userResponse.json();
|
||||
|
||||
// Store the credentials
|
||||
// Store the credentials (legacy format for existing push/pull operations)
|
||||
addCredential('https://github.com', {
|
||||
username: userData.login || 'git',
|
||||
password: tokenData.access_token,
|
||||
});
|
||||
|
||||
// Also store as host token for PR/contribution operations
|
||||
const hostToken: GitHostToken = {
|
||||
token: tokenData.access_token,
|
||||
username: userData.login,
|
||||
scopes: tokenData.scope ? tokenData.scope.split(',').map(s => s.trim()) : [],
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
addHostToken('github.com', hostToken);
|
||||
|
||||
setState(prev => ({ ...prev, isLoading: false }));
|
||||
return true;
|
||||
} catch (error) {
|
||||
|
||||
+15
-1
@@ -31,8 +31,16 @@ const gitCredentialSchema = z.object({
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
const gitHostTokenSchema = z.object({
|
||||
token: z.string(),
|
||||
username: z.string().optional(),
|
||||
scopes: z.array(z.string()).optional(),
|
||||
createdAt: z.number().optional(),
|
||||
});
|
||||
|
||||
const gitSettingsSchema = z.object({
|
||||
credentials: z.record(z.string(), gitCredentialSchema),
|
||||
hostTokens: z.record(z.string(), gitHostTokenSchema).optional(),
|
||||
name: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
coAuthorEnabled: z.boolean().optional(),
|
||||
@@ -84,6 +92,7 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
|
||||
export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
const defaultSettings: GitSettings = {
|
||||
credentials: {},
|
||||
hostTokens: {},
|
||||
coAuthorEnabled: true,
|
||||
};
|
||||
|
||||
@@ -91,7 +100,12 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
try {
|
||||
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
|
||||
const data = JSON.parse(content);
|
||||
return gitSettingsSchema.parse(data);
|
||||
const parsed = gitSettingsSchema.parse(data);
|
||||
// Ensure hostTokens exists even if not in parsed data
|
||||
return {
|
||||
...parsed,
|
||||
hostTokens: parsed.hostTokens || {},
|
||||
};
|
||||
} catch {
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
PullRequestCheck,
|
||||
} from './types';
|
||||
|
||||
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> {
|
||||
const data = await this.fetch<any>(`/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 {
|
||||
const data = await this.fetch<any>(`/repos/${owner}/${repo}`);
|
||||
return data.permissions?.push === true || data.permissions?.admin === true;
|
||||
} catch (error) {
|
||||
// If we can't check permissions, assume no push access
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async createFork(owner: string, repo: string): Promise<GitFork> {
|
||||
const data = await this.fetch<any>(`/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,
|
||||
};
|
||||
}
|
||||
|
||||
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
|
||||
try {
|
||||
// Check if the fork already exists
|
||||
const data = await this.fetch<any>(`/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<any>(`/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<any>(`/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<any[]>(`/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<any>(`/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<any>(`/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> {
|
||||
const data = await this.fetch<any>('/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: any): PullRequest {
|
||||
const state = data.merged ? 'merged' : data.state;
|
||||
|
||||
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: any): 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
PullRequestCheck,
|
||||
} from './types';
|
||||
|
||||
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> {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<any>(`/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 {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<any>(`/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> {
|
||||
const projectPath = this.encodeProjectPath(owner, repo);
|
||||
const data = await this.fetch<any>(`/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 {
|
||||
const forkPath = this.encodeProjectPath(username, upstreamRepo);
|
||||
const data = await this.fetch<any>(`/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<any>(`/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<any>(`/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<any[]>(`/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<any>(`/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<any>(`/projects/${projectPath}/merge_requests/${number}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
state_event: 'close',
|
||||
}),
|
||||
});
|
||||
|
||||
return this.transformMergeRequest(data);
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<GitHostUser> {
|
||||
const data = await this.fetch<any>('/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: any): 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: any): PullRequestCheck[] | undefined {
|
||||
if (!data.pipeline) return undefined;
|
||||
|
||||
return [{
|
||||
name: 'Pipeline',
|
||||
status: data.pipeline.status === 'running' ? 'pending' :
|
||||
data.pipeline.status === 'success' ? 'success' : 'failure',
|
||||
conclusion: data.pipeline.status,
|
||||
detailsUrl: data.pipeline.web_url,
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
GitRepository,
|
||||
GitFork,
|
||||
PullRequest,
|
||||
CreatePullRequestOptions,
|
||||
GitHostUser,
|
||||
PullRequestCheck,
|
||||
} from './types';
|
||||
|
||||
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> {
|
||||
const data = await this.fetch<any>(`/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 {
|
||||
const data = await this.fetch<any>(`/repos/${owner}/${repo}`);
|
||||
return data.permissions?.push === true || data.permissions?.admin === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async createFork(owner: string, repo: string): Promise<GitFork> {
|
||||
const data = await this.fetch<any>(`/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 {
|
||||
const data = await this.fetch<any>(`/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<any>(`/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<any>(`/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<any[]>(`/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<any>(`/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<any>(`/repos/${owner}/${repo}/pulls/${number}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ state: 'closed' }),
|
||||
});
|
||||
|
||||
return this.transformPullRequest(data);
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<GitHostUser> {
|
||||
const data = await this.fetch<any>('/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: any): PullRequest {
|
||||
const state = data.merged ? 'merged' : data.state;
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
export * from './types';
|
||||
export { GitHubProvider } from './GitHubProvider';
|
||||
export { GitLabProvider } from './GitLabProvider';
|
||||
export { GiteaProvider } from './GiteaProvider';
|
||||
|
||||
import { GitHubProvider } from './GitHubProvider';
|
||||
import { GitLabProvider } from './GitLabProvider';
|
||||
import { GiteaProvider } from './GiteaProvider';
|
||||
import { detectGitHost } from './types';
|
||||
import type { GitHostProvider, GitHostConfig } from './types';
|
||||
|
||||
/**
|
||||
* Create a Git host provider instance based on the repository URL
|
||||
*/
|
||||
export function createGitHostProvider(
|
||||
url: string,
|
||||
config: GitHostConfig,
|
||||
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;
|
||||
}
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* 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' | 'unknown' {
|
||||
try {
|
||||
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 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;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { StarButton } from '@/components/StarButton';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { ContributeButton, PRStatusBadge } from '@/components/contribute';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -157,6 +158,12 @@ export function ProjectView() {
|
||||
<div className="flex items-center gap-2">
|
||||
{project ? (
|
||||
<>
|
||||
<PRStatusBadge projectDir={`/projects/${project.id}`} />
|
||||
<ContributeButton
|
||||
projectDir={`/projects/${project.id}`}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
/>
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
@@ -362,10 +369,16 @@ export function ProjectView() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right side - Star and Actions Menu */}
|
||||
{/* Right side - PR Status, Contribute, Star and Actions Menu */}
|
||||
<div className="flex items-center gap-2">
|
||||
{project ? (
|
||||
<>
|
||||
<PRStatusBadge projectDir={`/projects/${project.id}`} />
|
||||
<ContributeButton
|
||||
projectDir={`/projects/${project.id}`}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
/>
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
|
||||
Reference in new issue
Block a user