| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | pub mod api; |
| 14 | pub mod remote; |
| 15 | |
| 16 | use std::collections::HashMap; |
| 17 | use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError}; |
| 18 | use std::time::Duration; |
| 19 | |
| 20 | use forge_core::issues::{IssueState, MAX_BODY, MAX_TITLE, StateReason}; |
| 21 | use forge_core::releases::{MAX_ASSET_NAME_LEN, NewRelease}; |
| 22 | use forge_core::store::imports::{ImportJob, ImportOrigin, ImportState}; |
| 23 | use forge_core::{Repo, Store, User}; |
| 24 | use forge_git::mirror::{RemoteAuth, mirror_fetch}; |
| 25 | use serde::{Deserialize, Serialize}; |
| 26 | use tokio::sync::{Semaphore, watch}; |
| 27 | |
| 28 | use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi}; |
| 29 | pub use self::remote::{ |
| 30 | default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, |
| 31 | }; |
| 32 | use crate::live::Topic; |
| 33 | use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; |
| 34 | use crate::state::AppState; |
| 35 | |
| 36 | |
| 37 | const GIT_TIMEOUT: Duration = Duration::from_secs(60 * 60); |
| 38 | |
| 39 | static SLOTS: Semaphore = Semaphore::const_new(2); |
| 40 | const IMPORTED_PR_LABEL: &str = "imported PR"; |
| 41 | const IMPORTED_PR_COLOR: &str = "#8b7bd8"; |
| 42 | const FALLBACK_LABEL_COLOR: &str = "#8b949e"; |
| 43 | |
| 44 | const IMPORT_BUMP_BATCH: usize = 25; |
| 45 | |
| 46 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 47 | pub enum Source { |
| 48 | Git, |
| 49 | GitHub, |
| 50 | GitLab, |
| 51 | Forgejo, |
| 52 | } |
| 53 | |
| 54 | impl Source { |
| 55 | pub fn as_str(self) -> &'static str { |
| 56 | match self { |
| 57 | Source::Git => "git", |
| 58 | Source::GitHub => "github", |
| 59 | Source::GitLab => "gitlab", |
| 60 | Source::Forgejo => "forgejo", |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | pub fn parse(s: &str) -> Option<Self> { |
| 65 | match s { |
| 66 | "git" => Some(Source::Git), |
| 67 | "github" => Some(Source::GitHub), |
| 68 | "gitlab" => Some(Source::GitLab), |
| 69 | |
| 70 | "forgejo" | "gitea" => Some(Source::Forgejo), |
| 71 | _ => None, |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | |
| 76 | pub fn label(self) -> &'static str { |
| 77 | match self { |
| 78 | Source::Git => "git", |
| 79 | Source::GitHub => "GitHub", |
| 80 | Source::GitLab => "GitLab", |
| 81 | Source::Forgejo => "Forgejo", |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 88 | pub struct ImportOptions { |
| 89 | #[serde(default)] |
| 90 | pub labels: bool, |
| 91 | #[serde(default)] |
| 92 | pub issues: bool, |
| 93 | #[serde(default)] |
| 94 | pub pulls: bool, |
| 95 | #[serde(default)] |
| 96 | pub releases: bool, |
| 97 | } |
| 98 | |
| 99 | impl ImportOptions { |
| 100 | pub fn any_api(&self) -> bool { |
| 101 | self.labels || self.issues || self.pulls || self.releases |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | |
| 106 | #[derive(Clone)] |
| 107 | pub struct JobSpec { |
| 108 | pub source: Source, |
| 109 | |
| 110 | pub remote: String, |
| 111 | |
| 112 | pub instance: String, |
| 113 | pub token: Option<String>, |
| 114 | |
| 115 | pub git_user: String, |
| 116 | pub options: ImportOptions, |
| 117 | } |
| 118 | |
| 119 | impl std::fmt::Debug for JobSpec { |
| 120 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 121 | f.debug_struct("JobSpec") |
| 122 | .field("source", &self.source) |
| 123 | .field("remote", &self.remote) |
| 124 | .field("token", &self.token.as_ref().map(|_| "[redacted]")) |
| 125 | .finish() |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | impl JobSpec { |
| 130 | pub fn clone_url(&self) -> String { |
| 131 | match self.source { |
| 132 | Source::Git => self.remote.clone(), |
| 133 | Source::GitHub => format!("https://github.com/{}.git", self.remote), |
| 134 | Source::GitLab | Source::Forgejo => format!( |
| 135 | "{}/{}.git", |
| 136 | self.instance.trim_end_matches('/'), |
| 137 | self.remote |
| 138 | ), |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn auth(&self) -> Option<RemoteAuth> { |
| 143 | let token = self.token.as_ref().filter(|t| !t.is_empty())?; |
| 144 | let username = match self.source { |
| 145 | Source::GitHub => "x-access-token".to_owned(), |
| 146 | Source::GitLab | Source::Forgejo => "oauth2".to_owned(), |
| 147 | Source::Git if self.git_user.is_empty() => "git".to_owned(), |
| 148 | Source::Git => self.git_user.clone(), |
| 149 | }; |
| 150 | Some(RemoteAuth { |
| 151 | username, |
| 152 | secret: token.clone().into_bytes(), |
| 153 | }) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | |
| 158 | |
| 159 | #[derive(Clone)] |
| 160 | pub enum Transport { |
| 161 | Net, |
| 162 | #[cfg(any(test, feature = "test-support"))] |
| 163 | Local(String), |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> = |
| 169 | LazyLock::new(|| Mutex::new(HashMap::new())); |
| 170 | |
| 171 | fn hub() -> MutexGuard<'static, HashMap<String, watch::Sender<u64>>> { |
| 172 | HUB.lock().unwrap_or_else(PoisonError::into_inner) |
| 173 | } |
| 174 | |
| 175 | |
| 176 | pub fn subscribe(job_id: &str) -> watch::Receiver<u64> { |
| 177 | hub() |
| 178 | .entry(job_id.to_owned()) |
| 179 | .or_insert_with(|| watch::channel(0).0) |
| 180 | .subscribe() |
| 181 | } |
| 182 | |
| 183 | fn bump(job_id: &str) { |
| 184 | let mut hub = hub(); |
| 185 | if let Some(tx) = hub.get(job_id) { |
| 186 | tx.send_modify(|n| *n = n.wrapping_add(1)); |
| 187 | if tx.receiver_count() == 0 { |
| 188 | hub.remove(job_id); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | |
| 194 | fn close(job_id: &str) { |
| 195 | if let Some(tx) = hub().remove(job_id) { |
| 196 | tx.send_modify(|n| *n = n.wrapping_add(1)); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | #[derive(Clone)] |
| 203 | struct Reporter { |
| 204 | store: Store, |
| 205 | job_id: String, |
| 206 | } |
| 207 | |
| 208 | impl Reporter { |
| 209 | async fn log(&self, level: &str, message: impl AsRef<str>) { |
| 210 | if let Err(e) = self |
| 211 | .store |
| 212 | .add_import_event(&self.job_id, level, message.as_ref()) |
| 213 | .await |
| 214 | { |
| 215 | tracing::warn!(error = %e, "import: could not record a progress line"); |
| 216 | } |
| 217 | bump(&self.job_id); |
| 218 | } |
| 219 | |
| 220 | async fn stage(&self, stage: &str, done: usize, total: usize) { |
| 221 | let (done, total) = (done as i64, total as i64); |
| 222 | if let Err(e) = self |
| 223 | .store |
| 224 | .set_import_progress(&self.job_id, stage, done, total) |
| 225 | .await |
| 226 | { |
| 227 | tracing::warn!(error = %e, "import: could not record progress"); |
| 228 | } |
| 229 | bump(&self.job_id); |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | pub fn origin_note(source: &str, author: &str, created: &str, url: &str) -> String { |
| 238 | let clean: String = author |
| 239 | .chars() |
| 240 | .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) |
| 241 | .take(60) |
| 242 | .collect(); |
| 243 | let who = if clean.is_empty() { "unknown" } else { &clean }; |
| 244 | let date: String = created.chars().take(10).collect(); |
| 245 | let mut line = format!("> Originally by \\@{who} on {source}"); |
| 246 | if !date.is_empty() && date.bytes().all(|b| b.is_ascii_digit() || b == b'-') { |
| 247 | line.push_str(", "); |
| 248 | line.push_str(&date); |
| 249 | } |
| 250 | let safe_url = url.starts_with("https://") |
| 251 | && !url |
| 252 | .chars() |
| 253 | .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ')' | '(' | '<' | '>')); |
| 254 | if safe_url { |
| 255 | line.push_str(&format!(", [original]({url})")); |
| 256 | } |
| 257 | line.push_str("\n\n"); |
| 258 | line |
| 259 | } |
| 260 | |
| 261 | |
| 262 | pub fn with_note(note: &str, body: &str) -> String { |
| 263 | let mut text = format!("{note}{body}"); |
| 264 | if text.len() > MAX_BODY { |
| 265 | let mut end = MAX_BODY - 16; |
| 266 | while !text.is_char_boundary(end) { |
| 267 | end -= 1; |
| 268 | } |
| 269 | text.truncate(end); |
| 270 | text.push_str("\n\n(cut)"); |
| 271 | } |
| 272 | text |
| 273 | } |
| 274 | |
| 275 | fn clip_title(title: &str) -> String { |
| 276 | let t: String = title |
| 277 | .chars() |
| 278 | .filter(|c| !c.is_control()) |
| 279 | .take(MAX_TITLE) |
| 280 | .collect(); |
| 281 | let t = t.trim(); |
| 282 | if t.is_empty() { |
| 283 | "(untitled)".to_owned() |
| 284 | } else { |
| 285 | t.to_owned() |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | |
| 290 | pub fn asset_name(name: &str) -> String { |
| 291 | let mut out: String = name |
| 292 | .chars() |
| 293 | .map(|c| { |
| 294 | if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') { |
| 295 | c |
| 296 | } else { |
| 297 | '_' |
| 298 | } |
| 299 | }) |
| 300 | .collect(); |
| 301 | while out.starts_with('.') { |
| 302 | out.remove(0); |
| 303 | } |
| 304 | out.truncate(MAX_ASSET_NAME_LEN); |
| 305 | if out.is_empty() { |
| 306 | "asset".to_owned() |
| 307 | } else { |
| 308 | out |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { |
| 316 | |
| 317 | state.live.bump(&Topic::Imports(job.user_id.clone())); |
| 318 | tokio::spawn(async move { |
| 319 | let Ok(_slot) = SLOTS.acquire().await else { |
| 320 | return; |
| 321 | }; |
| 322 | run_production(&state, &job, &spec).await; |
| 323 | state.live.bump(&Topic::Imports(job.user_id.clone())); |
| 324 | }); |
| 325 | } |
| 326 | |
| 327 | async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { |
| 328 | let rep = Reporter { |
| 329 | store: state.store.clone(), |
| 330 | job_id: job.id.clone(), |
| 331 | }; |
| 332 | let notice: Notice = { |
| 333 | let rep = rep.clone(); |
| 334 | std::sync::Arc::new(move |msg: String| { |
| 335 | let rep = rep.clone(); |
| 336 | tokio::spawn(async move { rep.log("warn", msg).await }); |
| 337 | }) |
| 338 | }; |
| 339 | let wants_api = spec.options.any_api() && spec.source != Source::Git; |
| 340 | if !wants_api { |
| 341 | run_job::<GitHub>(state, job, spec, None, &Transport::Net).await; |
| 342 | return; |
| 343 | } |
| 344 | match spec.source { |
| 345 | Source::GitHub => match make_github(state, spec.token.clone(), notice) { |
| 346 | Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, |
| 347 | Err(e) => fail(state, &rep, &e).await, |
| 348 | }, |
| 349 | Source::GitLab => match make_gitlab(state, &spec.instance, spec.token.clone(), notice) { |
| 350 | Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, |
| 351 | Err(e) => fail(state, &rep, &e).await, |
| 352 | }, |
| 353 | Source::Forgejo => match make_forgejo(state, &spec.instance, spec.token.clone(), notice) { |
| 354 | Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, |
| 355 | Err(e) => fail(state, &rep, &e).await, |
| 356 | }, |
| 357 | Source::Git => {} |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | async fn fail(state: &AppState, rep: &Reporter, message: &str) { |
| 362 | tracing::warn!(job = %rep.job_id, %message, "import failed"); |
| 363 | rep.log("error", message).await; |
| 364 | if let Err(e) = state |
| 365 | .store |
| 366 | .set_import_state(&rep.job_id, ImportState::Failed, Some(message)) |
| 367 | .await |
| 368 | { |
| 369 | tracing::error!(error = %e, "import: could not record a failure"); |
| 370 | } |
| 371 | close(&rep.job_id); |
| 372 | } |
| 373 | |
| 374 | |
| 375 | pub async fn run_job<A: RemoteApi>( |
| 376 | state: &AppState, |
| 377 | job: &ImportJob, |
| 378 | spec: &JobSpec, |
| 379 | api: Option<&A>, |
| 380 | transport: &Transport, |
| 381 | ) { |
| 382 | let rep = Reporter { |
| 383 | store: state.store.clone(), |
| 384 | job_id: job.id.clone(), |
| 385 | }; |
| 386 | if let Err(e) = state |
| 387 | .store |
| 388 | .set_import_state(&job.id, ImportState::Running, None) |
| 389 | .await |
| 390 | { |
| 391 | tracing::error!(error = %e, "import: could not start the job"); |
| 392 | return; |
| 393 | } |
| 394 | bump(&job.id); |
| 395 | state.live.bump(&Topic::Imports(job.user_id.clone())); |
| 396 | match run_steps(state, job, spec, api, transport, &rep).await { |
| 397 | Ok(summary) => { |
| 398 | rep.log("info", summary).await; |
| 399 | rep.stage("done", 0, 0).await; |
| 400 | if let Err(e) = state |
| 401 | .store |
| 402 | .set_import_state(&job.id, ImportState::Done, None) |
| 403 | .await |
| 404 | { |
| 405 | tracing::error!(error = %e, "import: could not finish the job"); |
| 406 | } |
| 407 | close(&job.id); |
| 408 | } |
| 409 | Err(message) => fail(state, &rep, &message).await, |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | async fn run_steps<A: RemoteApi>( |
| 414 | state: &AppState, |
| 415 | job: &ImportJob, |
| 416 | spec: &JobSpec, |
| 417 | api: Option<&A>, |
| 418 | transport: &Transport, |
| 419 | rep: &Reporter, |
| 420 | ) -> Result<String, String> { |
| 421 | let repo_id = job.repo_id.clone().ok_or("the repository is gone")?; |
| 422 | let repo = state |
| 423 | .store |
| 424 | .repo_by_id(&repo_id) |
| 425 | .await |
| 426 | .map_err(|e| e.to_string())? |
| 427 | .ok_or("the repository is gone")?; |
| 428 | let user = state |
| 429 | .store |
| 430 | .user_by_id(&job.user_id) |
| 431 | .await |
| 432 | .map_err(|e| e.to_string())? |
| 433 | .ok_or("the importing user is gone")?; |
| 434 | |
| 435 | rep.stage("git", 0, 0).await; |
| 436 | rep.log("info", "Fetching branches and tags").await; |
| 437 | fetch_git(state, &repo, spec, transport).await?; |
| 438 | let repo = sync_default_branch(state, repo, rep).await; |
| 439 | rep.log("info", "Git data imported").await; |
| 440 | |
| 441 | let (Some(api), true) = (api, spec.options.any_api()) else { |
| 442 | return Ok("Import finished".to_owned()); |
| 443 | }; |
| 444 | let run = Run { |
| 445 | state, |
| 446 | rep, |
| 447 | repo: &repo, |
| 448 | user: &user, |
| 449 | api, |
| 450 | spec, |
| 451 | }; |
| 452 | let mut totals = Totals::default(); |
| 453 | if spec.options.labels { |
| 454 | run.labels(&mut totals).await?; |
| 455 | run.milestones(&mut totals).await?; |
| 456 | } |
| 457 | if spec.options.issues || spec.options.pulls { |
| 458 | run.issues(&mut totals).await?; |
| 459 | } |
| 460 | if spec.options.releases { |
| 461 | run.releases(&mut totals).await?; |
| 462 | } |
| 463 | Ok(format!( |
| 464 | "Import finished: {} labels, {} milestones, {} issues, {} pull requests, {} comments, {} releases, {} assets{}", |
| 465 | totals.labels, |
| 466 | totals.milestones, |
| 467 | totals.issues, |
| 468 | totals.pulls, |
| 469 | totals.comments, |
| 470 | totals.releases, |
| 471 | totals.assets, |
| 472 | if totals.skipped > 0 { |
| 473 | format!(", {} skipped", totals.skipped) |
| 474 | } else { |
| 475 | String::new() |
| 476 | } |
| 477 | )) |
| 478 | } |
| 479 | |
| 480 | async fn fetch_git( |
| 481 | state: &AppState, |
| 482 | repo: &Repo, |
| 483 | spec: &JobSpec, |
| 484 | transport: &Transport, |
| 485 | ) -> Result<(), String> { |
| 486 | let repo_dir = |
| 487 | forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; |
| 488 | let url = spec.clone_url(); |
| 489 | let fetch = async { |
| 490 | match transport { |
| 491 | Transport::Net => { |
| 492 | let policy = policy(state); |
| 493 | let pin = check_remote(&url, &policy).await?; |
| 494 | let auth = spec.auth(); |
| 495 | mirror_fetch( |
| 496 | &state.git, |
| 497 | &repo_dir, |
| 498 | &url, |
| 499 | auth.as_ref(), |
| 500 | policy.allow_http, |
| 501 | pin.as_ref(), |
| 502 | GIT_TIMEOUT, |
| 503 | ) |
| 504 | .await |
| 505 | .map_err(|e| e.to_string()) |
| 506 | } |
| 507 | #[cfg(any(test, feature = "test-support"))] |
| 508 | Transport::Local(path) => { |
| 509 | forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT) |
| 510 | .await |
| 511 | .map_err(|e| e.to_string()) |
| 512 | } |
| 513 | } |
| 514 | }; |
| 515 | pull_refs(state, repo, fetch).await.map(|_| ()) |
| 516 | } |
| 517 | |
| 518 | |
| 519 | |
| 520 | async fn sync_default_branch(state: &AppState, repo: Repo, rep: &Reporter) -> Repo { |
| 521 | let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) else { |
| 522 | return repo; |
| 523 | }; |
| 524 | let head = forge_git::command::GitCommand::new(&state.git, "symbolic-ref") |
| 525 | .git_dir(&dir) |
| 526 | .arg("--short") |
| 527 | .arg("HEAD") |
| 528 | .output() |
| 529 | .await |
| 530 | .ok() |
| 531 | .map(|out| String::from_utf8_lossy(&out).trim().to_owned()) |
| 532 | .filter(|b| !b.is_empty()); |
| 533 | let Some(head) = head else { |
| 534 | return repo; |
| 535 | }; |
| 536 | if head == repo.default_branch { |
| 537 | return repo; |
| 538 | } |
| 539 | if let Err(e) = state |
| 540 | .store |
| 541 | .update_repo_general(&repo.id, &repo.description, &head) |
| 542 | .await |
| 543 | { |
| 544 | rep.log("warn", format!("could not set the default branch: {e}")) |
| 545 | .await; |
| 546 | return repo; |
| 547 | } |
| 548 | state |
| 549 | .store |
| 550 | .repo_by_id(&repo.id) |
| 551 | .await |
| 552 | .ok() |
| 553 | .flatten() |
| 554 | .unwrap_or(repo) |
| 555 | } |
| 556 | |
| 557 | #[derive(Default)] |
| 558 | struct Totals { |
| 559 | labels: usize, |
| 560 | milestones: usize, |
| 561 | issues: usize, |
| 562 | pulls: usize, |
| 563 | comments: usize, |
| 564 | releases: usize, |
| 565 | assets: usize, |
| 566 | skipped: usize, |
| 567 | } |
| 568 | |
| 569 | fn api_err(e: ApiError) -> String { |
| 570 | e.to_string() |
| 571 | } |
| 572 | |
| 573 | struct Run<'a, A> { |
| 574 | state: &'a AppState, |
| 575 | rep: &'a Reporter, |
| 576 | repo: &'a Repo, |
| 577 | user: &'a User, |
| 578 | api: &'a A, |
| 579 | spec: &'a JobSpec, |
| 580 | } |
| 581 | |
| 582 | impl<A: RemoteApi> Run<'_, A> { |
| 583 | fn store(&self) -> &Store { |
| 584 | &self.state.store |
| 585 | } |
| 586 | |
| 587 | |
| 588 | |
| 589 | fn bump_issues(&self) { |
| 590 | self.state.live.bump_repo_issues(&self.repo.id); |
| 591 | } |
| 592 | |
| 593 | async fn mapped(&self, kind: &str, ext: &str) -> Result<Option<ImportOrigin>, String> { |
| 594 | self.store() |
| 595 | .import_origin(&self.repo.id, kind, ext) |
| 596 | .await |
| 597 | .map_err(|e| e.to_string()) |
| 598 | } |
| 599 | |
| 600 | async fn record(&self, kind: &str, ext: &str, local: &str, author: &str, url: &str) { |
| 601 | let origin = ImportOrigin { |
| 602 | local_id: local.to_owned(), |
| 603 | author: author.to_owned(), |
| 604 | url: url.to_owned(), |
| 605 | }; |
| 606 | if let Err(e) = self |
| 607 | .store() |
| 608 | .record_import_origin(&self.repo.id, kind, ext, &origin) |
| 609 | .await |
| 610 | { |
| 611 | tracing::warn!(error = %e, "import: could not record an id mapping"); |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | async fn labels(&self, totals: &mut Totals) -> Result<(), String> { |
| 616 | self.rep.stage("labels", 0, 0).await; |
| 617 | let labels = self.api.labels(&self.spec.remote).await.map_err(api_err)?; |
| 618 | let total = labels.len(); |
| 619 | for (i, label) in labels.into_iter().enumerate() { |
| 620 | self.rep.stage("labels", i, total).await; |
| 621 | let key = label.name.to_lowercase(); |
| 622 | if self.mapped("label", &key).await?.is_some() { |
| 623 | continue; |
| 624 | } |
| 625 | let description: String = label |
| 626 | .description |
| 627 | .chars() |
| 628 | .take(forge_core::issues::MAX_LABEL_DESCRIPTION) |
| 629 | .collect(); |
| 630 | match self |
| 631 | .store() |
| 632 | .create_label(&self.repo.id, &label.name, &label.color, &description) |
| 633 | .await |
| 634 | { |
| 635 | Ok(created) => { |
| 636 | self.record("label", &key, &created.id, "", "").await; |
| 637 | totals.labels += 1; |
| 638 | } |
| 639 | Err(forge_core::Error::Conflict(_)) => {} |
| 640 | Err(e) => { |
| 641 | totals.skipped += 1; |
| 642 | self.rep |
| 643 | .log("warn", format!("label `{}` skipped: {e}", label.name)) |
| 644 | .await; |
| 645 | } |
| 646 | } |
| 647 | } |
| 648 | self.bump_issues(); |
| 649 | self.rep.log("info", format!("{total} labels read")).await; |
| 650 | Ok(()) |
| 651 | } |
| 652 | |
| 653 | async fn milestones(&self, totals: &mut Totals) -> Result<(), String> { |
| 654 | self.rep.stage("milestones", 0, 0).await; |
| 655 | let items = self |
| 656 | .api |
| 657 | .milestones(&self.spec.remote) |
| 658 | .await |
| 659 | .map_err(api_err)?; |
| 660 | let total = items.len(); |
| 661 | for (i, m) in items.into_iter().enumerate() { |
| 662 | self.rep.stage("milestones", i, total).await; |
| 663 | if self.mapped("milestone", &m.id).await?.is_some() { |
| 664 | continue; |
| 665 | } |
| 666 | let created = match self |
| 667 | .store() |
| 668 | .create_milestone(&self.repo.id, &m.title, &m.description, m.due_on.as_deref()) |
| 669 | .await |
| 670 | { |
| 671 | Ok(created) => created, |
| 672 | Err(e) => { |
| 673 | totals.skipped += 1; |
| 674 | self.rep |
| 675 | .log("warn", format!("milestone `{}` skipped: {e}", m.title)) |
| 676 | .await; |
| 677 | continue; |
| 678 | } |
| 679 | }; |
| 680 | if m.closed |
| 681 | && let Err(e) = self |
| 682 | .store() |
| 683 | .update_milestone( |
| 684 | &self.repo.id, |
| 685 | &created.id, |
| 686 | &created.title, |
| 687 | &created.description, |
| 688 | created.due_on.as_deref(), |
| 689 | IssueState::Closed, |
| 690 | ) |
| 691 | .await |
| 692 | { |
| 693 | self.rep |
| 694 | .log("warn", format!("milestone `{}` stays open: {e}", m.title)) |
| 695 | .await; |
| 696 | } |
| 697 | self.record("milestone", &m.id, &created.id, "", "").await; |
| 698 | totals.milestones += 1; |
| 699 | } |
| 700 | self.bump_issues(); |
| 701 | Ok(()) |
| 702 | } |
| 703 | |
| 704 | |
| 705 | async fn label_id( |
| 706 | &self, |
| 707 | cache: &mut HashMap<String, String>, |
| 708 | name: &str, |
| 709 | color: &str, |
| 710 | ) -> Option<String> { |
| 711 | let key = name.trim().to_lowercase(); |
| 712 | if let Some(id) = cache.get(&key) { |
| 713 | return Some(id.clone()); |
| 714 | } |
| 715 | match self |
| 716 | .store() |
| 717 | .create_label(&self.repo.id, name, color, "") |
| 718 | .await |
| 719 | { |
| 720 | Ok(label) => { |
| 721 | cache.insert(key, label.id.clone()); |
| 722 | Some(label.id) |
| 723 | } |
| 724 | Err(_) => None, |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | async fn issues(&self, totals: &mut Totals) -> Result<(), String> { |
| 729 | self.rep.stage("issues", 0, 0).await; |
| 730 | let mut items: Vec<ExtIssue> = self |
| 731 | .api |
| 732 | .issues(&self.spec.remote) |
| 733 | .await |
| 734 | .map_err(api_err)? |
| 735 | .into_iter() |
| 736 | .filter(|i| { |
| 737 | if i.is_pr { |
| 738 | self.spec.options.pulls |
| 739 | } else { |
| 740 | self.spec.options.issues |
| 741 | } |
| 742 | }) |
| 743 | .collect(); |
| 744 | items.sort_by_key(|i| (i.is_pr, i.number)); |
| 745 | |
| 746 | |
| 747 | if matches!(self.spec.source, Source::GitHub | Source::Forgejo) { |
| 748 | items.sort_by_key(|i| i.number); |
| 749 | } |
| 750 | let total = items.len(); |
| 751 | let mut labels: HashMap<String, String> = self |
| 752 | .store() |
| 753 | .list_labels(&self.repo.id) |
| 754 | .await |
| 755 | .map_err(|e| e.to_string())? |
| 756 | .into_iter() |
| 757 | .map(|l| (l.name.to_lowercase(), l.id)) |
| 758 | .collect(); |
| 759 | let milestones: HashMap<String, String> = self |
| 760 | .store() |
| 761 | .list_milestones(&self.repo.id, None) |
| 762 | .await |
| 763 | .map_err(|e| e.to_string())? |
| 764 | .into_iter() |
| 765 | .map(|m| (m.title.to_lowercase(), m.id)) |
| 766 | .collect(); |
| 767 | self.rep |
| 768 | .log( |
| 769 | "info", |
| 770 | format!("Importing {total} issues and pull requests"), |
| 771 | ) |
| 772 | .await; |
| 773 | let mut created_since_bump = 0usize; |
| 774 | for (i, item) in items.iter().enumerate() { |
| 775 | self.rep.stage("issues", i, total).await; |
| 776 | let kind = if item.is_pr { "pull" } else { "issue" }; |
| 777 | let ext = item.number.to_string(); |
| 778 | let local = match self.mapped(kind, &ext).await? { |
| 779 | Some(o) => o.local_id, |
| 780 | None => match self.create_item(item, &mut labels, &milestones).await { |
| 781 | Ok(id) => { |
| 782 | self.record(kind, &ext, &id, &item.author, &item.url).await; |
| 783 | created_since_bump += 1; |
| 784 | if created_since_bump == IMPORT_BUMP_BATCH { |
| 785 | created_since_bump = 0; |
| 786 | self.bump_issues(); |
| 787 | } |
| 788 | if item.is_pr { |
| 789 | totals.pulls += 1; |
| 790 | } else { |
| 791 | totals.issues += 1; |
| 792 | } |
| 793 | id |
| 794 | } |
| 795 | Err(e) => { |
| 796 | totals.skipped += 1; |
| 797 | self.rep |
| 798 | .log("warn", format!("#{} skipped: {e}", item.number)) |
| 799 | .await; |
| 800 | continue; |
| 801 | } |
| 802 | }, |
| 803 | }; |
| 804 | let comments = self |
| 805 | .api |
| 806 | .comments(&self.spec.remote, item) |
| 807 | .await |
| 808 | .map_err(api_err)?; |
| 809 | for c in comments { |
| 810 | if self |
| 811 | .mapped("comment", &format!("{kind}:{}", c.id)) |
| 812 | .await? |
| 813 | .is_some() |
| 814 | { |
| 815 | continue; |
| 816 | } |
| 817 | let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url); |
| 818 | let body = with_note(¬e, &c.body); |
| 819 | match self.store().add_comment(&local, &self.user.id, &body).await { |
| 820 | Ok(created) => { |
| 821 | self.record( |
| 822 | "comment", |
| 823 | &format!("{kind}:{}", c.id), |
| 824 | &created.id, |
| 825 | &c.author, |
| 826 | &c.url, |
| 827 | ) |
| 828 | .await; |
| 829 | totals.comments += 1; |
| 830 | } |
| 831 | Err(e) => { |
| 832 | totals.skipped += 1; |
| 833 | self.rep |
| 834 | .log( |
| 835 | "warn", |
| 836 | format!("a comment on #{} skipped: {e}", item.number), |
| 837 | ) |
| 838 | .await; |
| 839 | } |
| 840 | } |
| 841 | } |
| 842 | } |
| 843 | self.rep.stage("issues", total, total).await; |
| 844 | self.bump_issues(); |
| 845 | Ok(()) |
| 846 | } |
| 847 | |
| 848 | |
| 849 | async fn create_item( |
| 850 | &self, |
| 851 | item: &ExtIssue, |
| 852 | labels: &mut HashMap<String, String>, |
| 853 | milestones: &HashMap<String, String>, |
| 854 | ) -> Result<String, forge_core::Error> { |
| 855 | let source = self.spec.source.label(); |
| 856 | let mut note = origin_note(source, &item.author, &item.created_at, &item.url); |
| 857 | if item.is_pr { |
| 858 | let how = if item.merged { |
| 859 | "merged" |
| 860 | } else if item.closed { |
| 861 | "closed" |
| 862 | } else { |
| 863 | "open" |
| 864 | }; |
| 865 | note.push_str(&format!( |
| 866 | "> Imported pull request ({how}). Its branches may no longer exist, so there is nothing to merge here.\n\n" |
| 867 | )); |
| 868 | } |
| 869 | let body = with_note(¬e, &item.body); |
| 870 | let issue = self |
| 871 | .store() |
| 872 | .create_issue( |
| 873 | &self.repo.id, |
| 874 | &self.user.id, |
| 875 | &clip_title(&item.title), |
| 876 | &body, |
| 877 | ) |
| 878 | .await?; |
| 879 | let mut ids = Vec::new(); |
| 880 | for name in &item.labels { |
| 881 | if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await { |
| 882 | ids.push(id); |
| 883 | } |
| 884 | } |
| 885 | if item.is_pr |
| 886 | && let Some(id) = self |
| 887 | .label_id(labels, IMPORTED_PR_LABEL, IMPORTED_PR_COLOR) |
| 888 | .await |
| 889 | { |
| 890 | ids.push(id); |
| 891 | } |
| 892 | ids.dedup(); |
| 893 | if !ids.is_empty() { |
| 894 | self.store() |
| 895 | .set_issue_labels(&issue.id, &self.user.id, &ids) |
| 896 | .await?; |
| 897 | } |
| 898 | if let Some(id) = item |
| 899 | .milestone |
| 900 | .as_ref() |
| 901 | .and_then(|t| milestones.get(&t.to_lowercase())) |
| 902 | { |
| 903 | self.store() |
| 904 | .set_issue_milestone(&issue.id, &self.user.id, Some(id)) |
| 905 | .await?; |
| 906 | } |
| 907 | if item.closed { |
| 908 | let reason = if item.not_planned { |
| 909 | StateReason::NotPlanned |
| 910 | } else { |
| 911 | StateReason::Completed |
| 912 | }; |
| 913 | self.store() |
| 914 | .set_issue_state( |
| 915 | &issue.id, |
| 916 | Some(&self.user.id), |
| 917 | IssueState::Closed, |
| 918 | Some(reason), |
| 919 | serde_json::Value::Null, |
| 920 | ) |
| 921 | .await?; |
| 922 | } |
| 923 | Ok(issue.id) |
| 924 | } |
| 925 | |
| 926 | async fn releases(&self, totals: &mut Totals) -> Result<(), String> { |
| 927 | self.rep.stage("releases", 0, 0).await; |
| 928 | let releases = self |
| 929 | .api |
| 930 | .releases(&self.spec.remote) |
| 931 | .await |
| 932 | .map_err(api_err)?; |
| 933 | let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id) |
| 934 | .map_err(|e| e.to_string())?; |
| 935 | let refs = ref_snapshot(self.state, &repo_dir).await?; |
| 936 | let max_bytes = self.state.live().releases.max_asset_mb * 1024 * 1024; |
| 937 | let total = releases.len(); |
| 938 | for (i, rel) in releases.iter().enumerate() { |
| 939 | self.rep.stage("releases", i, total).await; |
| 940 | let Some(release) = self.release_of(rel, &refs, totals).await? else { |
| 941 | continue; |
| 942 | }; |
| 943 | for asset in &rel.assets { |
| 944 | self.asset(&release, rel, asset, max_bytes, totals).await?; |
| 945 | } |
| 946 | } |
| 947 | self.rep.stage("releases", total, total).await; |
| 948 | Ok(()) |
| 949 | } |
| 950 | |
| 951 | |
| 952 | |
| 953 | async fn release_of( |
| 954 | &self, |
| 955 | rel: &ExtRelease, |
| 956 | refs: &std::collections::BTreeMap<String, String>, |
| 957 | totals: &mut Totals, |
| 958 | ) -> Result<Option<forge_core::releases::Release>, String> { |
| 959 | if let Some(o) = self.mapped("release", &rel.id).await? { |
| 960 | return self |
| 961 | .store() |
| 962 | .release(&o.local_id) |
| 963 | .await |
| 964 | .map_err(|e| e.to_string()); |
| 965 | } |
| 966 | let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else { |
| 967 | totals.skipped += 1; |
| 968 | self.rep |
| 969 | .log( |
| 970 | "warn", |
| 971 | format!( |
| 972 | "release `{}` skipped: its tag is not in the git data", |
| 973 | rel.tag |
| 974 | ), |
| 975 | ) |
| 976 | .await; |
| 977 | return Ok(None); |
| 978 | }; |
| 979 | if let Some(existing) = self |
| 980 | .store() |
| 981 | .release_by_tag(&self.repo.id, &rel.tag) |
| 982 | .await |
| 983 | .map_err(|e| e.to_string())? |
| 984 | { |
| 985 | self.record("release", &rel.id, &existing.id, &rel.author, &rel.url) |
| 986 | .await; |
| 987 | return Ok(Some(existing)); |
| 988 | } |
| 989 | let note = origin_note( |
| 990 | self.spec.source.label(), |
| 991 | &rel.author, |
| 992 | &rel.created_at, |
| 993 | &rel.url, |
| 994 | ); |
| 995 | let body = with_note(¬e, &rel.body); |
| 996 | let title = clip_title(&rel.title); |
| 997 | let created = self |
| 998 | .store() |
| 999 | .create_release(&NewRelease { |
| 1000 | repo_id: &self.repo.id, |
| 1001 | tag: &rel.tag, |
| 1002 | target_oid: oid, |
| 1003 | title: &title, |
| 1004 | body: &body, |
| 1005 | draft: rel.draft, |
| 1006 | prerelease: rel.prerelease, |
| 1007 | author_id: &self.user.id, |
| 1008 | }) |
| 1009 | .await; |
| 1010 | match created { |
| 1011 | Ok(release) => { |
| 1012 | self.record("release", &rel.id, &release.id, &rel.author, &rel.url) |
| 1013 | .await; |
| 1014 | totals.releases += 1; |
| 1015 | Ok(Some(release)) |
| 1016 | } |
| 1017 | Err(e) => { |
| 1018 | totals.skipped += 1; |
| 1019 | self.rep |
| 1020 | .log("warn", format!("release `{}` skipped: {e}", rel.tag)) |
| 1021 | .await; |
| 1022 | Ok(None) |
| 1023 | } |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | async fn asset( |
| 1028 | &self, |
| 1029 | release: &forge_core::releases::Release, |
| 1030 | rel: &ExtRelease, |
| 1031 | asset: &ExtAsset, |
| 1032 | max_bytes: u64, |
| 1033 | totals: &mut Totals, |
| 1034 | ) -> Result<(), String> { |
| 1035 | let ext = format!("{}:{}", rel.id, asset.id); |
| 1036 | if self.mapped("asset", &ext).await?.is_some() { |
| 1037 | return Ok(()); |
| 1038 | } |
| 1039 | if asset.size > max_bytes { |
| 1040 | totals.skipped += 1; |
| 1041 | self.rep |
| 1042 | .log( |
| 1043 | "warn", |
| 1044 | format!( |
| 1045 | "asset `{}` skipped: larger than the upload limit", |
| 1046 | asset.name |
| 1047 | ), |
| 1048 | ) |
| 1049 | .await; |
| 1050 | return Ok(()); |
| 1051 | } |
| 1052 | self.rep |
| 1053 | .log("info", format!("Downloading asset {}", asset.name)) |
| 1054 | .await; |
| 1055 | let stream = match self.api.download(asset, max_bytes).await { |
| 1056 | Ok(stream) => stream, |
| 1057 | Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => { |
| 1058 | return Err(e.to_string()); |
| 1059 | } |
| 1060 | Err(e) => { |
| 1061 | totals.skipped += 1; |
| 1062 | self.rep |
| 1063 | .log("warn", format!("asset `{}` skipped: {e}", asset.name)) |
| 1064 | .await; |
| 1065 | return Ok(()); |
| 1066 | } |
| 1067 | }; |
| 1068 | let name = asset_name(&asset.name); |
| 1069 | let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str()); |
| 1070 | match crate::release_ops::put_asset( |
| 1071 | self.state, |
| 1072 | self.repo, |
| 1073 | release, |
| 1074 | self.user, |
| 1075 | &name, |
| 1076 | content_type, |
| 1077 | stream, |
| 1078 | max_bytes, |
| 1079 | ) |
| 1080 | .await |
| 1081 | { |
| 1082 | Ok((stored, _)) => { |
| 1083 | self.record("asset", &ext, &stored.id, &rel.author, &asset.url) |
| 1084 | .await; |
| 1085 | totals.assets += 1; |
| 1086 | } |
| 1087 | Err(e) => { |
| 1088 | totals.skipped += 1; |
| 1089 | self.rep |
| 1090 | .log( |
| 1091 | "warn", |
| 1092 | format!("asset `{}` skipped: {}", asset.name, e.message()), |
| 1093 | ) |
| 1094 | .await; |
| 1095 | } |
| 1096 | } |
| 1097 | Ok(()) |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | |
| 1102 | pub async fn on_boot(state: &AppState) { |
| 1103 | match state.store.fail_interrupted_imports().await { |
| 1104 | Ok(0) => {} |
| 1105 | Ok(n) => tracing::warn!(count = n, "import: marked interrupted jobs as failed"), |
| 1106 | Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"), |
| 1107 | } |
| 1108 | } |