import { error } from "@sveltejs/kit"; import type { Did } from "@atcute/lexicons/syntax"; import type { RepoInfo } from "$lib/components/repo/types"; import { createBobbinClient } from "./client"; import { branches as listBranches, gitTarget, type GitServiceConfig } from "./gitclient"; import { listCommits, toMirrorCommitSummary } from "./gitmirror"; import { listRepos } from "./records"; import { repoNameOf, sortBranches, toBranchSummary, type BranchEntry, type BranchSummary, type CommitSummary } from "./repo"; export type PullSource = "patch" | "branch" | "fork"; const SOURCES: PullSource[] = ["patch", "branch", "fork"]; export const parseSource = (raw: string | null | undefined): PullSource | null => { const value = raw?.toLowerCase() as PullSource | undefined; return value && SOURCES.includes(value) ? value : null; }; const branchTime = (branch: BranchEntry): number => { const when = branch.commit?.Committer?.When; return when ? Date.parse(when) : NaN; }; /** newest commit first; branches with no commit sort last, order otherwise kept */ export const sortBranchesByRecency = (branches: readonly BranchEntry[]): BranchEntry[] => branches .map((branch, index) => ({ branch, index, time: branchTime(branch) })) .sort((a, b) => { const aMissing = Number.isNaN(a.time); const bMissing = Number.isNaN(b.time); if (aMissing || bMissing) return aMissing === bMissing ? a.index - b.index : aMissing ? 1 : -1; return b.time - a.time || a.index - b.index; }) .map((entry) => entry.branch); /** you can't open a PR from the default branch, so it never appears as a source */ export const sourceBranchChoices = (branches: readonly BranchEntry[]): BranchEntry[] => sortBranchesByRecency(branches.filter((branch) => !branch.is_default)); const named = (branches: readonly BranchEntry[], name: string): boolean => branches.some((branch) => branch.reference.name === name); export const defaultTargetBranch = (branches: readonly BranchEntry[], current: string): string => { if (current && named(branches, current)) return current; return branches.find((branch) => branch.is_default)?.reference.name ?? ""; }; export const defaultSourceBranch = ( source: PullSource, current: string, branchChoices: readonly BranchEntry[], forkBranches: readonly BranchEntry[] ): string => { if (source === "patch") return current; const candidates = source === "fork" ? forkBranches : branchChoices; if (current && named(candidates, current)) return current; return candidates[0]?.reference.name ?? ""; }; export interface ComposeSelection { source: PullSource; sourceBranch: string; targetBranch: string; /** repo did of the chosen fork */ fork: string; } export const composeQuery = (selection: ComposeSelection): string => { const query = new URLSearchParams(); if (selection.source !== "branch") query.set("source", selection.source); if (selection.sourceBranch) query.set("sourceBranch", selection.sourceBranch); if (selection.targetBranch) query.set("targetBranch", selection.targetBranch); if (selection.source === "fork" && selection.fork) query.set("fork", selection.fork); return query.toString(); }; const BRANCH_LIMIT = 500; const COMMIT_LIMIT = 100; // one of the viewer's forks, as the fork picker needs it export interface ForkOption { uri: string; repoDid: string; name: string; knot: string; } export interface ComposeData { commits: CommitSummary[]; commitsError: string; // `owner/repo` of the source repo, for the browse-at-commit links sourceRepoPath: string; branches: BranchSummary[]; sourceBranches: BranchEntry[]; forkBranches: BranchEntry[]; forks: ForkOption[]; source: PullSource; sourceBranch: string; targetBranch: string; fork: string; patch: string; sourceRepoDid: string; sourceKnot: string; showDetails: boolean; prefillError: string; } // the route load calls this for the active account, the component calls it // again client-side when the pick diverges since only the fork lane depends // on the identity export const loadCompose = async (args: { config: GitServiceConfig; repo: RepoInfo | Promise; viewer: { did: string; handle: string } | null; params: URLSearchParams; fetch: typeof globalThis.fetch; }): Promise => { const { config, repo: repoInput, viewer, params, fetch: fetchFn } = args; const repo = await repoInput; const repoDid = repo.repoDid; if (!repoDid) throw error(404, "This repository has not been indexed yet"); const ctx = createBobbinClient({ serviceUrl: config.bobbinUrl, fetch: fetchFn }); const source: PullSource = parseSource(params.get("source")) ?? "branch"; const [branchList, forkList] = await Promise.all([ listBranches(gitTarget(config, repo, fetchFn), BRANCH_LIMIT) .then((page) => page.branches ?? []) .catch(() => [] as BranchEntry[]), viewer ? listRepos(ctx, viewer.did, { limit: 100 }) .then((page) => page.items // `source` is any uri: an at-uri means a fork, anything else is // an import, same test the repo layout's resolveSource makes .filter( (item) => item.value.source?.startsWith("at://") && item.value.repoDid ) .map((item): ForkOption => ({ uri: item.uri, repoDid: item.value.repoDid as string, name: repoNameOf(item), knot: item.value.knot })) ) .catch(() => [] as ForkOption[]) : Promise.resolve([] as ForkOption[]) ]); let fork = params.get("fork") ?? ""; if (source === "fork" && !fork && forkList.length === 1) fork = forkList[0].repoDid; const forkRepo = forkList.find((entry) => entry.repoDid === fork); let prefillError = ""; let forkBranches: BranchEntry[] = []; if (source === "fork" && forkRepo) { try { const page = await listBranches( gitTarget(config, { uri: forkRepo.uri, repoDid: forkRepo.repoDid }, fetchFn), BRANCH_LIMIT ); forkBranches = sortBranchesByRecency(page.branches ?? []); } catch (cause) { prefillError = cause instanceof Error ? cause.message : String(cause); } } const sourceBranches = sourceBranchChoices(branchList); const targetBranch = defaultTargetBranch(branchList, params.get("targetBranch") ?? ""); const sourceBranch = defaultSourceBranch( source, params.get("sourceBranch") ?? "", sourceBranches, forkBranches ); const sourceRepoDid = fork || repoDid; const hasComparison = Boolean(sourceRepoDid && sourceBranch && targetBranch); let commits: CommitSummary[] = []; let commitsError = ""; if (hasComparison && source !== "patch") { try { const page = await listCommits(ctx, { repo: sourceRepoDid as Did, ranges: [`${targetBranch}..${sourceBranch}`], limit: COMMIT_LIMIT }); commits = page.commits.map(toMirrorCommitSummary); } catch (cause) { commitsError = cause instanceof Error ? cause.message : String(cause); } } return { commits, commitsError, sourceRepoPath: forkRepo ? `${viewer?.handle ?? repo.ownerHandle}/${forkRepo.name}` : `${repo.ownerHandle}/${repo.name}`, branches: sortBranches(branchList.map(toBranchSummary)), sourceBranches, forkBranches, forks: forkList, source, sourceBranch, targetBranch, fork, patch: params.get("patch") ?? "", sourceRepoDid, sourceKnot: forkRepo?.knot ?? repo.knot, showDetails: hasComparison, prefillError }; };