forge
Explore
Log in

Don't you dare go Hollow

Import from Forgejo and Gitea

Browse files at this commit

08d9c2e58590d35b141eef6a0fa6a93b0ec7f476Ahmet Kaan GümüşParent: 6216322
  • feat
    • import from Forgejo and Gitea
Show full message
✨ feat: import from Forgejo and Gitea

Forgejo and Gitea (Codeberg included) join GitHub and GitLab as import sources: the repo plus labels, milestones, issues, pull requests with comments and releases with assets, over /api/v1 with limit/page pagination (Link and X-Total-Count), bulk listing and the same outbound address policy. The token is sent as Authorization: token and never stored.
crates/forge-web/src/i18n/migrate.rsmodified+19 -4
@@ -14,12 +14,14 @@ pub enum K {
1414 SrcGit,
1515 SrcGitHub,
1616 SrcGitLab,
17+ SrcForgejo,
1718 GitUrl,
1819 GitUser,
1920 GitPassword,
2021 GitHubRepo,
2122 GitLabInstance,
2223 GitLabProject,
24+ ForgejoInstance,
2325 TokenOptional,
2426 TokenHelp,
2527 TargetOwner,
@@ -40,6 +42,7 @@ pub enum K {
4042 BulkIntro,
4143 BulkOwnerGitHub,
4244 BulkOwnerGitLab,
45+ BulkOwnerForgejo,
4346 BulkListButton,
4447 BulkSelectHeading,
4548 BulkSelectAll,
@@ -98,12 +101,14 @@ const ALL: &[K] = &[
98101 K::SrcGit,
99102 K::SrcGitHub,
100103 K::SrcGitLab,
104+ K::SrcForgejo,
101105 K::GitUrl,
102106 K::GitUser,
103107 K::GitPassword,
104108 K::GitHubRepo,
105109 K::GitLabInstance,
106110 K::GitLabProject,
111+ K::ForgejoInstance,
107112 K::TokenOptional,
108113 K::TokenHelp,
109114 K::TargetOwner,
@@ -123,6 +128,7 @@ const ALL: &[K] = &[
123128 K::BulkIntro,
124129 K::BulkOwnerGitHub,
125130 K::BulkOwnerGitLab,
131+ K::BulkOwnerForgejo,
126132 K::BulkListButton,
127133 K::BulkSelectHeading,
128134 K::BulkSelectAll,
@@ -182,6 +188,7 @@ fn pair(key: K) -> (&'static str, &'static str) {
182188 K::SrcGit => ("Git URL", "Git URL'si"),
183189 K::SrcGitHub => ("GitHub", "GitHub"),
184190 K::SrcGitLab => ("GitLab", "GitLab"),
191+ K::SrcForgejo => ("Forgejo / Gitea", "Forgejo / Gitea"),
185192 K::GitUrl => ("Repository URL", "Depo URL'si"),
186193 K::GitUser => ("Username (optional)", "Kullanıcı adı (isteğe bağlı)"),
187194 K::GitPassword => (
@@ -191,6 +198,10 @@ fn pair(key: K) -> (&'static str, &'static str) {
191198 K::GitHubRepo => ("Repository (owner/name)", "Depo (sahip/ad)"),
192199 K::GitLabInstance => ("GitLab address", "GitLab adresi"),
193200 K::GitLabProject => ("Project path", "Proje yolu"),
201+ K::ForgejoInstance => (
202+ "Forgejo or Gitea address (Codeberg works too)",
203+ "Forgejo veya Gitea adresi (Codeberg da olur)",
204+ ),
194205 K::TokenOptional => ("Access token (optional)", "Erişim belirteci (isteğe bağlı)"),
195206 K::TokenHelp => (
196207 "Needed for private repositories and higher rate limits. It is used only while the import runs and is never stored.",
@@ -209,8 +220,8 @@ fn pair(key: K) -> (&'static str, &'static str) {
209220 K::OptPulls => ("Pull requests (as issues)", "Çekme istekleri (konu olarak)"),
210221 K::OptReleases => ("Releases and their files", "Sürümler ve dosyaları"),
211222 K::OptionsNote => (
212- "Authors with no account here are shown as \"originally by @name on GitHub\". Pull requests become issues marked \"imported PR\", because their branches may be gone.",
213- "Burada hesabı olmayan yazarlar \"@ad tarafından, GitHub'da\" olarak gösterilir. Çekme istekleri, dalları silinmiş olabileceğinden \"imported PR\" işaretli konulara dönüşür.",
223+ "Authors with no account here are shown as \"originally by @name on the source site\". Pull requests become issues marked \"imported PR\", because their branches may be gone.",
224+ "Burada hesabı olmayan yazarlar \"@ad tarafından, kaynak sitede\" olarak gösterilir. Çekme istekleri, dalları silinmiş olabileceğinden \"imported PR\" işaretli konulara dönüşür.",
214225 ),
215226 K::StartImport => ("Start import", "İçe aktarmayı başlat"),
216227 K::BulkLink => ("Import several repositories", "Birden çok depoyu içe aktar"),
@@ -224,6 +235,10 @@ fn pair(key: K) -> (&'static str, &'static str) {
224235 "GitHub user or organization",
225236 "GitHub kullanıcısı veya kuruluşu",
226237 ),
238+ K::BulkOwnerForgejo => (
239+ "User or organization (empty with a token lists your own)",
240+ "Kullanıcı veya kuruluş (belirteçle boş bırakırsanız kendi depolarınız listelenir)",
241+ ),
227242 K::BulkOwnerGitLab => ("GitLab user or group", "GitLab kullanıcısı veya grubu"),
228243 K::BulkListButton => ("List repositories", "Depoları listele"),
229244 K::BulkSelectHeading => (
@@ -262,8 +277,8 @@ fn pair(key: K) -> (&'static str, &'static str) {
262277 "Bu depo adresi geçerli değil.",
263278 ),
264279 K::ErrBadInstance => (
265- "That GitLab address is not valid.",
266- "Bu GitLab adresi geçerli değil.",
280+ "That instance address is not valid.",
281+ "Bu sunucu adresi geçerli değil.",
267282 ),
268283 K::ErrBadOwner => (
269284 "That user or organization name is not valid.",
crates/forge-web/src/importer/api.rsmodified+351 -9
@@ -14,6 +14,8 @@ use serde::de::DeserializeOwned;
1414
1515 const PER_PAGE: usize = 100;
1616 /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.
17+/// Forgejo and Gitea cap `limit` at 50 by default.
18+const FORGEJO_LIMIT: usize = 50;
1719 const MAX_PAGES: usize = 500;
1820 /// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues.
1921 const MAX_RATE_WAIT: u64 = 15 * 60;
@@ -184,12 +186,22 @@ pub fn rate_wait(
184186
185187 pub type Notice = Arc<dyn Fn(String) + Send + Sync>;
186188
189+/// How the token is presented to the API host.
190+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191+pub enum Auth {
192+ /// `Authorization: Bearer`.
193+ GitHub,
194+ /// `PRIVATE-TOKEN`.
195+ GitLab,
196+ /// `Authorization: token`.
197+ Forgejo,
198+}
199+
187200 /// A client under the outbound policy, with the token kept private to the API host.
188201 pub struct Http {
189202 client: reqwest::Client,
190203 token: Option<String>,
191- /// `Authorization: Bearer` (GitHub) or `PRIVATE-TOKEN` (GitLab).
192- gitlab: bool,
204+ auth: Auth,
193205 auth_host: String,
194206 notice: Notice,
195207 }
@@ -198,7 +210,7 @@ impl Http {
198210 pub fn new(
199211 client: reqwest::Client,
200212 token: Option<String>,
201- gitlab: bool,
213+ auth: Auth,
202214 auth_host: String,
203215 notice: Notice,
204216 ) -> Self {
@@ -206,7 +218,7 @@ impl Http {
206218 Http {
207219 client,
208220 token,
209- gitlab,
221+ auth,
210222 auth_host,
211223 notice,
212224 }
@@ -225,11 +237,12 @@ impl Http {
225237 && Self::host_of(url) == self.auth_host
226238 && let Some(token) = &self.token
227239 {
228- req = if self.gitlab {
229- req.header("PRIVATE-TOKEN", token)
230- } else {
231- req.header(AUTHORIZATION, format!("Bearer {token}"))
232- .header("X-GitHub-Api-Version", "2022-11-28")
240+ req = match self.auth {
241+ Auth::GitLab => req.header("PRIVATE-TOKEN", token),
242+ Auth::GitHub => req
243+ .header(AUTHORIZATION, format!("Bearer {token}"))
244+ .header("X-GitHub-Api-Version", "2022-11-28"),
245+ Auth::Forgejo => req.header(AUTHORIZATION, format!("token {token}")),
233246 };
234247 }
235248 req
@@ -326,6 +339,35 @@ impl Http {
326339 Ok(out)
327340 }
328341
342+ /// Every page of a Forgejo/Gitea list endpoint (`limit`, `page`). The `Link` header decides
343+ /// when it ends; without one, `X-Total-Count`; without either, the first short page.
344+ pub async fn limit_pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {
345+ let sep = if base.contains('?') { '&' } else { '?' };
346+ let mut out: Vec<T> = Vec::new();
347+ for page in 1..=MAX_PAGES {
348+ let url = format!("{base}{sep}limit={FORGEJO_LIMIT}&page={page}");
349+ let resp = self.send(&url, "application/json", true).await?;
350+ let link = Self::header(resp.headers(), "link");
351+ let total = Self::header(resp.headers(), "x-total-count")
352+ .and_then(|v| v.trim().parse::<usize>().ok());
353+ let bytes = Self::body(resp, MAX_JSON_BYTES).await?;
354+ let items: Vec<T> =
355+ serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))?;
356+ let got = items.len();
357+ out.extend(items);
358+ let done = got == 0
359+ || match (&link, total) {
360+ (Some(l), _) => !l.contains("rel=\"next\""),
361+ (None, Some(total)) => out.len() >= total,
362+ (None, None) => got < FORGEJO_LIMIT,
363+ };
364+ if done {
365+ break;
366+ }
367+ }
368+ Ok(out)
369+ }
370+
329371 /// Downloads a file, following redirects by hand: the token goes to the API host only, and
330372 /// each hop is fetched under the same address policy as every other request.
331373 pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<Vec<u8>> {
@@ -1034,6 +1076,306 @@ impl RemoteApi for GitLab {
10341076 }
10351077 }
10361078
1079+// ---- Forgejo and Gitea ----
1080+
1081+/// A Forgejo or Gitea instance (Codeberg among them), over `/api/v1`.
1082+pub struct Forgejo {
1083+ http: Http,
1084+ /// `https://host`, the web address the asset links must start with.
1085+ origin: String,
1086+ /// `https://host/api/v1`.
1087+ base: String,
1088+}
1089+
1090+impl Forgejo {
1091+ /// `instance` is the instance's web address, e.g. `https://codeberg.org`.
1092+ pub fn new(http: Http, instance: &str) -> Self {
1093+ let origin = instance.trim_end_matches('/').to_owned();
1094+ Forgejo {
1095+ http,
1096+ base: format!("{origin}/api/v1"),
1097+ origin,
1098+ }
1099+ }
1100+}
1101+
1102+#[derive(Deserialize)]
1103+struct FjUser {
1104+ login: Option<String>,
1105+ username: Option<String>,
1106+}
1107+
1108+fn fj_user(u: Option<FjUser>) -> String {
1109+ u.and_then(|u| u.login.filter(|l| !l.is_empty()).or(u.username))
1110+ .unwrap_or_default()
1111+}
1112+
1113+#[derive(Deserialize)]
1114+struct FjLabel {
1115+ name: String,
1116+ color: Option<String>,
1117+ description: Option<String>,
1118+}
1119+
1120+#[derive(Deserialize)]
1121+struct FjMilestone {
1122+ id: i64,
1123+ title: String,
1124+ description: Option<String>,
1125+ state: String,
1126+ due_on: Option<String>,
1127+}
1128+
1129+#[derive(Deserialize)]
1130+struct FjMilestoneRef {
1131+ title: String,
1132+}
1133+
1134+#[derive(Deserialize)]
1135+struct FjIssue {
1136+ number: i64,
1137+ title: String,
1138+ body: Option<String>,
1139+ state: String,
1140+ user: Option<FjUser>,
1141+ #[serde(default)]
1142+ labels: Vec<FjLabel>,
1143+ milestone: Option<FjMilestoneRef>,
1144+ created_at: Option<String>,
1145+ html_url: Option<String>,
1146+ /// Set on `/pulls` items.
1147+ #[serde(default)]
1148+ merged: bool,
1149+}
1150+
1151+#[derive(Deserialize)]
1152+struct FjComment {
1153+ id: i64,
1154+ body: Option<String>,
1155+ user: Option<FjUser>,
1156+ created_at: Option<String>,
1157+ html_url: Option<String>,
1158+}
1159+
1160+#[derive(Deserialize)]
1161+struct FjAsset {
1162+ id: i64,
1163+ name: String,
1164+ size: Option<u64>,
1165+ browser_download_url: String,
1166+}
1167+
1168+#[derive(Deserialize)]
1169+struct FjRelease {
1170+ id: i64,
1171+ tag_name: String,
1172+ name: Option<String>,
1173+ body: Option<String>,
1174+ #[serde(default)]
1175+ draft: bool,
1176+ #[serde(default)]
1177+ prerelease: bool,
1178+ author: Option<FjUser>,
1179+ created_at: Option<String>,
1180+ html_url: Option<String>,
1181+ #[serde(default)]
1182+ assets: Vec<FjAsset>,
1183+}
1184+
1185+#[derive(Deserialize)]
1186+struct FjRepo {
1187+ name: String,
1188+ full_name: String,
1189+ description: Option<String>,
1190+ #[serde(default)]
1191+ private: bool,
1192+ #[serde(default)]
1193+ fork: bool,
1194+ #[serde(default)]
1195+ archived: bool,
1196+ default_branch: Option<String>,
1197+ html_url: Option<String>,
1198+}
1199+
1200+fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue {
1201+ ExtIssue {
1202+ number: i.number,
1203+ title: i.title,
1204+ body: s(i.body),
1205+ closed: i.state != "open",
1206+ not_planned: false,
1207+ merged: is_pr && i.merged,
1208+ author: fj_user(i.user),
1209+ labels: i.labels.into_iter().map(|l| l.name).collect(),
1210+ milestone: i.milestone.map(|m| m.title),
1211+ created_at: s(i.created_at),
1212+ url: s(i.html_url),
1213+ is_pr,
1214+ }
1215+}
1216+
1217+fn fj_release(r: FjRelease) -> ExtRelease {
1218+ ExtRelease {
1219+ id: r.id.to_string(),
1220+ title: r
1221+ .name
1222+ .filter(|n| !n.is_empty())
1223+ .unwrap_or_else(|| r.tag_name.clone()),
1224+ tag: r.tag_name,
1225+ body: s(r.body),
1226+ draft: r.draft,
1227+ prerelease: r.prerelease,
1228+ author: fj_user(r.author),
1229+ created_at: s(r.created_at),
1230+ url: s(r.html_url),
1231+ assets: r
1232+ .assets
1233+ .into_iter()
1234+ .map(|a| ExtAsset {
1235+ id: a.id.to_string(),
1236+ name: a.name,
1237+ size: a.size.unwrap_or(0),
1238+ content_type: String::new(),
1239+ url: a.browser_download_url,
1240+ })
1241+ .collect(),
1242+ }
1243+}
1244+
1245+impl RemoteApi for Forgejo {
1246+ async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
1247+ // An empty owner means "mine", which needs a token.
1248+ let raw: Vec<FjRepo> = if owner.is_empty() {
1249+ self.http
1250+ .limit_pages(&format!("{}/user/repos", self.base))
1251+ .await?
1252+ } else {
1253+ if !valid_segment(owner) {
1254+ return Err(ApiError::NotFound("owner".into()));
1255+ }
1256+ let org: ApiResult<Vec<FjRepo>> = self
1257+ .http
1258+ .limit_pages(&format!("{}/orgs/{owner}/repos", self.base))
1259+ .await;
1260+ match org {
1261+ Ok(raw) => raw,
1262+ Err(ApiError::NotFound(_)) => {
1263+ self.http
1264+ .limit_pages(&format!("{}/users/{owner}/repos", self.base))
1265+ .await?
1266+ }
1267+ Err(e) => return Err(e),
1268+ }
1269+ };
1270+ Ok(raw
1271+ .into_iter()
1272+ .map(|r| ExtRepo {
1273+ name: r.name,
1274+ full_name: r.full_name,
1275+ description: s(r.description),
1276+ private: r.private,
1277+ fork: r.fork,
1278+ archived: r.archived,
1279+ default_branch: s(r.default_branch),
1280+ web_url: s(r.html_url),
1281+ })
1282+ .collect())
1283+ }
1284+
1285+ async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> {
1286+ check_repo(repo, 2, 2)?;
1287+ let raw: Vec<FjLabel> = self
1288+ .http
1289+ .limit_pages(&format!("{}/repos/{repo}/labels", self.base))
1290+ .await?;
1291+ Ok(raw
1292+ .into_iter()
1293+ .map(|l| ExtLabel {
1294+ name: l.name,
1295+ color: format!("#{}", s(l.color).trim_start_matches('#')),
1296+ description: s(l.description),
1297+ })
1298+ .collect())
1299+ }
1300+
1301+ async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> {
1302+ check_repo(repo, 2, 2)?;
1303+ let raw: Vec<FjMilestone> = self
1304+ .http
1305+ .limit_pages(&format!("{}/repos/{repo}/milestones?state=all", self.base))
1306+ .await?;
1307+ Ok(raw
1308+ .into_iter()
1309+ .map(|m| ExtMilestone {
1310+ id: m.id.to_string(),
1311+ title: m.title,
1312+ description: s(m.description),
1313+ closed: m.state == "closed",
1314+ due_on: m.due_on.as_deref().and_then(day),
1315+ })
1316+ .collect())
1317+ }
1318+
1319+ async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> {
1320+ check_repo(repo, 2, 2)?;
1321+ let issues: Vec<FjIssue> = self
1322+ .http
1323+ .limit_pages(&format!(
1324+ "{}/repos/{repo}/issues?type=issues&state=all&sort=oldest",
1325+ self.base
1326+ ))
1327+ .await?;
1328+ let pulls: Vec<FjIssue> = self
1329+ .http
1330+ .limit_pages(&format!(
1331+ "{}/repos/{repo}/pulls?state=all&sort=oldest",
1332+ self.base
1333+ ))
1334+ .await?;
1335+ let mut out: Vec<ExtIssue> = issues.into_iter().map(|i| fj_issue(i, false)).collect();
1336+ out.extend(pulls.into_iter().map(|i| fj_issue(i, true)));
1337+ Ok(out)
1338+ }
1339+
1340+ async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
1341+ check_repo(repo, 2, 2)?;
1342+ let raw: Vec<FjComment> = self
1343+ .http
1344+ .limit_pages(&format!(
1345+ "{}/repos/{repo}/issues/{}/comments",
1346+ self.base, issue.number
1347+ ))
1348+ .await?;
1349+ Ok(raw
1350+ .into_iter()
1351+ .map(|c| ExtComment {
1352+ id: c.id.to_string(),
1353+ author: fj_user(c.user),
1354+ body: s(c.body),
1355+ created_at: s(c.created_at),
1356+ url: s(c.html_url),
1357+ })
1358+ .collect())
1359+ }
1360+
1361+ async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> {
1362+ check_repo(repo, 2, 2)?;
1363+ let raw: Vec<FjRelease> = self
1364+ .http
1365+ .limit_pages(&format!("{}/repos/{repo}/releases", self.base))
1366+ .await?;
1367+ // The list embeds each release's assets, so `/releases/{id}/assets` is not needed.
1368+ Ok(raw.into_iter().map(fj_release).collect())
1369+ }
1370+
1371+ async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<Vec<u8>> {
1372+ if !asset.url.starts_with(&format!("{}/", self.origin)) {
1373+ return Err(ApiError::Http("unexpected asset address".into()));
1374+ }
1375+ self.http.download(&asset.url, max_bytes).await
1376+ }
1377+}
1378+
10371379 #[cfg(test)]
10381380 mod tests {
10391381 use super::*;
crates/forge-web/src/importer/forgejo_tests.rsadded+402 -0
@@ -0,0 +1,402 @@
1+//! Forgejo and Gitea import tests against a tiny local HTTP server that speaks `/api/v1`: the real
2+//! [`Forgejo`] client, real pagination, nothing on the network.
3+
4+use std::sync::{Arc, Mutex};
5+
6+use serde_json::{Value, json};
7+use tokio::io::{AsyncReadExt, AsyncWriteExt};
8+use tokio::net::TcpListener;
9+
10+use super::*;
11+use crate::importer::api::{Auth, Forgejo, Http};
12+
13+type Reply = (Vec<(String, String)>, Vec<u8>);
14+type Log = Arc<Mutex<Vec<(String, Option<String>)>>>;
15+
16+/// Binds a port and returns the base address with the listener.
17+async fn bind() -> (TcpListener, String) {
18+ let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
19+ let base = format!("http://{}", listener.local_addr().expect("addr"));
20+ (listener, base)
21+}
22+
23+/// Serves `handler(target)` for every GET; `None` is a 404. Returns the request log
24+/// (target, `Authorization` header).
25+fn serve<F>(listener: TcpListener, handler: F) -> Log
26+where
27+ F: Fn(&str) -> Option<Reply> + Send + Sync + 'static,
28+{
29+ let log: Log = Arc::default();
30+ let seen = log.clone();
31+ let handler = Arc::new(handler);
32+ tokio::spawn(async move {
33+ loop {
34+ let Ok((mut sock, _)) = listener.accept().await else {
35+ return;
36+ };
37+ let handler = handler.clone();
38+ let seen = seen.clone();
39+ tokio::spawn(async move {
40+ let mut buf = Vec::new();
41+ let mut chunk = [0u8; 2048];
42+ while !buf.windows(4).any(|w| w == b"\r\n\r\n") {
43+ match sock.read(&mut chunk).await {
44+ Ok(0) | Err(_) => return,
45+ Ok(n) => buf.extend_from_slice(&chunk[..n]),
46+ }
47+ }
48+ let text = String::from_utf8_lossy(&buf).into_owned();
49+ let target = text
50+ .lines()
51+ .next()
52+ .and_then(|l| l.split_whitespace().nth(1))
53+ .unwrap_or("/")
54+ .to_owned();
55+ let auth = text.lines().find_map(|l| {
56+ let (k, v) = l.split_once(':')?;
57+ k.eq_ignore_ascii_case("authorization")
58+ .then(|| v.trim().to_owned())
59+ });
60+ seen.lock().unwrap().push((target.clone(), auth));
61+ let out = match handler(&target) {
62+ Some((headers, body)) => {
63+ let mut head = format!(
64+ "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n",
65+ body.len()
66+ );
67+ for (k, v) in headers {
68+ head.push_str(&format!("{k}: {v}\r\n"));
69+ }
70+ head.push_str("\r\n");
71+ let mut out = head.into_bytes();
72+ out.extend(body);
73+ out
74+ }
75+ None => {
76+ b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
77+ .to_vec()
78+ }
79+ };
80+ let _ = sock.write_all(&out).await;
81+ let _ = sock.shutdown().await;
82+ });
83+ }
84+ });
85+ log
86+}
87+
88+fn json_reply(headers: Vec<(&str, String)>, body: &Value) -> Option<Reply> {
89+ let mut all = vec![("content-type".to_owned(), "application/json".to_owned())];
90+ all.extend(headers.into_iter().map(|(k, v)| (k.to_owned(), v)));
91+ Some((all, body.to_string().into_bytes()))
92+}
93+
94+fn page_of(target: &str) -> usize {
95+ target
96+ .split(['?', '&'])
97+ .find_map(|p| p.strip_prefix("page="))
98+ .and_then(|v| v.parse().ok())
99+ .unwrap_or(1)
100+}
101+
102+fn client(base: &str, token: Option<&str>) -> Forgejo {
103+ let notice: super::super::api::Notice = Arc::new(|_| {});
104+ let http = Http::new(
105+ reqwest::Client::new(),
106+ token.map(str::to_owned),
107+ Auth::Forgejo,
108+ "127.0.0.1".into(),
109+ notice,
110+ );
111+ Forgejo::new(http, base)
112+}
113+
114+fn issue_json(n: i64, state: &str) -> Value {
115+ json!({
116+ "number": n, "title": format!("Issue {n}"), "body": "text", "state": state,
117+ "user": {"login": "hubot"}, "labels": [{"name": "bug", "color": "d73a4a"}],
118+ "milestone": null, "created_at": "2020-01-02T03:04:05Z",
119+ "html_url": format!("https://codeberg.example/tahinli/project/issues/{n}"),
120+ })
121+}
122+
123+#[tokio::test]
124+async fn pagination_follows_the_link_header_with_a_limit_of_fifty() {
125+ let (listener, base) = bind().await;
126+ let log = serve(listener, |target| {
127+ if !target.starts_with("/api/v1/repos/tahinli/project/issues?type=issues") {
128+ return json_reply(vec![], &json!([]));
129+ }
130+ match page_of(target) {
131+ 1 => json_reply(
132+ vec![
133+ ("x-total-count", "52".into()),
134+ (
135+ "link",
136+ "<http://x/api/v1/p?page=2>; rel=\"next\", <http://x/api/v1/p?page=2>; rel=\"last\""
137+ .into(),
138+ ),
139+ ],
140+ &Value::Array((1..=50).map(|n| issue_json(n, "open")).collect()),
141+ ),
142+ 2 => json_reply(
143+ vec![
144+ ("x-total-count", "52".into()),
145+ ("link", "<http://x/api/v1/p?page=1>; rel=\"prev\"".into()),
146+ ],
147+ &Value::Array((51..=52).map(|n| issue_json(n, "closed")).collect()),
148+ ),
149+ _ => json_reply(vec![], &json!([])),
150+ }
151+ });
152+ let api = client(&base, Some("abc123"));
153+ let issues = api.issues("tahinli/project").await.unwrap();
154+ let plain: Vec<_> = issues.iter().filter(|i| !i.is_pr).collect();
155+ assert_eq!(plain.len(), 52, "both pages were read");
156+ assert!(plain[51].closed && !plain[0].closed);
157+ assert_eq!(plain[0].author, "hubot");
158+ assert_eq!(plain[0].labels, vec!["bug"]);
159+
160+ let log = log.lock().unwrap();
161+ let issue_calls: Vec<_> = log
162+ .iter()
163+ .filter(|(t, _)| t.contains("type=issues"))
164+ .collect();
165+ assert_eq!(issue_calls.len(), 2, "stopped when the link had no next");
166+ assert!(issue_calls[0].0.contains("limit=50"));
167+ assert!(issue_calls[0].0.contains("page=1") && issue_calls[1].0.contains("page=2"));
168+ assert!(
169+ log.iter()
170+ .all(|(_, auth)| auth.as_deref() == Some("token abc123")),
171+ "every request carries the token header"
172+ );
173+}
174+
175+#[tokio::test]
176+async fn the_total_count_stops_a_listing_with_no_link_header() {
177+ let (listener, base) = bind().await;
178+ let log = serve(listener, |target| {
179+ json_reply(
180+ vec![("x-total-count", "50".into())],
181+ &Value::Array(
182+ (0..50)
183+ .map(|i| json!({"name": format!("l{i}"), "color": "00aabb"}))
184+ .collect(),
185+ ),
186+ )
187+ .filter(|_| target.contains("/labels"))
188+ });
189+ let api = client(&base, None);
190+ let labels = api.labels("tahinli/project").await.unwrap();
191+ assert_eq!(labels.len(), 50);
192+ assert_eq!(labels[0].color, "#00aabb");
193+ assert_eq!(
194+ log.lock().unwrap().len(),
195+ 1,
196+ "a full page of exactly the total is the end"
197+ );
198+ assert!(
199+ log.lock().unwrap()[0].1.is_none(),
200+ "no token, no Authorization header"
201+ );
202+}
203+
204+#[tokio::test]
205+async fn pulls_map_merged_closed_and_open() {
206+ let (listener, base) = bind().await;
207+ serve(listener, |target| {
208+ if target.contains("/pulls?") {
209+ let mut merged = issue_json(2, "closed");
210+ merged["merged"] = json!(true);
211+ let closed = issue_json(3, "closed");
212+ let mut open = issue_json(4, "open");
213+ open["milestone"] = json!({"title": "v1"});
214+ json_reply(vec![], &json!([merged, closed, open]))
215+ } else if target.contains("/issues?") {
216+ json_reply(vec![], &json!([issue_json(1, "open")]))
217+ } else {
218+ None
219+ }
220+ });
221+ let api = client(&base, None);
222+ let all = api.issues("tahinli/project").await.unwrap();
223+ assert_eq!(all.len(), 4);
224+ assert!(!all[0].is_pr);
225+ let pulls: Vec<_> = all.iter().filter(|i| i.is_pr).collect();
226+ assert!(pulls[0].closed && pulls[0].merged);
227+ assert!(pulls[1].closed && !pulls[1].merged);
228+ assert!(!pulls[2].closed);
229+ assert_eq!(pulls[2].milestone.as_deref(), Some("v1"));
230+}
231+
232+#[tokio::test]
233+async fn bulk_listing_tries_the_org_then_the_user_and_supports_own_repos() {
234+ let (listener, base) = bind().await;
235+ let repo = |name: &str, private: bool| {
236+ json!({"name": name, "full_name": format!("tahinli/{name}"), "private": private,
237+ "fork": false, "archived": false, "default_branch": "main", "description": null})
238+ };
239+ let log = serve(listener, move |target| {
240+ if target.starts_with("/api/v1/users/tahinli/repos") {
241+ json_reply(vec![], &json!([repo("a", false)]))
242+ } else if target.starts_with("/api/v1/user/repos") {
243+ json_reply(vec![], &json!([repo("a", false), repo("b", true)]))
244+ } else {
245+ None
246+ }
247+ });
248+ let api = client(&base, Some("t"));
249+ let public = api.list_repos("tahinli").await.unwrap();
250+ assert_eq!(public.len(), 1);
251+ assert_eq!(public[0].full_name, "tahinli/a");
252+ assert!(
253+ log.lock().unwrap()[0]
254+ .0
255+ .starts_with("/api/v1/orgs/tahinli/repos"),
256+ "the org is tried first"
257+ );
258+ let mine = api.list_repos("").await.unwrap();
259+ assert_eq!(mine.len(), 2);
260+ assert!(mine[1].private);
261+}
262+
263+#[tokio::test]
264+async fn a_bad_asset_address_is_refused_before_any_request() {
265+ let (listener, base) = bind().await;
266+ let log = serve(listener, |_| None);
267+ let api = client(&base, Some("t"));
268+ let asset = ExtAsset {
269+ url: "https://elsewhere.example/a.bin".into(),
270+ ..ExtAsset::default()
271+ };
272+ assert!(api.download(&asset, 100).await.is_err());
273+ assert!(log.lock().unwrap().is_empty());
274+}
275+
276+#[tokio::test]
277+async fn full_forgejo_import_maps_issues_pulls_comments_labels_and_releases() {
278+ let fx = fixture().await;
279+ let (listener, base) = bind().await;
280+ let origin = base.clone();
281+ serve(listener, move |target| {
282+ let path = target.split('?').next().unwrap_or_default();
283+ match path {
284+ "/api/v1/repos/tahinli/project/labels" => json_reply(
285+ vec![],
286+ &json!([{"name": "bug", "color": "d73a4a", "description": "Broken"}]),
287+ ),
288+ "/api/v1/repos/tahinli/project/milestones" => json_reply(
289+ vec![],
290+ &json!([{"id": 9, "title": "v1", "description": "", "state": "closed",
291+ "due_on": "2020-05-06T00:00:00Z"}]),
292+ ),
293+ "/api/v1/repos/tahinli/project/issues" => {
294+ json_reply(vec![], &json!([issue_json(1, "closed")]))
295+ }
296+ "/api/v1/repos/tahinli/project/pulls" => {
297+ let mut pr = issue_json(2, "closed");
298+ pr["title"] = json!("Add the thing");
299+ pr["merged"] = json!(true);
300+ json_reply(vec![], &json!([pr]))
301+ }
302+ "/api/v1/repos/tahinli/project/issues/1/comments" => json_reply(
303+ vec![],
304+ &json!([{"id": 11, "body": "same here", "user": {"login": "hubot"},
305+ "created_at": "2020-01-03T00:00:00Z",
306+ "html_url": "https://codeberg.example/c/11"}]),
307+ ),
308+ "/api/v1/repos/tahinli/project/issues/2/comments" => json_reply(vec![], &json!([])),
309+ "/api/v1/repos/tahinli/project/releases" => json_reply(
310+ vec![],
311+ &json!([{"id": 5, "tag_name": "v1", "name": "", "body": "notes", "draft": false,
312+ "prerelease": false, "author": {"login": "hubot"},
313+ "created_at": "2021-01-01T00:00:00Z",
314+ "html_url": "https://codeberg.example/r/5",
315+ "assets": [{"id": 1, "name": "app.tar.gz", "size": 5,
316+ "browser_download_url": format!("{origin}/attachments/uuid-1")}]}]),
317+ ),
318+ "/attachments/uuid-1" => Some((vec![], b"hello".to_vec())),
319+ _ => None,
320+ }
321+ });
322+ let api = client(&base, Some(TOKEN));
323+ let job = new_job(&fx, Source::Forgejo).await;
324+ let mut spec = spec(Source::Forgejo, everything());
325+ spec.instance = base.clone();
326+ run_job(
327+ &fx.state,
328+ &job,
329+ &spec,
330+ Some(&api),
331+ &Transport::Local(fx.upstream.clone()),
332+ )
333+ .await;
334+
335+ let store = &fx.state.store;
336+ let job = store.import_job(&job.id).await.unwrap().unwrap();
337+ assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
338+
339+ let all = IssueFilter {
340+ state: None,
341+ per_page: 100,
342+ ..IssueFilter::default()
343+ };
344+ let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();
345+ assert_eq!(total, 2);
346+ let issue = items.iter().find(|i| i.issue.title == "Issue 1").unwrap();
347+ assert_eq!(issue.issue.state, IssueState::Closed);
348+ assert!(
349+ issue
350+ .issue
351+ .body
352+ .starts_with("> Originally by \\@hubot on Forgejo, 2020-01-02"),
353+ "{}",
354+ issue.issue.body
355+ );
356+ assert!(issue.labels.iter().any(|l| l.name == "bug"));
357+ let pull = items
358+ .iter()
359+ .find(|i| i.issue.title == "Add the thing")
360+ .unwrap();
361+ assert!(pull.issue.body.contains("Imported pull request (merged)"));
362+ let comments = store.list_comments(&issue.issue.id).await.unwrap();
363+ assert_eq!(comments.len(), 1);
364+ assert!(comments[0].body.ends_with("same here"));
365+
366+ let release = store
367+ .release_by_tag(&fx.repo.id, "v1")
368+ .await
369+ .unwrap()
370+ .unwrap();
371+ assert!(release.body.contains("notes"));
372+ let assets = store.list_release_assets(&release.id).await.unwrap();
373+ assert_eq!(assets.len(), 1);
374+ assert_eq!(assets[0].name, "app.tar.gz");
375+ assert_eq!(assets[0].size, 5);
376+}
377+
378+#[test]
379+fn forgejo_remotes_take_a_url_or_a_path_with_an_instance() {
380+ use crate::importer::parse_remote;
381+ assert_eq!(
382+ parse_remote(
383+ Source::Forgejo,
384+ "https://codeberg.org/tahinli/forge.git",
385+ ""
386+ ),
387+ Some(("tahinli/forge".into(), "https://codeberg.org".into()))
388+ );
389+ assert_eq!(
390+ parse_remote(Source::Forgejo, "tahinli/forge", "https://codeberg.org/"),
391+ Some(("tahinli/forge".into(), "https://codeberg.org".into()))
392+ );
393+ assert_eq!(
394+ parse_remote(Source::Forgejo, "a/b/c", "https://codeberg.org"),
395+ None
396+ );
397+ assert_eq!(parse_remote(Source::Forgejo, "tahinli/forge", ""), None);
398+ assert_eq!(Source::parse("gitea"), Some(Source::Forgejo));
399+ let mut s = spec(Source::Forgejo, ImportOptions::default());
400+ s.instance = "https://codeberg.org/".into();
401+ assert_eq!(s.clone_url(), "https://codeberg.org/tahinli/project.git");
402+}
crates/forge-web/src/importer/mod.rsmodified+20 -9
@@ -1,7 +1,7 @@
1-//! Repository import: a one-shot copy of a repo from a git URL, GitHub or GitLab.
1+//! Repository import: a one-shot copy of a repo from a git URL, GitHub, GitLab or Forgejo/Gitea.
22 //!
33 //! The git data comes from the same fetch the pull mirrors use, once, into a normal repo (no mirror
4-//! row is created). For GitHub and GitLab the job can also copy labels, milestones, issues with
4+//! row is created). For the forge sources the job can also copy labels, milestones, issues with
55 //! comments, pull requests (as issues marked "imported PR") and releases with their assets, through
66 //! a [`RemoteApi`]. Progress is written to the database and every step wakes the job page's event
77 //! stream, so the page updates with no polling.
@@ -26,7 +26,9 @@ use serde::{Deserialize, Serialize};
2626 use tokio::sync::{Semaphore, watch};
2727
2828 use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi};
29-pub use self::remote::{default_name, make_github, make_gitlab, parse_remote, source_ref};
29+pub use self::remote::{
30+ default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref,
31+};
3032 use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot};
3133 use crate::state::AppState;
3234
@@ -43,6 +45,7 @@ pub enum Source {
4345 Git,
4446 GitHub,
4547 GitLab,
48+ Forgejo,
4649 }
4750
4851 impl Source {
@@ -51,6 +54,7 @@ impl Source {
5154 Source::Git => "git",
5255 Source::GitHub => "github",
5356 Source::GitLab => "gitlab",
57+ Source::Forgejo => "forgejo",
5458 }
5559 }
5660
@@ -59,6 +63,8 @@ impl Source {
5963 "git" => Some(Source::Git),
6064 "github" => Some(Source::GitHub),
6165 "gitlab" => Some(Source::GitLab),
66+ // Gitea speaks the same API.
67+ "forgejo" | "gitea" => Some(Source::Forgejo),
6268 _ => None,
6369 }
6470 }
@@ -69,6 +75,7 @@ impl Source {
6975 Source::Git => "git",
7076 Source::GitHub => "GitHub",
7177 Source::GitLab => "GitLab",
78+ Source::Forgejo => "Forgejo",
7279 }
7380 }
7481 }
@@ -98,7 +105,7 @@ pub struct JobSpec {
98105 pub source: Source,
99106 /// The URL for `git`, `owner/repo` for GitHub, the project path for GitLab.
100107 pub remote: String,
101- /// The GitLab instance, e.g. `https://gitlab.com`.
108+ /// The GitLab or Forgejo instance, e.g. `https://gitlab.com`.
102109 pub instance: String,
103110 pub token: Option<String>,
104111 /// The user name sent with the token for a plain git URL.
@@ -121,7 +128,7 @@ impl JobSpec {
121128 match self.source {
122129 Source::Git => self.remote.clone(),
123130 Source::GitHub => format!("https://github.com/{}.git", self.remote),
124- Source::GitLab => format!(
131+ Source::GitLab | Source::Forgejo => format!(
125132 "{}/{}.git",
126133 self.instance.trim_end_matches('/'),
127134 self.remote
@@ -133,7 +140,7 @@ impl JobSpec {
133140 let token = self.token.as_ref().filter(|t| !t.is_empty())?;
134141 let username = match self.source {
135142 Source::GitHub => "x-access-token".to_owned(),
136- Source::GitLab => "oauth2".to_owned(),
143+ Source::GitLab | Source::Forgejo => "oauth2".to_owned(),
137144 Source::Git if self.git_user.is_empty() => "git".to_owned(),
138145 Source::Git => self.git_user.clone(),
139146 };
@@ -337,6 +344,10 @@ async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) {
337344 Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await,
338345 Err(e) => fail(state, &rep, &e).await,
339346 },
347+ Source::Forgejo => match make_forgejo(state, &spec.instance, spec.token.clone(), notice) {
348+ Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await,
349+ Err(e) => fail(state, &rep, &e).await,
350+ },
340351 Source::Git => {}
341352 }
342353 }
@@ -710,9 +721,9 @@ impl<A: RemoteApi> Run<'_, A> {
710721 })
711722 .collect();
712723 items.sort_by_key(|i| (i.is_pr, i.number));
713- // GitHub numbers issues and pull requests together; GitLab keeps two sequences. Sorting
714- // by number alone keeps GitHub numbers aligned, so do that for it.
715- if self.spec.source == Source::GitHub {
724+ // GitHub and Forgejo number issues and pull requests together; GitLab keeps two sequences. Sorting
725+ // by number alone keeps GitHub numbers aligned, so do that for them.
726+ if matches!(self.spec.source, Source::GitHub | Source::Forgejo) {
716727 items.sort_by_key(|i| i.number);
717728 }
718729 let total = items.len();
crates/forge-web/src/importer/remote.rsmodified+32 -8
@@ -3,7 +3,7 @@
33 use std::time::Duration;
44
55 use super::Source;
6-use super::api::{self, GitHub, GitLab, Http, Notice};
6+use super::api::{self, Auth, Forgejo, GitHub, GitLab, Http, Notice};
77 use crate::mirrors::policy;
88 use crate::state::AppState;
99 use crate::webhooks::client::{policy_client, validate_url};
@@ -19,7 +19,7 @@ pub fn make_github(
1919 Ok(GitHub::new(Http::new(
2020 client,
2121 token,
22- false,
22+ Auth::GitHub,
2323 "api.github.com".into(),
2424 notice,
2525 )))
@@ -41,13 +41,34 @@ pub fn make_gitlab(
4141 let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
4242 .map_err(|e| format!("could not build the HTTP client: {e}"))?;
4343 Ok(GitLab::new(
44- Http::new(client, token, true, host, notice),
44+ Http::new(client, token, Auth::GitLab, host, notice),
45+ instance,
46+ ))
47+}
48+
49+/// A Forgejo or Gitea client for `instance`, which must pass the outbound policy.
50+pub fn make_forgejo(
51+ state: &AppState,
52+ instance: &str,
53+ token: Option<String>,
54+ notice: Notice,
55+) -> Result<Forgejo, String> {
56+ let instance = instance.trim_end_matches('/');
57+ let host = validate_url(instance, &policy(state))
58+ .map_err(|e| format!("instance address refused: {e}"))?
59+ .host_str()
60+ .unwrap_or_default()
61+ .to_ascii_lowercase();
62+ let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
63+ .map_err(|e| format!("could not build the HTTP client: {e}"))?;
64+ Ok(Forgejo::new(
65+ Http::new(client, token, Auth::Forgejo, host, notice),
4566 instance,
4667 ))
4768 }
4869
4970 /// Splits what the user typed into `(remote, instance)` for a source. `None` when it is not a
50-/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab takes a project URL
71+/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab and Forgejo take a project URL
5172 /// (`https://host/group/project`) or, with `instance` given, a bare path.
5273 pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> {
5374 let text = text.trim();
@@ -62,7 +83,8 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin
6283 let path = path.strip_suffix(".git").unwrap_or(path);
6384 api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new()))
6485 }
65- Source::GitLab => {
86+ Source::GitLab | Source::Forgejo => {
87+ let max = if source == Source::GitLab { 20 } else { 2 };
6688 if let Some((scheme, rest)) = text
6789 .strip_prefix("https://")
6890 .map(|r| ("https", r))
@@ -71,7 +93,7 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin
7193 let (host, path) = rest.split_once('/')?;
7294 let path = path.trim_end_matches('/');
7395 let path = path.strip_suffix(".git").unwrap_or(path);
74- if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, 20) {
96+ if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, max) {
7597 return None;
7698 }
7799 return Some((path.to_owned(), format!("{scheme}://{host}")));
@@ -85,7 +107,7 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin
85107 let ok = !host.is_empty()
86108 && !host.contains('@')
87109 && !host.contains('/')
88- && api::valid_path(path, 2, 20);
110+ && api::valid_path(path, 2, max);
89111 ok.then(|| (path.to_owned(), instance.to_owned()))
90112 }
91113 }
@@ -94,7 +116,9 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin
94116 /// The reference stored on a job and shown to the user: no credential in it.
95117 pub fn source_ref(source: Source, remote: &str, instance: &str) -> String {
96118 match source {
97- Source::GitLab => format!("{}/{}", instance.trim_end_matches('/'), remote),
119+ Source::GitLab | Source::Forgejo => {
120+ format!("{}/{}", instance.trim_end_matches('/'), remote)
121+ }
98122 _ => remote.to_owned(),
99123 }
100124 }
crates/forge-web/src/importer/tests.rsmodified+3 -0
@@ -542,3 +542,6 @@ fn asset_names_are_made_safe() {
542542 "a b/c?d"
543543 )));
544544 }
545+
546+#[path = "forgejo_tests.rs"]
547+mod forgejo;
crates/forge-web/src/pages/import.rsmodified+56 -22
@@ -24,8 +24,8 @@ use crate::i18n::migrate::{self as g, K};
2424 use crate::i18n::{self, Key, Lang};
2525 use crate::importer::api::{ApiError, RemoteApi};
2626 use crate::importer::{
27- self, ImportOptions, JobSpec, Source, default_name, make_github, make_gitlab, parse_remote,
28- source_ref,
27+ self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab,
28+ parse_remote, source_ref,
2929 };
3030 use crate::pages::ci_runs::{changed_event, events_response};
3131 use crate::pages::new_repo::{owner_choices, repo_owner};
@@ -125,6 +125,27 @@ fn source_of(raw: Option<&str>) -> Source {
125125 raw.and_then(Source::parse).unwrap_or(Source::GitHub)
126126 }
127127
128+/// The instance a source form starts with.
129+fn default_instance(source: Source) -> &'static str {
130+ match source {
131+ Source::Forgejo => "https://codeberg.org",
132+ _ => "https://gitlab.com",
133+ }
134+}
135+
136+/// Sources that are self-hostable and so take an instance address.
137+fn has_instance(source: Source) -> bool {
138+ matches!(source, Source::GitLab | Source::Forgejo)
139+}
140+
141+fn instance_label(lang: Lang, source: Source) -> &'static str {
142+ if source == Source::Forgejo {
143+ g::t(lang, K::ForgejoInstance)
144+ } else {
145+ g::t(lang, K::GitLabInstance)
146+ }
147+}
148+
128149 fn token_of(raw: &str) -> Option<String> {
129150 let t = raw.trim();
130151 (!t.is_empty()).then(|| t.to_owned())
@@ -150,11 +171,13 @@ async fn source_tabs(lang: Lang, base: &str, active: Source) -> Result<impl View
150171 let git = format!("{base}?source=git");
151172 let github = format!("{base}?source=github");
152173 let gitlab = format!("{base}?source=gitlab");
174+ let forgejo = format!("{base}?source=forgejo");
153175 Ok(view! {
154176 <nav class="import-sources" aria-label=(g::t(lang, K::TabImport))>
155177 <a href=(git.as_str()) class="import-source" aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a>
156178 <a href=(github.as_str()) class="import-source" aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a>
157179 <a href=(gitlab.as_str()) class="import-source" aria-current=((active == Source::GitLab).then_some("page"))>(g::t(lang, K::SrcGitLab))</a>
180+ <a href=(forgejo.as_str()) class="import-source" aria-current=((active == Source::Forgejo).then_some("page"))>(g::t(lang, K::SrcForgejo))</a>
158181 </nav>
159182 })
160183 }
@@ -213,7 +236,7 @@ impl Draft {
213236 Draft {
214237 source,
215238 remote: String::new(),
216- instance: "https://gitlab.com".into(),
239+ instance: default_instance(source).into(),
217240 git_user: String::new(),
218241 owner: String::new(),
219242 name: String::new(),
@@ -265,7 +288,8 @@ async fn import_form(
265288 };
266289 let source_value = source.as_str();
267290 let is_git = source == Source::Git;
268- let is_gitlab = source == Source::GitLab;
291+ let has_instance = has_instance(source);
292+ let instance_label = instance_label(lang, source);
269293 let bulk_href = if is_git {
270294 String::new()
271295 } else {
@@ -273,13 +297,13 @@ async fn import_form(
273297 };
274298 let remote_label = match source {
275299 Source::Git => g::t(lang, K::GitUrl),
276- Source::GitHub => g::t(lang, K::GitHubRepo),
300+ Source::GitHub | Source::Forgejo => g::t(lang, K::GitHubRepo),
277301 Source::GitLab => g::t(lang, K::GitLabProject),
278302 };
279303 let remote_placeholder = match source {
280304 Source::Git => "https://example.org/tahinli/project.git",
281305 Source::GitHub => "tahinli/project",
282- Source::GitLab => "tahinli/project",
306+ Source::GitLab | Source::Forgejo => "tahinli/project",
283307 };
284308 let token_label = if is_git {
285309 g::t(lang, K::GitPassword)
@@ -306,9 +330,9 @@ async fn import_form(
306330 source_tabs(lang: lang, base: "/new/import", active: source)
307331 <p class="muted small">(g::t(lang, K::ImportIntro))</p>
308332 <div class="newrepo-card">
309- if is_gitlab {
333+ if has_instance {
310334 <label>
311- <span>(g::t(lang, K::GitLabInstance))</span>
335+ <span>(instance_label)</span>
312336 <input type="url" name="instance" value=(draft.instance.as_str()) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono">
313337 </label>
314338 }
@@ -406,7 +430,7 @@ async fn start_single(
406430 ) -> Result<std::result::Result<String, String>> {
407431 let state = app_context::<AppState>(cx);
408432 let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else {
409- let message = if source == Source::GitLab && form.remote.trim().starts_with("http") {
433+ let message = if has_instance(source) && form.remote.trim().starts_with("http") {
410434 g::t(lang, K::ErrBadInstance)
411435 } else {
412436 g::t(lang, K::ErrBadRemote)
@@ -537,13 +561,16 @@ async fn bulk_form(
537561 owners: Vec<String>,
538562 error: Option<String>,
539563 ) -> Result<impl View> {
540- let is_gitlab = source == Source::GitLab;
564+ let has_instance = has_instance(source);
565+ let instance_label = instance_label(lang, source);
541566 let source_value = source.as_str();
542- let owner_label = if is_gitlab {
543- g::t(lang, K::BulkOwnerGitLab)
544- } else {
545- g::t(lang, K::BulkOwnerGitHub)
567+ let owner_label = match source {
568+ Source::GitLab => g::t(lang, K::BulkOwnerGitLab),
569+ Source::Forgejo => g::t(lang, K::BulkOwnerForgejo),
570+ _ => g::t(lang, K::BulkOwnerGitHub),
546571 };
572+ // A Forgejo token can list its own repositories, so the owner may stay empty.
573+ let owner_required = source != Source::Forgejo;
547574 Ok(view! {
548575 newrepo_tabs(lang: lang, active: "import")
549576 if let Some(message) = error {
@@ -562,15 +589,15 @@ async fn bulk_form(
562589 source_tabs(lang: lang, base: "/new/import/bulk", active: source)
563590 <p class="muted small">(g::t(lang, K::BulkIntro))</p>
564591 <div class="newrepo-card">
565- if is_gitlab {
592+ if has_instance {
566593 <label>
567- <span>(g::t(lang, K::GitLabInstance))</span>
594+ <span>(instance_label)</span>
568595 <input type="url" name="instance" value=(instance) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono">
569596 </label>
570597 }
571598 <label>
572599 <span>(owner_label)</span>
573- <input type="text" name="from" required=(true) autocomplete="off" spellcheck="false" maxlength="100" class="newrepo-mono">
600+ <input type="text" name="from" required=(owner_required) autocomplete="off" spellcheck="false" maxlength="100" class="newrepo-mono">
574601 </label>
575602 <label>
576603 <span>(g::t(lang, K::TokenOptional))</span>
@@ -702,7 +729,7 @@ async fn bulk_page(cx: &Cx) -> Result<impl View> {
702729 let csrf = viewer.1.csrf_token.clone();
703730 Ok(view! { cx =>
704731 shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer),
705- bulk_form(lang: lang, csrf: csrf.as_str(), source: source, instance: "https://gitlab.com", owners: owners, error: query.error.clone().filter(|e| e.len() < 300)))
732+ bulk_form(lang: lang, csrf: csrf.as_str(), source: source, instance: default_instance(source), owners: owners, error: query.error.clone().filter(|e| e.len() < 300)))
706733 })
707734 }
708735
@@ -726,6 +753,11 @@ async fn list_remote(
726753 .list_repos(from)
727754 .await
728755 }
756+ Source::Forgejo => {
757+ make_forgejo(state, instance, token, notice)?
758+ .list_repos(from)
759+ .await
760+ }
729761 _ => make_github(state, token, notice)?.list_repos(from).await,
730762 };
731763 listed.map_err(|e: ApiError| e.to_string())
@@ -742,10 +774,10 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
742774 };
743775 let owners = owner_choices(state, &viewer.0).await?;
744776 let csrf = viewer.1.csrf_token.clone();
745- let instance = if source == Source::GitLab && !form.instance.trim().is_empty() {
777+ let instance = if has_instance(source) && !form.instance.trim().is_empty() {
746778 form.instance.trim().to_owned()
747779 } else {
748- "https://gitlab.com".to_owned()
780+ default_instance(source).to_owned()
749781 };
750782
751783 if form.stage == "run" {
@@ -754,8 +786,10 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
754786 }
755787
756788 let from = form.from.trim();
757- let bad_owner =
758- !crate::importer::api::valid_path(from, 1, if source == Source::GitLab { 20 } else { 1 });
789+ let owner_max = if source == Source::GitLab { 20 } else { 1 };
790+ // Forgejo lists the token's own repositories for an empty owner.
791+ let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some();
792+ let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max);
759793 let result = if bad_owner {
760794 Err(g::t(lang, K::ErrBadOwner).to_owned())
761795 } else {