Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { canonicalRepositoryPath } from "@t3tools/shared/git";
3import {
4 buildCommitUrl,
5 changeRequestUrlBelow,
6 type ChangeRequestHostIdentity,
7 defineSourceControl,
8 isChangeRequestAuthorityOfProject,
9 isChangeRequestInProjectRepository,
10 isChangeRequestOnProjectHost,
11 parseChangeRequestPath,
12 parseIssuePath,
13 parseCommitPath,
14 repositoryUrlFromPagePath,
15 projectChangeRequestHost,
16 remoteWebOrigin,
17} from "@t3tools/source-control-core/shared/definition";
18import { icon } from "./icon.ts";
19
20const CHECKOUT_COMMAND = /^tea\s+(?:pr|pulls?)\s+(?:checkout|co)\s+(.+)$/i;
21const CHANGE_REQUEST_REFERENCE =
22 /^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)+[^/\s]+\/pulls\/(\d+)(?:[/?#].*)?$/i;
23
24// Forgejo and Gitea run on any hostname, possibly mounted below a path.
25const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u;
26const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/commit\/([0-9a-f]+)\/?$/iu;
27const ISSUE_PATH = /^\/([^/]+(?:\/[^/]+)+)\/issues\/(\d+)(?:\/|$)/u;
28const REPOSITORY_PAGE_PATH = /^\/([^/]+(?:\/[^/]+)+?)\/src\/(?:branch|tag|commit)\/[^/]/u;
29
30const KIND = SourceControlProviderKind.make("forgejo");
31
32function isForgejoHost(hostname: string): boolean {
33 const host = hostname.toLowerCase();
34 return (
35 host === "codeberg.org" ||
36 host.split(".").includes("forgejo") ||
37 host.split(".").includes("gitea")
38 );
39}
40
41const changeRequestHeadRef = (number: number) => `refs/pull/${number}/head`;
42
43/**
44 * The repository's browser URL the server resolved from the signed-in account, which is the
45 * only place a Forgejo mounted below a path says so.
46 */
47function resolvedWebUrl(identity: ChangeRequestHostIdentity): URL | null {
48 if (!identity?.webUrl) return null;
49 try {
50 const url = new URL(identity.webUrl);
51 return url.protocol === "http:" || url.protocol === "https:" ? url : null;
52 } catch {
53 return null;
54 }
55}
56
57/** A server's identity includes its port, which only its web URL or an HTTP remote names. */
58function changeRequestHost(identity: ChangeRequestHostIdentity): string {
59 const web = resolvedWebUrl(identity);
60 if (web) return web.host.toLowerCase();
61 try {
62 const remote = new URL(identity?.locator?.remoteUrl ?? "");
63 if (remote.protocol === "http:" || remote.protocol === "https:") {
64 return remote.host.toLowerCase();
65 }
66 } catch {
67 // SSH remotes do not name the web server.
68 }
69 return projectChangeRequestHost(identity, KIND);
70}
71
72export const definition = defineSourceControl({
73 kind: KIND,
74 label: "Forgejo",
75 pickerLabel: "Forgejo / Gitea",
76 icon,
77 searchKeywords: ["gitea", "tea", "codeberg"],
78 changeRequest: {
79 shortLabel: "PR",
80 shortLabelWithArticle: "a PR",
81 singular: "pull request",
82 plural: "pull requests",
83 },
84 repositoryPathHint: "owner/repo",
85 // Codeberg is the public Forgejo; any other server is self-hosted.
86 publicHost: "codeberg.org",
87 publishDescription: "Your signed-in server",
88 publishHost: (signedInHost) => signedInHost ?? "your server",
89 newRepositoryOwner: (account) => (account ? { owner: account } : null),
90 defaultCloneTransport: "https",
91 // The server's resolved web URL wins; otherwise an HTTP remote on the same host names the
92 // origin, which may carry a port. SSH remotes say nothing about the web origin.
93 changeRequestUrl: ({ host, repository, number, remoteUrl, webUrl }) =>
94 webUrl
95 ? changeRequestUrlBelow(webUrl, `pulls/${number}`)
96 : `${remoteWebOrigin(host, remoteUrl)}/${repository}/pulls/${number}`,
97 // A server's identity includes its port, so the link carries it.
98 parseChangeRequestUrl: (url) => {
99 const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH);
100 return link === null ? null : { ...link, authority: url.host.toLowerCase() };
101 },
102 // `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea,
103 // unless a Forgejo project on that host vouches for it.
104 parseIssueUrl: (url, known) =>
105 known || isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null,
106 changeRequestUrlFromReferenceAutolink: () => null,
107 commitUrl: (input) => buildCommitUrl(input, "commit"),
108 parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH),
109 repositoryUrlFromPage: (url, known) => {
110 // A mount path may itself contain `src/branch/`, so a `.git` path is always the clone URL.
111 if (url.pathname.replace(/\/$/u, "").endsWith(".git")) return null;
112 const repositoryUrl = repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH);
113 // Elsewhere the same path is a GitLab project nested under groups named `src` and `branch`.
114 return repositoryUrl === null || known ? repositoryUrl : url.href;
115 },
116 changeRequestActions: new Set(["merge", "close", "reopen", "update-branch"] as const),
117 // Neither `fj` nor `tea` checks out by number.
118 checkoutCommand: ({ number, repositoryUrl }) =>
119 repositoryUrl
120 ? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' ${changeRequestHeadRef(number)} && git checkout -B pulls/${number} FETCH_HEAD`
121 : null,
122 // tea also takes `pull` for `pulls` and `m` for `merge`.
123 changeRequestCloseCommand: /\b(?:tea\s+(?:pr|pulls?)|fj\s+pr)\s+(?:merge|m|close)\b/u,
124 authorProfileUrl: () => null,
125 hardLineBreaks: true,
126 // Forgejo refuses a change request review without a summary, even with inline comments.
127 reviewSummaryRequired: (verdict) => verdict === "request-changes",
128 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
129 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
130 checkoutChangeRequestHost: () => null,
131 changeRequestHeadRef,
132 recognizeRemote: ({ remoteUrl, host, hostname }) =>
133 isForgejoHost(hostname)
134 ? {
135 kind: KIND,
136 name: "Forgejo",
137 baseUrl: /^https?:/iu.test(remoteUrl) ? new URL(remoteUrl).origin : `https://${host}`,
138 }
139 : null,
140 changeRequestHost,
141 isChangeRequestInRepository: (identity, link) => {
142 if (!isChangeRequestAuthorityOfProject(identity, link)) return false;
143 const web = resolvedWebUrl(identity);
144 if (!web)
145 return isChangeRequestInProjectRepository(changeRequestHost(identity), identity, link);
146 return (
147 web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
148 canonicalRepositoryPath(web.pathname.replace(/^\/+|\/+$/g, "")) ===
149 canonicalRepositoryPath(link.repository)
150 );
151 },
152 // A server mounted below a path serves only repositories under that mount.
153 canReadChangeRequestOnHost: (identity, link) => {
154 const web = resolvedWebUrl(identity);
155 if (!web) return isChangeRequestOnProjectHost(changeRequestHost(identity), identity, link);
156 const mount = web.pathname
157 .replace(/^\/+|\/+$/g, "")
158 .split("/")
159 .slice(0, -2)
160 .join("/");
161 return (
162 web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() &&
163 (!mount || link.repository.toLowerCase().startsWith(`${mount.toLowerCase()}/`))
164 );
165 },
166});