Import from Forgejo and Gitea
Browse files at this commit08d9c2e58590d35b141eef6a0fa6a93b0ec7f476Parent: 6216322- feat
- import from Forgejo and Gitea
7 changed files +883 -52
- crates/forge-web/src/i18n/migrate.rs +19 -4
- crates/forge-web/src/importer/api.rs +351 -9
- crates/forge-web/src/importer/forgejo_tests.rs +402 -0
- crates/forge-web/src/importer/mod.rs +20 -9
- crates/forge-web/src/importer/remote.rs +32 -8
- crates/forge-web/src/importer/tests.rs +3 -0
- crates/forge-web/src/pages/import.rs +56 -22
crates/forge-web/src/i18n/migrate.rsmodified+19 -4
| @@ -14,12 +14,14 @@ pub enum K { | |||
| 14 | SrcGit, | 14 | SrcGit, |
| 15 | SrcGitHub, | 15 | SrcGitHub, |
| 16 | SrcGitLab, | 16 | SrcGitLab, |
| 17 | + SrcForgejo, | ||
| 17 | GitUrl, | 18 | GitUrl, |
| 18 | GitUser, | 19 | GitUser, |
| 19 | GitPassword, | 20 | GitPassword, |
| 20 | GitHubRepo, | 21 | GitHubRepo, |
| 21 | GitLabInstance, | 22 | GitLabInstance, |
| 22 | GitLabProject, | 23 | GitLabProject, |
| 24 | + ForgejoInstance, | ||
| 23 | TokenOptional, | 25 | TokenOptional, |
| 24 | TokenHelp, | 26 | TokenHelp, |
| 25 | TargetOwner, | 27 | TargetOwner, |
| @@ -40,6 +42,7 @@ pub enum K { | |||
| 40 | BulkIntro, | 42 | BulkIntro, |
| 41 | BulkOwnerGitHub, | 43 | BulkOwnerGitHub, |
| 42 | BulkOwnerGitLab, | 44 | BulkOwnerGitLab, |
| 45 | + BulkOwnerForgejo, | ||
| 43 | BulkListButton, | 46 | BulkListButton, |
| 44 | BulkSelectHeading, | 47 | BulkSelectHeading, |
| 45 | BulkSelectAll, | 48 | BulkSelectAll, |
| @@ -98,12 +101,14 @@ const ALL: &[K] = &[ | |||
| 98 | K::SrcGit, | 101 | K::SrcGit, |
| 99 | K::SrcGitHub, | 102 | K::SrcGitHub, |
| 100 | K::SrcGitLab, | 103 | K::SrcGitLab, |
| 104 | + K::SrcForgejo, | ||
| 101 | K::GitUrl, | 105 | K::GitUrl, |
| 102 | K::GitUser, | 106 | K::GitUser, |
| 103 | K::GitPassword, | 107 | K::GitPassword, |
| 104 | K::GitHubRepo, | 108 | K::GitHubRepo, |
| 105 | K::GitLabInstance, | 109 | K::GitLabInstance, |
| 106 | K::GitLabProject, | 110 | K::GitLabProject, |
| 111 | + K::ForgejoInstance, | ||
| 107 | K::TokenOptional, | 112 | K::TokenOptional, |
| 108 | K::TokenHelp, | 113 | K::TokenHelp, |
| 109 | K::TargetOwner, | 114 | K::TargetOwner, |
| @@ -123,6 +128,7 @@ const ALL: &[K] = &[ | |||
| 123 | K::BulkIntro, | 128 | K::BulkIntro, |
| 124 | K::BulkOwnerGitHub, | 129 | K::BulkOwnerGitHub, |
| 125 | K::BulkOwnerGitLab, | 130 | K::BulkOwnerGitLab, |
| 131 | + K::BulkOwnerForgejo, | ||
| 126 | K::BulkListButton, | 132 | K::BulkListButton, |
| 127 | K::BulkSelectHeading, | 133 | K::BulkSelectHeading, |
| 128 | K::BulkSelectAll, | 134 | K::BulkSelectAll, |
| @@ -182,6 +188,7 @@ fn pair(key: K) -> (&'static str, &'static str) { | |||
| 182 | K::SrcGit => ("Git URL", "Git URL'si"), | 188 | K::SrcGit => ("Git URL", "Git URL'si"), |
| 183 | K::SrcGitHub => ("GitHub", "GitHub"), | 189 | K::SrcGitHub => ("GitHub", "GitHub"), |
| 184 | K::SrcGitLab => ("GitLab", "GitLab"), | 190 | K::SrcGitLab => ("GitLab", "GitLab"), |
| 191 | + K::SrcForgejo => ("Forgejo / Gitea", "Forgejo / Gitea"), | ||
| 185 | K::GitUrl => ("Repository URL", "Depo URL'si"), | 192 | K::GitUrl => ("Repository URL", "Depo URL'si"), |
| 186 | K::GitUser => ("Username (optional)", "Kullanıcı adı (isteğe bağlı)"), | 193 | K::GitUser => ("Username (optional)", "Kullanıcı adı (isteğe bağlı)"), |
| 187 | K::GitPassword => ( | 194 | K::GitPassword => ( |
| @@ -191,6 +198,10 @@ fn pair(key: K) -> (&'static str, &'static str) { | |||
| 191 | K::GitHubRepo => ("Repository (owner/name)", "Depo (sahip/ad)"), | 198 | K::GitHubRepo => ("Repository (owner/name)", "Depo (sahip/ad)"), |
| 192 | K::GitLabInstance => ("GitLab address", "GitLab adresi"), | 199 | K::GitLabInstance => ("GitLab address", "GitLab adresi"), |
| 193 | K::GitLabProject => ("Project path", "Proje yolu"), | 200 | 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 | + ), | ||
| 194 | K::TokenOptional => ("Access token (optional)", "Erişim belirteci (isteğe bağlı)"), | 205 | K::TokenOptional => ("Access token (optional)", "Erişim belirteci (isteğe bağlı)"), |
| 195 | K::TokenHelp => ( | 206 | K::TokenHelp => ( |
| 196 | "Needed for private repositories and higher rate limits. It is used only while the import runs and is never stored.", | 207 | "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) { | |||
| 209 | K::OptPulls => ("Pull requests (as issues)", "Çekme istekleri (konu olarak)"), | 220 | K::OptPulls => ("Pull requests (as issues)", "Çekme istekleri (konu olarak)"), |
| 210 | K::OptReleases => ("Releases and their files", "Sürümler ve dosyaları"), | 221 | K::OptReleases => ("Releases and their files", "Sürümler ve dosyaları"), |
| 211 | K::OptionsNote => ( | 222 | 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.", | 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.", |
| 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.", | 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.", |
| 214 | ), | 225 | ), |
| 215 | K::StartImport => ("Start import", "İçe aktarmayı başlat"), | 226 | K::StartImport => ("Start import", "İçe aktarmayı başlat"), |
| 216 | K::BulkLink => ("Import several repositories", "Birden çok depoyu içe aktar"), | 227 | K::BulkLink => ("Import several repositories", "Birden çok depoyu içe aktar"), |
| @@ -224,6 +235,10 @@ fn pair(key: K) -> (&'static str, &'static str) { | |||
| 224 | "GitHub user or organization", | 235 | "GitHub user or organization", |
| 225 | "GitHub kullanıcısı veya kuruluşu", | 236 | "GitHub kullanıcısı veya kuruluşu", |
| 226 | ), | 237 | ), |
| 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 | + ), | ||
| 227 | K::BulkOwnerGitLab => ("GitLab user or group", "GitLab kullanıcısı veya grubu"), | 242 | K::BulkOwnerGitLab => ("GitLab user or group", "GitLab kullanıcısı veya grubu"), |
| 228 | K::BulkListButton => ("List repositories", "Depoları listele"), | 243 | K::BulkListButton => ("List repositories", "Depoları listele"), |
| 229 | K::BulkSelectHeading => ( | 244 | K::BulkSelectHeading => ( |
| @@ -262,8 +277,8 @@ fn pair(key: K) -> (&'static str, &'static str) { | |||
| 262 | "Bu depo adresi geçerli değil.", | 277 | "Bu depo adresi geçerli değil.", |
| 263 | ), | 278 | ), |
| 264 | K::ErrBadInstance => ( | 279 | K::ErrBadInstance => ( |
| 265 | - "That GitLab address is not valid.", | 280 | + "That instance address is not valid.", |
| 266 | - "Bu GitLab adresi geçerli değil.", | 281 | + "Bu sunucu adresi geçerli değil.", |
| 267 | ), | 282 | ), |
| 268 | K::ErrBadOwner => ( | 283 | K::ErrBadOwner => ( |
| 269 | "That user or organization name is not valid.", | 284 | "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; | |||
| 14 | 14 | ||
| 15 | const PER_PAGE: usize = 100; | 15 | const PER_PAGE: usize = 100; |
| 16 | /// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever. | 16 | /// 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; | ||
| 17 | const MAX_PAGES: usize = 500; | 19 | const MAX_PAGES: usize = 500; |
| 18 | /// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues. | 20 | /// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues. |
| 19 | const MAX_RATE_WAIT: u64 = 15 * 60; | 21 | const MAX_RATE_WAIT: u64 = 15 * 60; |
| @@ -184,12 +186,22 @@ pub fn rate_wait( | |||
| 184 | 186 | ||
| 185 | pub type Notice = Arc<dyn Fn(String) + Send + Sync>; | 187 | pub type Notice = Arc<dyn Fn(String) + Send + Sync>; |
| 186 | 188 | ||
| 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 | + | ||
| 187 | /// A client under the outbound policy, with the token kept private to the API host. | 200 | /// A client under the outbound policy, with the token kept private to the API host. |
| 188 | pub struct Http { | 201 | pub struct Http { |
| 189 | client: reqwest::Client, | 202 | client: reqwest::Client, |
| 190 | token: Option<String>, | 203 | token: Option<String>, |
| 191 | - /// `Authorization: Bearer` (GitHub) or `PRIVATE-TOKEN` (GitLab). | 204 | + auth: Auth, |
| 192 | - gitlab: bool, | ||
| 193 | auth_host: String, | 205 | auth_host: String, |
| 194 | notice: Notice, | 206 | notice: Notice, |
| 195 | } | 207 | } |
| @@ -198,7 +210,7 @@ impl Http { | |||
| 198 | pub fn new( | 210 | pub fn new( |
| 199 | client: reqwest::Client, | 211 | client: reqwest::Client, |
| 200 | token: Option<String>, | 212 | token: Option<String>, |
| 201 | - gitlab: bool, | 213 | + auth: Auth, |
| 202 | auth_host: String, | 214 | auth_host: String, |
| 203 | notice: Notice, | 215 | notice: Notice, |
| 204 | ) -> Self { | 216 | ) -> Self { |
| @@ -206,7 +218,7 @@ impl Http { | |||
| 206 | Http { | 218 | Http { |
| 207 | client, | 219 | client, |
| 208 | token, | 220 | token, |
| 209 | - gitlab, | 221 | + auth, |
| 210 | auth_host, | 222 | auth_host, |
| 211 | notice, | 223 | notice, |
| 212 | } | 224 | } |
| @@ -225,11 +237,12 @@ impl Http { | |||
| 225 | && Self::host_of(url) == self.auth_host | 237 | && Self::host_of(url) == self.auth_host |
| 226 | && let Some(token) = &self.token | 238 | && let Some(token) = &self.token |
| 227 | { | 239 | { |
| 228 | - req = if self.gitlab { | 240 | + req = match self.auth { |
| 229 | - req.header("PRIVATE-TOKEN", token) | 241 | + Auth::GitLab => req.header("PRIVATE-TOKEN", token), |
| 230 | - } else { | 242 | + Auth::GitHub => req |
| 231 | - req.header(AUTHORIZATION, format!("Bearer {token}")) | 243 | + .header(AUTHORIZATION, format!("Bearer {token}")) |
| 232 | - .header("X-GitHub-Api-Version", "2022-11-28") | 244 | + .header("X-GitHub-Api-Version", "2022-11-28"), |
| 245 | + Auth::Forgejo => req.header(AUTHORIZATION, format!("token {token}")), | ||
| 233 | }; | 246 | }; |
| 234 | } | 247 | } |
| 235 | req | 248 | req |
| @@ -326,6 +339,35 @@ impl Http { | |||
| 326 | Ok(out) | 339 | Ok(out) |
| 327 | } | 340 | } |
| 328 | 341 | ||
| 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 | + | ||
| 329 | /// Downloads a file, following redirects by hand: the token goes to the API host only, and | 371 | /// Downloads a file, following redirects by hand: the token goes to the API host only, and |
| 330 | /// each hop is fetched under the same address policy as every other request. | 372 | /// each hop is fetched under the same address policy as every other request. |
| 331 | pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<Vec<u8>> { | 373 | pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<Vec<u8>> { |
| @@ -1034,6 +1076,306 @@ impl RemoteApi for GitLab { | |||
| 1034 | } | 1076 | } |
| 1035 | } | 1077 | } |
| 1036 | 1078 | ||
| 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 | + | ||
| 1037 | #[cfg(test)] | 1379 | #[cfg(test)] |
| 1038 | mod tests { | 1380 | mod tests { |
| 1039 | use super::*; | 1381 | 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. |
| 2 | //! | 2 | //! |
| 3 | //! The git data comes from the same fetch the pull mirrors use, once, into a normal repo (no mirror | 3 | //! 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 |
| 5 | //! comments, pull requests (as issues marked "imported PR") and releases with their assets, through | 5 | //! comments, pull requests (as issues marked "imported PR") and releases with their assets, through |
| 6 | //! a [`RemoteApi`]. Progress is written to the database and every step wakes the job page's event | 6 | //! a [`RemoteApi`]. Progress is written to the database and every step wakes the job page's event |
| 7 | //! stream, so the page updates with no polling. | 7 | //! stream, so the page updates with no polling. |
| @@ -26,7 +26,9 @@ use serde::{Deserialize, Serialize}; | |||
| 26 | use tokio::sync::{Semaphore, watch}; | 26 | use tokio::sync::{Semaphore, watch}; |
| 27 | 27 | ||
| 28 | use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi}; | 28 | 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 | +}; | ||
| 30 | use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; | 32 | use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; |
| 31 | use crate::state::AppState; | 33 | use crate::state::AppState; |
| 32 | 34 | ||
| @@ -43,6 +45,7 @@ pub enum Source { | |||
| 43 | Git, | 45 | Git, |
| 44 | GitHub, | 46 | GitHub, |
| 45 | GitLab, | 47 | GitLab, |
| 48 | + Forgejo, | ||
| 46 | } | 49 | } |
| 47 | 50 | ||
| 48 | impl Source { | 51 | impl Source { |
| @@ -51,6 +54,7 @@ impl Source { | |||
| 51 | Source::Git => "git", | 54 | Source::Git => "git", |
| 52 | Source::GitHub => "github", | 55 | Source::GitHub => "github", |
| 53 | Source::GitLab => "gitlab", | 56 | Source::GitLab => "gitlab", |
| 57 | + Source::Forgejo => "forgejo", | ||
| 54 | } | 58 | } |
| 55 | } | 59 | } |
| 56 | 60 | ||
| @@ -59,6 +63,8 @@ impl Source { | |||
| 59 | "git" => Some(Source::Git), | 63 | "git" => Some(Source::Git), |
| 60 | "github" => Some(Source::GitHub), | 64 | "github" => Some(Source::GitHub), |
| 61 | "gitlab" => Some(Source::GitLab), | 65 | "gitlab" => Some(Source::GitLab), |
| 66 | + // Gitea speaks the same API. | ||
| 67 | + "forgejo" | "gitea" => Some(Source::Forgejo), | ||
| 62 | _ => None, | 68 | _ => None, |
| 63 | } | 69 | } |
| 64 | } | 70 | } |
| @@ -69,6 +75,7 @@ impl Source { | |||
| 69 | Source::Git => "git", | 75 | Source::Git => "git", |
| 70 | Source::GitHub => "GitHub", | 76 | Source::GitHub => "GitHub", |
| 71 | Source::GitLab => "GitLab", | 77 | Source::GitLab => "GitLab", |
| 78 | + Source::Forgejo => "Forgejo", | ||
| 72 | } | 79 | } |
| 73 | } | 80 | } |
| 74 | } | 81 | } |
| @@ -98,7 +105,7 @@ pub struct JobSpec { | |||
| 98 | pub source: Source, | 105 | pub source: Source, |
| 99 | /// The URL for `git`, `owner/repo` for GitHub, the project path for GitLab. | 106 | /// The URL for `git`, `owner/repo` for GitHub, the project path for GitLab. |
| 100 | pub remote: String, | 107 | pub remote: String, |
| 101 | - /// The GitLab instance, e.g. `https://gitlab.com`. | 108 | + /// The GitLab or Forgejo instance, e.g. `https://gitlab.com`. |
| 102 | pub instance: String, | 109 | pub instance: String, |
| 103 | pub token: Option<String>, | 110 | pub token: Option<String>, |
| 104 | /// The user name sent with the token for a plain git URL. | 111 | /// The user name sent with the token for a plain git URL. |
| @@ -121,7 +128,7 @@ impl JobSpec { | |||
| 121 | match self.source { | 128 | match self.source { |
| 122 | Source::Git => self.remote.clone(), | 129 | Source::Git => self.remote.clone(), |
| 123 | Source::GitHub => format!("https://github.com/{}.git", self.remote), | 130 | Source::GitHub => format!("https://github.com/{}.git", self.remote), |
| 124 | - Source::GitLab => format!( | 131 | + Source::GitLab | Source::Forgejo => format!( |
| 125 | "{}/{}.git", | 132 | "{}/{}.git", |
| 126 | self.instance.trim_end_matches('/'), | 133 | self.instance.trim_end_matches('/'), |
| 127 | self.remote | 134 | self.remote |
| @@ -133,7 +140,7 @@ impl JobSpec { | |||
| 133 | let token = self.token.as_ref().filter(|t| !t.is_empty())?; | 140 | let token = self.token.as_ref().filter(|t| !t.is_empty())?; |
| 134 | let username = match self.source { | 141 | let username = match self.source { |
| 135 | Source::GitHub => "x-access-token".to_owned(), | 142 | Source::GitHub => "x-access-token".to_owned(), |
| 136 | - Source::GitLab => "oauth2".to_owned(), | 143 | + Source::GitLab | Source::Forgejo => "oauth2".to_owned(), |
| 137 | Source::Git if self.git_user.is_empty() => "git".to_owned(), | 144 | Source::Git if self.git_user.is_empty() => "git".to_owned(), |
| 138 | Source::Git => self.git_user.clone(), | 145 | Source::Git => self.git_user.clone(), |
| 139 | }; | 146 | }; |
| @@ -337,6 +344,10 @@ async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { | |||
| 337 | Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, | 344 | Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, |
| 338 | Err(e) => fail(state, &rep, &e).await, | 345 | Err(e) => fail(state, &rep, &e).await, |
| 339 | }, | 346 | }, |
| 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 | + }, | ||
| 340 | Source::Git => {} | 351 | Source::Git => {} |
| 341 | } | 352 | } |
| 342 | } | 353 | } |
| @@ -710,9 +721,9 @@ impl<A: RemoteApi> Run<'_, A> { | |||
| 710 | }) | 721 | }) |
| 711 | .collect(); | 722 | .collect(); |
| 712 | items.sort_by_key(|i| (i.is_pr, i.number)); | 723 | items.sort_by_key(|i| (i.is_pr, i.number)); |
| 713 | - // GitHub numbers issues and pull requests together; GitLab keeps two sequences. Sorting | 724 | + // GitHub and Forgejo number issues and pull requests together; GitLab keeps two sequences. Sorting |
| 714 | - // by number alone keeps GitHub numbers aligned, so do that for it. | 725 | + // by number alone keeps GitHub numbers aligned, so do that for them. |
| 715 | - if self.spec.source == Source::GitHub { | 726 | + if matches!(self.spec.source, Source::GitHub | Source::Forgejo) { |
| 716 | items.sort_by_key(|i| i.number); | 727 | items.sort_by_key(|i| i.number); |
| 717 | } | 728 | } |
| 718 | let total = items.len(); | 729 | let total = items.len(); |
crates/forge-web/src/importer/remote.rsmodified+32 -8
| @@ -3,7 +3,7 @@ | |||
| 3 | use std::time::Duration; | 3 | use std::time::Duration; |
| 4 | 4 | ||
| 5 | use super::Source; | 5 | use super::Source; |
| 6 | -use super::api::{self, GitHub, GitLab, Http, Notice}; | 6 | +use super::api::{self, Auth, Forgejo, GitHub, GitLab, Http, Notice}; |
| 7 | use crate::mirrors::policy; | 7 | use crate::mirrors::policy; |
| 8 | use crate::state::AppState; | 8 | use crate::state::AppState; |
| 9 | use crate::webhooks::client::{policy_client, validate_url}; | 9 | use crate::webhooks::client::{policy_client, validate_url}; |
| @@ -19,7 +19,7 @@ pub fn make_github( | |||
| 19 | Ok(GitHub::new(Http::new( | 19 | Ok(GitHub::new(Http::new( |
| 20 | client, | 20 | client, |
| 21 | token, | 21 | token, |
| 22 | - false, | 22 | + Auth::GitHub, |
| 23 | "api.github.com".into(), | 23 | "api.github.com".into(), |
| 24 | notice, | 24 | notice, |
| 25 | ))) | 25 | ))) |
| @@ -41,13 +41,34 @@ pub fn make_gitlab( | |||
| 41 | let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") | 41 | let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") |
| 42 | .map_err(|e| format!("could not build the HTTP client: {e}"))?; | 42 | .map_err(|e| format!("could not build the HTTP client: {e}"))?; |
| 43 | Ok(GitLab::new( | 43 | 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), | ||
| 45 | instance, | 66 | instance, |
| 46 | )) | 67 | )) |
| 47 | } | 68 | } |
| 48 | 69 | ||
| 49 | /// Splits what the user typed into `(remote, instance)` for a source. `None` when it is not a | 70 | /// 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 |
| 51 | /// (`https://host/group/project`) or, with `instance` given, a bare path. | 72 | /// (`https://host/group/project`) or, with `instance` given, a bare path. |
| 52 | pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> { | 73 | pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> { |
| 53 | let text = text.trim(); | 74 | let text = text.trim(); |
| @@ -62,7 +83,8 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin | |||
| 62 | let path = path.strip_suffix(".git").unwrap_or(path); | 83 | let path = path.strip_suffix(".git").unwrap_or(path); |
| 63 | api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new())) | 84 | api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new())) |
| 64 | } | 85 | } |
| 65 | - Source::GitLab => { | 86 | + Source::GitLab | Source::Forgejo => { |
| 87 | + let max = if source == Source::GitLab { 20 } else { 2 }; | ||
| 66 | if let Some((scheme, rest)) = text | 88 | if let Some((scheme, rest)) = text |
| 67 | .strip_prefix("https://") | 89 | .strip_prefix("https://") |
| 68 | .map(|r| ("https", r)) | 90 | .map(|r| ("https", r)) |
| @@ -71,7 +93,7 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin | |||
| 71 | let (host, path) = rest.split_once('/')?; | 93 | let (host, path) = rest.split_once('/')?; |
| 72 | let path = path.trim_end_matches('/'); | 94 | let path = path.trim_end_matches('/'); |
| 73 | let path = path.strip_suffix(".git").unwrap_or(path); | 95 | 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) { |
| 75 | return None; | 97 | return None; |
| 76 | } | 98 | } |
| 77 | return Some((path.to_owned(), format!("{scheme}://{host}"))); | 99 | return Some((path.to_owned(), format!("{scheme}://{host}"))); |
| @@ -85,7 +107,7 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin | |||
| 85 | let ok = !host.is_empty() | 107 | let ok = !host.is_empty() |
| 86 | && !host.contains('@') | 108 | && !host.contains('@') |
| 87 | && !host.contains('/') | 109 | && !host.contains('/') |
| 88 | - && api::valid_path(path, 2, 20); | 110 | + && api::valid_path(path, 2, max); |
| 89 | ok.then(|| (path.to_owned(), instance.to_owned())) | 111 | ok.then(|| (path.to_owned(), instance.to_owned())) |
| 90 | } | 112 | } |
| 91 | } | 113 | } |
| @@ -94,7 +116,9 @@ pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(Strin | |||
| 94 | /// The reference stored on a job and shown to the user: no credential in it. | 116 | /// The reference stored on a job and shown to the user: no credential in it. |
| 95 | pub fn source_ref(source: Source, remote: &str, instance: &str) -> String { | 117 | pub fn source_ref(source: Source, remote: &str, instance: &str) -> String { |
| 96 | match source { | 118 | match source { |
| 97 | - Source::GitLab => format!("{}/{}", instance.trim_end_matches('/'), remote), | 119 | + Source::GitLab | Source::Forgejo => { |
| 120 | + format!("{}/{}", instance.trim_end_matches('/'), remote) | ||
| 121 | + } | ||
| 98 | _ => remote.to_owned(), | 122 | _ => remote.to_owned(), |
| 99 | } | 123 | } |
| 100 | } | 124 | } |
crates/forge-web/src/importer/tests.rsmodified+3 -0
| @@ -542,3 +542,6 @@ fn asset_names_are_made_safe() { | |||
| 542 | "a b/c?d" | 542 | "a b/c?d" |
| 543 | ))); | 543 | ))); |
| 544 | } | 544 | } |
| 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}; | |||
| 24 | use crate::i18n::{self, Key, Lang}; | 24 | use crate::i18n::{self, Key, Lang}; |
| 25 | use crate::importer::api::{ApiError, RemoteApi}; | 25 | use crate::importer::api::{ApiError, RemoteApi}; |
| 26 | use crate::importer::{ | 26 | use crate::importer::{ |
| 27 | - self, ImportOptions, JobSpec, Source, default_name, make_github, make_gitlab, parse_remote, | 27 | + self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, |
| 28 | - source_ref, | 28 | + parse_remote, source_ref, |
| 29 | }; | 29 | }; |
| 30 | use crate::pages::ci_runs::{changed_event, events_response}; | 30 | use crate::pages::ci_runs::{changed_event, events_response}; |
| 31 | use crate::pages::new_repo::{owner_choices, repo_owner}; | 31 | use crate::pages::new_repo::{owner_choices, repo_owner}; |
| @@ -125,6 +125,27 @@ fn source_of(raw: Option<&str>) -> Source { | |||
| 125 | raw.and_then(Source::parse).unwrap_or(Source::GitHub) | 125 | raw.and_then(Source::parse).unwrap_or(Source::GitHub) |
| 126 | } | 126 | } |
| 127 | 127 | ||
| 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 | + | ||
| 128 | fn token_of(raw: &str) -> Option<String> { | 149 | fn token_of(raw: &str) -> Option<String> { |
| 129 | let t = raw.trim(); | 150 | let t = raw.trim(); |
| 130 | (!t.is_empty()).then(|| t.to_owned()) | 151 | (!t.is_empty()).then(|| t.to_owned()) |
| @@ -150,11 +171,13 @@ async fn source_tabs(lang: Lang, base: &str, active: Source) -> Result<impl View | |||
| 150 | let git = format!("{base}?source=git"); | 171 | let git = format!("{base}?source=git"); |
| 151 | let github = format!("{base}?source=github"); | 172 | let github = format!("{base}?source=github"); |
| 152 | let gitlab = format!("{base}?source=gitlab"); | 173 | let gitlab = format!("{base}?source=gitlab"); |
| 174 | + let forgejo = format!("{base}?source=forgejo"); | ||
| 153 | Ok(view! { | 175 | Ok(view! { |
| 154 | <nav class="import-sources" aria-label=(g::t(lang, K::TabImport))> | 176 | <nav class="import-sources" aria-label=(g::t(lang, K::TabImport))> |
| 155 | <a href=(git.as_str()) class="import-source" aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a> | 177 | <a href=(git.as_str()) class="import-source" aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a> |
| 156 | <a href=(github.as_str()) class="import-source" aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a> | 178 | <a href=(github.as_str()) class="import-source" aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a> |
| 157 | <a href=(gitlab.as_str()) class="import-source" aria-current=((active == Source::GitLab).then_some("page"))>(g::t(lang, K::SrcGitLab))</a> | 179 | <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> | ||
| 158 | </nav> | 181 | </nav> |
| 159 | }) | 182 | }) |
| 160 | } | 183 | } |
| @@ -213,7 +236,7 @@ impl Draft { | |||
| 213 | Draft { | 236 | Draft { |
| 214 | source, | 237 | source, |
| 215 | remote: String::new(), | 238 | remote: String::new(), |
| 216 | - instance: "https://gitlab.com".into(), | 239 | + instance: default_instance(source).into(), |
| 217 | git_user: String::new(), | 240 | git_user: String::new(), |
| 218 | owner: String::new(), | 241 | owner: String::new(), |
| 219 | name: String::new(), | 242 | name: String::new(), |
| @@ -265,7 +288,8 @@ async fn import_form( | |||
| 265 | }; | 288 | }; |
| 266 | let source_value = source.as_str(); | 289 | let source_value = source.as_str(); |
| 267 | let is_git = source == Source::Git; | 290 | 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); | ||
| 269 | let bulk_href = if is_git { | 293 | let bulk_href = if is_git { |
| 270 | String::new() | 294 | String::new() |
| 271 | } else { | 295 | } else { |
| @@ -273,13 +297,13 @@ async fn import_form( | |||
| 273 | }; | 297 | }; |
| 274 | let remote_label = match source { | 298 | let remote_label = match source { |
| 275 | Source::Git => g::t(lang, K::GitUrl), | 299 | 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), |
| 277 | Source::GitLab => g::t(lang, K::GitLabProject), | 301 | Source::GitLab => g::t(lang, K::GitLabProject), |
| 278 | }; | 302 | }; |
| 279 | let remote_placeholder = match source { | 303 | let remote_placeholder = match source { |
| 280 | Source::Git => "https://example.org/tahinli/project.git", | 304 | Source::Git => "https://example.org/tahinli/project.git", |
| 281 | Source::GitHub => "tahinli/project", | 305 | Source::GitHub => "tahinli/project", |
| 282 | - Source::GitLab => "tahinli/project", | 306 | + Source::GitLab | Source::Forgejo => "tahinli/project", |
| 283 | }; | 307 | }; |
| 284 | let token_label = if is_git { | 308 | let token_label = if is_git { |
| 285 | g::t(lang, K::GitPassword) | 309 | g::t(lang, K::GitPassword) |
| @@ -306,9 +330,9 @@ async fn import_form( | |||
| 306 | source_tabs(lang: lang, base: "/new/import", active: source) | 330 | source_tabs(lang: lang, base: "/new/import", active: source) |
| 307 | <p class="muted small">(g::t(lang, K::ImportIntro))</p> | 331 | <p class="muted small">(g::t(lang, K::ImportIntro))</p> |
| 308 | <div class="newrepo-card"> | 332 | <div class="newrepo-card"> |
| 309 | - if is_gitlab { | 333 | + if has_instance { |
| 310 | <label> | 334 | <label> |
| 311 | - <span>(g::t(lang, K::GitLabInstance))</span> | 335 | + <span>(instance_label)</span> |
| 312 | <input type="url" name="instance" value=(draft.instance.as_str()) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono"> | 336 | <input type="url" name="instance" value=(draft.instance.as_str()) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono"> |
| 313 | </label> | 337 | </label> |
| 314 | } | 338 | } |
| @@ -406,7 +430,7 @@ async fn start_single( | |||
| 406 | ) -> Result<std::result::Result<String, String>> { | 430 | ) -> Result<std::result::Result<String, String>> { |
| 407 | let state = app_context::<AppState>(cx); | 431 | let state = app_context::<AppState>(cx); |
| 408 | let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else { | 432 | 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") { |
| 410 | g::t(lang, K::ErrBadInstance) | 434 | g::t(lang, K::ErrBadInstance) |
| 411 | } else { | 435 | } else { |
| 412 | g::t(lang, K::ErrBadRemote) | 436 | g::t(lang, K::ErrBadRemote) |
| @@ -537,13 +561,16 @@ async fn bulk_form( | |||
| 537 | owners: Vec<String>, | 561 | owners: Vec<String>, |
| 538 | error: Option<String>, | 562 | error: Option<String>, |
| 539 | ) -> Result<impl View> { | 563 | ) -> 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); | ||
| 541 | let source_value = source.as_str(); | 566 | let source_value = source.as_str(); |
| 542 | - let owner_label = if is_gitlab { | 567 | + let owner_label = match source { |
| 543 | - g::t(lang, K::BulkOwnerGitLab) | 568 | + Source::GitLab => g::t(lang, K::BulkOwnerGitLab), |
| 544 | - } else { | 569 | + Source::Forgejo => g::t(lang, K::BulkOwnerForgejo), |
| 545 | - g::t(lang, K::BulkOwnerGitHub) | 570 | + _ => g::t(lang, K::BulkOwnerGitHub), |
| 546 | }; | 571 | }; |
| 572 | + // A Forgejo token can list its own repositories, so the owner may stay empty. | ||
| 573 | + let owner_required = source != Source::Forgejo; | ||
| 547 | Ok(view! { | 574 | Ok(view! { |
| 548 | newrepo_tabs(lang: lang, active: "import") | 575 | newrepo_tabs(lang: lang, active: "import") |
| 549 | if let Some(message) = error { | 576 | if let Some(message) = error { |
| @@ -562,15 +589,15 @@ async fn bulk_form( | |||
| 562 | source_tabs(lang: lang, base: "/new/import/bulk", active: source) | 589 | source_tabs(lang: lang, base: "/new/import/bulk", active: source) |
| 563 | <p class="muted small">(g::t(lang, K::BulkIntro))</p> | 590 | <p class="muted small">(g::t(lang, K::BulkIntro))</p> |
| 564 | <div class="newrepo-card"> | 591 | <div class="newrepo-card"> |
| 565 | - if is_gitlab { | 592 | + if has_instance { |
| 566 | <label> | 593 | <label> |
| 567 | - <span>(g::t(lang, K::GitLabInstance))</span> | 594 | + <span>(instance_label)</span> |
| 568 | <input type="url" name="instance" value=(instance) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono"> | 595 | <input type="url" name="instance" value=(instance) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono"> |
| 569 | </label> | 596 | </label> |
| 570 | } | 597 | } |
| 571 | <label> | 598 | <label> |
| 572 | <span>(owner_label)</span> | 599 | <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"> |
| 574 | </label> | 601 | </label> |
| 575 | <label> | 602 | <label> |
| 576 | <span>(g::t(lang, K::TokenOptional))</span> | 603 | <span>(g::t(lang, K::TokenOptional))</span> |
| @@ -702,7 +729,7 @@ async fn bulk_page(cx: &Cx) -> Result<impl View> { | |||
| 702 | let csrf = viewer.1.csrf_token.clone(); | 729 | let csrf = viewer.1.csrf_token.clone(); |
| 703 | Ok(view! { cx => | 730 | Ok(view! { cx => |
| 704 | shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), | 731 | 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))) |
| 706 | }) | 733 | }) |
| 707 | } | 734 | } |
| 708 | 735 | ||
| @@ -726,6 +753,11 @@ async fn list_remote( | |||
| 726 | .list_repos(from) | 753 | .list_repos(from) |
| 727 | .await | 754 | .await |
| 728 | } | 755 | } |
| 756 | + Source::Forgejo => { | ||
| 757 | + make_forgejo(state, instance, token, notice)? | ||
| 758 | + .list_repos(from) | ||
| 759 | + .await | ||
| 760 | + } | ||
| 729 | _ => make_github(state, token, notice)?.list_repos(from).await, | 761 | _ => make_github(state, token, notice)?.list_repos(from).await, |
| 730 | }; | 762 | }; |
| 731 | listed.map_err(|e: ApiError| e.to_string()) | 763 | 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> { | |||
| 742 | }; | 774 | }; |
| 743 | let owners = owner_choices(state, &viewer.0).await?; | 775 | let owners = owner_choices(state, &viewer.0).await?; |
| 744 | let csrf = viewer.1.csrf_token.clone(); | 776 | 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() { |
| 746 | form.instance.trim().to_owned() | 778 | form.instance.trim().to_owned() |
| 747 | } else { | 779 | } else { |
| 748 | - "https://gitlab.com".to_owned() | 780 | + default_instance(source).to_owned() |
| 749 | }; | 781 | }; |
| 750 | 782 | ||
| 751 | if form.stage == "run" { | 783 | if form.stage == "run" { |
| @@ -754,8 +786,10 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> { | |||
| 754 | } | 786 | } |
| 755 | 787 | ||
| 756 | let from = form.from.trim(); | 788 | let from = form.from.trim(); |
| 757 | - let bad_owner = | 789 | + let owner_max = if source == Source::GitLab { 20 } else { 1 }; |
| 758 | - !crate::importer::api::valid_path(from, 1, 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); | ||
| 759 | let result = if bad_owner { | 793 | let result = if bad_owner { |
| 760 | Err(g::t(lang, K::ErrBadOwner).to_owned()) | 794 | Err(g::t(lang, K::ErrBadOwner).to_owned()) |
| 761 | } else { | 795 | } else { |