Remove all the git menus

This commit is contained in:
Alex Gleason committed 2025-12-22 15:47:31 -06:00
1 parent 8eeea7b188
commit d72729f379
24 files changed
-9650

No files matched your search

-303
View File
@@ -1,303 +0,0 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
PullRequestCheck,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GitHubPRResponse {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}
export class GitHubProvider implements GitHostProvider {
readonly name = 'GitHub';
readonly apiBaseUrl = 'https://api.github.com';
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, corsProxy?: string) {
this.config = config;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `Bearer ${this.config.token}`,
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitHub API error (${response.status}): ${errorText}`);
}
return response.json();
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GitHubRepo {
owner: { login: string };
name: string;
full_name: string;
default_branch: string;
clone_url: string;
html_url: string;
description: string;
private: boolean;
}
const data = await this.fetch<GitHubRepo>(`/repos/${owner}/${repo}`);
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
defaultBranch: data.default_branch,
cloneUrl: data.clone_url,
webUrl: data.html_url,
description: data.description,
isPrivate: data.private,
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GitHubRepoWithPermissions {
permissions?: { push?: boolean; admin?: boolean };
}
const data = await this.fetch<GitHubRepoWithPermissions>(`/repos/${owner}/${repo}`);
return data.permissions?.push === true || data.permissions?.admin === true;
} catch {
// If we can't check permissions, assume no push access
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GitHubFork {
owner: { login: string };
name: string;
clone_url: string;
html_url: string;
}
const data = await this.fetch<GitHubFork>(`/repos/${owner}/${repo}/forks`, {
method: 'POST',
});
return {
owner: data.owner.login,
name: data.name,
fullName: `${data.owner.login}/${data.name}`,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GitHubForkCheck {
fork: boolean;
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
// Check if the fork already exists
const data = await this.fetch<GitHubForkCheck>(`/repos/${username}/${upstreamRepo}`);
// Verify it's actually a fork of the upstream repo
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent.full_name,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
const [baseOwner, baseRepo] = options.baseRepo.split('/');
const [headOwner] = options.headRepo.split('/');
// Format head ref for cross-repo PR
const head = headOwner !== baseOwner
? `${headOwner}:${options.headBranch}`
: options.headBranch;
const data = await this.fetch<GitHubPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: options.title,
body: options.body || '',
head,
base: options.baseBranch,
maintainer_can_modify: options.maintainerCanModify ?? true,
}),
});
return this.transformPullRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
return this.transformPullRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const data = await this.fetch<GitHubPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
return data.map(pr => this.transformPullRequest(pr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(options),
});
return this.transformPullRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GitHubPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state: 'closed' }),
});
return this.transformPullRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GitHubUser {
login: string;
name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GitHubUser>('/user');
return {
username: data.login,
name: data.name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const [headOwner, headRepoName] = headRepo.split('/');
return `https://github.com/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}?expand=1`;
}
private transformPullRequest(data: {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}): PullRequest {
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
return {
number: data.number,
title: data.title,
body: data.body,
state,
headBranch: data.head.ref,
baseBranch: data.base.ref,
headRepo: data.head.repo?.full_name || '',
baseRepo: data.base.repo.full_name,
url: data.html_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.user.login,
mergeable: data.mergeable,
checks: this.transformChecks(data),
};
}
private transformChecks(_data: unknown): PullRequestCheck[] | undefined {
// GitHub's check runs are in a separate API call, so we don't have them here
// This would need a separate API call to /repos/{owner}/{repo}/commits/{ref}/check-runs
return undefined;
}
}
-328
View File
@@ -1,328 +0,0 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
PullRequestCheck,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GitLabMRResponse {
id: number;
iid: number;
state: string;
title: string;
description: string;
web_url: string;
created_at: string;
updated_at: string;
author: { username: string };
source_branch: string;
target_branch: string;
source_project_id: number;
target_project_id: number;
merge_status?: string;
merged_at?: string;
pipeline?: {
status: string;
web_url: string;
};
}
export class GitLabProvider implements GitHostProvider {
readonly name = 'GitLab';
readonly apiBaseUrl = 'https://gitlab.com/api/v4';
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, corsProxy?: string) {
this.config = config;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Authorization': `Bearer ${this.config.token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitLab API error (${response.status}): ${errorText}`);
}
return response.json();
}
private encodeProjectPath(owner: string, repo: string): string {
return encodeURIComponent(`${owner}/${repo}`);
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GitLabProject {
namespace: { path: string };
path: string;
path_with_namespace: string;
default_branch: string;
http_url_to_repo: string;
web_url: string;
description: string;
visibility: string;
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabProject>(`/projects/${projectPath}`);
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
defaultBranch: data.default_branch,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
description: data.description,
isPrivate: data.visibility === 'private',
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GitLabProjectWithPermissions {
permissions?: {
project_access?: { access_level?: number };
};
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabProjectWithPermissions>(`/projects/${projectPath}`);
// GitLab permissions are more granular
// developer (30), maintainer (40), or owner (50) can push
const accessLevel = data.permissions?.project_access?.access_level || 0;
return accessLevel >= 30;
} catch {
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GitLabFork {
namespace: { path: string };
path: string;
path_with_namespace: string;
http_url_to_repo: string;
web_url: string;
forked_from_project?: { path_with_namespace: string };
}
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabFork>(`/projects/${projectPath}/fork`, {
method: 'POST',
});
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
parentFullName: data.forked_from_project?.path_with_namespace || `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GitLabForkCheck {
namespace: { path: string };
path: string;
path_with_namespace: string;
http_url_to_repo: string;
web_url: string;
forked_from_project?: { path_with_namespace: string };
}
const forkPath = this.encodeProjectPath(username, upstreamRepo);
const data = await this.fetch<GitLabForkCheck>(`/projects/${forkPath}`);
// Check if it's a fork of the upstream
if (data.forked_from_project?.path_with_namespace === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.namespace.path,
name: data.path,
fullName: data.path_with_namespace,
cloneUrl: data.http_url_to_repo,
webUrl: data.web_url,
parentFullName: data.forked_from_project.path_with_namespace,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
// In GitLab, MRs are created on the source (fork) project
const sourceProjectPath = this.encodeProjectPath(options.headRepo.split('/')[0], options.headRepo.split('/')[1]);
const [targetOwner, targetRepo] = options.baseRepo.split('/');
const data = await this.fetch<GitLabMRResponse>(`/projects/${sourceProjectPath}/merge_requests`, {
method: 'POST',
body: JSON.stringify({
source_branch: options.headBranch,
target_branch: options.baseBranch,
target_project_id: this.encodeProjectPath(targetOwner, targetRepo),
title: options.title,
description: options.body || '',
allow_collaboration: options.maintainerCanModify ?? true,
}),
});
return this.transformMergeRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`);
return this.transformMergeRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const projectPath = this.encodeProjectPath(owner, repo);
const stateParam = state === 'all' ? 'all' : state === 'open' ? 'opened' : 'closed';
const data = await this.fetch<GitLabMRResponse[]>(`/projects/${projectPath}/merge_requests?state=${stateParam}`);
return data.map(mr => this.transformMergeRequest(mr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
method: 'PUT',
body: JSON.stringify({
title: options.title,
description: options.body,
}),
});
return this.transformMergeRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const projectPath = this.encodeProjectPath(owner, repo);
const data = await this.fetch<GitLabMRResponse>(`/projects/${projectPath}/merge_requests/${number}`, {
method: 'PUT',
body: JSON.stringify({
state_event: 'close',
}),
});
return this.transformMergeRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GitLabUser {
username: string;
name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GitLabUser>('/user');
return {
username: data.username,
name: data.name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const [headOwner, headRepoName] = headRepo.split('/');
return `https://gitlab.com/${baseRepo}/-/merge_requests/new?merge_request[source_branch]=${headBranch}&merge_request[source_project]=${headOwner}/${headRepoName}&merge_request[target_branch]=${baseBranch}`;
}
private transformMergeRequest(data: GitLabMRResponse): PullRequest {
const state = data.state === 'merged' ? 'merged' : data.state === 'opened' ? 'open' : 'closed';
return {
number: data.iid, // GitLab uses iid (internal id) for MRs
title: data.title,
body: data.description,
state,
headBranch: data.source_branch,
baseBranch: data.target_branch,
headRepo: data.source_project_id?.toString() || '',
baseRepo: data.target_project_id?.toString() || '',
url: data.web_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.author.username,
mergeable: data.merge_status === 'can_be_merged',
checks: this.transformPipeline(data),
};
}
private transformPipeline(data: GitLabMRResponse): PullRequestCheck[] | undefined {
if (!data.pipeline) return undefined;
const mapConclusion = (status: string): PullRequestCheck['conclusion'] => {
switch (status) {
case 'success': return 'success';
case 'failed': return 'failure';
case 'canceled': return 'cancelled';
case 'skipped': return 'skipped';
default: return undefined;
}
};
return [{
name: 'Pipeline',
status: data.pipeline.status === 'running' ? 'pending' :
data.pipeline.status === 'success' ? 'success' : 'failure',
conclusion: mapConclusion(data.pipeline.status),
detailsUrl: data.pipeline.web_url,
}];
}
}
-293
View File
@@ -1,293 +0,0 @@
import { proxyUrl } from '../proxyUrl';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface GiteaPRResponse {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}
export class GiteaProvider implements GitHostProvider {
readonly name: string;
readonly apiBaseUrl: string;
private config: GitHostConfig;
private corsProxy?: string;
constructor(config: GitHostConfig, apiBaseUrl: string, name = 'Gitea', corsProxy?: string) {
this.config = config;
this.apiBaseUrl = apiBaseUrl;
this.name = name;
this.corsProxy = corsProxy;
}
private async fetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const url = `${this.apiBaseUrl}${path}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
...options,
headers: {
'Authorization': `token ${this.config.token}`,
'Content-Type': 'application/json',
...options.headers,
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${this.name} API error (${response.status}): ${errorText}`);
}
return response.json();
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
interface GiteaRepo {
owner: { login: string };
name: string;
full_name: string;
default_branch: string;
clone_url: string;
html_url: string;
description: string;
private: boolean;
}
const data = await this.fetch<GiteaRepo>(`/repos/${owner}/${repo}`);
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
defaultBranch: data.default_branch,
cloneUrl: data.clone_url,
webUrl: data.html_url,
description: data.description,
isPrivate: data.private,
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
try {
interface GiteaRepoWithPermissions {
permissions?: { push?: boolean; admin?: boolean };
}
const data = await this.fetch<GiteaRepoWithPermissions>(`/repos/${owner}/${repo}`);
return data.permissions?.push === true || data.permissions?.admin === true;
} catch {
return false;
}
}
async createFork(owner: string, repo: string): Promise<GitFork> {
interface GiteaFork {
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
const data = await this.fetch<GiteaFork>(`/repos/${owner}/${repo}/forks`, {
method: 'POST',
});
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent?.full_name || `${owner}/${repo}`,
};
}
async getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null> {
try {
interface GiteaForkCheck {
fork: boolean;
owner: { login: string };
name: string;
full_name: string;
clone_url: string;
html_url: string;
parent?: { full_name: string };
}
const data = await this.fetch<GiteaForkCheck>(`/repos/${username}/${upstreamRepo}`);
if (data.fork && data.parent?.full_name === `${upstreamOwner}/${upstreamRepo}`) {
return {
owner: data.owner.login,
name: data.name,
fullName: data.full_name,
cloneUrl: data.clone_url,
webUrl: data.html_url,
parentFullName: data.parent.full_name,
};
}
return null;
} catch {
return null;
}
}
async waitForFork(
upstreamOwner: string,
upstreamRepo: string,
username: string,
timeout = 30000
): Promise<GitFork> {
const startTime = Date.now();
const pollInterval = 1000;
while (Date.now() - startTime < timeout) {
const fork = await this.getFork(upstreamOwner, upstreamRepo, username);
if (fork) {
return fork;
}
await new Promise(resolve => setTimeout(resolve, pollInterval));
}
throw new Error('Timeout waiting for fork to be created');
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
const [baseOwner, baseRepo] = options.baseRepo.split('/');
const [headOwner] = options.headRepo.split('/');
// Format head ref for cross-repo PR
const head = headOwner !== baseOwner
? `${headOwner}:${options.headBranch}`
: options.headBranch;
const data = await this.fetch<GiteaPRResponse>(`/repos/${baseOwner}/${baseRepo}/pulls`, {
method: 'POST',
body: JSON.stringify({
title: options.title,
body: options.body || '',
head,
base: options.baseBranch,
}),
});
return this.transformPullRequest(data);
}
async getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`);
return this.transformPullRequest(data);
}
async listPullRequests(
owner: string,
repo: string,
state: 'open' | 'closed' | 'all' = 'open'
): Promise<PullRequest[]> {
const data = await this.fetch<GiteaPRResponse[]>(`/repos/${owner}/${repo}/pulls?state=${state}`);
return data.map(pr => this.transformPullRequest(pr));
}
async updatePullRequest(
owner: string,
repo: string,
number: number,
options: { title?: string; body?: string }
): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
body: JSON.stringify(options),
});
return this.transformPullRequest(data);
}
async closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest> {
const data = await this.fetch<GiteaPRResponse>(`/repos/${owner}/${repo}/pulls/${number}`, {
method: 'PATCH',
body: JSON.stringify({ state: 'closed' }),
});
return this.transformPullRequest(data);
}
async getCurrentUser(): Promise<GitHostUser> {
interface GiteaUser {
login: string;
full_name: string;
email: string;
avatar_url: string;
}
const data = await this.fetch<GiteaUser>('/user');
return {
username: data.login,
name: data.full_name,
email: data.email,
avatarUrl: data.avatar_url,
};
}
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string {
const baseUrl = this.apiBaseUrl.replace('/api/v1', '');
const [headOwner, headRepoName] = headRepo.split('/');
return `${baseUrl}/${baseRepo}/compare/${baseBranch}...${headOwner}:${headRepoName}:${headBranch}`;
}
private transformPullRequest(data: {
id: number;
number: number;
state: string;
title: string;
body: string;
html_url: string;
created_at: string;
updated_at: string;
user: { login: string };
head: { ref: string; repo: { full_name: string } };
base: { ref: string; repo: { full_name: string } };
mergeable?: boolean;
merged?: boolean;
}): PullRequest {
const state: 'open' | 'closed' | 'merged' = data.merged ? 'merged' : data.state as 'open' | 'closed';
return {
number: data.number,
title: data.title,
body: data.body,
state,
headBranch: data.head.ref,
baseBranch: data.base.ref,
headRepo: data.head.repo?.full_name || '',
baseRepo: data.base.repo.full_name,
url: data.html_url,
createdAt: new Date(data.created_at),
updatedAt: new Date(data.updated_at),
author: data.user.login,
mergeable: data.mergeable,
};
}
}
-257
View File
@@ -1,257 +0,0 @@
import { NRelay1, type NostrEvent } from '@nostrify/nostrify';
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
import type {
GitHostProvider,
GitHostConfig,
GitRepository,
GitFork,
PullRequest,
CreatePullRequestOptions,
GitHostUser,
} from './types';
interface NostrSigner {
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
}
/**
* Nostr Git provider implementing NIP-34 (git stuff)
* Enables creating patches/PRs on Nostr git repositories
*/
export class NostrGitProvider implements GitHostProvider {
readonly name = 'Nostr Git';
readonly apiBaseUrl = ''; // Not applicable for Nostr
private relay: NRelay1;
private signer: NostrSigner;
private pubkey: string;
private relayUrls: string[];
constructor(config: GitHostConfig & { signer: NostrSigner; pubkey: string; relayUrls: string[] }) {
this.signer = config.signer;
this.pubkey = config.pubkey;
this.relayUrls = config.relayUrls;
// For Nostr git, we need to publish to the repository's designated relays
// The relay will be set dynamically when we know which repo we're working with
this.relay = new NRelay1('wss://relay.nostr.band'); // Default, will be changed
}
private async queryRepo(owner: string, repo: string): Promise<NostrEvent> {
// Query for repository announcement (kind 30617)
// d tag is the repo-id (usually kebab-case short name)
const events = await this.relay.query([
{
kinds: [30617],
authors: [owner], // owner is the pubkey
'#d': [repo], // repo is the d tag identifier
limit: 1,
}
]) as NostrEvent[];
if (events.length === 0) {
throw new Error(`Repository not found: ${owner}/${repo}`);
}
return events[0];
}
async getRepository(owner: string, repo: string): Promise<GitRepository> {
const event = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const repoAnn = parseRepositoryAnnouncement(event);
// Update relay to use repository's designated relays
if (repoAnn.relays.length > 0) {
this.relayUrls = repoAnn.relays;
this.relay = new NRelay1(repoAnn.relays[0]);
}
return {
owner,
name: repoAnn.name || repo,
fullName: `${owner}/${repo}`,
defaultBranch: 'main', // Nostr git doesn't specify, assume main
cloneUrl: repoAnn.httpsCloneUrls[0] || '',
webUrl: repoAnn.webUrls[0] || '',
description: repoAnn.description,
isPrivate: false, // All Nostr repos are public
};
}
async canUserPush(owner: string, repo: string): Promise<boolean> {
// In Nostr git, anyone can submit patches (kind 1617)
// But only maintainers can apply them
// Check if current user is listed as a maintainer
const event = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(event);
// Repo owner is always a maintainer
const isMaintainer = owner === this.pubkey || parsed.maintainers.includes(this.pubkey);
return isMaintainer;
}
async createFork(owner: string, repo: string): Promise<GitFork> {
// In Nostr git, there's no explicit "fork" concept
// Users submit patches to the original repo
// For compatibility with the PR flow, we return a "virtual fork"
const repoEvent = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(repoEvent);
// The "fork" is actually just the user's local copy
// We'll use this to track that patches come from the user
return {
owner: this.pubkey,
name: repo,
fullName: `${this.pubkey}/${repo}`,
cloneUrl: parsed.httpsCloneUrls[0] || '',
webUrl: parsed.webUrls[0] || '',
parentFullName: `${owner}/${repo}`,
};
}
async getFork(_upstreamOwner: string, _upstreamRepo: string, _username: string): Promise<GitFork | null> {
// Nostr git doesn't have forks - patches are submitted directly
// Return null to indicate no fork exists
return null;
}
async waitForFork(upstreamOwner: string, upstreamRepo: string, _username: string, _timeout = 10000): Promise<GitFork> {
// Create a virtual fork immediately
return this.createFork(upstreamOwner, upstreamRepo);
}
async createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest> {
// In Nostr git, a "pull request" is a patch event (kind 1617)
// The patch content should be the output of `git format-patch`
const [owner, repo] = options.baseRepo.split('/');
const repoEvent = await this.queryRepo(owner, repo);
// Parse the NIP-34 repository announcement
const parsed = parseRepositoryAnnouncement(repoEvent);
// Get the earliest unique commit (euc) for the repository
const euc = parsed.earliestCommit;
// Create patch content from the provided body or generate a simple patch description
const patchContent = options.body ||
`Patch proposal: ${options.title}\n\nFrom: ${options.headBranch}\nTo: ${options.baseBranch}`;
// Create patch event (kind 1617)
const patchEvent = await this.signer.signEvent({
kind: 1617,
content: patchContent,
tags: [
['a', `30617:${owner}:${repo}`], // Reference to repository announcement
['p', owner], // Repository owner
['t', 'root'], // Root patch in series
['t', 'root-revision'], // First patch in a revision
['subject', options.title], // Use subject tag for title
// Optional: Add r tag for euc if available
...(euc ? [['r', euc]] : []),
],
created_at: Math.floor(Date.now() / 1000),
});
// Publish to repository's designated relays
await this.relay.event(patchEvent);
// Return a PullRequest-compatible object
return {
number: parseInt(patchEvent.id.slice(0, 8), 16), // Use first 8 chars of event ID as number
title: options.title,
body: options.body,
state: 'open',
headBranch: options.headBranch,
baseBranch: options.baseBranch,
headRepo: options.headRepo,
baseRepo: options.baseRepo,
url: `nostr:${patchEvent.id}`, // Nostr event reference
createdAt: new Date(patchEvent.created_at * 1000),
updatedAt: new Date(patchEvent.created_at * 1000),
author: this.pubkey,
};
}
async getPullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
// Query for patch event by converting number back to event ID
// This is a limitation - we'd need to store the mapping or query differently
throw new Error('Getting specific patches by number is not yet implemented for Nostr git');
}
async listPullRequests(owner: string, repo: string, _state: 'open' | 'closed' | 'all' = 'open'): Promise<PullRequest[]> {
// Query for patch events (kind 1617) referencing this repository
const events = await this.relay.query([
{
kinds: [1617],
'#a': [`30617:${owner}:${repo}`],
'#t': ['root'], // Only root patches, not replies
limit: 50,
}
]);
// For state filtering, we'd need to check status events (kind 1630-1633)
// For now, return all as 'open'
return events.map(event => ({
number: parseInt(event.id.slice(0, 8), 16),
title: event.tags.find((t: string[]) => t[0] === 'subject')?.[1] || 'Untitled patch',
body: event.content,
state: 'open' as const,
headBranch: 'unknown', // Not stored in NIP-34
baseBranch: 'unknown', // Not stored in NIP-34
headRepo: `${event.pubkey}/${repo}`,
baseRepo: `${owner}/${repo}`,
url: `nostr:${event.id}`,
createdAt: new Date(event.created_at * 1000),
updatedAt: new Date(event.created_at * 1000),
author: event.pubkey,
}));
}
async updatePullRequest(_owner: string, _repo: string, _number: number, _options: { title?: string; body?: string }): Promise<PullRequest> {
// In Nostr git, you can't edit events - you'd create a new revision
throw new Error('Updating patches is not supported - create a new revision instead');
}
async closePullRequest(_owner: string, _repo: string, _number: number): Promise<PullRequest> {
// To close a patch, publish a status event (kind 1632 - Closed)
throw new Error('Closing patches via status events is not yet implemented');
}
async getCurrentUser(): Promise<GitHostUser> {
// In Nostr, we can query the user's profile (kind 0)
const profiles = await this.relay.query([
{
kinds: [0],
authors: [this.pubkey],
limit: 1,
}
]);
if (profiles.length > 0) {
const profile = JSON.parse(profiles[0].content);
return {
username: profile.name || this.pubkey.slice(0, 8),
name: profile.display_name || profile.name,
email: profile.nip05,
avatarUrl: profile.picture,
};
}
return {
username: this.pubkey.slice(0, 8),
};
}
getCompareUrl(_baseRepo: string, _baseBranch: string, _headRepo: string, _headBranch: string): string {
// Nostr git doesn't have a web compare view
// Could potentially link to a Nostr client that displays patches
return '';
}
}
-64
View File
@@ -1,64 +0,0 @@
export * from './types';
export { GitHubProvider } from './GitHubProvider';
export { GitLabProvider } from './GitLabProvider';
export { GiteaProvider } from './GiteaProvider';
export { NostrGitProvider } from './NostrGitProvider';
import { GitHubProvider } from './GitHubProvider';
import { GitLabProvider } from './GitLabProvider';
import { GiteaProvider } from './GiteaProvider';
import { NostrGitProvider } from './NostrGitProvider';
import { detectGitHost } from './types';
import type { GitHostProvider, GitHostConfig } from './types';
import type { NostrEvent } from '@nostrify/nostrify';
/**
* Create a Git host provider instance based on the repository URL
*/
interface NostrSigner {
signEvent: (event: { kind: number; content: string; tags: string[][]; created_at: number }) => Promise<NostrEvent>;
}
export function createGitHostProvider(
url: string,
config: GitHostConfig & { signer?: NostrSigner; pubkey?: string; relayUrls?: string[] },
corsProxy?: string
): GitHostProvider | null {
const hostType = detectGitHost(url);
switch (hostType) {
case 'github':
return new GitHubProvider(config, corsProxy);
case 'gitlab':
return new GitLabProvider(config, corsProxy);
case 'codeberg':
return new GiteaProvider(config, 'https://codeberg.org/api/v1', 'Codeberg', corsProxy);
case 'gitea':
// Extract API URL from repository URL
try {
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
const apiUrl = `${parsed.protocol}//${parsed.hostname}/api/v1`;
return new GiteaProvider(config, apiUrl, 'Gitea', corsProxy);
} catch {
return null;
}
case 'nostr':
// Nostr git requires signer and pubkey
if (!config.signer || !config.pubkey) {
throw new Error('Nostr git requires signer and pubkey in config');
}
return new NostrGitProvider({
token: config.token,
signer: config.signer,
pubkey: config.pubkey,
relayUrls: config.relayUrls || ['wss://relay.nostr.band'],
});
default:
return null;
}
}
-186
View File
@@ -1,186 +0,0 @@
import { nip19 } from 'nostr-tools';
/**
* Git host provider abstraction for PR/MR operations
*/
export interface GitHostUser {
username: string;
name?: string;
email?: string;
avatarUrl?: string;
}
export interface GitRepository {
owner: string;
name: string;
fullName: string; // e.g. "owner/repo"
defaultBranch: string;
cloneUrl: string;
webUrl: string;
description?: string;
isPrivate: boolean;
}
export interface GitFork {
owner: string;
name: string;
fullName: string;
cloneUrl: string;
webUrl: string;
parentFullName: string; // The upstream repo
}
export interface PullRequest {
number: number;
title: string;
body?: string;
state: 'open' | 'closed' | 'merged';
headBranch: string;
baseBranch: string;
headRepo: string; // Full name of head repo (fork)
baseRepo: string; // Full name of base repo (upstream)
url: string;
createdAt: Date;
updatedAt: Date;
author: string;
mergeable?: boolean;
checks?: PullRequestCheck[];
}
export interface PullRequestCheck {
name: string;
status: 'pending' | 'success' | 'failure' | 'cancelled';
conclusion?: 'success' | 'failure' | 'neutral' | 'cancelled' | 'skipped' | 'timed_out' | 'action_required';
detailsUrl?: string;
}
export interface CreatePullRequestOptions {
title: string;
body?: string;
headBranch: string;
baseBranch: string;
headRepo: string; // For cross-repo PRs (from fork)
baseRepo: string; // The upstream repo
maintainerCanModify?: boolean;
}
export interface GitHostConfig {
token: string;
username?: string;
}
/**
* Abstract interface for Git hosting providers (GitHub, GitLab, Gitea, etc.)
*/
export interface GitHostProvider {
readonly name: string;
readonly apiBaseUrl: string;
// Repository operations
getRepository(owner: string, repo: string): Promise<GitRepository>;
canUserPush(owner: string, repo: string): Promise<boolean>;
// Fork operations
createFork(owner: string, repo: string): Promise<GitFork>;
getFork(upstreamOwner: string, upstreamRepo: string, username: string): Promise<GitFork | null>;
waitForFork(upstreamOwner: string, upstreamRepo: string, username: string, timeout?: number): Promise<GitFork>;
// Pull request operations
createPullRequest(options: CreatePullRequestOptions): Promise<PullRequest>;
getPullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
listPullRequests(owner: string, repo: string, state?: 'open' | 'closed' | 'all'): Promise<PullRequest[]>;
updatePullRequest(owner: string, repo: string, number: number, options: { title?: string; body?: string }): Promise<PullRequest>;
closePullRequest(owner: string, repo: string, number: number): Promise<PullRequest>;
// User operations
getCurrentUser(): Promise<GitHostUser>;
// Utility
getCompareUrl(baseRepo: string, baseBranch: string, headRepo: string, headBranch: string): string;
}
/**
* Detect Git host from repository URL
*/
export function detectGitHost(url: string): 'github' | 'gitlab' | 'gitea' | 'codeberg' | 'nostr' | 'unknown' {
try {
// Check for Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
if (url.startsWith('nostr://')) {
return 'nostr';
}
const parsed = new URL(url.replace(/^git@/, 'https://').replace(/\.git$/, ''));
const hostname = parsed.hostname.toLowerCase();
if (hostname === 'github.com') return 'github';
if (hostname === 'gitlab.com') return 'gitlab';
if (hostname === 'codeberg.org') return 'codeberg';
if (hostname.includes('gitea')) return 'gitea';
return 'unknown';
} catch {
return 'unknown';
}
}
/**
* Parse repository owner and name from URL
*/
export function parseRepoUrl(url: string): { owner: string; repo: string } | null {
try {
// Handle Nostr git URLs (format: nostr://<pubkey>/<repo-id>)
if (url.startsWith('nostr://')) {
const match = url.match(/^nostr:\/\/([^/]+)\/(.+)$/);
if (match) {
let owner = match[1]; // pubkey in hex or npub
const repo = match[2]; // repo-id (d tag)
// Convert npub to hex if needed
if (owner.startsWith('npub1')) {
try {
const decoded = nip19.decode(owner);
if (decoded.type === 'npub') {
owner = decoded.data;
}
} catch (err) {
console.error('Failed to decode npub:', err);
return null;
}
}
return {
owner, // pubkey in hex
repo, // repo-id (d tag)
};
}
}
// Handle git@ URLs
const normalized = url.replace(/^git@([^:]+):/, 'https://$1/').replace(/\.git$/, '');
const parsed = new URL(normalized);
const parts = parsed.pathname.split('/').filter(Boolean);
if (parts.length >= 2) {
return {
owner: parts[0],
repo: parts[1],
};
}
} catch {
// Invalid URL
}
return null;
}
/**
* Format repository URL for display
*/
export function formatRepoUrl(url: string): string {
const parsed = parseRepoUrl(url);
if (parsed) {
return `${parsed.owner}/${parsed.repo}`;
}
return url;
}