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:
shakespeare.diy committed 2025-10-14 21:29:15 -05:00
1 parent 4226159f5d
commit add685257b
18 files changed
+2670 -5

No files matched your search

+234
View File
@@ -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;
}
}
+254
View File
@@ -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,
}];
}
}
+223
View File
@@ -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,
};
}
}
+45
View File
@@ -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;
}
}
+152
View File
@@ -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;
}