From 08d9c2e58590d35b141eef6a0fa6a93b0ec7f476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 22:22:26 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20import=20from=20Forgejo=20a?= =?UTF-8?q?nd=20Gitea?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 23 +- crates/forge-web/src/importer/api.rs | 360 +++++++++++++++- .../forge-web/src/importer/forgejo_tests.rs | 402 ++++++++++++++++++ crates/forge-web/src/importer/mod.rs | 29 +- crates/forge-web/src/importer/remote.rs | 40 +- crates/forge-web/src/importer/tests.rs | 3 + crates/forge-web/src/pages/import.rs | 78 +++- 7 files changed, 883 insertions(+), 52 deletions(-) create mode 100644 crates/forge-web/src/importer/forgejo_tests.rs diff --git a/crates/forge-web/src/i18n/migrate.rs b/crates/forge-web/src/i18n/migrate.rs index 1104d2c..eca1ad8 100644 --- a/crates/forge-web/src/i18n/migrate.rs +++ b/crates/forge-web/src/i18n/migrate.rs @@ -14,12 +14,14 @@ pub enum K { SrcGit, SrcGitHub, SrcGitLab, + SrcForgejo, GitUrl, GitUser, GitPassword, GitHubRepo, GitLabInstance, GitLabProject, + ForgejoInstance, TokenOptional, TokenHelp, TargetOwner, @@ -40,6 +42,7 @@ pub enum K { BulkIntro, BulkOwnerGitHub, BulkOwnerGitLab, + BulkOwnerForgejo, BulkListButton, BulkSelectHeading, BulkSelectAll, @@ -98,12 +101,14 @@ const ALL: &[K] = &[ K::SrcGit, K::SrcGitHub, K::SrcGitLab, + K::SrcForgejo, K::GitUrl, K::GitUser, K::GitPassword, K::GitHubRepo, K::GitLabInstance, K::GitLabProject, + K::ForgejoInstance, K::TokenOptional, K::TokenHelp, K::TargetOwner, @@ -123,6 +128,7 @@ const ALL: &[K] = &[ K::BulkIntro, K::BulkOwnerGitHub, K::BulkOwnerGitLab, + K::BulkOwnerForgejo, K::BulkListButton, K::BulkSelectHeading, K::BulkSelectAll, @@ -182,6 +188,7 @@ fn pair(key: K) -> (&'static str, &'static str) { K::SrcGit => ("Git URL", "Git URL'si"), K::SrcGitHub => ("GitHub", "GitHub"), K::SrcGitLab => ("GitLab", "GitLab"), + K::SrcForgejo => ("Forgejo / Gitea", "Forgejo / Gitea"), K::GitUrl => ("Repository URL", "Depo URL'si"), K::GitUser => ("Username (optional)", "Kullanıcı adı (isteğe bağlı)"), K::GitPassword => ( @@ -191,6 +198,10 @@ fn pair(key: K) -> (&'static str, &'static str) { K::GitHubRepo => ("Repository (owner/name)", "Depo (sahip/ad)"), K::GitLabInstance => ("GitLab address", "GitLab adresi"), K::GitLabProject => ("Project path", "Proje yolu"), + K::ForgejoInstance => ( + "Forgejo or Gitea address (Codeberg works too)", + "Forgejo veya Gitea adresi (Codeberg da olur)", + ), K::TokenOptional => ("Access token (optional)", "Erişim belirteci (isteğe bağlı)"), K::TokenHelp => ( "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) { K::OptPulls => ("Pull requests (as issues)", "Çekme istekleri (konu olarak)"), K::OptReleases => ("Releases and their files", "Sürümler ve dosyaları"), K::OptionsNote => ( - "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.", - "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.", + "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.", + "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.", ), K::StartImport => ("Start import", "İçe aktarmayı başlat"), K::BulkLink => ("Import several repositories", "Birden çok depoyu içe aktar"), @@ -224,6 +235,10 @@ fn pair(key: K) -> (&'static str, &'static str) { "GitHub user or organization", "GitHub kullanıcısı veya kuruluşu", ), + K::BulkOwnerForgejo => ( + "User or organization (empty with a token lists your own)", + "Kullanıcı veya kuruluş (belirteçle boş bırakırsanız kendi depolarınız listelenir)", + ), K::BulkOwnerGitLab => ("GitLab user or group", "GitLab kullanıcısı veya grubu"), K::BulkListButton => ("List repositories", "Depoları listele"), K::BulkSelectHeading => ( @@ -262,8 +277,8 @@ fn pair(key: K) -> (&'static str, &'static str) { "Bu depo adresi geçerli değil.", ), K::ErrBadInstance => ( - "That GitLab address is not valid.", - "Bu GitLab adresi geçerli değil.", + "That instance address is not valid.", + "Bu sunucu adresi geçerli değil.", ), K::ErrBadOwner => ( "That user or organization name is not valid.", diff --git a/crates/forge-web/src/importer/api.rs b/crates/forge-web/src/importer/api.rs index d5a4ff9..410fe98 100644 --- a/crates/forge-web/src/importer/api.rs +++ b/crates/forge-web/src/importer/api.rs @@ -14,6 +14,8 @@ use serde::de::DeserializeOwned; const PER_PAGE: usize = 100; /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever. +/// Forgejo and Gitea cap `limit` at 50 by default. +const FORGEJO_LIMIT: usize = 50; const MAX_PAGES: usize = 500; /// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues. const MAX_RATE_WAIT: u64 = 15 * 60; @@ -184,12 +186,22 @@ pub fn rate_wait( pub type Notice = Arc; +/// How the token is presented to the API host. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Auth { + /// `Authorization: Bearer`. + GitHub, + /// `PRIVATE-TOKEN`. + GitLab, + /// `Authorization: token`. + Forgejo, +} + /// A client under the outbound policy, with the token kept private to the API host. pub struct Http { client: reqwest::Client, token: Option, - /// `Authorization: Bearer` (GitHub) or `PRIVATE-TOKEN` (GitLab). - gitlab: bool, + auth: Auth, auth_host: String, notice: Notice, } @@ -198,7 +210,7 @@ impl Http { pub fn new( client: reqwest::Client, token: Option, - gitlab: bool, + auth: Auth, auth_host: String, notice: Notice, ) -> Self { @@ -206,7 +218,7 @@ impl Http { Http { client, token, - gitlab, + auth, auth_host, notice, } @@ -225,11 +237,12 @@ impl Http { && Self::host_of(url) == self.auth_host && let Some(token) = &self.token { - req = if self.gitlab { - req.header("PRIVATE-TOKEN", token) - } else { - req.header(AUTHORIZATION, format!("Bearer {token}")) - .header("X-GitHub-Api-Version", "2022-11-28") + req = match self.auth { + Auth::GitLab => req.header("PRIVATE-TOKEN", token), + Auth::GitHub => req + .header(AUTHORIZATION, format!("Bearer {token}")) + .header("X-GitHub-Api-Version", "2022-11-28"), + Auth::Forgejo => req.header(AUTHORIZATION, format!("token {token}")), }; } req @@ -326,6 +339,35 @@ impl Http { Ok(out) } + /// Every page of a Forgejo/Gitea list endpoint (`limit`, `page`). The `Link` header decides + /// when it ends; without one, `X-Total-Count`; without either, the first short page. + pub async fn limit_pages(&self, base: &str) -> ApiResult> { + let sep = if base.contains('?') { '&' } else { '?' }; + let mut out: Vec = Vec::new(); + for page in 1..=MAX_PAGES { + let url = format!("{base}{sep}limit={FORGEJO_LIMIT}&page={page}"); + let resp = self.send(&url, "application/json", true).await?; + let link = Self::header(resp.headers(), "link"); + let total = Self::header(resp.headers(), "x-total-count") + .and_then(|v| v.trim().parse::().ok()); + let bytes = Self::body(resp, MAX_JSON_BYTES).await?; + let items: Vec = + serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))?; + let got = items.len(); + out.extend(items); + let done = got == 0 + || match (&link, total) { + (Some(l), _) => !l.contains("rel=\"next\""), + (None, Some(total)) => out.len() >= total, + (None, None) => got < FORGEJO_LIMIT, + }; + if done { + break; + } + } + Ok(out) + } + /// Downloads a file, following redirects by hand: the token goes to the API host only, and /// each hop is fetched under the same address policy as every other request. pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult> { @@ -1034,6 +1076,306 @@ impl RemoteApi for GitLab { } } +// ---- Forgejo and Gitea ---- + +/// A Forgejo or Gitea instance (Codeberg among them), over `/api/v1`. +pub struct Forgejo { + http: Http, + /// `https://host`, the web address the asset links must start with. + origin: String, + /// `https://host/api/v1`. + base: String, +} + +impl Forgejo { + /// `instance` is the instance's web address, e.g. `https://codeberg.org`. + pub fn new(http: Http, instance: &str) -> Self { + let origin = instance.trim_end_matches('/').to_owned(); + Forgejo { + http, + base: format!("{origin}/api/v1"), + origin, + } + } +} + +#[derive(Deserialize)] +struct FjUser { + login: Option, + username: Option, +} + +fn fj_user(u: Option) -> String { + u.and_then(|u| u.login.filter(|l| !l.is_empty()).or(u.username)) + .unwrap_or_default() +} + +#[derive(Deserialize)] +struct FjLabel { + name: String, + color: Option, + description: Option, +} + +#[derive(Deserialize)] +struct FjMilestone { + id: i64, + title: String, + description: Option, + state: String, + due_on: Option, +} + +#[derive(Deserialize)] +struct FjMilestoneRef { + title: String, +} + +#[derive(Deserialize)] +struct FjIssue { + number: i64, + title: String, + body: Option, + state: String, + user: Option, + #[serde(default)] + labels: Vec, + milestone: Option, + created_at: Option, + html_url: Option, + /// Set on `/pulls` items. + #[serde(default)] + merged: bool, +} + +#[derive(Deserialize)] +struct FjComment { + id: i64, + body: Option, + user: Option, + created_at: Option, + html_url: Option, +} + +#[derive(Deserialize)] +struct FjAsset { + id: i64, + name: String, + size: Option, + browser_download_url: String, +} + +#[derive(Deserialize)] +struct FjRelease { + id: i64, + tag_name: String, + name: Option, + body: Option, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + author: Option, + created_at: Option, + html_url: Option, + #[serde(default)] + assets: Vec, +} + +#[derive(Deserialize)] +struct FjRepo { + name: String, + full_name: String, + description: Option, + #[serde(default)] + private: bool, + #[serde(default)] + fork: bool, + #[serde(default)] + archived: bool, + default_branch: Option, + html_url: Option, +} + +fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue { + ExtIssue { + number: i.number, + title: i.title, + body: s(i.body), + closed: i.state != "open", + not_planned: false, + merged: is_pr && i.merged, + author: fj_user(i.user), + labels: i.labels.into_iter().map(|l| l.name).collect(), + milestone: i.milestone.map(|m| m.title), + created_at: s(i.created_at), + url: s(i.html_url), + is_pr, + } +} + +fn fj_release(r: FjRelease) -> ExtRelease { + ExtRelease { + id: r.id.to_string(), + title: r + .name + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| r.tag_name.clone()), + tag: r.tag_name, + body: s(r.body), + draft: r.draft, + prerelease: r.prerelease, + author: fj_user(r.author), + created_at: s(r.created_at), + url: s(r.html_url), + assets: r + .assets + .into_iter() + .map(|a| ExtAsset { + id: a.id.to_string(), + name: a.name, + size: a.size.unwrap_or(0), + content_type: String::new(), + url: a.browser_download_url, + }) + .collect(), + } +} + +impl RemoteApi for Forgejo { + async fn list_repos(&self, owner: &str) -> ApiResult> { + // An empty owner means "mine", which needs a token. + let raw: Vec = if owner.is_empty() { + self.http + .limit_pages(&format!("{}/user/repos", self.base)) + .await? + } else { + if !valid_segment(owner) { + return Err(ApiError::NotFound("owner".into())); + } + let org: ApiResult> = self + .http + .limit_pages(&format!("{}/orgs/{owner}/repos", self.base)) + .await; + match org { + Ok(raw) => raw, + Err(ApiError::NotFound(_)) => { + self.http + .limit_pages(&format!("{}/users/{owner}/repos", self.base)) + .await? + } + Err(e) => return Err(e), + } + }; + Ok(raw + .into_iter() + .map(|r| ExtRepo { + name: r.name, + full_name: r.full_name, + description: s(r.description), + private: r.private, + fork: r.fork, + archived: r.archived, + default_branch: s(r.default_branch), + web_url: s(r.html_url), + }) + .collect()) + } + + async fn labels(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .limit_pages(&format!("{}/repos/{repo}/labels", self.base)) + .await?; + Ok(raw + .into_iter() + .map(|l| ExtLabel { + name: l.name, + color: format!("#{}", s(l.color).trim_start_matches('#')), + description: s(l.description), + }) + .collect()) + } + + async fn milestones(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .limit_pages(&format!("{}/repos/{repo}/milestones?state=all", self.base)) + .await?; + Ok(raw + .into_iter() + .map(|m| ExtMilestone { + id: m.id.to_string(), + title: m.title, + description: s(m.description), + closed: m.state == "closed", + due_on: m.due_on.as_deref().and_then(day), + }) + .collect()) + } + + async fn issues(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let issues: Vec = self + .http + .limit_pages(&format!( + "{}/repos/{repo}/issues?type=issues&state=all&sort=oldest", + self.base + )) + .await?; + let pulls: Vec = self + .http + .limit_pages(&format!( + "{}/repos/{repo}/pulls?state=all&sort=oldest", + self.base + )) + .await?; + let mut out: Vec = issues.into_iter().map(|i| fj_issue(i, false)).collect(); + out.extend(pulls.into_iter().map(|i| fj_issue(i, true))); + Ok(out) + } + + async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .limit_pages(&format!( + "{}/repos/{repo}/issues/{}/comments", + self.base, issue.number + )) + .await?; + Ok(raw + .into_iter() + .map(|c| ExtComment { + id: c.id.to_string(), + author: fj_user(c.user), + body: s(c.body), + created_at: s(c.created_at), + url: s(c.html_url), + }) + .collect()) + } + + async fn releases(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .limit_pages(&format!("{}/repos/{repo}/releases", self.base)) + .await?; + // The list embeds each release's assets, so `/releases/{id}/assets` is not needed. + Ok(raw.into_iter().map(fj_release).collect()) + } + + async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult> { + if !asset.url.starts_with(&format!("{}/", self.origin)) { + return Err(ApiError::Http("unexpected asset address".into())); + } + self.http.download(&asset.url, max_bytes).await + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/forge-web/src/importer/forgejo_tests.rs b/crates/forge-web/src/importer/forgejo_tests.rs new file mode 100644 index 0000000..b76f6aa --- /dev/null +++ b/crates/forge-web/src/importer/forgejo_tests.rs @@ -0,0 +1,402 @@ +//! Forgejo and Gitea import tests against a tiny local HTTP server that speaks `/api/v1`: the real +//! [`Forgejo`] client, real pagination, nothing on the network. + +use std::sync::{Arc, Mutex}; + +use serde_json::{Value, json}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +use super::*; +use crate::importer::api::{Auth, Forgejo, Http}; + +type Reply = (Vec<(String, String)>, Vec); +type Log = Arc)>>>; + +/// Binds a port and returns the base address with the listener. +async fn bind() -> (TcpListener, String) { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let base = format!("http://{}", listener.local_addr().expect("addr")); + (listener, base) +} + +/// Serves `handler(target)` for every GET; `None` is a 404. Returns the request log +/// (target, `Authorization` header). +fn serve(listener: TcpListener, handler: F) -> Log +where + F: Fn(&str) -> Option + Send + Sync + 'static, +{ + let log: Log = Arc::default(); + let seen = log.clone(); + let handler = Arc::new(handler); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let handler = handler.clone(); + let seen = seen.clone(); + tokio::spawn(async move { + let mut buf = Vec::new(); + let mut chunk = [0u8; 2048]; + while !buf.windows(4).any(|w| w == b"\r\n\r\n") { + match sock.read(&mut chunk).await { + Ok(0) | Err(_) => return, + Ok(n) => buf.extend_from_slice(&chunk[..n]), + } + } + let text = String::from_utf8_lossy(&buf).into_owned(); + let target = text + .lines() + .next() + .and_then(|l| l.split_whitespace().nth(1)) + .unwrap_or("/") + .to_owned(); + let auth = text.lines().find_map(|l| { + let (k, v) = l.split_once(':')?; + k.eq_ignore_ascii_case("authorization") + .then(|| v.trim().to_owned()) + }); + seen.lock().unwrap().push((target.clone(), auth)); + let out = match handler(&target) { + Some((headers, body)) => { + let mut head = format!( + "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n", + body.len() + ); + for (k, v) in headers { + head.push_str(&format!("{k}: {v}\r\n")); + } + head.push_str("\r\n"); + let mut out = head.into_bytes(); + out.extend(body); + out + } + None => { + b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" + .to_vec() + } + }; + let _ = sock.write_all(&out).await; + let _ = sock.shutdown().await; + }); + } + }); + log +} + +fn json_reply(headers: Vec<(&str, String)>, body: &Value) -> Option { + let mut all = vec![("content-type".to_owned(), "application/json".to_owned())]; + all.extend(headers.into_iter().map(|(k, v)| (k.to_owned(), v))); + Some((all, body.to_string().into_bytes())) +} + +fn page_of(target: &str) -> usize { + target + .split(['?', '&']) + .find_map(|p| p.strip_prefix("page=")) + .and_then(|v| v.parse().ok()) + .unwrap_or(1) +} + +fn client(base: &str, token: Option<&str>) -> Forgejo { + let notice: super::super::api::Notice = Arc::new(|_| {}); + let http = Http::new( + reqwest::Client::new(), + token.map(str::to_owned), + Auth::Forgejo, + "127.0.0.1".into(), + notice, + ); + Forgejo::new(http, base) +} + +fn issue_json(n: i64, state: &str) -> Value { + json!({ + "number": n, "title": format!("Issue {n}"), "body": "text", "state": state, + "user": {"login": "hubot"}, "labels": [{"name": "bug", "color": "d73a4a"}], + "milestone": null, "created_at": "2020-01-02T03:04:05Z", + "html_url": format!("https://codeberg.example/tahinli/project/issues/{n}"), + }) +} + +#[tokio::test] +async fn pagination_follows_the_link_header_with_a_limit_of_fifty() { + let (listener, base) = bind().await; + let log = serve(listener, |target| { + if !target.starts_with("/api/v1/repos/tahinli/project/issues?type=issues") { + return json_reply(vec![], &json!([])); + } + match page_of(target) { + 1 => json_reply( + vec![ + ("x-total-count", "52".into()), + ( + "link", + "; rel=\"next\", ; rel=\"last\"" + .into(), + ), + ], + &Value::Array((1..=50).map(|n| issue_json(n, "open")).collect()), + ), + 2 => json_reply( + vec![ + ("x-total-count", "52".into()), + ("link", "; rel=\"prev\"".into()), + ], + &Value::Array((51..=52).map(|n| issue_json(n, "closed")).collect()), + ), + _ => json_reply(vec![], &json!([])), + } + }); + let api = client(&base, Some("abc123")); + let issues = api.issues("tahinli/project").await.unwrap(); + let plain: Vec<_> = issues.iter().filter(|i| !i.is_pr).collect(); + assert_eq!(plain.len(), 52, "both pages were read"); + assert!(plain[51].closed && !plain[0].closed); + assert_eq!(plain[0].author, "hubot"); + assert_eq!(plain[0].labels, vec!["bug"]); + + let log = log.lock().unwrap(); + let issue_calls: Vec<_> = log + .iter() + .filter(|(t, _)| t.contains("type=issues")) + .collect(); + assert_eq!(issue_calls.len(), 2, "stopped when the link had no next"); + assert!(issue_calls[0].0.contains("limit=50")); + assert!(issue_calls[0].0.contains("page=1") && issue_calls[1].0.contains("page=2")); + assert!( + log.iter() + .all(|(_, auth)| auth.as_deref() == Some("token abc123")), + "every request carries the token header" + ); +} + +#[tokio::test] +async fn the_total_count_stops_a_listing_with_no_link_header() { + let (listener, base) = bind().await; + let log = serve(listener, |target| { + json_reply( + vec![("x-total-count", "50".into())], + &Value::Array( + (0..50) + .map(|i| json!({"name": format!("l{i}"), "color": "00aabb"})) + .collect(), + ), + ) + .filter(|_| target.contains("/labels")) + }); + let api = client(&base, None); + let labels = api.labels("tahinli/project").await.unwrap(); + assert_eq!(labels.len(), 50); + assert_eq!(labels[0].color, "#00aabb"); + assert_eq!( + log.lock().unwrap().len(), + 1, + "a full page of exactly the total is the end" + ); + assert!( + log.lock().unwrap()[0].1.is_none(), + "no token, no Authorization header" + ); +} + +#[tokio::test] +async fn pulls_map_merged_closed_and_open() { + let (listener, base) = bind().await; + serve(listener, |target| { + if target.contains("/pulls?") { + let mut merged = issue_json(2, "closed"); + merged["merged"] = json!(true); + let closed = issue_json(3, "closed"); + let mut open = issue_json(4, "open"); + open["milestone"] = json!({"title": "v1"}); + json_reply(vec![], &json!([merged, closed, open])) + } else if target.contains("/issues?") { + json_reply(vec![], &json!([issue_json(1, "open")])) + } else { + None + } + }); + let api = client(&base, None); + let all = api.issues("tahinli/project").await.unwrap(); + assert_eq!(all.len(), 4); + assert!(!all[0].is_pr); + let pulls: Vec<_> = all.iter().filter(|i| i.is_pr).collect(); + assert!(pulls[0].closed && pulls[0].merged); + assert!(pulls[1].closed && !pulls[1].merged); + assert!(!pulls[2].closed); + assert_eq!(pulls[2].milestone.as_deref(), Some("v1")); +} + +#[tokio::test] +async fn bulk_listing_tries_the_org_then_the_user_and_supports_own_repos() { + let (listener, base) = bind().await; + let repo = |name: &str, private: bool| { + json!({"name": name, "full_name": format!("tahinli/{name}"), "private": private, + "fork": false, "archived": false, "default_branch": "main", "description": null}) + }; + let log = serve(listener, move |target| { + if target.starts_with("/api/v1/users/tahinli/repos") { + json_reply(vec![], &json!([repo("a", false)])) + } else if target.starts_with("/api/v1/user/repos") { + json_reply(vec![], &json!([repo("a", false), repo("b", true)])) + } else { + None + } + }); + let api = client(&base, Some("t")); + let public = api.list_repos("tahinli").await.unwrap(); + assert_eq!(public.len(), 1); + assert_eq!(public[0].full_name, "tahinli/a"); + assert!( + log.lock().unwrap()[0] + .0 + .starts_with("/api/v1/orgs/tahinli/repos"), + "the org is tried first" + ); + let mine = api.list_repos("").await.unwrap(); + assert_eq!(mine.len(), 2); + assert!(mine[1].private); +} + +#[tokio::test] +async fn a_bad_asset_address_is_refused_before_any_request() { + let (listener, base) = bind().await; + let log = serve(listener, |_| None); + let api = client(&base, Some("t")); + let asset = ExtAsset { + url: "https://elsewhere.example/a.bin".into(), + ..ExtAsset::default() + }; + assert!(api.download(&asset, 100).await.is_err()); + assert!(log.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn full_forgejo_import_maps_issues_pulls_comments_labels_and_releases() { + let fx = fixture().await; + let (listener, base) = bind().await; + let origin = base.clone(); + serve(listener, move |target| { + let path = target.split('?').next().unwrap_or_default(); + match path { + "/api/v1/repos/tahinli/project/labels" => json_reply( + vec![], + &json!([{"name": "bug", "color": "d73a4a", "description": "Broken"}]), + ), + "/api/v1/repos/tahinli/project/milestones" => json_reply( + vec![], + &json!([{"id": 9, "title": "v1", "description": "", "state": "closed", + "due_on": "2020-05-06T00:00:00Z"}]), + ), + "/api/v1/repos/tahinli/project/issues" => { + json_reply(vec![], &json!([issue_json(1, "closed")])) + } + "/api/v1/repos/tahinli/project/pulls" => { + let mut pr = issue_json(2, "closed"); + pr["title"] = json!("Add the thing"); + pr["merged"] = json!(true); + json_reply(vec![], &json!([pr])) + } + "/api/v1/repos/tahinli/project/issues/1/comments" => json_reply( + vec![], + &json!([{"id": 11, "body": "same here", "user": {"login": "hubot"}, + "created_at": "2020-01-03T00:00:00Z", + "html_url": "https://codeberg.example/c/11"}]), + ), + "/api/v1/repos/tahinli/project/issues/2/comments" => json_reply(vec![], &json!([])), + "/api/v1/repos/tahinli/project/releases" => json_reply( + vec![], + &json!([{"id": 5, "tag_name": "v1", "name": "", "body": "notes", "draft": false, + "prerelease": false, "author": {"login": "hubot"}, + "created_at": "2021-01-01T00:00:00Z", + "html_url": "https://codeberg.example/r/5", + "assets": [{"id": 1, "name": "app.tar.gz", "size": 5, + "browser_download_url": format!("{origin}/attachments/uuid-1")}]}]), + ), + "/attachments/uuid-1" => Some((vec![], b"hello".to_vec())), + _ => None, + } + }); + let api = client(&base, Some(TOKEN)); + let job = new_job(&fx, Source::Forgejo).await; + let mut spec = spec(Source::Forgejo, everything()); + spec.instance = base.clone(); + run_job( + &fx.state, + &job, + &spec, + Some(&api), + &Transport::Local(fx.upstream.clone()), + ) + .await; + + let store = &fx.state.store; + let job = store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(job.state, ImportState::Done, "{:?}", job.error); + + let all = IssueFilter { + state: None, + per_page: 100, + ..IssueFilter::default() + }; + let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); + assert_eq!(total, 2); + let issue = items.iter().find(|i| i.issue.title == "Issue 1").unwrap(); + assert_eq!(issue.issue.state, IssueState::Closed); + assert!( + issue + .issue + .body + .starts_with("> Originally by \\@hubot on Forgejo, 2020-01-02"), + "{}", + issue.issue.body + ); + assert!(issue.labels.iter().any(|l| l.name == "bug")); + let pull = items + .iter() + .find(|i| i.issue.title == "Add the thing") + .unwrap(); + assert!(pull.issue.body.contains("Imported pull request (merged)")); + let comments = store.list_comments(&issue.issue.id).await.unwrap(); + assert_eq!(comments.len(), 1); + assert!(comments[0].body.ends_with("same here")); + + let release = store + .release_by_tag(&fx.repo.id, "v1") + .await + .unwrap() + .unwrap(); + assert!(release.body.contains("notes")); + let assets = store.list_release_assets(&release.id).await.unwrap(); + assert_eq!(assets.len(), 1); + assert_eq!(assets[0].name, "app.tar.gz"); + assert_eq!(assets[0].size, 5); +} + +#[test] +fn forgejo_remotes_take_a_url_or_a_path_with_an_instance() { + use crate::importer::parse_remote; + assert_eq!( + parse_remote( + Source::Forgejo, + "https://codeberg.org/tahinli/forge.git", + "" + ), + Some(("tahinli/forge".into(), "https://codeberg.org".into())) + ); + assert_eq!( + parse_remote(Source::Forgejo, "tahinli/forge", "https://codeberg.org/"), + Some(("tahinli/forge".into(), "https://codeberg.org".into())) + ); + assert_eq!( + parse_remote(Source::Forgejo, "a/b/c", "https://codeberg.org"), + None + ); + assert_eq!(parse_remote(Source::Forgejo, "tahinli/forge", ""), None); + assert_eq!(Source::parse("gitea"), Some(Source::Forgejo)); + let mut s = spec(Source::Forgejo, ImportOptions::default()); + s.instance = "https://codeberg.org/".into(); + assert_eq!(s.clone_url(), "https://codeberg.org/tahinli/project.git"); +} diff --git a/crates/forge-web/src/importer/mod.rs b/crates/forge-web/src/importer/mod.rs index a843cb1..4187e78 100644 --- a/crates/forge-web/src/importer/mod.rs +++ b/crates/forge-web/src/importer/mod.rs @@ -1,7 +1,7 @@ -//! Repository import: a one-shot copy of a repo from a git URL, GitHub or GitLab. +//! Repository import: a one-shot copy of a repo from a git URL, GitHub, GitLab or Forgejo/Gitea. //! //! The git data comes from the same fetch the pull mirrors use, once, into a normal repo (no mirror -//! row is created). For GitHub and GitLab the job can also copy labels, milestones, issues with +//! row is created). For the forge sources the job can also copy labels, milestones, issues with //! comments, pull requests (as issues marked "imported PR") and releases with their assets, through //! a [`RemoteApi`]. Progress is written to the database and every step wakes the job page's event //! stream, so the page updates with no polling. @@ -26,7 +26,9 @@ use serde::{Deserialize, Serialize}; use tokio::sync::{Semaphore, watch}; use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi}; -pub use self::remote::{default_name, make_github, make_gitlab, parse_remote, source_ref}; +pub use self::remote::{ + default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, +}; use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; use crate::state::AppState; @@ -43,6 +45,7 @@ pub enum Source { Git, GitHub, GitLab, + Forgejo, } impl Source { @@ -51,6 +54,7 @@ impl Source { Source::Git => "git", Source::GitHub => "github", Source::GitLab => "gitlab", + Source::Forgejo => "forgejo", } } @@ -59,6 +63,8 @@ impl Source { "git" => Some(Source::Git), "github" => Some(Source::GitHub), "gitlab" => Some(Source::GitLab), + // Gitea speaks the same API. + "forgejo" | "gitea" => Some(Source::Forgejo), _ => None, } } @@ -69,6 +75,7 @@ impl Source { Source::Git => "git", Source::GitHub => "GitHub", Source::GitLab => "GitLab", + Source::Forgejo => "Forgejo", } } } @@ -98,7 +105,7 @@ pub struct JobSpec { pub source: Source, /// The URL for `git`, `owner/repo` for GitHub, the project path for GitLab. pub remote: String, - /// The GitLab instance, e.g. `https://gitlab.com`. + /// The GitLab or Forgejo instance, e.g. `https://gitlab.com`. pub instance: String, pub token: Option, /// The user name sent with the token for a plain git URL. @@ -121,7 +128,7 @@ impl JobSpec { match self.source { Source::Git => self.remote.clone(), Source::GitHub => format!("https://github.com/{}.git", self.remote), - Source::GitLab => format!( + Source::GitLab | Source::Forgejo => format!( "{}/{}.git", self.instance.trim_end_matches('/'), self.remote @@ -133,7 +140,7 @@ impl JobSpec { let token = self.token.as_ref().filter(|t| !t.is_empty())?; let username = match self.source { Source::GitHub => "x-access-token".to_owned(), - Source::GitLab => "oauth2".to_owned(), + Source::GitLab | Source::Forgejo => "oauth2".to_owned(), Source::Git if self.git_user.is_empty() => "git".to_owned(), Source::Git => self.git_user.clone(), }; @@ -337,6 +344,10 @@ async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, Err(e) => fail(state, &rep, &e).await, }, + Source::Forgejo => match make_forgejo(state, &spec.instance, spec.token.clone(), notice) { + Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, + Err(e) => fail(state, &rep, &e).await, + }, Source::Git => {} } } @@ -710,9 +721,9 @@ impl Run<'_, A> { }) .collect(); items.sort_by_key(|i| (i.is_pr, i.number)); - // GitHub numbers issues and pull requests together; GitLab keeps two sequences. Sorting - // by number alone keeps GitHub numbers aligned, so do that for it. - if self.spec.source == Source::GitHub { + // GitHub and Forgejo number issues and pull requests together; GitLab keeps two sequences. Sorting + // by number alone keeps GitHub numbers aligned, so do that for them. + if matches!(self.spec.source, Source::GitHub | Source::Forgejo) { items.sort_by_key(|i| i.number); } let total = items.len(); diff --git a/crates/forge-web/src/importer/remote.rs b/crates/forge-web/src/importer/remote.rs index 9d14ba1..fe47977 100644 --- a/crates/forge-web/src/importer/remote.rs +++ b/crates/forge-web/src/importer/remote.rs @@ -3,7 +3,7 @@ use std::time::Duration; use super::Source; -use super::api::{self, GitHub, GitLab, Http, Notice}; +use super::api::{self, Auth, Forgejo, GitHub, GitLab, Http, Notice}; use crate::mirrors::policy; use crate::state::AppState; use crate::webhooks::client::{policy_client, validate_url}; @@ -19,7 +19,7 @@ pub fn make_github( Ok(GitHub::new(Http::new( client, token, - false, + Auth::GitHub, "api.github.com".into(), notice, ))) @@ -41,13 +41,34 @@ pub fn make_gitlab( let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") .map_err(|e| format!("could not build the HTTP client: {e}"))?; Ok(GitLab::new( - Http::new(client, token, true, host, notice), + Http::new(client, token, Auth::GitLab, host, notice), + instance, + )) +} + +/// A Forgejo or Gitea client for `instance`, which must pass the outbound policy. +pub fn make_forgejo( + state: &AppState, + instance: &str, + token: Option, + notice: Notice, +) -> Result { + let instance = instance.trim_end_matches('/'); + let host = validate_url(instance, &policy(state)) + .map_err(|e| format!("instance address refused: {e}"))? + .host_str() + .unwrap_or_default() + .to_ascii_lowercase(); + let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") + .map_err(|e| format!("could not build the HTTP client: {e}"))?; + Ok(Forgejo::new( + Http::new(client, token, Auth::Forgejo, host, notice), instance, )) } /// Splits what the user typed into `(remote, instance)` for a source. `None` when it is not a -/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab takes a project URL +/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab and Forgejo take a project URL /// (`https://host/group/project`) or, with `instance` given, a bare path. pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> { let text = text.trim(); @@ -62,7 +83,8 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin let path = path.strip_suffix(".git").unwrap_or(path); api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new())) } - Source::GitLab => { + Source::GitLab | Source::Forgejo => { + let max = if source == Source::GitLab { 20 } else { 2 }; if let Some((scheme, rest)) = text .strip_prefix("https://") .map(|r| ("https", r)) @@ -71,7 +93,7 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin let (host, path) = rest.split_once('/')?; let path = path.trim_end_matches('/'); let path = path.strip_suffix(".git").unwrap_or(path); - if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, 20) { + if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, max) { return None; } return Some((path.to_owned(), format!("{scheme}://{host}"))); @@ -85,7 +107,7 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin let ok = !host.is_empty() && !host.contains('@') && !host.contains('/') - && api::valid_path(path, 2, 20); + && api::valid_path(path, 2, max); ok.then(|| (path.to_owned(), instance.to_owned())) } } @@ -94,7 +116,9 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin /// The reference stored on a job and shown to the user: no credential in it. pub fn source_ref(source: Source, remote: &str, instance: &str) -> String { match source { - Source::GitLab => format!("{}/{}", instance.trim_end_matches('/'), remote), + Source::GitLab | Source::Forgejo => { + format!("{}/{}", instance.trim_end_matches('/'), remote) + } _ => remote.to_owned(), } } diff --git a/crates/forge-web/src/importer/tests.rs b/crates/forge-web/src/importer/tests.rs index ae05842..7f6636a 100644 --- a/crates/forge-web/src/importer/tests.rs +++ b/crates/forge-web/src/importer/tests.rs @@ -542,3 +542,6 @@ fn asset_names_are_made_safe() { "a b/c?d" ))); } + +#[path = "forgejo_tests.rs"] +mod forgejo; diff --git a/crates/forge-web/src/pages/import.rs b/crates/forge-web/src/pages/import.rs index f0ddd63..0f86f65 100644 --- a/crates/forge-web/src/pages/import.rs +++ b/crates/forge-web/src/pages/import.rs @@ -24,8 +24,8 @@ use crate::i18n::migrate::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::importer::api::{ApiError, RemoteApi}; use crate::importer::{ - self, ImportOptions, JobSpec, Source, default_name, make_github, make_gitlab, parse_remote, - source_ref, + self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, + parse_remote, source_ref, }; use crate::pages::ci_runs::{changed_event, events_response}; use crate::pages::new_repo::{owner_choices, repo_owner}; @@ -125,6 +125,27 @@ fn source_of(raw: Option<&str>) -> Source { raw.and_then(Source::parse).unwrap_or(Source::GitHub) } +/// The instance a source form starts with. +fn default_instance(source: Source) -> &'static str { + match source { + Source::Forgejo => "https://codeberg.org", + _ => "https://gitlab.com", + } +} + +/// Sources that are self-hostable and so take an instance address. +fn has_instance(source: Source) -> bool { + matches!(source, Source::GitLab | Source::Forgejo) +} + +fn instance_label(lang: Lang, source: Source) -> &'static str { + if source == Source::Forgejo { + g::t(lang, K::ForgejoInstance) + } else { + g::t(lang, K::GitLabInstance) + } +} + fn token_of(raw: &str) -> Option { let t = raw.trim(); (!t.is_empty()).then(|| t.to_owned()) @@ -150,11 +171,13 @@ async fn source_tabs(lang: Lang, base: &str, active: Source) -> Result (g::t(lang, K::SrcGit)) (g::t(lang, K::SrcGitHub)) (g::t(lang, K::SrcGitLab)) + (g::t(lang, K::SrcForgejo)) }) } @@ -213,7 +236,7 @@ impl Draft { Draft { source, remote: String::new(), - instance: "https://gitlab.com".into(), + instance: default_instance(source).into(), git_user: String::new(), owner: String::new(), name: String::new(), @@ -265,7 +288,8 @@ async fn import_form( }; let source_value = source.as_str(); let is_git = source == Source::Git; - let is_gitlab = source == Source::GitLab; + let has_instance = has_instance(source); + let instance_label = instance_label(lang, source); let bulk_href = if is_git { String::new() } else { @@ -273,13 +297,13 @@ async fn import_form( }; let remote_label = match source { Source::Git => g::t(lang, K::GitUrl), - Source::GitHub => g::t(lang, K::GitHubRepo), + Source::GitHub | Source::Forgejo => g::t(lang, K::GitHubRepo), Source::GitLab => g::t(lang, K::GitLabProject), }; let remote_placeholder = match source { Source::Git => "https://example.org/tahinli/project.git", Source::GitHub => "tahinli/project", - Source::GitLab => "tahinli/project", + Source::GitLab | Source::Forgejo => "tahinli/project", }; let token_label = if is_git { g::t(lang, K::GitPassword) @@ -306,9 +330,9 @@ async fn import_form( source_tabs(lang: lang, base: "/new/import", active: source)

(g::t(lang, K::ImportIntro))

- if is_gitlab { + if has_instance { } @@ -406,7 +430,7 @@ async fn start_single( ) -> Result> { let state = app_context::(cx); let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else { - let message = if source == Source::GitLab && form.remote.trim().starts_with("http") { + let message = if has_instance(source) && form.remote.trim().starts_with("http") { g::t(lang, K::ErrBadInstance) } else { g::t(lang, K::ErrBadRemote) @@ -537,13 +561,16 @@ async fn bulk_form( owners: Vec, error: Option, ) -> Result { - let is_gitlab = source == Source::GitLab; + let has_instance = has_instance(source); + let instance_label = instance_label(lang, source); let source_value = source.as_str(); - let owner_label = if is_gitlab { - g::t(lang, K::BulkOwnerGitLab) - } else { - g::t(lang, K::BulkOwnerGitHub) + let owner_label = match source { + Source::GitLab => g::t(lang, K::BulkOwnerGitLab), + Source::Forgejo => g::t(lang, K::BulkOwnerForgejo), + _ => g::t(lang, K::BulkOwnerGitHub), }; + // A Forgejo token can list its own repositories, so the owner may stay empty. + let owner_required = source != Source::Forgejo; Ok(view! { newrepo_tabs(lang: lang, active: "import") if let Some(message) = error { @@ -562,15 +589,15 @@ async fn bulk_form( source_tabs(lang: lang, base: "/new/import/bulk", active: source)

(g::t(lang, K::BulkIntro))

- if is_gitlab { + if has_instance { }