diff --git a/Cargo.lock b/Cargo.lock index 83ae480..0a8adb3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2025,7 +2025,6 @@ dependencies = [ "tempfile", "tokio", "tokio-util", - "zip", ] [[package]] @@ -2117,14 +2116,12 @@ dependencies = [ "reqwest", "rpassword", "serde_json", - "tar", "tempfile", "time", "tokio", "topcoat", "tracing", "tracing-subscriber", - "zip", ] [[package]] @@ -2168,7 +2165,6 @@ dependencies = [ "async-compression", "base64 0.23.1", "bytes", - "flate2", "forge-ci", "forge-core", "forge-git", @@ -2192,7 +2188,6 @@ dependencies = [ "serde_json", "sha2 0.11.1", "similar", - "tar", "tempfile", "time", "tokio", @@ -2252,7 +2247,6 @@ dependencies = [ "serde", "serde_json", "similar", - "tar", "tempfile", "time", "tokio", @@ -2286,7 +2280,6 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", - "tar", "tempfile", "time", "tokio", diff --git a/crates/forge-core/src/store/exports.rs b/crates/forge-core/src/store/exports.rs deleted file mode 100644 index d3fe7a5..0000000 --- a/crates/forge-core/src/store/exports.rs +++ /dev/null @@ -1,150 +0,0 @@ -use std::time::Duration; - -use turso::{Row, Value}; - -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; -use crate::error::Result; -use crate::time::{now_stamp, stamp_after}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ExportState { - Building, - Ready, - Failed, -} - -string_enum!(ExportState { - Building = "building", - Ready = "ready", - Failed = "failed", -}); - -#[derive(Debug, Clone, PartialEq)] -pub struct DataExport { - pub id: String, - pub user_id: String, - pub state: ExportState, - pub size: i64, - pub error: Option, - pub created_at: String, - pub ready_at: Option, - pub expires_at: String, -} - -const COLS: &str = "id, user_id, state, size, error, created_at, ready_at, expires_at"; - -fn map_export(row: &Row) -> Result { - Ok(DataExport { - id: col_text(row, 0)?, - user_id: col_text(row, 1)?, - state: col_text(row, 2)? - .parse::() - .unwrap_or(ExportState::Building), - size: col_int(row, 3)?, - error: col_opt_text(row, 4)?, - created_at: col_text(row, 5)?, - ready_at: col_opt_text(row, 6)?, - expires_at: col_text(row, 7)?, - }) -} - -impl Store { - pub async fn create_export(&self, user_id: &str, ttl: Duration) -> Result { - let id = new_id(); - let now = now_stamp(); - let expires = stamp_after(ttl); - { - let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO data_exports (id, user_id, created_at, expires_at) \ - VALUES (?1, ?2, ?3, ?4)", - (id.clone(), user_id.to_owned(), now, expires), - ) - .await - .map_err(db_err)?; - } - self.data_export(&id).await?.ok_or_else(super::missing_row) - } - - pub async fn data_export(&self, id: &str) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_opt( - &conn, - &format!("SELECT {COLS} FROM data_exports WHERE id = ?1"), - (id.to_owned(),), - map_export, - ) - .await - } - - pub async fn list_exports(&self, user_id: &str) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_all( - &conn, - &format!( - "SELECT {COLS} FROM data_exports WHERE user_id = ?1 ORDER BY created_at DESC, id DESC" - ), - (user_id.to_owned(),), - map_export, - ) - .await - } - - pub async fn mark_export_ready(&self, id: &str, size: i64, ttl: Duration) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE data_exports SET state = 'ready', size = ?2, ready_at = ?3, expires_at = ?4 \ - WHERE id = ?1", - vec![ - Value::Text(id.to_owned()), - Value::Integer(size), - Value::Text(now_stamp()), - Value::Text(stamp_after(ttl)), - ], - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn mark_export_failed(&self, id: &str, error: &str) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE data_exports SET state = 'failed', error = ?2 WHERE id = ?1", - (id.to_owned(), error.to_owned()), - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn expired_exports(&self, now: &str) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_all( - &conn, - &format!("SELECT {COLS} FROM data_exports WHERE expires_at <= ?1"), - (now.to_owned(),), - map_export, - ) - .await - } - - pub async fn delete_export(&self, id: &str) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute("DELETE FROM data_exports WHERE id = ?1", (id.to_owned(),)) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn fail_interrupted_exports(&self) -> Result { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE data_exports SET state = 'failed', error = 'interrupted by a server restart' \ - WHERE state = 'building'", - (), - ) - .await - .map_err(db_err) - } -} diff --git a/crates/forge-core/src/store/imports.rs b/crates/forge-core/src/store/imports.rs deleted file mode 100644 index 57599fa..0000000 --- a/crates/forge-core/src/store/imports.rs +++ /dev/null @@ -1,340 +0,0 @@ -use turso::{Row, Value}; - -use super::issues::parse_db; -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text}; -use crate::error::Result; -use crate::time::now_stamp; - -pub const MAX_EVENTS: i64 = 500; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ImportState { - Queued, - Running, - Done, - Failed, -} - -string_enum!(ImportState { - Queued = "queued", - Running = "running", - Done = "done", - Failed = "failed", -}); - -impl ImportState { - pub fn is_finished(self) -> bool { - matches!(self, ImportState::Done | ImportState::Failed) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ImportJob { - pub id: String, - pub user_id: String, - pub repo_id: Option, - pub source: String, - pub source_ref: String, - pub options: String, - pub state: ImportState, - pub stage: String, - pub done: i64, - pub total: i64, - pub error: Option, - pub created_at: String, - pub updated_at: String, - pub finished_at: Option, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ImportEvent { - pub seq: i64, - pub level: String, - pub message: String, - pub created_at: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct ImportOrigin { - pub local_id: String, - pub author: String, - pub url: String, -} - -const JOB_COLS: &str = "id, user_id, repo_id, source, source_ref, options, state, stage, done, \ - total, error, created_at, updated_at, finished_at"; - -fn map_job(row: &Row) -> Result { - Ok(ImportJob { - id: col_text(row, 0)?, - user_id: col_text(row, 1)?, - repo_id: col_opt_text(row, 2)?, - source: col_text(row, 3)?, - source_ref: col_text(row, 4)?, - options: col_text(row, 5)?, - state: parse_db(&col_text(row, 6)?)?, - stage: col_text(row, 7)?, - done: col_int(row, 8)?, - total: col_int(row, 9)?, - error: col_opt_text(row, 10)?, - created_at: col_text(row, 11)?, - updated_at: col_text(row, 12)?, - finished_at: col_opt_text(row, 13)?, - }) -} - -impl Store { - pub async fn create_import_job( - &self, - user_id: &str, - repo_id: &str, - source: &str, - source_ref: &str, - options: &str, - ) -> Result { - let id = new_id(); - let now = now_stamp(); - { - let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO import_jobs (id, user_id, repo_id, source, source_ref, options, \ - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)", - vec![ - text(&id), - text(user_id), - text(repo_id), - text(source), - text(source_ref), - text(options), - text(&now), - ], - ) - .await - .map_err(db_err)?; - } - self.import_job(&id).await?.ok_or_else(super::missing_row) - } - - pub async fn import_job(&self, id: &str) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_opt( - &conn, - &format!("SELECT {JOB_COLS} FROM import_jobs WHERE id = ?1"), - (id.to_owned(),), - map_job, - ) - .await - } - - pub async fn list_import_jobs(&self, user_id: &str, limit: u32) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_all( - &conn, - &format!( - "SELECT {JOB_COLS} FROM import_jobs WHERE user_id = ?1 \ - ORDER BY created_at DESC, id DESC LIMIT ?2" - ), - (user_id.to_owned(), i64::from(limit.clamp(1, 200))), - map_job, - ) - .await - } - - pub async fn active_import_for_repo(&self, repo_id: &str) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_opt( - &conn, - &format!( - "SELECT {JOB_COLS} FROM import_jobs WHERE repo_id = ?1 \ - AND state IN ('queued', 'running') LIMIT 1" - ), - (repo_id.to_owned(),), - map_job, - ) - .await - } - - pub async fn set_import_state( - &self, - id: &str, - state: ImportState, - error: Option<&str>, - ) -> Result<()> { - let now = now_stamp(); - let finished = if state.is_finished() { - text(&now) - } else { - Value::Null - }; - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \ - WHERE id = ?1", - vec![ - text(id), - text(state.as_str()), - error.map_or(Value::Null, text), - text(&now), - finished, - ], - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn requeue_failed_import(&self, id: &str) -> Result { - let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE import_jobs SET state = 'queued', error = NULL, finished_at = NULL, \ - updated_at = ?2 WHERE id = ?1 AND state = 'failed' AND NOT EXISTS (\ - SELECT 1 FROM import_jobs other WHERE other.repo_id = \ - (SELECT repo_id FROM import_jobs WHERE id = ?1) \ - AND other.state IN ('queued', 'running'))", - vec![text(id), text(&now_stamp())], - ) - .await - .map_err(db_err)?; - Ok(changed > 0) - } - - pub async fn set_import_progress( - &self, - id: &str, - stage: &str, - done: i64, - total: i64, - ) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE import_jobs SET stage = ?2, done = ?3, total = ?4, updated_at = ?5 WHERE id = ?1", - vec![ - text(id), - text(stage), - Value::Integer(done), - Value::Integer(total), - text(&now_stamp()), - ], - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn add_import_event(&self, job_id: &str, level: &str, message: &str) -> Result<()> { - let conn = self.inner.conn.lock().await; - let next = fetch_opt( - &conn, - "SELECT COALESCE(MAX(seq), 0) + 1 FROM import_events WHERE job_id = ?1", - (job_id.to_owned(),), - |row| col_int(row, 0), - ) - .await? - .unwrap_or(1); - conn.execute( - "INSERT INTO import_events (job_id, seq, level, message, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5)", - vec![ - text(job_id), - Value::Integer(next), - text(level), - text(message), - text(&now_stamp()), - ], - ) - .await - .map_err(db_err)?; - conn.execute( - "DELETE FROM import_events WHERE job_id = ?1 AND seq <= ?2", - (job_id.to_owned(), next - MAX_EVENTS), - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn list_import_events(&self, job_id: &str, limit: u32) -> Result> { - let conn = self.inner.conn.lock().await; - let mut rows = fetch_all( - &conn, - "SELECT seq, level, message, created_at FROM import_events WHERE job_id = ?1 \ - ORDER BY seq DESC LIMIT ?2", - (job_id.to_owned(), i64::from(limit.clamp(1, 500))), - |row| { - Ok(ImportEvent { - seq: col_int(row, 0)?, - level: col_text(row, 1)?, - message: col_text(row, 2)?, - created_at: col_text(row, 3)?, - }) - }, - ) - .await?; - rows.reverse(); - Ok(rows) - } - - pub async fn import_origin( - &self, - repo_id: &str, - kind: &str, - ext_id: &str, - ) -> Result> { - let conn = self.inner.conn.lock().await; - fetch_opt( - &conn, - "SELECT local_id, orig_author, orig_url FROM import_map \ - WHERE repo_id = ?1 AND kind = ?2 AND ext_id = ?3", - (repo_id.to_owned(), kind.to_owned(), ext_id.to_owned()), - |row| { - Ok(ImportOrigin { - local_id: col_text(row, 0)?, - author: col_text(row, 1)?, - url: col_text(row, 2)?, - }) - }, - ) - .await - } - - pub async fn record_import_origin( - &self, - repo_id: &str, - kind: &str, - ext_id: &str, - origin: &ImportOrigin, - ) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "INSERT INTO import_map (repo_id, kind, ext_id, local_id, orig_author, orig_url) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(repo_id, kind, ext_id) DO UPDATE SET \ - local_id = excluded.local_id, orig_author = excluded.orig_author, \ - orig_url = excluded.orig_url", - vec![ - text(repo_id), - text(kind), - text(ext_id), - text(&origin.local_id), - text(&origin.author), - text(&origin.url), - ], - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn fail_interrupted_imports(&self) -> Result { - let now = now_stamp(); - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE import_jobs SET state = 'failed', updated_at = ?1, finished_at = ?1, \ - error = 'interrupted by a server restart, retry to continue' \ - WHERE state IN ('queued', 'running')", - (now,), - ) - .await - .map_err(db_err) - } -} diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index c401290..bc21208 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -7,9 +7,7 @@ pub mod ci; pub mod commit_status; pub mod contributions; pub mod edit_history_read; -pub mod exports; pub mod health; -pub mod imports; pub mod issues; pub mod labels; pub mod lfs; diff --git a/crates/forge-e2e/Cargo.toml b/crates/forge-e2e/Cargo.toml index 8e7a3c6..aa66b80 100644 --- a/crates/forge-e2e/Cargo.toml +++ b/crates/forge-e2e/Cargo.toml @@ -19,7 +19,6 @@ tokio.workspace = true tokio-util = { workspace = true, features = ["io"] } reqwest.workspace = true serde_json.workspace = true -zip = { workspace = true } tempfile.workspace = true scraper = { workspace = true } diff --git a/crates/forge-e2e/tests/e2e/section_nav_e2e.rs b/crates/forge-e2e/tests/e2e/section_nav_e2e.rs index 0d88190..21f210a 100644 --- a/crates/forge-e2e/tests/e2e/section_nav_e2e.rs +++ b/crates/forge-e2e/tests/e2e/section_nav_e2e.rs @@ -90,7 +90,6 @@ async fn settings_pages_get_the_settings_tabs() { "/settings/notifications", "/settings/security", "/settings/keys", - "/settings/export", ]; let pages = [ ("/settings/profile", "/settings/profile"), diff --git a/crates/forge-web-account/src/lib.rs b/crates/forge-web-account/src/lib.rs index 675be88..65ccf62 100644 --- a/crates/forge-web-account/src/lib.rs +++ b/crates/forge-web-account/src/lib.rs @@ -3,8 +3,8 @@ #[cfg(test)] pub(crate) use forge_web_app::test_support; pub(crate) use forge_web_app::{ - accent, alerts, api, audit, auth, backup, client_ip, custom_colour, exporter, i18n, importer, - live, mail, mirrors, render, self_update, signatures, state, theme, throttle, views, webhooks, + accent, alerts, api, audit, auth, backup, client_ip, custom_colour, i18n, live, mail, render, + self_update, signatures, state, theme, throttle, views, }; #[cfg(test)] pub(crate) use forge_web_app::{blobs, release_ops, replication}; diff --git a/crates/forge-web-account/src/pages/home.rs b/crates/forge-web-account/src/pages/home.rs index 8562f9f..f861fa7 100644 --- a/crates/forge-web-account/src/pages/home.rs +++ b/crates/forge-web-account/src/pages/home.rs @@ -9,7 +9,6 @@ use topcoat::view::{View, component, view}; use crate::auth::current_user; use crate::i18n::authoring::{self as ga}; -use crate::i18n::migrate::{self as mg, K as MGK}; use crate::i18n::needs::{self as ni, K as NK}; use crate::i18n::orgs::{self as g, K}; use crate::i18n::s; @@ -192,11 +191,9 @@ async fn signed_home(cx: &Cx, lang: Lang, data: SignedHome, may_org: bool) -> Re let repos_heading = s(lang, "Your repositories", "Depolarınız"); let all = s(lang, "View all", "Tümünü gör"); let no_repos = s(lang, "You have no repositories yet.", "Henüz deponuz yok."); - let import_label = mg::t(lang, MGK::TabImport); Ok(view! { head(title: g::t(lang, K::Home), (g::t(lang, K::NewRepository)) - (import_label) if may_org { (g::t(lang, K::NewOrganization)) } diff --git a/crates/forge-web-account/src/pages/import.rs b/crates/forge-web-account/src/pages/import.rs deleted file mode 100644 index b346ca0..0000000 --- a/crates/forge-web-account/src/pages/import.rs +++ /dev/null @@ -1,1420 +0,0 @@ -use std::collections::HashMap; - -use forge_core::store::imports::{ImportJob, ImportState}; -use forge_core::{AuditAction, Repo, User, Visibility}; -use forge_git::repo::{init_bare, repo_path}; -use futures_util::stream; -use serde::Deserialize; -use topcoat::Result; -use topcoat::context::{Cx, context}; -use topcoat::router::content::Form; -use topcoat::router::error::{SeeOther, not_found, see_other}; -use topcoat::router::response::Response; -use topcoat::router::{page, path_param, query_params, route}; -use topcoat::view::{View, component, view}; - -use crate::audit::{self, Actor, Target}; -use crate::auth::{require_csrf, require_user}; -use crate::i18n::migrate::{self as g, K}; -use crate::i18n::{self, Lang}; -use crate::importer::api::{ApiError, ExtRepo, RemoteApi}; -use crate::importer::{ - self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, - parse_remote, source_ref, -}; -use crate::live::{Topic, stream_changes}; -use crate::live::{changed_event, events_response}; -use crate::pages::new_repo::{owner_choices, repo_owner}; -use crate::pages::repo_ctx::still_readable; -use crate::state::AppState; -use crate::views::paging::{paginate, requested_page}; -use crate::views::parts::{SubPart, head}; -use crate::views::repo_list::{PageLink, pager, pager_links}; -use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message}; - -path_param!(job_id); - -const MAX_BULK: usize = 50; -const DEFAULT_BRANCH: &str = "main"; - -#[derive(Deserialize, Default)] -struct ImportForm { - #[serde(default)] - csrf: String, - #[serde(default)] - source: String, - #[serde(default)] - remote: String, - #[serde(default)] - instance: String, - #[serde(default)] - token: String, - #[serde(default)] - git_user: String, - #[serde(default)] - owner: String, - #[serde(default)] - name: String, - #[serde(default)] - description: String, - #[serde(default)] - visibility: String, - #[serde(default)] - opt_labels: String, - #[serde(default)] - opt_issues: String, - #[serde(default)] - opt_pulls: String, - #[serde(default)] - opt_releases: String, -} - -#[derive(Deserialize, Default)] -struct BulkForm { - #[serde(default)] - csrf: String, - #[serde(default)] - stage: String, - #[serde(default)] - source: String, - #[serde(default)] - instance: String, - #[serde(default)] - token: String, - #[serde(default)] - from: String, - #[serde(default)] - owner: String, - #[serde(default)] - visibility: String, - #[serde(default)] - opt_labels: String, - #[serde(default)] - opt_issues: String, - #[serde(default)] - opt_pulls: String, - #[serde(default)] - opt_releases: String, - #[serde(flatten)] - extra: HashMap, -} - -#[query_params(error = bad_request)] -struct SourceQuery { - source: Option, - error: Option, -} - -#[query_params(error = bad_request)] -struct JobsQuery { - skipped: Option, - page: Option, -} - -#[query_params(error = bad_request)] -struct SeenQuery { - v: Option, -} - -fn options_of(labels: &str, issues: &str, pulls: &str, releases: &str) -> ImportOptions { - ImportOptions { - labels: !labels.is_empty(), - issues: !issues.is_empty(), - pulls: !pulls.is_empty(), - releases: !releases.is_empty(), - } -} - -fn source_of(raw: Option<&str>) -> Source { - raw.and_then(Source::parse).unwrap_or(Source::GitHub) -} - -fn default_instance(source: Source) -> &'static str { - match source { - Source::Forgejo => "https://codeberg.org", - _ => "https://gitlab.com", - } -} - -fn has_instance(source: Source) -> bool { - matches!(source, Source::GitLab | Source::Forgejo) -} - -fn instance_label(lang: Lang, source: Source) -> &'static str { - if source == Source::Forgejo { - g::t(lang, K::ForgejoInstance) - } else { - g::t(lang, K::GitLabInstance) - } -} - -fn token_of(raw: &str) -> Option { - let t = raw.trim(); - (!t.is_empty()).then(|| t.to_owned()) -} - -#[component] -pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result { - let create = active == "create"; - let import = active == "import"; - let history = active == "history"; - Ok(view! { - - }) -} - -#[component] -async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result { - let git = format!("{base}?source=git"); - let github = format!("{base}?source=github"); - let gitlab = format!("{base}?source=gitlab"); - let forgejo = format!("{base}?source=forgejo"); - Ok(view! { - - }) -} - -#[component] -pub(crate) async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result { - Ok(view! { -
- (crate::i18n::misc::t(lang, crate::i18n::misc::K::VisibilityLegend)) -
- - -
-
- }) -} - -#[component] -async fn option_boxes(cx: &Cx, lang: Lang, opts: ImportOptions) -> Result { - Ok(view! { -
- (g::t(lang, K::WhatToImport)) -
- - - - -
-
- }) -} - -struct Draft { - source: Source, - remote: String, - instance: String, - git_user: String, - owner: String, - name: String, - description: String, - private: bool, - opts: ImportOptions, -} - -impl Draft { - fn fresh(source: Source) -> Self { - Draft { - source, - remote: String::new(), - instance: default_instance(source).into(), - git_user: String::new(), - owner: String::new(), - name: String::new(), - description: String::new(), - private: false, - opts: ImportOptions { - labels: true, - issues: true, - pulls: true, - releases: true, - }, - } - } - - fn from_form(form: &ImportForm, source: Source) -> Self { - Draft { - source, - remote: form.remote.trim().to_owned(), - instance: form.instance.trim().to_owned(), - git_user: form.git_user.trim().to_owned(), - owner: form.owner.trim().to_owned(), - name: form.name.trim().to_owned(), - description: form.description.clone(), - private: form.visibility != "public", - opts: options_of( - &form.opt_labels, - &form.opt_issues, - &form.opt_pulls, - &form.opt_releases, - ), - } - } -} - -#[component] -async fn import_form( - cx: &Cx, - lang: Lang, - username: String, - csrf: &str, - draft: Draft, - error: Option, - owners: Vec, -) -> Result { - let source = draft.source; - let selected_owner = if draft.owner.is_empty() { - owners.first().cloned().unwrap_or_default() - } else { - draft.owner.clone() - }; - let source_value = source.as_str(); - let is_git = source == Source::Git; - let has_instance = has_instance(source); - let instance_label = instance_label(lang, source); - let bulk_href = if is_git { - String::new() - } else { - format!("/new/import/bulk?source={source_value}") - }; - let remote_label = match source { - Source::Git => g::t(lang, K::GitUrl), - Source::GitHub | Source::Forgejo => g::t(lang, K::GitHubRepo), - Source::GitLab => g::t(lang, K::GitLabProject), - }; - let remote_placeholder = match source { - Source::Git => "https://example.org/tahinli/project.git", - Source::GitHub => "tahinli/project", - Source::GitLab | Source::Forgejo => "tahinli/project", - }; - let token_label = if is_git { - g::t(lang, K::GitPassword) - } else { - g::t(lang, K::TokenOptional) - }; - let private = draft.private; - let opts = draft.opts; - Ok(view! { - head(title: g::t(lang, K::ImportTitle)) - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - newrepo_tabs(lang: lang, active: "import") -
-
- if let Some(message) = error { - alert(message: message.as_str()) - } - csrf_field(token: csrf) - - source_tabs(lang: lang, base: "/new/import", active: source) - if has_instance { -
- - -
- } -
- - -
- if is_git { -
- - -
- } -
- - -
- if !is_git { - option_boxes(lang: lang, opts: opts) - } -
- - -
-
- - -
-
- - -
- visibility_pick(lang: lang, private: private) - -
- if !is_git { -
-

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

- -
- } -
- }) -} - -#[component] -async fn import_home( - cx: &Cx, - lang: Lang, - username: String, - csrf: String, - draft: Draft, - owners: Vec, -) -> Result { - Ok(view! { - import_form(lang: lang, username: username, csrf: csrf.as_str(), draft: draft, error: None, owners: owners) - }) -} - -#[component] -async fn import_error_body( - cx: &Cx, - lang: Lang, - username: String, - csrf: String, - draft: Draft, - error: String, - owners: Vec, -) -> Result { - Ok(view! { - import_form(lang: lang, username: username, csrf: csrf.as_str(), draft: draft, error: Some(error), owners: owners) - }) -} - -#[page("/new/import")] -async fn import_page(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let query = query_params::(cx)?; - let source = source_of(query.source.as_deref()); - let state = context::(cx); - let owners = owner_choices(state, &viewer.0).await?; - let csrf = viewer.1.csrf_token.clone(); - Ok(view! { - shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), - import_home(lang: lang, username: viewer.0.username.clone(), csrf: csrf, draft: Draft::fresh(source), owners: owners)) - }) -} - -#[page(POST "/new/import")] -async fn import_submit(cx: &Cx, Form(form): Form) -> Result { - let viewer = require_csrf(cx, &form.csrf).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let source = source_of(Some(&form.source)); - match start_single(cx, &viewer.0, lang, source, &form).await? { - Ok(job_id) => Err(see_other(format!("/import/{job_id}")).into()), - Err(message) => { - let owners = owner_choices(context::(cx), &viewer.0).await?; - let csrf = viewer.1.csrf_token.clone(); - let draft = Draft::from_form(&form, source); - Ok(view! { - shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), - import_error_body(lang: lang, username: viewer.0.username.clone(), csrf: csrf, draft: draft, error: message, owners: owners)) - }) - } - } -} - -async fn start_single( - cx: &Cx, - viewer: &User, - lang: Lang, - source: Source, - form: &ImportForm, -) -> Result> { - let state = context::(cx); - let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else { - let message = if has_instance(source) && form.remote.trim().starts_with("http") { - g::t(lang, K::ErrBadInstance) - } else { - g::t(lang, K::ErrBadRemote) - }; - return Ok(Err(message.to_owned())); - }; - if source == Source::Git - && crate::webhooks::client::validate_url(&remote, &crate::mirrors::policy(state)).is_err() - { - return Ok(Err(g::t(lang, K::ErrBadRemote).to_owned())); - } - let target = match repo_owner(state, viewer, lang, &form.owner).await? { - Ok(target) => target, - Err(message) => return Ok(Err(message)), - }; - let name = match form.name.trim() { - "" => default_name(&remote), - given => given.to_owned(), - }; - let spec = JobSpec { - source, - remote: remote.clone(), - instance: instance.clone(), - token: token_of(&form.token), - git_user: form.git_user.trim().to_owned(), - options: if source == Source::Git { - ImportOptions::default() - } else { - options_of( - &form.opt_labels, - &form.opt_issues, - &form.opt_pulls, - &form.opt_releases, - ) - }, - }; - let visibility = if form.visibility == "public" { - Visibility::Public - } else { - Visibility::Private - }; - begin( - cx, - viewer, - &target, - &name, - form.description.trim(), - visibility, - spec, - ) - .await -} - -async fn begin( - cx: &Cx, - actor: &User, - target: &User, - name: &str, - description: &str, - visibility: Visibility, - spec: JobSpec, -) -> Result> { - let state = context::(cx); - let lang = i18n::lang(cx, Some(actor)); - let name = match forge_core::names::validate_name(name) { - Ok(name) => name, - Err(e) => { - return Ok(Err(user_facing_message(&e).unwrap_or_else(|| { - crate::i18n::misc::t(lang, crate::i18n::misc::K::InvalidRepoName).to_owned() - }))); - } - }; - if description.chars().count() > 350 { - return Ok(Err(crate::i18n::misc::description_too_long(lang, 350))); - } - let repo = match state - .store - .create_repo(&target.id, &name, description, visibility, DEFAULT_BRANCH) - .await - { - Ok(repo) => { - state.live.bump_repo(&repo.owner_id, &repo.id); - repo - } - Err(e) => match user_facing_message(&e) { - Some(message) => return Ok(Err(message)), - None => return Err(e.into()), - }, - }; - let path = repo_path(&state.config.data_dir, &repo.id)?; - if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await { - state.store.delete_repo(&repo.id).await?; - return Ok(Err(crate::i18n::misc::git_init_failed(lang, e))); - } - let job = match state - .store - .create_import_job( - &actor.id, - &repo.id, - spec.source.as_str(), - &source_ref(spec.source, &spec.remote, &spec.instance), - &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()), - ) - .await - { - Ok(job) => job, - Err(e) => { - state.store.delete_repo(&repo.id).await?; - return Err(e.into()); - } - }; - let full_name = format!("{}/{}", repo.owner_name, repo.name); - audit::record( - &state.store, - Some(cx), - Actor::User(actor), - AuditAction::RepoCreated, - Target { - kind: "repo", - id: &repo.id, - name: &full_name, - }, - serde_json::json!({ "import": spec.source.as_str() }), - ) - .await; - importer::spawn_job(state.clone(), job.clone(), spec); - Ok(Ok(job.id)) -} - -#[component] -async fn bulk_form( - cx: &Cx, - lang: Lang, - username: String, - csrf: &str, - source: Source, - instance: &str, - owners: Vec, - error: Option, -) -> Result { - let has_instance = has_instance(source); - let instance_label = instance_label(lang, source); - let source_value = source.as_str(); - let owner_label = match source { - Source::GitLab => g::t(lang, K::BulkOwnerGitLab), - Source::Forgejo => g::t(lang, K::BulkOwnerForgejo), - _ => g::t(lang, K::BulkOwnerGitHub), - }; - let owner_required = source != Source::Forgejo; - Ok(view! { - head(title: g::t(lang, K::BulkTitle)) - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - newrepo_tabs(lang: lang, active: "import") -
-
- if let Some(message) = error { - alert(message: message.as_str()) - } - csrf_field(token: csrf) - - source_tabs(lang: lang, base: "/new/import/bulk", active: source) - - if has_instance { -
- - -
- } -
- - -
-
- - -
- - -
-
- }) -} - -#[component] -async fn bulk_select( - cx: &Cx, - lang: Lang, - username: String, - csrf: &str, - form: BulkFormEcho, - repos: Vec, - owners: Vec, -) -> Result { - let count = repos.len(); - let empty = repos.is_empty(); - let selected_owner = if form.owner.is_empty() { - owners.first().cloned().unwrap_or_default() - } else { - form.owner.clone() - }; - Ok(view! { - head(title: g::t(lang, K::BulkSelectHeading)) - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - newrepo_tabs(lang: lang, active: "import") -
-
- csrf_field(token: csrf) - - - - - - if empty { -

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

- } else { -
- - -
- visibility_pick(lang: lang, private: false) - option_boxes(lang: lang, opts: ImportOptions { labels: true, issues: true, pulls: true, releases: true }) - -
- for (i, repo) in repos.iter().enumerate() { - - } -
- - } -
-
- }) -} - -struct BulkFormEcho { - source: String, - instance: String, - token: String, - from: String, - owner: String, -} - -#[page("/new/import/bulk")] -async fn bulk_page(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let query = query_params::(cx)?; - let source = match source_of(query.source.as_deref()) { - Source::Git => Source::GitHub, - other => other, - }; - let owners = owner_choices(context::(cx), &viewer.0).await?; - let csrf = viewer.1.csrf_token.clone(); - Ok(view! { - shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), - bulk_form(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), source: source, instance: default_instance(source), owners: owners, error: query.error.clone().filter(|e| e.len() < 300))) - }) -} - -async fn list_remote( - state: &AppState, - source: Source, - instance: &str, - from: &str, - token: Option, -) -> std::result::Result, String> { - let notice: importer::api::Notice = std::sync::Arc::new(|_msg: String| {}); - let listed = match source { - Source::GitLab => { - make_gitlab(state, instance, token, notice)? - .list_repos(from) - .await - } - Source::Forgejo => { - make_forgejo(state, instance, token, notice)? - .list_repos(from) - .await - } - _ => make_github(state, token, notice)?.list_repos(from).await, - }; - listed.map_err(|e: ApiError| e.to_string()) -} - -#[page(POST "/new/import/bulk")] -async fn bulk_submit(cx: &Cx, Form(form): Form) -> Result { - let viewer = require_csrf(cx, &form.csrf).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let state = context::(cx); - let source = match source_of(Some(&form.source)) { - Source::Git => Source::GitHub, - other => other, - }; - let owners = owner_choices(state, &viewer.0).await?; - let csrf = viewer.1.csrf_token.clone(); - let instance = if has_instance(source) && !form.instance.trim().is_empty() { - form.instance.trim().to_owned() - } else { - default_instance(source).to_owned() - }; - - if form.stage == "run" { - let Err(redirect) = run_bulk(cx, &viewer.0, lang, source, &instance, &form).await; - return Err(redirect); - } - - let from = form.from.trim(); - let owner_max = if source == Source::GitLab { 20 } else { 1 }; - let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some(); - let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max); - let result = if bad_owner { - Err(g::t(lang, K::ErrBadOwner).to_owned()) - } else { - list_remote(state, source, &instance, from, token_of(&form.token)).await - }; - let (error, picker) = match result { - Err(message) => (Some(message), None), - Ok(found) => { - let echo = BulkFormEcho { - source: source.as_str().to_owned(), - instance: instance.clone(), - token: form.token.trim().to_owned(), - from: from.to_owned(), - owner: form.owner.trim().to_owned(), - }; - (None, Some((echo, found))) - } - }; - Ok(view! { - shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), - bulk_stage(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), source: source, instance: instance.as_str(), owners: owners, error: error, picker: picker)) - }) -} - -#[component] -async fn bulk_stage( - cx: &Cx, - lang: Lang, - username: String, - csrf: &str, - source: Source, - instance: &str, - owners: Vec, - error: Option, - picker: Option<(BulkFormEcho, Vec)>, -) -> Result { - Ok(view! { - if let Some((echo, repos)) = picker { - bulk_select(lang: lang, username: username, csrf: csrf, form: echo, repos: repos, owners: owners) - } else { - bulk_form(lang: lang, username: username, csrf: csrf, source: source, instance: instance, owners: owners, error: error) - } - }) -} - -async fn run_bulk( - cx: &Cx, - viewer: &User, - lang: Lang, - source: Source, - instance: &str, - form: &BulkForm, -) -> Result { - let state = context::(cx); - let mut picked: Vec<(usize, &String)> = form - .extra - .iter() - .filter_map(|(k, v)| Some((k.strip_prefix("sel_")?.parse::().ok()?, v))) - .collect(); - picked.sort_by_key(|(i, _)| *i); - let fail = |message: &str| -> Result { - Err(see_other(format!( - "/new/import/bulk?source={}&error={}", - source.as_str(), - crate::views::enc(message) - )) - .into()) - }; - if picked.is_empty() { - return fail(g::t(lang, K::ErrNothingSelected)); - } - if picked.len() > MAX_BULK { - return fail(g::t(lang, K::ErrTooMany)); - } - let target = match repo_owner(state, viewer, lang, &form.owner).await? { - Ok(target) => target, - Err(message) => return fail(&message), - }; - let options = options_of( - &form.opt_labels, - &form.opt_issues, - &form.opt_pulls, - &form.opt_releases, - ); - let visibility = if form.visibility == "public" { - Visibility::Public - } else { - Visibility::Private - }; - let failed: Vec = state - .store - .list_import_jobs(&viewer.id, 200) - .await? - .into_iter() - .filter(|job| job.state == ImportState::Failed) - .collect(); - let mut skipped: Vec = Vec::new(); - for (_, full_name) in picked { - let Some((remote, inst)) = parse_remote(source, full_name, instance) else { - continue; - }; - let spec = JobSpec { - source, - remote: remote.clone(), - instance: inst, - token: token_of(&form.token), - git_user: String::new(), - options, - }; - let name = default_name(&remote); - if let Some(repo) = state - .store - .repo_by_owner_and_name(&target.username, &name) - .await? - && let Some(job) = failed.iter().find(|job| { - job.repo_id.as_deref() == Some(repo.id.as_str()) && job.source == source.as_str() - }) - { - retry_job(state, job.clone(), &form.token).await?; - continue; - } - if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? { - tracing::info!(repo = %remote, %message, "bulk import: skipped a repository"); - skipped.push(format!("{name} ({message})")); - } - } - if skipped.is_empty() { - return Err(see_other("/import").into()); - } - let mut list = skipped.join(", "); - if list.len() > 1500 { - list.truncate(list.floor_char_boundary(1500)); - list.push('…'); - } - Err(see_other(format!("/import?skipped={}", crate::views::enc(&list))).into()) -} - -fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) { - match state { - ImportState::Queued => ("badge", g::t(lang, K::JobQueued)), - ImportState::Running => ("badge import-running", g::t(lang, K::JobRunning)), - ImportState::Done => ("badge public", g::t(lang, K::JobDone)), - ImportState::Failed => ("badge import-failed", g::t(lang, K::JobFailed)), - } -} - -fn stage_name(lang: Lang, stage: &str) -> &'static str { - match stage { - "git" => g::t(lang, K::StageGit), - "labels" => g::t(lang, K::StageLabels), - "milestones" => g::t(lang, K::StageMilestones), - "issues" => g::t(lang, K::StageIssues), - "releases" => g::t(lang, K::StageReleases), - "done" => g::t(lang, K::StageDone), - _ => "", - } -} - -async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Result> { - let Some(id) = &job.repo_id else { - return Ok(None); - }; - if !still_readable(&state.store, user, id).await { - return Ok(None); - } - Ok(state.store.repo_by_id(id).await?) -} - -async fn load_job_rows( - state: &AppState, - user_id: &str, - limit: u32, -) -> Result)>> { - let user = state.store.user_by_id(user_id).await?; - let jobs = state.store.list_import_jobs(user_id, limit).await?; - let mut rows = Vec::with_capacity(jobs.len()); - for job in jobs { - let repo = job_repo(state, user.as_ref(), &job).await?; - rows.push((job, repo)); - } - Ok(rows) -} - -#[component] -async fn job_rows(cx: &Cx, lang: Lang, jobs: Vec<(ImportJob, Option)>) -> Result { - Ok(view! { -
- for (job, repo) in jobs.iter() { -
- (job.source_ref.as_str()) - - (state_badge(lang, job.state).1) - " · " (g::t(lang, K::JobStarted)) " " rel_time(lang: lang, stamp: job.created_at.as_str()) - if let Some(repo) = repo { - " · " (format!("{}/{}", repo.owner_name, repo.name)) - } - -
- } -
- }) -} - -#[component] -async fn jobs_list( - cx: &Cx, - lang: Lang, - username: String, - jobs: Vec<(ImportJob, Option)>, - skipped: Option, - page: u64, - pages: u64, - nav: (Vec, Option, Option), -) -> Result { - let (links, prev, next) = nav; - let empty = jobs.is_empty(); - let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed); - Ok(view! { - head(title: g::t(lang, K::JobsTitle), live: Some("/import/events")) - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - newrepo_tabs(lang: lang, active: "history") -
- if retry { - - } - if let Some(message) = skipped { - alert(message: message.as_str()) - } - if empty { -

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

- - } else { - job_rows(lang: lang, jobs: jobs) - } - pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) -
- }) -} - -async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result { - let rows = load_job_rows(state, user_id, 50).await?; - Ok(rows - .iter() - .map(|(job, repo)| { - let repo = repo.as_ref().map_or(String::new(), |repo| { - format!("{}/{}", repo.owner_name, repo.name) - }); - format!( - "{} {} {} {repo}", - job.id, - job.state.as_str(), - job.source_ref - ) - }) - .collect::>() - .join("\n")) -} - -#[route(GET "/import/events")] -async fn jobs_events(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let state = context::(cx).clone(); - let user_id = viewer.0.id.clone(); - stream_changes( - cx, - &state.live.clone(), - &[Topic::Imports(user_id.clone())], - move || { - let state = state.clone(); - let user_id = user_id.clone(); - async move { jobs_fingerprint(&state, &user_id).await } - }, - ) - .await -} - -const HISTORY_ROWS: u64 = 10; - -#[page("/import")] -async fn jobs_page(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let state = context::(cx); - let query = query_params::(cx)?; - let all = state.store.list_import_jobs(&viewer.0.id, 1000).await?; - let (shown, page, pages) = paginate(all, requested_page(query.page.as_deref()), HISTORY_ROWS); - let user = state.store.user_by_id(&viewer.0.id).await?; - let mut rows = Vec::new(); - for job in shown { - let repo = job_repo(state, user.as_ref(), &job).await?; - rows.push((job, repo)); - } - let nav = pager_links(page, pages, |n| format!("/import?page={n}")); - let skipped = query - .skipped - .clone() - .filter(|s| !s.is_empty() && s.len() < 2000) - .map(|s| g::bulk_skipped(lang, &s)); - Ok(view! { - shell(title: g::t(lang, K::JobsTitle), viewer: Some(&viewer), jobs_list(lang: lang, username: viewer.0.username.clone(), jobs: rows, skipped: skipped, page: page, pages: pages, nav: nav)) - }) -} - -#[component] -async fn job_view( - cx: &Cx, - lang: Lang, - username: String, - csrf: &str, - job: ImportJob, - repo: Option, - log: Vec, -) -> Result { - let (badge_class, badge_text) = state_badge(lang, job.state); - let live = (!job.state.is_finished()).then(|| { - format!( - "/import/{}/events?v={}", - job.id, - crate::views::enc(&job.updated_at) - ) - }); - let stage = stage_name(lang, &job.stage); - let has_progress = job.total > 0 && !job.state.is_finished(); - let progress_text = g::progress_of(job.done, job.total); - let failed = job.state == ImportState::Failed; - let done = job.state == ImportState::Done; - let repo_href = repo - .as_ref() - .map(|r| format!("/{}/{}", r.owner_name, r.name)); - let retry_action = format!("/import/{}/retry", job.id); - let error = job.error.clone(); - let state_word = job.state.as_str(); - let empty_log = log.is_empty(); - let sub = vec![SubPart { - text: badge_text.to_owned(), - class: badge_class, - ..SubPart::default() - }]; - Ok(view! { - head(title: job.source_ref.as_str(), sub: sub, live: live.as_deref()) - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - newrepo_tabs(lang: lang, active: "history") -
-
- if !stage.is_empty() { -

- (stage) - if has_progress { - " · " (progress_text.as_str()) - } -

- } - if has_progress { - - } else if !job.state.is_finished() { - - } - if let Some(message) = error { - alert(message: message.as_str()) - } - if let Some(href) = repo_href.as_ref() { - if done { - - } - } -
- if failed { -
-
- csrf_field(token: csrf) -
- - -
- -
-
- } -
-

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

- if empty_log { -

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

- } else { -
    - for line in log.iter() { -
  1. (line.message.as_str())
  2. - } -
- } -
-
- }) -} - -async fn owned_job(cx: &Cx, viewer: &User) -> Result { - let id = job_id(cx).to_owned(); - let state = context::(cx); - match state.store.import_job(&id).await? { - Some(job) if job.user_id == viewer.id => Ok(job), - _ => Err(not_found().into()), - } -} - -#[page("/import/{job_id}")] -async fn job_page(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let state = context::(cx); - let job = owned_job(cx, &viewer.0).await?; - let repo = job_repo(state, Some(&viewer.0), &job).await?; - let log = state.store.list_import_events(&job.id, 200).await?; - let csrf = viewer.1.csrf_token.clone(); - let title = job.source_ref.clone(); - Ok(view! { - shell(title: title.as_str(), viewer: Some(&viewer), - job_view(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), job: job, repo: repo, log: log)) - }) -} - -#[route(GET "/import/{job_id}/events")] -async fn job_events(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let job = owned_job(cx, &viewer.0).await?; - let query = query_params::(cx)?; - let state = context::(cx); - let seen = query.v.clone().unwrap_or_default(); - let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id)); - let store = state.store.clone(); - let id = job.id.clone(); - let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| { - let store = store.clone(); - let id = id.clone(); - async move { - if ended { - return None; - } - loop { - let job = store.import_job(&id).await.ok().flatten()?; - if job.updated_at != seen { - seen = job.updated_at.clone(); - let finished = job.state.is_finished(); - return Some(( - changed_event(job.state.as_str().to_owned()), - (wake, seen, finished), - )); - } - if job.state.is_finished() { - return None; - } - let rx = wake.as_mut()?; - rx.changed().await.ok()?; - } - } - }); - events_response(cx, events) -} - -#[derive(Deserialize)] -struct RetryForm { - #[serde(default)] - csrf: String, - #[serde(default)] - token: String, -} - -async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result { - if job.state != ImportState::Failed { - return Ok(false); - } - let Some(source) = Source::parse(&job.source) else { - return Ok(false); - }; - let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else { - return Ok(false); - }; - let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default(); - if !state.store.requeue_failed_import(&job.id).await? { - return Ok(false); - } - state - .store - .add_import_event( - &job.id, - "info", - "Retrying; what was imported before is skipped", - ) - .await?; - let spec = JobSpec { - source, - remote, - instance, - token: token_of(token), - git_user: String::new(), - options, - }; - importer::spawn_job(state.clone(), job, spec); - Ok(true) -} - -#[route(POST "/import/{job_id}/retry")] -async fn job_retry(cx: &Cx, Form(form): Form) -> Result { - let viewer = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - let job = owned_job(cx, &viewer.0).await?; - let href = format!("/import/{}", job.id); - retry_job(state, job, &form.token).await?; - Err(see_other(href).into()) -} - -async fn retry_candidates(state: &AppState, viewer: &User) -> Result> { - let mut rows = Vec::new(); - for job in state.store.list_import_jobs(&viewer.id, 200).await? { - if job.state != ImportState::Failed { - continue; - } - let Some(repo) = job_repo(state, Some(viewer), &job).await? else { - continue; - }; - if state - .store - .active_import_for_repo(&repo.id) - .await? - .is_some() - { - continue; - } - rows.push((job, repo)); - } - Ok(rows) -} - -fn source_label(raw: &str) -> &'static str { - Source::parse(raw).map_or("", Source::label) -} - -#[component] -async fn retry_list( - cx: &Cx, - lang: Lang, - username: String, - csrf: &str, - rows: Vec<(ImportJob, Repo)>, -) -> Result { - let count = rows.len(); - let empty = rows.is_empty(); - Ok(view! { - head(title: g::t(lang, K::RetryFailedTitle)) - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - newrepo_tabs(lang: lang, active: "history") -
-
- csrf_field(token: csrf) - if empty { -

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

- } else { -
- - -
- -
- for (i, (job, repo)) in rows.iter().enumerate() { - - } -
- - } -
-
- }) -} - -#[page("/import/retry")] -async fn retry_page(cx: &Cx) -> Result { - let viewer = require_user(cx).await?; - let lang = i18n::lang(cx, Some(&viewer.0)); - let state = context::(cx); - let rows = retry_candidates(state, &viewer.0).await?; - let csrf = viewer.1.csrf_token.clone(); - Ok(view! { - shell(title: g::t(lang, K::RetryFailedTitle), viewer: Some(&viewer), - retry_list(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), rows: rows)) - }) -} - -#[derive(Deserialize)] -struct RetrySelectedForm { - #[serde(default)] - csrf: String, - #[serde(default)] - token: String, - #[serde(flatten)] - extra: HashMap, -} - -#[route(POST "/import/retry")] -async fn retry_submit(cx: &Cx, Form(form): Form) -> Result { - let viewer = require_csrf(cx, &form.csrf).await?; - let state = context::(cx); - let mut picked: Vec<(usize, &String)> = form - .extra - .iter() - .filter_map(|(k, v)| Some((k.strip_prefix("sel_")?.parse::().ok()?, v))) - .collect(); - picked.sort_by_key(|(i, _)| *i); - if picked.is_empty() { - return Err(see_other("/import/retry").into()); - } - for (_, id) in picked { - let Some(job) = state.store.import_job(id).await? else { - continue; - }; - if job.user_id != viewer.0.id { - continue; - } - retry_job(state, job, &form.token).await?; - } - Err(see_other("/import").into()) -} diff --git a/crates/forge-web-account/src/pages/import_tests.rs b/crates/forge-web-account/src/pages/import_tests.rs deleted file mode 100644 index 63f402a..0000000 --- a/crates/forge-web-account/src/pages/import_tests.rs +++ /dev/null @@ -1,157 +0,0 @@ -use forge_core::Store; -use topcoat::router::Router; - -use crate::auth::SESSION_COOKIE; -use crate::test_support::fixture::{send, send_form}; -use crate::test_support::{app_router, create_session, test_state}; - -const TOKEN: &str = "import-session"; -const CSRF: &str = "import-csrf"; -const OTHER: &str = "other-session"; - -struct Fixture { - _dir: tempfile::TempDir, - router: Router, - store: Store, - user_id: String, -} - -async fn fixture() -> Fixture { - let dir = tempfile::tempdir().expect("tempdir"); - let data_dir = dir.path().join("data"); - std::fs::create_dir_all(&data_dir).expect("data dir"); - let state = test_state(&data_dir).await; - let owner = state - .store - .create_user("tahinli", None, "h", false) - .await - .expect("user"); - let other = state - .store - .create_user("nina", None, "h", false) - .await - .expect("user"); - create_session(&state.store, &owner.id, TOKEN, CSRF).await; - create_session(&state.store, &other.id, OTHER, "other-csrf").await; - Fixture { - _dir: dir, - router: app_router(state.clone()), - store: state.store.clone(), - user_id: owner.id, - } -} - -fn session_cookie(token: &str) -> String { - format!("__Host-{SESSION_COOKIE}={token}") -} - -async fn scenario_pages_render(fx: &Fixture) { - let cookie = session_cookie(TOKEN); - for (uri, needle) in [ - ("/new/import?source=git", "Import a repository"), - ("/new/import?source=github", "Import a repository"), - ("/new/import?source=gitlab", "Import a repository"), - ( - "/new/import/bulk?source=github", - "Import several repositories", - ), - ("/import", "Import history"), - ("/settings/export", "Export your data"), - ] { - let reply = send(&fx.router, "GET", uri, Some(&cookie), None).await; - assert_eq!(reply.status, 200, "{uri}: {}", reply.body); - assert!(reply.body.contains(needle), "{uri} lacks {needle}"); - } -} - -async fn scenario_need_session(fx: &Fixture) { - for uri in [ - "/new/import", - "/new/import/bulk", - "/import", - "/settings/export", - ] { - let reply = send(&fx.router, "GET", uri, None, None).await; - assert_ne!(reply.status, 200, "{uri}: {}", reply.body); - } -} - -async fn scenario_csrf(fx: &Fixture) { - let cookie = session_cookie(TOKEN); - let form = "source=git&remote=https%3A%2F%2Fexample.org%2Fa.git&csrf=wrong".to_owned(); - let reply = send_form(&fx.router, "POST", "/new/import", Some(&cookie), Some(form)).await; - assert_ne!(reply.status, 303, "a bad token must not redirect to a job"); - assert!( - fx.store - .list_import_jobs(&fx.user_id, 10) - .await - .expect("jobs") - .is_empty() - ); - let reply = send_form( - &fx.router, - "POST", - "/settings/export", - Some(&cookie), - Some("csrf=wrong".into()), - ) - .await; - assert_ne!(reply.status, 303); - assert!( - fx.store - .list_exports(&fx.user_id) - .await - .expect("exports") - .is_empty() - ); -} - -async fn scenario_private_address(fx: &Fixture) { - let cookie = session_cookie(TOKEN); - let form = format!( - "csrf={CSRF}&source=git&remote=https%3A%2F%2F127.0.0.1%2Fa.git&owner=tahinli&visibility=private" - ); - let reply = send_form(&fx.router, "POST", "/new/import", Some(&cookie), Some(form)).await; - assert_ne!(reply.status, 500, "{}", reply.body); - assert!( - fx.store - .list_import_jobs(&fx.user_id, 10) - .await - .expect("jobs") - .is_empty(), - "no job for a refused address" - ); -} - -async fn scenario_archive(fx: &Fixture) { - let export = fx - .store - .create_export(&fx.user_id, std::time::Duration::from_secs(3600)) - .await - .expect("export"); - fx.store - .mark_export_ready(&export.id, 10, std::time::Duration::from_secs(3600)) - .await - .expect("ready"); - let uri = format!("/settings/export/{}/download", export.id); - let other = session_cookie(OTHER); - let reply = send(&fx.router, "GET", &uri, Some(&other), None).await; - assert_eq!(reply.status, 404, "a stranger gets not found"); - let reply = send(&fx.router, "GET", &uri, None, None).await; - assert_ne!(reply.status, 200); -} - -#[tokio::test] -async fn import_and_export_pages_render_and_need_a_session() { - let fx = fixture().await; - scenario_pages_render(&fx).await; - scenario_need_session(&fx).await; -} - -#[tokio::test] -async fn import_and_export_writes_are_refused_or_scoped() { - let fx = fixture().await; - scenario_csrf(&fx).await; - scenario_private_address(&fx).await; - scenario_archive(&fx).await; -} diff --git a/crates/forge-web-account/src/pages/mod.rs b/crates/forge-web-account/src/pages/mod.rs index 48d2cca..0a2c6f5 100644 --- a/crates/forge-web-account/src/pages/mod.rs +++ b/crates/forge-web-account/src/pages/mod.rs @@ -18,9 +18,6 @@ pub mod banner; pub mod explore; pub mod forgot; pub mod home; -pub mod import; -#[cfg(test)] -mod import_tests; pub mod invites; pub mod login; pub mod needs_you; @@ -43,7 +40,6 @@ pub mod register; #[cfg(test)] mod releases_tests; pub mod settings_appearance; -pub mod settings_export; pub mod settings_gpg; #[cfg(test)] mod settings_gpg_tests; diff --git a/crates/forge-web-account/src/pages/new_repo.rs b/crates/forge-web-account/src/pages/new_repo.rs index 0f0941d..b7b6ac3 100644 --- a/crates/forge-web-account/src/pages/new_repo.rs +++ b/crates/forge-web-account/src/pages/new_repo.rs @@ -222,7 +222,6 @@ async fn new_repo_form( Ok(view! { head(title: i18n::t(lang, Key::NewRepository)) crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) - crate::pages::import::newrepo_tabs(lang: lang, active: "create")
if let Some(message) = error { @@ -253,7 +252,7 @@ async fn new_repo_form( (g::t(lang, K::AddDefaultLabels)) - crate::pages::import::visibility_pick(lang: lang, private: private) + visibility_pick(lang: lang, private: private)
}) @@ -590,10 +662,32 @@ async fn build_page( two_factor, sessions: state.store.list_sessions(&viewer.0.id).await?, current_session_id: viewer.1.id.clone(), + owned_repos: state + .store + .list_repos_by_owner(&viewer.0.id) + .await? + .into_iter() + .map(|repo| format!("{}/{}", repo.owner_name, repo.name)) + .collect(), shown, }) } +async fn respond_delete( + cx: &Cx, + viewer: (User, Session), + error: Option, + throttled: Option, +) -> Result { + let shown = Shown { + part: Some("danger".to_owned()), + delete_error: error, + throttled, + ..Shown::default() + }; + respond(cx, viewer, shown).await +} + async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result { let state = context::(cx); let mut headers = HeaderMap::new(); @@ -691,9 +785,6 @@ async fn security_page(cx: &Cx) -> Result { let viewer = require_user(cx).await?; let lang = i18n::lang(cx, Some(&viewer.0)); let query = query_params::(cx)?; - if query.part.as_deref() == Some("danger") { - return Err(see_other("/settings/export?part=delete").into()); - } let saved = query.saved.clone(); let part = query.part.clone().or_else(|| { saved.as_deref().map(|saved| { @@ -912,16 +1003,16 @@ async fn account_delete(cx: &Cx, Form(form): Form) -> Result< let user_id = viewer.0.id.clone(); if form.confirm_username != viewer.0.username { let error = Some(t(lang, Key::ErrConfirmUsername).into()); - return settings_export::respond_delete(cx, viewer, error, None).await; + return respond_delete(cx, viewer, error, None).await; } if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? { let error = Some(refused.message.into()); - return settings_export::respond_delete(cx, viewer, error, refused.retry).await; + return respond_delete(cx, viewer, error, refused.retry).await; } if two_factor_enabled(&state.store, &user_id).await? { if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? { let error = Some(refused.message.into()); - return settings_export::respond_delete(cx, viewer, error, refused.retry).await; + return respond_delete(cx, viewer, error, refused.retry).await; } } let ghost = state.store.ensure_ghost_user().await?; @@ -945,7 +1036,7 @@ async fn account_delete(cx: &Cx, Form(form): Form) -> Result< Err(see_other("/").into()) } Err(e) => match user_facing_message(&e) { - Some(message) => settings_export::respond_delete(cx, viewer, Some(message), None).await, + Some(message) => respond_delete(cx, viewer, Some(message), None).await, None => Err(e.into()), }, } diff --git a/crates/forge-web-app/Cargo.toml b/crates/forge-web-app/Cargo.toml index db1aef7..edf5801 100644 --- a/crates/forge-web-app/Cargo.toml +++ b/crates/forge-web-app/Cargo.toml @@ -40,8 +40,6 @@ hmac.workspace = true similar = { workspace = true } ulid.workspace = true lettre.workspace = true -tar.workspace = true -flate2.workspace = true tempfile = { workspace = true, optional = true } diff --git a/crates/forge-web-app/src/exporter.rs b/crates/forge-web-app/src/exporter.rs deleted file mode 100644 index d64d7e4..0000000 --- a/crates/forge-web-app/src/exporter.rs +++ /dev/null @@ -1,412 +0,0 @@ -use std::collections::HashMap; -use std::io::{BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::{LazyLock, Mutex, PoisonError}; -use std::time::Duration; - -use forge_core::issues::IssueFilter; -use forge_core::store::exports::{DataExport, ExportState}; -use forge_core::time::now_stamp; -use forge_core::{IssueSort, Repo, User}; -use forge_git::backup::bundle_create; -use serde_json::{Value, json}; -use tokio::sync::watch; - -use crate::state::AppState; - -pub const EXPORT_TTL_DAYS: u64 = 7; -pub const EXPORT_TTL: Duration = Duration::from_secs(EXPORT_TTL_DAYS * 24 * 60 * 60); -const PAGE: u32 = 100; - -static HUB: LazyLock>>> = - LazyLock::new(|| Mutex::new(HashMap::new())); -static START: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - -pub fn subscribe(user_id: &str) -> watch::Receiver { - let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); - hub.retain(|_, tx| tx.receiver_count() > 0); - hub.entry(user_id.to_owned()) - .or_insert_with(|| watch::channel(0).0) - .subscribe() -} - -fn bump(user_id: &str) { - let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); - if let Some(tx) = hub.get(user_id) { - tx.send_modify(|n| *n = n.wrapping_add(1)); - if tx.receiver_count() == 0 { - hub.remove(user_id); - } - } -} - -fn export_dir(state: &AppState) -> PathBuf { - state.config.data_dir.join("exports") -} - -pub fn archive_path(state: &AppState, id: &str) -> PathBuf { - export_dir(state).join(format!("{id}.tar.gz")) -} - -fn partial_path(state: &AppState, id: &str) -> PathBuf { - export_dir(state).join(format!("{id}.tar.part")) -} - -async fn remove_archive(state: &AppState, id: &str) -> std::io::Result<()> { - for path in [archive_path(state, id), partial_path(state, id)] { - match tokio::fs::remove_file(&path).await { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e), - } - } - Ok(()) -} - -pub async fn start(state: &AppState, user: &User) -> forge_core::Result { - sweep_expired(state).await; - let _guard = START.lock().await; - if let Some(running) = state - .store - .list_exports(&user.id) - .await? - .into_iter() - .find(|e| e.state == ExportState::Building) - { - return Ok(running); - } - let export = state.store.create_export(&user.id, EXPORT_TTL).await?; - let task_state = state.clone(); - let task_user = user.clone(); - let id = export.id.clone(); - tokio::spawn(async move { - run(&task_state, &task_user, &id).await; - }); - Ok(export) -} - -async fn run(state: &AppState, user: &User, id: &str) { - let outcome = build(state, user, id).await; - match outcome { - Ok(size) => { - if let Err(e) = state - .store - .mark_export_ready(id, i64::try_from(size).unwrap_or(i64::MAX), EXPORT_TTL) - .await - { - tracing::error!(error = %e, "export: could not mark the export ready"); - } - notify_ready(state, user, id).await; - } - Err(message) => { - tracing::error!(error = %message, export_id = id, "export failed"); - let _ = remove_archive(state, id).await; - if let Err(e) = state.store.mark_export_failed(id, &message).await { - tracing::error!(error = %e, "export: could not record a failure"); - } - } - } - bump(&user.id); -} - -async fn notify_ready(state: &AppState, user: &User, id: &str) { - let Some(email) = user.email.as_deref().filter(|e| !e.is_empty()) else { - return; - }; - let base = state.config.base_url.trim_end_matches('/'); - let body = format!( - "Your data export is ready.\n\nDownload it at {base}/settings/export (you must be signed in). \ - It is removed after {EXPORT_TTL_DAYS} days.\n" - ); - if let Err(e) = crate::mail::enqueue( - state, - &format!("export:{id}"), - forge_core::mail::MailKind::Other, - Some(&user.id), - email, - "Your data export is ready", - &body, - ) - .await - { - tracing::warn!(error = %e, "export: could not queue the ready mail"); - } -} - -async fn build(state: &AppState, user: &User, id: &str) -> Result { - let dir = export_dir(state); - tokio::fs::create_dir_all(&dir) - .await - .map_err(|e| e.to_string())?; - let work = dir.join(format!("{id}.work")); - let _ = tokio::fs::remove_dir_all(&work).await; - tokio::fs::create_dir_all(work.join("repos")) - .await - .map_err(|e| e.to_string())?; - let result = stage_and_pack(state, user, id, &work).await; - let _ = tokio::fs::remove_dir_all(&work).await; - result -} - -async fn stage_and_pack( - state: &AppState, - user: &User, - id: &str, - work: &Path, -) -> Result { - write_json(&work.join("profile.json"), &profile_json(user)).await?; - let repos = state - .store - .list_repos_by_owner(&user.id) - .await - .map_err(|e| e.to_string())?; - for repo in &repos { - let repo_dir = work.join("repos").join(&repo.name); - tokio::fs::create_dir_all(&repo_dir) - .await - .map_err(|e| e.to_string())?; - stage_repo(state, repo, &repo_dir).await?; - } - let target = archive_path(state, id); - let partial = partial_path(state, id); - let (work_buf, partial_buf, name) = ( - work.to_path_buf(), - partial.clone(), - format!("forge-export-{}", user.username), - ); - tokio::task::spawn_blocking(move || pack(&work_buf, &partial_buf, &name)) - .await - .map_err(|e| e.to_string())??; - tokio::fs::rename(&partial, &target) - .await - .map_err(|e| e.to_string())?; - let meta = tokio::fs::metadata(&target) - .await - .map_err(|e| e.to_string())?; - Ok(meta.len()) -} - -fn pack(work: &Path, out: &Path, top: &str) -> Result<(), String> { - use std::os::unix::fs::OpenOptionsExt; - let file = std::fs::OpenOptions::new() - .write(true) - .create(true) - .truncate(true) - .mode(0o600) - .open(out) - .map_err(|e| e.to_string())?; - let gz = flate2::write::GzEncoder::new(file, flate2::Compression::default()); - let mut tar = tar::Builder::new(gz); - tar.append_dir_all(top, work).map_err(|e| e.to_string())?; - let gz = tar.into_inner().map_err(|e| e.to_string())?; - gz.finish().map_err(|e| e.to_string())?; - Ok(()) -} - -async fn write_json(path: &Path, value: &Value) -> Result<(), String> { - let text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?; - tokio::fs::write(path, text) - .await - .map_err(|e| e.to_string()) -} - -fn write_array_item( - out: &mut impl Write, - written: &mut usize, - value: &Value, -) -> Result<(), String> { - let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; - let lead: &[u8] = if *written == 0 { b"[\n " } else { b",\n " }; - out.write_all(lead) - .and_then(|()| out.write_all(text.replace('\n', "\n ").as_bytes())) - .map_err(|e| e.to_string())?; - *written += 1; - Ok(()) -} - -fn profile_json(user: &User) -> Value { - json!({ - "username": user.username, - "display_name": user.display_name, - "email": user.email, - "about": user.about, - "created_at": user.created_at, - "timezone": user.timezone, - "language": user.language, - "theme": user.theme, - "exported_at": now_stamp(), - }) -} - -async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), String> { - let git_dir = - forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; - let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle")) - .await - .map_err(|e| format!("bundling {}: {e}", repo.name))?; - - let labels = state - .store - .list_labels(&repo.id) - .await - .map_err(|e| e.to_string())?; - let milestones = state - .store - .list_milestones(&repo.id, None) - .await - .map_err(|e| e.to_string())?; - let meta = json!({ - "name": repo.name, - "description": repo.description, - "visibility": repo.visibility.as_str(), - "default_branch": repo.default_branch, - "created_at": repo.created_at, - "archived": repo.archived, - "has_bundle": bundled, - "labels": labels.iter().map(|l| json!({"name": l.name, "color": l.color, "description": l.description})).collect::>(), - "milestones": milestones.iter().map(|m| json!({ - "title": m.title, "description": m.description, "due_on": m.due_on, - "state": m.state.as_str(), "created_at": m.created_at, "closed_at": m.closed_at, - })).collect::>(), - }); - write_json(&dir.join("repo.json"), &meta).await?; - - let mut out = - BufWriter::new(std::fs::File::create(dir.join("issues.json")).map_err(|e| e.to_string())?); - let mut written = 0usize; - let mut page = 1; - loop { - let filter = IssueFilter { - state: None, - sort: IssueSort::Oldest, - page, - per_page: PAGE, - ..IssueFilter::default() - }; - let (items, total) = state - .store - .list_issues(&repo.id, &filter) - .await - .map_err(|e| e.to_string())?; - let got = items.len(); - for item in items { - let comments = state - .store - .list_comments(&item.issue.id) - .await - .map_err(|e| e.to_string())?; - let names = state - .store - .usernames_by_ids( - &comments - .iter() - .map(|c| c.author_id.clone()) - .collect::>(), - ) - .await - .map_err(|e| e.to_string())?; - let names: HashMap = - names.into_iter().map(|(k, (name, _))| (k, name)).collect(); - write_array_item( - &mut out, - &mut written, - &issue_json(&item, &comments, &names), - )?; - } - if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total { - break; - } - page += 1; - } - out.write_all(if written == 0 { b"[]" } else { b"\n]" }) - .and_then(|()| out.flush()) - .map_err(|e| e.to_string())?; - - let releases = state - .store - .list_releases(&repo.id) - .await - .map_err(|e| e.to_string())?; - let mut out = Vec::new(); - for r in releases { - let assets = state - .store - .list_release_assets(&r.id) - .await - .map_err(|e| e.to_string())?; - out.push(json!({ - "tag": r.tag, "title": r.title, "body": r.body, "draft": r.draft, - "prerelease": r.prerelease, "author": r.author_name, "target_oid": r.target_oid, - "created_at": r.created_at, "published_at": r.published_at, - "assets": assets.iter().map(|a| json!({ - "name": a.name, "size": a.size, "sha256": a.sha256, - "content_type": a.content_type, "downloads": a.download_count, - })).collect::>(), - })); - } - write_json(&dir.join("releases.json"), &Value::Array(out)).await -} - -fn issue_json( - item: &forge_core::IssueListItem, - comments: &[forge_core::Comment], - names: &HashMap, -) -> Value { - let i = &item.issue; - json!({ - "number": i.number, - "title": i.title, - "body": i.body, - "state": i.state.as_str(), - "author": item.author, - "labels": item.labels.iter().map(|l| l.name.clone()).collect::>(), - "assignees": item.assignees, - "created_at": i.created_at, - "closed_at": i.closed_at, - "comments": comments.iter().map(|c| json!({ - "author": names.get(&c.author_id).cloned().unwrap_or_default(), - "body": c.body, - "created_at": c.created_at, - })).collect::>(), - }) -} - -pub async fn sweep_expired(state: &AppState) { - let expired = match state.store.expired_exports(&now_stamp()).await { - Ok(rows) => rows, - Err(e) => { - tracing::warn!(error = %e, "export: could not list expired exports"); - return; - } - }; - for export in expired { - if let Err(e) = remove_archive(state, &export.id).await { - tracing::warn!(error = %e, "export: could not remove an expired archive"); - continue; - } - if let Err(e) = state.store.delete_export(&export.id).await { - tracing::warn!(error = %e, "export: could not delete an expired export row"); - } - bump(&export.user_id); - } -} - -pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> { - if let Err(e) = remove_archive(state, &export.id).await { - tracing::warn!(error = %e, "export: could not remove an archive"); - return Err(e.into()); - } - state.store.delete_export(&export.id).await?; - bump(&export.user_id); - Ok(()) -} - -pub async fn on_boot(state: &AppState) { - if let Err(e) = state.store.fail_interrupted_exports().await { - tracing::error!(error = %e, "export: could not clean up interrupted exports"); - } - sweep_expired(state).await; -} - -#[cfg(test)] -mod tests; diff --git a/crates/forge-web-app/src/exporter/tests.rs b/crates/forge-web-app/src/exporter/tests.rs deleted file mode 100644 index 27b5544..0000000 --- a/crates/forge-web-app/src/exporter/tests.rs +++ /dev/null @@ -1,171 +0,0 @@ -use std::io::Read; - -use forge_core::Visibility; -use forge_core::store::exports::ExportState; - -use super::*; -use crate::test_support::test_state; - -fn entries(path: &Path) -> Vec<(String, Vec)> { - let file = std::fs::File::open(path).expect("archive opens"); - let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(file)); - let mut out = Vec::new(); - for entry in archive.entries().expect("entries") { - let mut entry = entry.expect("entry"); - let name = entry.path().expect("path").display().to_string(); - let mut bytes = Vec::new(); - entry.read_to_end(&mut bytes).expect("read"); - out.push((name, bytes)); - } - out -} - -async fn setup() -> (AppState, User, Repo, tempfile::TempDir) { - let dir = tempfile::tempdir().expect("tempdir"); - let state = test_state(dir.path()).await; - let user = state - .store - .create_user("tahinli", Some("tahinli@example.com"), "unused", false) - .await - .expect("user"); - let repo = state - .store - .create_repo(&user.id, "project", "A project", Visibility::Public, "main") - .await - .expect("repo"); - let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path"); - forge_git::repo::init_bare(&state.git, &bare, "main") - .await - .expect("init"); - let run = |args: &[&str]| { - let out = std::process::Command::new("git") - .arg(format!("--git-dir={}", bare.display())) - .args(args) - .env("GIT_AUTHOR_NAME", "t") - .env("GIT_AUTHOR_EMAIL", "t@example.com") - .env("GIT_COMMITTER_NAME", "t") - .env("GIT_COMMITTER_EMAIL", "t@example.com") - .output() - .expect("git"); - assert!(out.status.success(), "{out:?}"); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - let tree = run(&["hash-object", "-t", "tree", "-w", "--stdin"]); - let commit = run(&["commit-tree", &tree, "-m", "first"]); - run(&["update-ref", "refs/heads/main", &commit]); - let issue = state - .store - .create_issue(&repo.id, &user.id, "It breaks", "steps") - .await - .expect("issue"); - state - .store - .add_comment(&issue.id, &user.id, "same here") - .await - .expect("comment"); - (state, user, repo, dir) -} - -#[tokio::test] -async fn the_archive_holds_the_profile_bundles_issues_and_releases() { - let (state, user, _repo, _dir) = setup().await; - let export = start(&state, &user).await.expect("start"); - let mut wake = subscribe(&user.id); - loop { - let row = state.store.data_export(&export.id).await.unwrap().unwrap(); - if row.state != ExportState::Building { - assert_eq!(row.state, ExportState::Ready, "{:?}", row.error); - assert!(row.size > 0); - break; - } - tokio::time::timeout(Duration::from_secs(60), wake.changed()) - .await - .expect("the export finishes") - .expect("signal open"); - } - - let files = entries(&archive_path(&state, &export.id)); - let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); - let has = |suffix: &str| names.iter().any(|n| n.ends_with(suffix)); - assert!(has("profile.json"), "{names:?}"); - assert!(has("repos/project/repo.bundle"), "{names:?}"); - assert!(has("repos/project/repo.json")); - assert!(has("repos/project/issues.json")); - assert!(has("repos/project/releases.json")); - - let read = |suffix: &str| { - let (_, bytes) = files.iter().find(|(n, _)| n.ends_with(suffix)).unwrap(); - String::from_utf8_lossy(bytes).into_owned() - }; - let profile = read("profile.json"); - assert!(profile.contains("tahinli@example.com")); - assert!( - !profile.contains("password"), - "no credential in the profile" - ); - let issues: serde_json::Value = serde_json::from_str(&read("issues.json")).unwrap(); - assert_eq!(issues[0]["title"], "It breaks"); - assert_eq!(issues[0]["comments"][0]["body"], "same here"); - assert_eq!(issues[0]["comments"][0]["author"], "tahinli"); - let bundle = files - .iter() - .find(|(n, _)| n.ends_with("repo.bundle")) - .unwrap(); - assert!(bundle.1.starts_with(b"# v2 git bundle") || bundle.1.starts_with(b"# v3 git bundle")); -} - -#[tokio::test] -async fn an_expired_export_is_removed_with_its_file() { - let (state, user, _repo, _dir) = setup().await; - let export = state - .store - .create_export(&user.id, Duration::from_secs(0)) - .await - .expect("export"); - let path = archive_path(&state, &export.id); - tokio::fs::create_dir_all(path.parent().unwrap()) - .await - .unwrap(); - tokio::fs::write(&path, b"x").await.unwrap(); - sweep_expired(&state).await; - assert!(state.store.data_export(&export.id).await.unwrap().is_none()); - assert!(!path.exists()); -} - -#[tokio::test] -async fn a_fresh_export_survives_the_sweep() { - let (state, user, _repo, _dir) = setup().await; - let export = state - .store - .create_export(&user.id, EXPORT_TTL) - .await - .unwrap(); - sweep_expired(&state).await; - assert!(state.store.data_export(&export.id).await.unwrap().is_some()); -} - -#[tokio::test] -async fn a_second_request_while_building_returns_the_running_export() { - let (state, user, _repo, _dir) = setup().await; - let running = state - .store - .create_export(&user.id, EXPORT_TTL) - .await - .unwrap(); - let again = start(&state, &user).await.unwrap(); - assert_eq!(again.id, running.id); -} - -#[tokio::test] -async fn ready_mail_is_queued_for_an_account_with_an_address() { - let (state, user, _repo, _dir) = setup().await; - notify_ready(&state, &user, "abc").await; - notify_ready(&state, &user, "abc").await; - let queued = state - .store - .list_mail(None, "9999-12-31T00:00:00Z", 10) - .await - .expect("mail list") - .len(); - assert_eq!(queued, 1, "one mail, however often the ready step runs"); -} diff --git a/crates/forge-web-app/src/importer/api.rs b/crates/forge-web-app/src/importer/api.rs deleted file mode 100644 index c1d78b0..0000000 --- a/crates/forge-web-app/src/importer/api.rs +++ /dev/null @@ -1,1482 +0,0 @@ -use std::fmt; -use std::future::Future; -use std::io; -use std::sync::Arc; -use std::time::Duration; - -use bytes::Bytes; -use futures_util::stream::{BoxStream, StreamExt}; -use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER}; -use serde::Deserialize; -use serde::de::DeserializeOwned; - -use crate::webhooks::client::{WebhookPolicy, validate_url}; - -pub type AssetStream = BoxStream<'static, io::Result>; - -const PER_PAGE: usize = 100; -const FORGEJO_LIMIT: usize = 50; -const MAX_PAGES: usize = 500; -const MAX_RATE_WAIT: u64 = 15 * 60; -const MAX_JSON_BYTES: usize = 32 * 1024 * 1024; -const MAX_REDIRECTS: usize = 5; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ApiError { - NotFound(String), - Unauthorized(String), - RateLimited { wait_secs: u64 }, - TooLarge, - Http(String), - Parse(String), -} - -impl fmt::Display for ApiError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ApiError::NotFound(what) => write!(f, "not found: {what}"), - ApiError::Unauthorized(what) => write!(f, "access denied: {what}"), - ApiError::RateLimited { wait_secs } => write!( - f, - "the rate limit is used up and resets in {}; retry then, nothing imported is lost", - wait_text(*wait_secs) - ), - ApiError::TooLarge => write!(f, "the file is larger than the allowed size"), - ApiError::Http(msg) => write!(f, "request failed: {msg}"), - ApiError::Parse(msg) => write!(f, "unexpected response: {msg}"), - } - } -} - -fn wait_text(secs: u64) -> String { - let plural = |n: u64| if n == 1 { "" } else { "s" }; - if secs < 60 { - return format!("{secs} second{}", plural(secs)); - } - let minutes = secs.div_ceil(60); - let (hours, rest) = (minutes / 60, minutes % 60); - match (hours, rest) { - (0, m) => format!("{m} minute{}", plural(m)), - (h, 0) => format!("{h} hour{}", plural(h)), - (h, m) => format!("{h} hour{} {m} minute{}", plural(h), plural(m)), - } -} - -pub type ApiResult = Result; - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtLabel { - pub name: String, - pub color: String, - pub description: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtMilestone { - pub id: String, - pub title: String, - pub description: String, - pub closed: bool, - pub due_on: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtIssue { - pub number: i64, - pub title: String, - pub body: String, - pub closed: bool, - pub not_planned: bool, - pub merged: bool, - pub author: String, - pub labels: Vec, - pub milestone: Option, - pub created_at: String, - pub url: String, - pub is_pr: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtComment { - pub id: String, - pub author: String, - pub body: String, - pub created_at: String, - pub url: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtAsset { - pub id: String, - pub name: String, - pub size: u64, - pub content_type: String, - pub url: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtRelease { - pub id: String, - pub tag: String, - pub title: String, - pub body: String, - pub draft: bool, - pub prerelease: bool, - pub author: String, - pub created_at: String, - pub url: String, - pub assets: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtRepo { - pub name: String, - pub full_name: String, - pub description: String, - pub private: bool, - pub fork: bool, - pub archived: bool, - pub default_branch: String, - pub web_url: String, -} - -pub trait RemoteApi: Send + Sync { - fn list_repos(&self, owner: &str) -> impl Future>> + Send; - fn labels(&self, repo: &str) -> impl Future>> + Send; - fn milestones(&self, repo: &str) -> impl Future>> + Send; - fn issues(&self, repo: &str) -> impl Future>> + Send; - fn comments( - &self, - repo: &str, - issue: &ExtIssue, - ) -> impl Future>> + Send; - fn releases(&self, repo: &str) -> impl Future>> + Send; - fn download( - &self, - asset: &ExtAsset, - max_bytes: u64, - ) -> impl Future> + Send; -} - -pub fn valid_segment(s: &str) -> bool { - !s.is_empty() - && s.len() <= 100 - && s != "." - && s != ".." - && s.bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) -} - -pub fn valid_path(path: &str, min: usize, max: usize) -> bool { - let parts: Vec<&str> = path.split('/').collect(); - (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p)) -} - -pub fn rate_wait( - retry_after: Option<&str>, - remaining: Option<&str>, - reset_unix: Option<&str>, - now_unix: i64, -) -> Option { - if let Some(secs) = retry_after.and_then(|v| v.trim().parse::().ok()) { - return Some(secs.max(1)); - } - if remaining.map(str::trim) == Some("0") { - let reset = reset_unix.and_then(|v| v.trim().parse::().ok())?; - return Some(u64::try_from(reset - now_unix).unwrap_or(0).max(1)); - } - None -} - -pub type Notice = Arc; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Auth { - GitHub, - GitLab, - Forgejo, -} - -pub struct Http { - client: reqwest::Client, - policy: WebhookPolicy, - token: Option, - auth: Auth, - auth_host: String, - notice: Notice, -} - -impl Http { - pub fn new( - client: reqwest::Client, - policy: WebhookPolicy, - token: Option, - auth: Auth, - auth_host: String, - notice: Notice, - ) -> Self { - let token = token.filter(|t| !t.trim().is_empty()); - Http { - client, - policy, - token, - auth, - auth_host, - notice, - } - } - - fn host_of(url: &str) -> String { - reqwest::Url::parse(url) - .ok() - .and_then(|u| u.host_str().map(str::to_ascii_lowercase)) - .unwrap_or_default() - } - - fn request(&self, url: &str, accept: &str, authed: bool) -> reqwest::RequestBuilder { - let mut req = self.client.get(url).header(ACCEPT, accept); - if authed - && Self::host_of(url) == self.auth_host - && let Some(token) = &self.token - { - req = match self.auth { - Auth::GitLab => req.header("PRIVATE-TOKEN", token), - Auth::GitHub => req - .header(AUTHORIZATION, format!("Bearer {token}")) - .header("X-GitHub-Api-Version", "2022-11-28"), - Auth::Forgejo => req.header(AUTHORIZATION, format!("token {token}")), - }; - } - req - } - - fn header(headers: &HeaderMap, name: &str) -> Option { - headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - } - - async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult { - validate_url(url, &self.policy) - .map_err(|e| ApiError::Http(format!("address refused: {e}")))?; - let mut attempt = 0u32; - loop { - attempt += 1; - let resp = self - .request(url, accept, authed) - .send() - .await - .map_err(|e| ApiError::Http(e.without_url().to_string()))?; - let status = resp.status(); - if status.is_success() || status.is_redirection() { - return Ok(resp); - } - let headers = resp.headers(); - match status.as_u16() { - 401 => return Err(ApiError::Unauthorized("the token was refused".into())), - 404 => return Err(ApiError::NotFound(Self::host_of(url))), - 403 | 429 => { - let wait = rate_wait( - Self::header(headers, RETRY_AFTER.as_str()).as_deref(), - Self::header(headers, "x-ratelimit-remaining").as_deref(), - Self::header(headers, "x-ratelimit-reset").as_deref(), - jiff::Timestamp::now().as_second(), - ) - .or_else(|| (status.as_u16() == 429).then_some(60)); - let Some(wait) = wait else { - return Err(ApiError::Unauthorized( - "the server refused the request (is the token valid and allowed to read this?)" - .into(), - )); - }; - if wait > MAX_RATE_WAIT || attempt > 4 { - return Err(ApiError::RateLimited { wait_secs: wait }); - } - (self.notice)(format!("Rate limited, waiting {wait} seconds")); - tokio::time::sleep(Duration::from_secs(wait)).await; - } - 500..=599 if attempt <= 3 => { - tokio::time::sleep(Duration::from_secs(u64::from(attempt) * 2)).await; - } - code => return Err(ApiError::Http(format!("status {code}"))), - } - } - } - - async fn body(resp: reqwest::Response, max: usize) -> ApiResult> { - let mut resp = resp; - let mut out = Vec::new(); - while let Some(chunk) = resp - .chunk() - .await - .map_err(|e| ApiError::Http(e.without_url().to_string()))? - { - if out.len() + chunk.len() > max { - return Err(ApiError::TooLarge); - } - out.extend_from_slice(&chunk); - } - Ok(out) - } - - pub async fn json(&self, url: &str) -> ApiResult { - let resp = self.send(url, "application/json", true).await?; - let bytes = Self::body(resp, MAX_JSON_BYTES).await?; - serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string())) - } - - pub async fn pages(&self, base: &str) -> ApiResult> { - let sep = if base.contains('?') { '&' } else { '?' }; - let mut out = Vec::new(); - for page in 1..=MAX_PAGES { - let url = format!("{base}{sep}per_page={PER_PAGE}&page={page}"); - let items: Vec = self.json(&url).await?; - let short = items.len() < PER_PAGE; - out.extend(items); - if short { - return Ok(out); - } - } - Err(ApiError::TooLarge) - } - - pub async fn limit_pages(&self, base: &str) -> ApiResult> { - let sep = if base.contains('?') { '&' } else { '?' }; - let mut out: Vec = Vec::new(); - for page in 1..=MAX_PAGES { - let url = format!("{base}{sep}limit={FORGEJO_LIMIT}&page={page}"); - let resp = self.send(&url, "application/json", true).await?; - let link = Self::header(resp.headers(), "link"); - let total = Self::header(resp.headers(), "x-total-count") - .and_then(|v| v.trim().parse::().ok()); - let bytes = Self::body(resp, MAX_JSON_BYTES).await?; - let items: Vec = - serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))?; - let got = items.len(); - out.extend(items); - let done = got == 0 - || match (&link, total) { - (Some(l), _) => !l.contains("rel=\"next\""), - (None, Some(total)) => out.len() >= total, - (None, None) => got < FORGEJO_LIMIT, - }; - if done { - return Ok(out); - } - } - Err(ApiError::TooLarge) - } - - pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult { - let mut current = url.to_owned(); - for _ in 0..=MAX_REDIRECTS { - let resp = self - .send(¤t, "application/octet-stream", true) - .await?; - if resp.status().is_redirection() { - let next = resp - .headers() - .get(LOCATION) - .and_then(|v| v.to_str().ok()) - .ok_or_else(|| ApiError::Http("redirect without a location".into()))?; - let base = - reqwest::Url::parse(¤t).map_err(|e| ApiError::Http(e.to_string()))?; - current = base - .join(next) - .map_err(|e| ApiError::Http(e.to_string()))? - .to_string(); - if !current.starts_with("https://") { - return Err(ApiError::Http("redirect to a non-https address".into())); - } - continue; - } - if let Some(len) = resp.content_length() - && len > max_bytes - { - return Err(ApiError::TooLarge); - } - return Ok(Self::stream(resp, max_bytes)); - } - Err(ApiError::Http("too many redirects".into())) - } - - fn stream(resp: reqwest::Response, max: u64) -> AssetStream { - let mut seen: u64 = 0; - Box::pin(resp.bytes_stream().map(move |chunk| { - let chunk: reqwest::Result = chunk; - let chunk = chunk.map_err(|e| io::Error::other(e.without_url().to_string()))?; - seen = seen.saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); - if seen > max { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "the file is larger than the allowed size", - )); - } - Ok(chunk) - })) - } -} - -fn day(stamp: &str) -> Option { - let d = stamp.get(..10)?; - let ok = d.as_bytes().iter().enumerate().all(|(i, b)| match i { - 4 | 7 => *b == b'-', - _ => b.is_ascii_digit(), - }); - ok.then(|| d.to_owned()) -} - -fn s(v: Option) -> String { - v.unwrap_or_default() -} - -pub struct GitHub { - http: Http, - base: String, -} - -impl GitHub { - pub fn new(http: Http) -> Self { - GitHub { - http, - base: "https://api.github.com".into(), - } - } -} - -#[derive(Deserialize)] -struct GhUser { - login: Option, -} - -#[derive(Deserialize)] -struct GhLabel { - name: String, - color: Option, - description: Option, -} - -#[derive(Deserialize)] -struct GhMilestone { - number: i64, - title: String, - description: Option, - state: String, - due_on: Option, -} - -#[derive(Deserialize)] -struct GhPull { - merged_at: Option, -} - -#[derive(Deserialize)] -struct GhIssue { - number: i64, - title: String, - body: Option, - state: String, - state_reason: Option, - user: Option, - #[serde(default)] - labels: Vec, - milestone: Option, - created_at: Option, - html_url: Option, - pull_request: Option, -} - -#[derive(Deserialize)] -struct GhMilestoneRef { - title: String, -} - -#[derive(Deserialize)] -struct GhComment { - id: i64, - body: Option, - user: Option, - created_at: Option, - html_url: Option, -} - -#[derive(Deserialize)] -struct GhAsset { - id: i64, - name: String, - size: Option, - content_type: Option, - url: String, -} - -#[derive(Deserialize)] -struct GhRelease { - id: i64, - tag_name: String, - name: Option, - body: Option, - #[serde(default)] - draft: bool, - #[serde(default)] - prerelease: bool, - author: Option, - created_at: Option, - html_url: Option, - #[serde(default)] - assets: Vec, -} - -#[derive(Deserialize)] -struct GhRepo { - name: String, - full_name: String, - description: Option, - #[serde(default)] - private: bool, - #[serde(default)] - fork: bool, - #[serde(default)] - archived: bool, - default_branch: Option, - html_url: Option, -} - -fn login(u: Option) -> String { - u.and_then(|u| u.login).unwrap_or_default() -} - -fn release_title(name: Option, tag: &str) -> String { - name.filter(|n| !n.is_empty()) - .unwrap_or_else(|| tag.to_owned()) -} - -async fn or_user( - org: ApiResult>, - user: impl Future>>, -) -> ApiResult> { - match org { - Err(ApiError::NotFound(_)) => user.await, - other => other, - } -} - -#[cfg(test)] -fn parse_github_labels(json: &[u8]) -> ApiResult> { - let raw: Vec = from_json(json)?; - Ok(raw.into_iter().map(label_of).collect()) -} - -fn label_of(l: GhLabel) -> ExtLabel { - ExtLabel { - name: l.name, - color: format!("#{}", s(l.color).trim_start_matches('#')), - description: s(l.description), - } -} - -#[cfg(test)] -fn from_json(json: &[u8]) -> ApiResult { - serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string())) -} - -#[cfg(test)] -fn parse_github_issues(json: &[u8]) -> ApiResult> { - let raw: Vec = from_json(json)?; - Ok(raw.into_iter().map(gh_issue).collect()) -} - -fn gh_issue(i: GhIssue) -> ExtIssue { - let merged = i - .pull_request - .as_ref() - .is_some_and(|p| p.merged_at.is_some()); - ExtIssue { - number: i.number, - title: i.title, - body: s(i.body), - closed: i.state == "closed", - not_planned: i.state_reason.as_deref() == Some("not_planned"), - merged, - author: login(i.user), - labels: i.labels.into_iter().map(|l| l.name).collect(), - milestone: i.milestone.map(|m| m.title), - created_at: s(i.created_at), - url: s(i.html_url), - is_pr: i.pull_request.is_some(), - } -} - -#[cfg(test)] -fn parse_github_releases(json: &[u8]) -> ApiResult> { - let raw: Vec = from_json(json)?; - Ok(raw - .into_iter() - .map(|r| ExtRelease { - id: r.id.to_string(), - title: r - .name - .filter(|n| !n.is_empty()) - .unwrap_or_else(|| r.tag_name.clone()), - tag: r.tag_name, - body: s(r.body), - draft: r.draft, - prerelease: r.prerelease, - author: login(r.author), - created_at: s(r.created_at), - url: s(r.html_url), - assets: r - .assets - .into_iter() - .map(|a| ExtAsset { - id: a.id.to_string(), - name: a.name, - size: a.size.unwrap_or(0), - content_type: s(a.content_type), - url: a.url, - }) - .collect(), - }) - .collect()) -} - -impl RemoteApi for GitHub { - async fn list_repos(&self, owner: &str) -> ApiResult> { - if !valid_segment(owner) { - return Err(ApiError::NotFound("owner".into())); - } - let org: ApiResult> = self - .http - .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base)) - .await; - let raw = or_user( - org, - self.http - .pages(&format!("{}/users/{owner}/repos?type=owner", self.base)), - ) - .await?; - Ok(raw - .into_iter() - .map(|r| ExtRepo { - name: r.name, - full_name: r.full_name, - description: s(r.description), - private: r.private, - fork: r.fork, - archived: r.archived, - default_branch: s(r.default_branch), - web_url: s(r.html_url), - }) - .collect()) - } - - async fn labels(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .pages(&format!("{}/repos/{repo}/labels", self.base)) - .await?; - Ok(raw.into_iter().map(label_of).collect()) - } - - async fn milestones(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .pages(&format!("{}/repos/{repo}/milestones?state=all", self.base)) - .await?; - Ok(raw - .into_iter() - .map(|m| ExtMilestone { - id: m.number.to_string(), - title: m.title, - description: s(m.description), - closed: m.state == "closed", - due_on: m.due_on.as_deref().and_then(day), - }) - .collect()) - } - - async fn issues(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .pages(&format!( - "{}/repos/{repo}/issues?state=all&sort=created&direction=asc", - self.base - )) - .await?; - Ok(raw.into_iter().map(gh_issue).collect()) - } - - async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .pages(&format!( - "{}/repos/{repo}/issues/{}/comments", - self.base, issue.number - )) - .await?; - Ok(raw - .into_iter() - .map(|c| ExtComment { - id: c.id.to_string(), - author: login(c.user), - body: s(c.body), - created_at: s(c.created_at), - url: s(c.html_url), - }) - .collect()) - } - - async fn releases(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .pages(&format!("{}/repos/{repo}/releases", self.base)) - .await?; - Ok(raw.into_iter().map(gh_release).collect()) - } - - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult { - if !asset.url.starts_with("https://api.github.com/") { - return Err(ApiError::Http("unexpected asset address".into())); - } - self.http.download(&asset.url, max_bytes).await - } -} - -fn gh_release(r: GhRelease) -> ExtRelease { - ExtRelease { - id: r.id.to_string(), - title: release_title(r.name, &r.tag_name), - tag: r.tag_name, - body: s(r.body), - draft: r.draft, - prerelease: r.prerelease, - author: login(r.author), - created_at: s(r.created_at), - url: s(r.html_url), - assets: r - .assets - .into_iter() - .map(|a| ExtAsset { - id: a.id.to_string(), - name: a.name, - size: a.size.unwrap_or(0), - content_type: s(a.content_type), - url: a.url, - }) - .collect(), - } -} - -fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> { - if valid_path(repo, min, max) { - Ok(()) - } else { - Err(ApiError::NotFound("repository path".into())) - } -} - -pub struct GitLab { - http: Http, - base: String, -} - -impl GitLab { - pub fn new(http: Http, instance: &str) -> Self { - GitLab { - http, - base: format!("{}/api/v4", instance.trim_end_matches('/')), - } - } - - fn project(&self, repo: &str) -> ApiResult { - check_repo(repo, 2, 20)?; - Ok(format!( - "{}/projects/{}", - self.base, - repo.replace('/', "%2F") - )) - } -} - -#[derive(Deserialize)] -struct GlUser { - username: Option, -} - -#[derive(Deserialize)] -struct GlLabel { - name: String, - color: Option, - description: Option, -} - -#[derive(Deserialize)] -struct GlMilestone { - id: i64, - title: String, - description: Option, - state: String, - due_date: Option, -} - -#[derive(Deserialize)] -struct GlMilestoneRef { - title: String, -} - -#[derive(Deserialize)] -struct GlIssue { - iid: i64, - title: String, - description: Option, - state: String, - author: Option, - #[serde(default)] - labels: Vec, - milestone: Option, - created_at: Option, - web_url: Option, -} - -#[derive(Deserialize)] -struct GlNote { - id: i64, - body: Option, - author: Option, - created_at: Option, - #[serde(default)] - system: bool, -} - -#[derive(Deserialize)] -struct GlLink { - id: i64, - name: String, - url: String, - direct_asset_url: Option, -} - -#[derive(Deserialize, Default)] -struct GlAssets { - #[serde(default)] - links: Vec, -} - -#[derive(Deserialize)] -struct GlRelease { - tag_name: String, - name: Option, - description: Option, - created_at: Option, - #[serde(default)] - upcoming_release: bool, - author: Option, - #[serde(default)] - assets: GlAssets, - #[serde(rename = "_links")] - links: Option, -} - -#[derive(Deserialize)] -struct GlSelf { - #[serde(rename = "self")] - self_url: Option, -} - -#[derive(Deserialize)] -struct GlProject { - path: String, - path_with_namespace: String, - description: Option, - visibility: Option, - default_branch: Option, - web_url: Option, - #[serde(default)] - archived: bool, - forked_from_project: Option, -} - -fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue { - ExtIssue { - number: i.iid, - title: i.title, - body: s(i.description), - closed: i.state != "opened", - not_planned: false, - merged: i.state == "merged", - author: i.author.and_then(|a| a.username).unwrap_or_default(), - labels: i.labels, - milestone: i.milestone.map(|m| m.title), - created_at: s(i.created_at), - url: s(i.web_url), - is_pr, - } -} - -#[cfg(test)] -fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult> { - let raw: Vec = from_json(json)?; - Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect()) -} - -#[cfg(test)] -fn parse_gitlab_releases(json: &[u8]) -> ApiResult> { - let raw: Vec = from_json(json)?; - Ok(raw.into_iter().map(gl_release).collect()) -} - -fn gl_release(r: GlRelease) -> ExtRelease { - ExtRelease { - id: r.tag_name.clone(), - title: release_title(r.name, &r.tag_name), - tag: r.tag_name, - body: s(r.description), - draft: r.upcoming_release, - prerelease: false, - author: r.author.and_then(|a| a.username).unwrap_or_default(), - created_at: s(r.created_at), - url: r.links.and_then(|l| l.self_url).unwrap_or_default(), - assets: r - .assets - .links - .into_iter() - .map(|l| ExtAsset { - id: l.id.to_string(), - name: l.name, - size: 0, - content_type: String::new(), - url: l - .direct_asset_url - .filter(|u| !u.is_empty()) - .unwrap_or(l.url), - }) - .collect(), - } -} - -impl RemoteApi for GitLab { - async fn list_repos(&self, owner: &str) -> ApiResult> { - check_repo(owner, 1, 20)?; - let enc = owner.replace('/', "%2F"); - let group: ApiResult> = self - .http - .pages(&format!( - "{}/groups/{enc}/projects?include_subgroups=false&simple=false", - self.base - )) - .await; - let raw = or_user( - group, - self.http - .pages(&format!("{}/users/{enc}/projects", self.base)), - ) - .await?; - Ok(raw - .into_iter() - .map(|p| ExtRepo { - name: p.path, - full_name: p.path_with_namespace, - description: s(p.description), - private: p.visibility.as_deref() != Some("public"), - fork: p.forked_from_project.is_some(), - archived: p.archived, - default_branch: s(p.default_branch), - web_url: s(p.web_url), - }) - .collect()) - } - - async fn labels(&self, repo: &str) -> ApiResult> { - let raw: Vec = self - .http - .pages(&format!("{}/labels", self.project(repo)?)) - .await?; - Ok(raw - .into_iter() - .map(|l| ExtLabel { - name: l.name, - color: s(l.color), - description: s(l.description), - }) - .collect()) - } - - async fn milestones(&self, repo: &str) -> ApiResult> { - let raw: Vec = self - .http - .pages(&format!("{}/milestones", self.project(repo)?)) - .await?; - Ok(raw - .into_iter() - .map(|m| ExtMilestone { - id: m.id.to_string(), - title: m.title, - description: s(m.description), - closed: m.state == "closed", - due_on: m.due_date.as_deref().and_then(day), - }) - .collect()) - } - - async fn issues(&self, repo: &str) -> ApiResult> { - let project = self.project(repo)?; - let issues: Vec = self - .http - .pages(&format!( - "{project}/issues?state=all&order_by=created_at&sort=asc" - )) - .await?; - let pulls: Vec = self - .http - .pages(&format!( - "{project}/merge_requests?state=all&order_by=created_at&sort=asc" - )) - .await?; - let mut out: Vec = issues.into_iter().map(|i| gl_issue(i, false)).collect(); - out.extend(pulls.into_iter().map(|i| gl_issue(i, true))); - Ok(out) - } - - async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult> { - let kind = if issue.is_pr { - "merge_requests" - } else { - "issues" - }; - let raw: Vec = self - .http - .pages(&format!( - "{}/{kind}/{}/notes?sort=asc&order_by=created_at", - self.project(repo)?, - issue.number - )) - .await?; - Ok(raw - .into_iter() - .filter(|n| !n.system) - .map(|n| ExtComment { - id: n.id.to_string(), - author: n.author.and_then(|a| a.username).unwrap_or_default(), - body: s(n.body), - created_at: s(n.created_at), - url: format!("{}#note_{}", issue.url, n.id), - }) - .collect()) - } - - async fn releases(&self, repo: &str) -> ApiResult> { - let raw: Vec = self - .http - .pages(&format!("{}/releases", self.project(repo)?)) - .await?; - Ok(raw.into_iter().map(gl_release).collect()) - } - - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult { - if !asset.url.starts_with("https://") { - return Err(ApiError::Http("unexpected asset address".into())); - } - self.http.download(&asset.url, max_bytes).await - } -} - -pub struct Forgejo { - http: Http, - origin: String, - base: String, -} - -impl Forgejo { - pub fn new(http: Http, instance: &str) -> Self { - let origin = instance.trim_end_matches('/').to_owned(); - Forgejo { - http, - base: format!("{origin}/api/v1"), - origin, - } - } -} - -#[derive(Deserialize)] -struct FjUser { - login: Option, - username: Option, -} - -fn fj_user(u: Option) -> String { - u.and_then(|u| u.login.filter(|l| !l.is_empty()).or(u.username)) - .unwrap_or_default() -} - -#[derive(Deserialize)] -struct FjLabel { - name: String, - color: Option, - description: Option, -} - -#[derive(Deserialize)] -struct FjMilestone { - id: i64, - title: String, - description: Option, - state: String, - due_on: Option, -} - -#[derive(Deserialize)] -struct FjMilestoneRef { - title: String, -} - -#[derive(Deserialize)] -struct FjIssue { - number: i64, - title: String, - body: Option, - state: String, - user: Option, - #[serde(default)] - labels: Vec, - milestone: Option, - created_at: Option, - html_url: Option, - #[serde(default)] - merged: bool, -} - -#[derive(Deserialize)] -struct FjComment { - id: i64, - body: Option, - user: Option, - created_at: Option, - html_url: Option, -} - -#[derive(Deserialize)] -struct FjAsset { - id: i64, - name: String, - size: Option, - browser_download_url: String, -} - -#[derive(Deserialize)] -struct FjRelease { - id: i64, - tag_name: String, - name: Option, - body: Option, - #[serde(default)] - draft: bool, - #[serde(default)] - prerelease: bool, - author: Option, - created_at: Option, - html_url: Option, - #[serde(default)] - assets: Vec, -} - -#[derive(Deserialize)] -struct FjRepo { - name: String, - full_name: String, - description: Option, - #[serde(default)] - private: bool, - #[serde(default)] - fork: bool, - #[serde(default)] - archived: bool, - default_branch: Option, - html_url: Option, -} - -fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue { - ExtIssue { - number: i.number, - title: i.title, - body: s(i.body), - closed: i.state != "open", - not_planned: false, - merged: is_pr && i.merged, - author: fj_user(i.user), - labels: i.labels.into_iter().map(|l| l.name).collect(), - milestone: i.milestone.map(|m| m.title), - created_at: s(i.created_at), - url: s(i.html_url), - is_pr, - } -} - -fn fj_release(r: FjRelease) -> ExtRelease { - ExtRelease { - id: r.id.to_string(), - title: release_title(r.name, &r.tag_name), - tag: r.tag_name, - body: s(r.body), - draft: r.draft, - prerelease: r.prerelease, - author: fj_user(r.author), - created_at: s(r.created_at), - url: s(r.html_url), - assets: r - .assets - .into_iter() - .map(|a| ExtAsset { - id: a.id.to_string(), - name: a.name, - size: a.size.unwrap_or(0), - content_type: String::new(), - url: a.browser_download_url, - }) - .collect(), - } -} - -impl RemoteApi for Forgejo { - async fn list_repos(&self, owner: &str) -> ApiResult> { - let raw: Vec = if owner.is_empty() { - self.http - .limit_pages(&format!("{}/user/repos", self.base)) - .await? - } else { - if !valid_segment(owner) { - return Err(ApiError::NotFound("owner".into())); - } - let org: ApiResult> = self - .http - .limit_pages(&format!("{}/orgs/{owner}/repos", self.base)) - .await; - or_user( - org, - self.http - .limit_pages(&format!("{}/users/{owner}/repos", self.base)), - ) - .await? - }; - Ok(raw - .into_iter() - .map(|r| ExtRepo { - name: r.name, - full_name: r.full_name, - description: s(r.description), - private: r.private, - fork: r.fork, - archived: r.archived, - default_branch: s(r.default_branch), - web_url: s(r.html_url), - }) - .collect()) - } - - async fn labels(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .limit_pages(&format!("{}/repos/{repo}/labels", self.base)) - .await?; - Ok(raw - .into_iter() - .map(|l| ExtLabel { - name: l.name, - color: format!("#{}", s(l.color).trim_start_matches('#')), - description: s(l.description), - }) - .collect()) - } - - async fn milestones(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .limit_pages(&format!("{}/repos/{repo}/milestones?state=all", self.base)) - .await?; - Ok(raw - .into_iter() - .map(|m| ExtMilestone { - id: m.id.to_string(), - title: m.title, - description: s(m.description), - closed: m.state == "closed", - due_on: m.due_on.as_deref().and_then(day), - }) - .collect()) - } - - async fn issues(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let issues: Vec = self - .http - .limit_pages(&format!( - "{}/repos/{repo}/issues?type=issues&state=all&sort=oldest", - self.base - )) - .await?; - let pulls: Vec = self - .http - .limit_pages(&format!( - "{}/repos/{repo}/pulls?state=all&sort=oldest", - self.base - )) - .await?; - let mut out: Vec = issues.into_iter().map(|i| fj_issue(i, false)).collect(); - out.extend(pulls.into_iter().map(|i| fj_issue(i, true))); - Ok(out) - } - - async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .limit_pages(&format!( - "{}/repos/{repo}/issues/{}/comments", - self.base, issue.number - )) - .await?; - Ok(raw - .into_iter() - .map(|c| ExtComment { - id: c.id.to_string(), - author: fj_user(c.user), - body: s(c.body), - created_at: s(c.created_at), - url: s(c.html_url), - }) - .collect()) - } - - async fn releases(&self, repo: &str) -> ApiResult> { - check_repo(repo, 2, 2)?; - let raw: Vec = self - .http - .limit_pages(&format!("{}/repos/{repo}/releases", self.base)) - .await?; - Ok(raw.into_iter().map(fj_release).collect()) - } - - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult { - if !asset.url.starts_with(&format!("{}/", self.origin)) { - return Err(ApiError::Http("unexpected asset address".into())); - } - self.http.download(&asset.url, max_bytes).await - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn segments_reject_traversal_and_separators() { - assert!(valid_segment("tahinli")); - assert!(valid_segment("my-repo_1.rs")); - assert!(!valid_segment("..")); - assert!(!valid_segment("a/b")); - assert!(!valid_segment("a?b")); - assert!(!valid_segment("")); - assert!(valid_path("tahinli/forge", 2, 2)); - assert!(!valid_path("tahinli", 2, 2)); - assert!(!valid_path("a/b/c", 2, 2)); - assert!(valid_path("grp/sub/proj", 2, 20)); - } - - #[test] - fn wait_text_reads_naturally() { - assert_eq!(wait_text(45), "45 seconds"); - assert_eq!(wait_text(60), "1 minute"); - assert_eq!(wait_text(3188), "54 minutes"); - assert_eq!(wait_text(3600), "1 hour"); - assert_eq!(wait_text(3661), "1 hour 2 minutes"); - } - - #[test] - fn rate_limit_waits_follow_the_headers() { - assert_eq!(rate_wait(Some("30"), None, None, 100), Some(30)); - assert_eq!(rate_wait(None, Some("0"), Some("160"), 100), Some(60)); - assert_eq!(rate_wait(None, Some("0"), Some("90"), 100), Some(1)); - assert_eq!(rate_wait(None, Some("12"), Some("160"), 100), None); - assert_eq!(rate_wait(None, None, None, 100), None); - assert_eq!(rate_wait(None, Some("0"), None, 100), None); - } - - #[test] - fn github_issues_and_pulls_parse() { - let json = br##"[ - {"number":1,"title":"Bug","body":"it breaks","state":"closed","state_reason":"not_planned", - "user":{"login":"octocat"},"labels":[{"name":"bug","color":"d73a4a"}], - "milestone":{"title":"v1"},"created_at":"2020-01-02T03:04:05Z", - "html_url":"https://github.com/o/r/issues/1"}, - {"number":2,"title":"Add x","body":null,"state":"closed","user":{"login":"hubot"}, - "labels":[],"milestone":null,"created_at":"2020-02-02T00:00:00Z", - "html_url":"https://github.com/o/r/pull/2","pull_request":{"merged_at":"2020-02-03T00:00:00Z"}} - ]"##; - let items = parse_github_issues(json).unwrap(); - assert_eq!(items.len(), 2); - assert!(items[0].closed && items[0].not_planned && !items[0].is_pr); - assert_eq!(items[0].labels, vec!["bug"]); - assert_eq!(items[0].milestone.as_deref(), Some("v1")); - assert!(items[1].is_pr && items[1].merged); - assert_eq!(items[1].body, ""); - assert_eq!(items[1].author, "hubot"); - } - - #[test] - fn github_labels_get_a_hash() { - let labels = - parse_github_labels(br#"[{"name":"bug","color":"d73a4a","description":null}]"#) - .unwrap(); - assert_eq!(labels[0].color, "#d73a4a"); - assert_eq!(labels[0].description, ""); - } - - #[test] - fn github_releases_carry_assets() { - let json = br#"[{"id":7,"tag_name":"v1.0","name":"","body":"notes","draft":false, - "prerelease":true,"author":{"login":"octocat"},"created_at":"2021-01-01T00:00:00Z", - "html_url":"https://github.com/o/r/releases/tag/v1.0", - "assets":[{"id":9,"name":"app.tar.gz","size":12,"content_type":"application/gzip", - "url":"https://api.github.com/repos/o/r/releases/assets/9"}]}]"#; - let rel = parse_github_releases(json).unwrap(); - assert_eq!(rel[0].title, "v1.0", "a blank name falls back to the tag"); - assert!(rel[0].prerelease); - assert_eq!(rel[0].assets[0].name, "app.tar.gz"); - assert_eq!(rel[0].assets[0].size, 12); - } - - #[test] - fn gitlab_states_map() { - let json = br#"[ - {"iid":3,"title":"MR","description":"d","state":"merged","author":{"username":"tahinli"}, - "labels":["x"],"milestone":null,"created_at":"2022-01-01T00:00:00Z","web_url":"https://gl/x/-/merge_requests/3"}, - {"iid":4,"title":"open","description":null,"state":"opened","author":null,"labels":[], - "created_at":null,"web_url":null}]"#; - let items = parse_gitlab_issues(json, true).unwrap(); - assert!(items[0].closed && items[0].merged && items[0].is_pr); - assert!(!items[1].closed); - assert_eq!(items[1].author, ""); - } - - #[test] - fn gitlab_release_links_become_assets() { - let json = br#"[{"tag_name":"v2","name":"Two","description":"n","created_at":"2022-01-01T00:00:00Z", - "assets":{"links":[{"id":1,"name":"bin","url":"https://x/a","direct_asset_url":"https://x/direct"}]}}]"#; - let rel = parse_gitlab_releases(json).unwrap(); - assert_eq!(rel[0].assets[0].url, "https://x/direct"); - assert_eq!(rel[0].tag, "v2"); - } - - #[test] - fn day_keeps_only_a_valid_date_prefix() { - assert_eq!(day("2020-05-06T00:00:00Z").as_deref(), Some("2020-05-06")); - assert_eq!(day("garbage!!!").as_deref(), None); - assert_eq!(day("x").as_deref(), None); - } -} diff --git a/crates/forge-web-app/src/importer/mod.rs b/crates/forge-web-app/src/importer/mod.rs deleted file mode 100644 index 99eeec8..0000000 --- a/crates/forge-web-app/src/importer/mod.rs +++ /dev/null @@ -1,1088 +0,0 @@ -pub mod api; -pub mod remote; - -use std::collections::HashMap; -use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError}; -use std::time::Duration; - -use forge_core::issues::{IssueState, MAX_BODY, MAX_TITLE, StateReason}; -use forge_core::releases::{MAX_ASSET_NAME_LEN, NewRelease}; -use forge_core::store::imports::{ImportJob, ImportOrigin, ImportState}; -use forge_core::{Repo, Store, User}; -use forge_git::mirror::{RemoteAuth, mirror_fetch}; -use serde::{Deserialize, Serialize}; -use tokio::sync::{Semaphore, watch}; - -use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi}; -pub use self::remote::{ - default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, -}; -use crate::live::Topic; -use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; -use crate::state::AppState; - -const GIT_TIMEOUT: Duration = Duration::from_secs(60 * 60); -static SLOTS: Semaphore = Semaphore::const_new(2); -const IMPORTED_PR_LABEL: &str = "imported PR"; -const IMPORTED_PR_COLOR: &str = "#8b7bd8"; -const FALLBACK_LABEL_COLOR: &str = "#8b949e"; -const IMPORT_BUMP_BATCH: usize = 25; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Source { - Git, - GitHub, - GitLab, - Forgejo, -} - -impl Source { - pub fn as_str(self) -> &'static str { - match self { - Source::Git => "git", - Source::GitHub => "github", - Source::GitLab => "gitlab", - Source::Forgejo => "forgejo", - } - } - - pub fn parse(s: &str) -> Option { - match s { - "git" => Some(Source::Git), - "github" => Some(Source::GitHub), - "gitlab" => Some(Source::GitLab), - "forgejo" | "gitea" => Some(Source::Forgejo), - _ => None, - } - } - - pub fn label(self) -> &'static str { - match self { - Source::Git => "git", - Source::GitHub => "GitHub", - Source::GitLab => "GitLab", - Source::Forgejo => "Forgejo", - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct ImportOptions { - #[serde(default)] - pub labels: bool, - #[serde(default)] - pub issues: bool, - #[serde(default)] - pub pulls: bool, - #[serde(default)] - pub releases: bool, -} - -impl ImportOptions { - pub fn any_api(&self) -> bool { - self.labels || self.issues || self.pulls || self.releases - } -} - -#[derive(Clone)] -pub struct JobSpec { - pub source: Source, - pub remote: String, - pub instance: String, - pub token: Option, - pub git_user: String, - pub options: ImportOptions, -} - -impl std::fmt::Debug for JobSpec { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("JobSpec") - .field("source", &self.source) - .field("remote", &self.remote) - .field("token", &self.token.as_ref().map(|_| "[redacted]")) - .finish() - } -} - -impl JobSpec { - pub fn clone_url(&self) -> String { - match self.source { - Source::Git => self.remote.clone(), - Source::GitHub => format!("https://github.com/{}.git", self.remote), - Source::GitLab | Source::Forgejo => format!( - "{}/{}.git", - self.instance.trim_end_matches('/'), - self.remote - ), - } - } - - fn auth(&self) -> Option { - let token = self.token.as_ref().filter(|t| !t.is_empty())?; - let username = match self.source { - Source::GitHub => "x-access-token".to_owned(), - Source::GitLab | Source::Forgejo => "oauth2".to_owned(), - Source::Git if self.git_user.is_empty() => "git".to_owned(), - Source::Git => self.git_user.clone(), - }; - Some(RemoteAuth { - username, - secret: token.clone().into_bytes(), - }) - } -} - -#[derive(Clone)] -pub enum Transport { - Net, - #[cfg(any(test, feature = "test-support"))] - Local(String), -} - -static HUB: LazyLock>>> = - LazyLock::new(|| Mutex::new(HashMap::new())); - -fn hub() -> MutexGuard<'static, HashMap>> { - HUB.lock().unwrap_or_else(PoisonError::into_inner) -} - -pub fn subscribe(job_id: &str) -> watch::Receiver { - hub() - .entry(job_id.to_owned()) - .or_insert_with(|| watch::channel(0).0) - .subscribe() -} - -fn bump(job_id: &str) { - let mut hub = hub(); - if let Some(tx) = hub.get(job_id) { - tx.send_modify(|n| *n = n.wrapping_add(1)); - if tx.receiver_count() == 0 { - hub.remove(job_id); - } - } -} - -fn close(job_id: &str) { - if let Some(tx) = hub().remove(job_id) { - tx.send_modify(|n| *n = n.wrapping_add(1)); - } -} - -#[derive(Clone)] -struct Reporter { - store: Store, - job_id: String, -} - -impl Reporter { - async fn log(&self, level: &str, message: impl AsRef) { - if let Err(e) = self - .store - .add_import_event(&self.job_id, level, message.as_ref()) - .await - { - tracing::warn!(error = %e, "import: could not record a progress line"); - } - bump(&self.job_id); - } - - async fn stage(&self, stage: &str, done: usize, total: usize) { - let (done, total) = (done as i64, total as i64); - if let Err(e) = self - .store - .set_import_progress(&self.job_id, stage, done, total) - .await - { - tracing::warn!(error = %e, "import: could not record progress"); - } - bump(&self.job_id); - } -} - -pub fn origin_note(source: &str, author: &str, created: &str, url: &str) -> String { - let clean: String = author - .chars() - .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) - .take(60) - .collect(); - let who = if clean.is_empty() { "unknown" } else { &clean }; - let date: String = created.chars().take(10).collect(); - let mut line = format!("> Originally by \\@{who} on {source}"); - if !date.is_empty() && date.bytes().all(|b| b.is_ascii_digit() || b == b'-') { - line.push_str(", "); - line.push_str(&date); - } - let safe_url = url.starts_with("https://") - && !url - .chars() - .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ')' | '(' | '<' | '>')); - if safe_url { - line.push_str(&format!(", [original]({url})")); - } - line.push_str("\n\n"); - line -} - -pub fn with_note(note: &str, body: &str) -> String { - let mut text = format!("{note}{body}"); - if text.len() > MAX_BODY { - let mut end = MAX_BODY - 16; - while !text.is_char_boundary(end) { - end -= 1; - } - text.truncate(end); - text.push_str("\n\n(cut)"); - } - text -} - -fn clip_title(title: &str) -> String { - let t: String = title - .chars() - .filter(|c| !c.is_control()) - .take(MAX_TITLE) - .collect(); - let t = t.trim(); - if t.is_empty() { - "(untitled)".to_owned() - } else { - t.to_owned() - } -} - -pub fn asset_name(name: &str) -> String { - let cleaned: String = name - .chars() - .map(|c| { - if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') { - c - } else { - '_' - } - }) - .collect(); - let mut out = cleaned.trim_start_matches('.').to_owned(); - out.truncate(MAX_ASSET_NAME_LEN); - if out.is_empty() { - "asset".to_owned() - } else { - out - } -} - -pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { - state.live.bump(&Topic::Imports(job.user_id.clone())); - tokio::spawn(async move { - let Ok(_slot) = SLOTS.acquire().await else { - return; - }; - run_production(&state, &job, &spec).await; - state.live.bump(&Topic::Imports(job.user_id.clone())); - }); -} - -async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { - let rep = Reporter { - store: state.store.clone(), - job_id: job.id.clone(), - }; - let notice: Notice = { - let rep = rep.clone(); - std::sync::Arc::new(move |msg: String| { - let rep = rep.clone(); - tokio::spawn(async move { rep.log("warn", msg).await }); - }) - }; - let wants_api = spec.options.any_api() && spec.source != Source::Git; - if !wants_api { - run_job::(state, job, spec, None, &Transport::Net).await; - return; - } - match spec.source { - Source::GitHub => match make_github(state, spec.token.clone(), notice) { - Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, - Err(e) => fail(state, &rep, &e).await, - }, - Source::GitLab => match make_gitlab(state, &spec.instance, spec.token.clone(), notice) { - Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, - Err(e) => fail(state, &rep, &e).await, - }, - Source::Forgejo => match make_forgejo(state, &spec.instance, spec.token.clone(), notice) { - Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, - Err(e) => fail(state, &rep, &e).await, - }, - Source::Git => run_job::(state, job, spec, None, &Transport::Net).await, - } -} - -async fn fail(state: &AppState, rep: &Reporter, message: &str) { - tracing::warn!(job = %rep.job_id, %message, "import failed"); - rep.log("error", message).await; - if let Err(e) = state - .store - .set_import_state(&rep.job_id, ImportState::Failed, Some(message)) - .await - { - tracing::error!(error = %e, "import: could not record a failure"); - } - close(&rep.job_id); -} - -pub async fn run_job( - state: &AppState, - job: &ImportJob, - spec: &JobSpec, - api: Option<&A>, - transport: &Transport, -) { - let rep = Reporter { - store: state.store.clone(), - job_id: job.id.clone(), - }; - if let Err(e) = state - .store - .set_import_state(&job.id, ImportState::Running, None) - .await - { - tracing::error!(error = %e, "import: could not start the job"); - return; - } - bump(&job.id); - state.live.bump(&Topic::Imports(job.user_id.clone())); - match run_steps(state, job, spec, api, transport, &rep).await { - Ok(summary) => { - rep.log("info", summary).await; - rep.stage("done", 0, 0).await; - if let Err(e) = state - .store - .set_import_state(&job.id, ImportState::Done, None) - .await - { - tracing::error!(error = %e, "import: could not finish the job"); - } - close(&job.id); - } - Err(message) => fail(state, &rep, &message).await, - } -} - -async fn run_steps( - state: &AppState, - job: &ImportJob, - spec: &JobSpec, - api: Option<&A>, - transport: &Transport, - rep: &Reporter, -) -> Result { - let repo_id = job.repo_id.clone().ok_or("the repository is gone")?; - let repo = state - .store - .repo_by_id(&repo_id) - .await - .map_err(|e| e.to_string())? - .ok_or("the repository is gone")?; - let user = state - .store - .user_by_id(&job.user_id) - .await - .map_err(|e| e.to_string())? - .ok_or("the importing user is gone")?; - - rep.stage("git", 0, 0).await; - rep.log("info", "Fetching branches and tags").await; - fetch_git(state, &repo, spec, transport).await?; - let repo = sync_default_branch(state, repo, rep).await; - rep.log("info", "Git data imported").await; - - let (Some(api), true) = (api, spec.options.any_api()) else { - return Ok("Import finished".to_owned()); - }; - let run = Run { - state, - rep, - repo: &repo, - user: &user, - api, - spec, - }; - let mut totals = Totals::default(); - if spec.options.labels { - run.labels(&mut totals).await?; - run.milestones(&mut totals).await?; - } - if spec.options.issues || spec.options.pulls { - run.issues(&mut totals).await?; - } - if spec.options.releases { - run.releases(&mut totals).await?; - } - Ok(format!( - "Import finished: {} labels, {} milestones, {} issues, {} pull requests, {} comments, {} releases, {} assets{}", - totals.labels, - totals.milestones, - totals.issues, - totals.pulls, - totals.comments, - totals.releases, - totals.assets, - if totals.skipped > 0 { - format!(", {} skipped", totals.skipped) - } else { - String::new() - } - )) -} - -async fn fetch_git( - state: &AppState, - repo: &Repo, - spec: &JobSpec, - transport: &Transport, -) -> Result<(), String> { - let repo_dir = - forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; - let url = spec.clone_url(); - let fetch = async { - match transport { - Transport::Net => { - let policy = policy(state); - let pin = check_remote(&url, &policy).await?; - let auth = spec.auth(); - mirror_fetch( - &state.git, - &repo_dir, - &url, - auth.as_ref(), - policy.allow_http, - pin.as_ref(), - GIT_TIMEOUT, - ) - .await - .map_err(|e| e.to_string()) - } - #[cfg(any(test, feature = "test-support"))] - Transport::Local(path) => { - forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT) - .await - .map_err(|e| e.to_string()) - } - } - }; - pull_refs(state, repo, fetch).await.map(|_| ()) -} - -async fn sync_default_branch(state: &AppState, repo: Repo, rep: &Reporter) -> Repo { - let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) else { - return repo; - }; - let head = forge_git::command::GitCommand::new(&state.git, "symbolic-ref") - .git_dir(&dir) - .arg("--short") - .arg("HEAD") - .output() - .await - .ok() - .map(|out| String::from_utf8_lossy(&out).trim().to_owned()) - .filter(|b| !b.is_empty()); - let Some(head) = head else { - return repo; - }; - if head == repo.default_branch { - return repo; - } - if let Err(e) = state - .store - .update_repo_general(&repo.id, &repo.description, &head) - .await - { - rep.log("warn", format!("could not set the default branch: {e}")) - .await; - return repo; - } - state - .store - .repo_by_id(&repo.id) - .await - .ok() - .flatten() - .unwrap_or(repo) -} - -#[derive(Default)] -struct Totals { - labels: usize, - milestones: usize, - issues: usize, - pulls: usize, - comments: usize, - releases: usize, - assets: usize, - skipped: usize, -} - -struct Run<'a, A> { - state: &'a AppState, - rep: &'a Reporter, - repo: &'a Repo, - user: &'a User, - api: &'a A, - spec: &'a JobSpec, -} - -impl Run<'_, A> { - fn store(&self) -> &Store { - &self.state.store - } - - fn bump_issues(&self) { - self.state.live.bump_repo_issues(&self.repo.id); - } - - async fn mapped(&self, kind: &str, ext: &str) -> Result, String> { - self.store() - .import_origin(&self.repo.id, kind, ext) - .await - .map_err(|e| e.to_string()) - } - - async fn record(&self, kind: &str, ext: &str, local: &str, author: &str, url: &str) { - let origin = ImportOrigin { - local_id: local.to_owned(), - author: author.to_owned(), - url: url.to_owned(), - }; - if let Err(e) = self - .store() - .record_import_origin(&self.repo.id, kind, ext, &origin) - .await - { - tracing::warn!(error = %e, "import: could not record an id mapping"); - } - } - - async fn labels(&self, totals: &mut Totals) -> Result<(), String> { - self.rep.stage("labels", 0, 0).await; - let labels = self - .api - .labels(&self.spec.remote) - .await - .map_err(|e| e.to_string())?; - let total = labels.len(); - for (i, label) in labels.into_iter().enumerate() { - self.rep.stage("labels", i, total).await; - let key = label.name.to_lowercase(); - if self.mapped("label", &key).await?.is_some() { - continue; - } - let description: String = label - .description - .chars() - .take(forge_core::issues::MAX_LABEL_DESCRIPTION) - .collect(); - match self - .store() - .create_label(&self.repo.id, &label.name, &label.color, &description) - .await - { - Ok(created) => { - self.record("label", &key, &created.id, "", "").await; - totals.labels += 1; - } - Err(forge_core::Error::Conflict(_)) => {} - Err(e) => { - totals.skipped += 1; - self.rep - .log("warn", format!("label `{}` skipped: {e}", label.name)) - .await; - } - } - } - self.bump_issues(); - self.rep.log("info", format!("{total} labels read")).await; - Ok(()) - } - - async fn milestones(&self, totals: &mut Totals) -> Result<(), String> { - self.rep.stage("milestones", 0, 0).await; - let items = self - .api - .milestones(&self.spec.remote) - .await - .map_err(|e| e.to_string())?; - let total = items.len(); - for (i, m) in items.into_iter().enumerate() { - self.rep.stage("milestones", i, total).await; - if self.mapped("milestone", &m.id).await?.is_some() { - continue; - } - let created = match self - .store() - .create_milestone(&self.repo.id, &m.title, &m.description, m.due_on.as_deref()) - .await - { - Ok(created) => created, - Err(e) => { - totals.skipped += 1; - self.rep - .log("warn", format!("milestone `{}` skipped: {e}", m.title)) - .await; - continue; - } - }; - if m.closed - && let Err(e) = self - .store() - .update_milestone( - &self.repo.id, - &created.id, - &created.title, - &created.description, - created.due_on.as_deref(), - IssueState::Closed, - ) - .await - { - self.rep - .log("warn", format!("milestone `{}` stays open: {e}", m.title)) - .await; - } - self.record("milestone", &m.id, &created.id, "", "").await; - totals.milestones += 1; - } - self.bump_issues(); - Ok(()) - } - - async fn label_id( - &self, - cache: &mut HashMap, - name: &str, - color: &str, - ) -> Option { - let key = name.trim().to_lowercase(); - if let Some(id) = cache.get(&key) { - return Some(id.clone()); - } - match self - .store() - .create_label(&self.repo.id, name, color, "") - .await - { - Ok(label) => { - cache.insert(key, label.id.clone()); - Some(label.id) - } - Err(e) => { - self.rep - .log("warn", format!("label `{name}` not set: {e}")) - .await; - None - } - } - } - - async fn issues(&self, totals: &mut Totals) -> Result<(), String> { - self.rep.stage("issues", 0, 0).await; - let mut items: Vec = self - .api - .issues(&self.spec.remote) - .await - .map_err(|e| e.to_string())? - .into_iter() - .filter(|i| { - if i.is_pr { - self.spec.options.pulls - } else { - self.spec.options.issues - } - }) - .collect(); - if matches!(self.spec.source, Source::GitHub | Source::Forgejo) { - items.sort_by_key(|i| i.number); - } else { - items.sort_by_key(|i| (i.is_pr, i.number)); - } - let total = items.len(); - let mut labels: HashMap = self - .store() - .list_labels(&self.repo.id) - .await - .map_err(|e| e.to_string())? - .into_iter() - .map(|l| (l.name.to_lowercase(), l.id)) - .collect(); - let milestones: HashMap = self - .store() - .list_milestones(&self.repo.id, None) - .await - .map_err(|e| e.to_string())? - .into_iter() - .map(|m| (m.title.to_lowercase(), m.id)) - .collect(); - self.rep - .log( - "info", - format!("Importing {total} issues and pull requests"), - ) - .await; - let mut created_since_bump = 0usize; - for (i, item) in items.iter().enumerate() { - self.rep.stage("issues", i, total).await; - let kind = if item.is_pr { "pull" } else { "issue" }; - let ext = item.number.to_string(); - let local = match self.mapped(kind, &ext).await? { - Some(o) => o.local_id, - None => match self.create_item(item, &mut labels, &milestones).await { - Ok(id) => { - created_since_bump += 1; - if created_since_bump == IMPORT_BUMP_BATCH { - created_since_bump = 0; - self.bump_issues(); - } - if item.is_pr { - totals.pulls += 1; - } else { - totals.issues += 1; - } - id - } - Err(e) => { - totals.skipped += 1; - self.rep - .log("warn", format!("#{} skipped: {e}", item.number)) - .await; - continue; - } - }, - }; - self.import_comments(kind, &local, item, totals).await?; - } - self.rep.stage("issues", total, total).await; - self.bump_issues(); - Ok(()) - } - - async fn import_comments( - &self, - kind: &str, - local: &str, - item: &ExtIssue, - totals: &mut Totals, - ) -> Result<(), String> { - let comments = self - .api - .comments(&self.spec.remote, item) - .await - .map_err(|e| e.to_string())?; - for c in comments { - if self - .mapped("comment", &format!("{kind}:{}", c.id)) - .await? - .is_some() - { - continue; - } - let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url); - let body = with_note(¬e, &c.body); - match self.store().add_comment(local, &self.user.id, &body).await { - Ok(created) => { - self.record( - "comment", - &format!("{kind}:{}", c.id), - &created.id, - &c.author, - &c.url, - ) - .await; - totals.comments += 1; - } - Err(e) => { - totals.skipped += 1; - self.rep - .log( - "warn", - format!("a comment on #{} skipped: {e}", item.number), - ) - .await; - } - } - } - Ok(()) - } - - async fn create_item( - &self, - item: &ExtIssue, - labels: &mut HashMap, - milestones: &HashMap, - ) -> Result { - let source = self.spec.source.label(); - let mut note = origin_note(source, &item.author, &item.created_at, &item.url); - if item.is_pr { - let how = if item.merged { - "merged" - } else if item.closed { - "closed" - } else { - "open" - }; - note.push_str(&format!( - "> Imported pull request ({how}). Its branches may no longer exist, so there is nothing to merge here.\n\n" - )); - } - let body = with_note(¬e, &item.body); - let issue = self - .store() - .create_issue( - &self.repo.id, - &self.user.id, - &clip_title(&item.title), - &body, - ) - .await?; - let kind = if item.is_pr { "pull" } else { "issue" }; - self.record( - kind, - &item.number.to_string(), - &issue.id, - &item.author, - &item.url, - ) - .await; - let mut ids = Vec::new(); - for name in &item.labels { - if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await { - ids.push(id); - } - } - if item.is_pr - && let Some(id) = self - .label_id(labels, IMPORTED_PR_LABEL, IMPORTED_PR_COLOR) - .await - { - ids.push(id); - } - if !ids.is_empty() { - self.store() - .set_issue_labels(&issue.id, &self.user.id, &ids) - .await?; - } - if let Some(id) = item - .milestone - .as_ref() - .and_then(|t| milestones.get(&t.to_lowercase())) - { - self.store() - .set_issue_milestone(&issue.id, &self.user.id, Some(id)) - .await?; - } - if item.closed { - let reason = if item.not_planned { - StateReason::NotPlanned - } else { - StateReason::Completed - }; - self.store() - .set_issue_state( - &issue.id, - Some(&self.user.id), - IssueState::Closed, - Some(reason), - serde_json::Value::Null, - ) - .await?; - } - Ok(issue.id) - } - - async fn releases(&self, totals: &mut Totals) -> Result<(), String> { - self.rep.stage("releases", 0, 0).await; - let releases = self - .api - .releases(&self.spec.remote) - .await - .map_err(|e| e.to_string())?; - let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id) - .map_err(|e| e.to_string())?; - let refs = ref_snapshot(self.state, &repo_dir).await?; - let max_bytes = self.state.live().releases.max_asset_mb * 1024 * 1024; - let total = releases.len(); - for (i, rel) in releases.iter().enumerate() { - self.rep.stage("releases", i, total).await; - let Some(release) = self.release_of(rel, &refs, totals).await? else { - continue; - }; - for asset in &rel.assets { - self.asset(&release, rel, asset, max_bytes, totals).await?; - } - } - self.rep.stage("releases", total, total).await; - Ok(()) - } - - async fn release_of( - &self, - rel: &ExtRelease, - refs: &std::collections::BTreeMap, - totals: &mut Totals, - ) -> Result, String> { - if let Some(o) = self.mapped("release", &rel.id).await? { - let found = self - .store() - .release(&o.local_id) - .await - .map_err(|e| e.to_string())?; - if found.is_none() { - totals.skipped += 1; - self.rep - .log( - "warn", - format!("release `{}` skipped: it was deleted here", rel.tag), - ) - .await; - } - return Ok(found); - } - let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else { - totals.skipped += 1; - self.rep - .log( - "warn", - format!( - "release `{}` skipped: its tag is not in the git data", - rel.tag - ), - ) - .await; - return Ok(None); - }; - if let Some(existing) = self - .store() - .release_by_tag(&self.repo.id, &rel.tag) - .await - .map_err(|e| e.to_string())? - { - self.record("release", &rel.id, &existing.id, &rel.author, &rel.url) - .await; - return Ok(Some(existing)); - } - let note = origin_note( - self.spec.source.label(), - &rel.author, - &rel.created_at, - &rel.url, - ); - let body = with_note(¬e, &rel.body); - let title = clip_title(&rel.title); - let created = self - .store() - .create_release(&NewRelease { - repo_id: &self.repo.id, - tag: &rel.tag, - target_oid: oid, - title: &title, - body: &body, - draft: rel.draft, - prerelease: rel.prerelease, - author_id: &self.user.id, - }) - .await; - match created { - Ok(release) => { - self.record("release", &rel.id, &release.id, &rel.author, &rel.url) - .await; - totals.releases += 1; - Ok(Some(release)) - } - Err(e) => { - totals.skipped += 1; - self.rep - .log("warn", format!("release `{}` skipped: {e}", rel.tag)) - .await; - Ok(None) - } - } - } - - async fn asset( - &self, - release: &forge_core::releases::Release, - rel: &ExtRelease, - asset: &ExtAsset, - max_bytes: u64, - totals: &mut Totals, - ) -> Result<(), String> { - let ext = format!("{}:{}", rel.id, asset.id); - if self.mapped("asset", &ext).await?.is_some() { - return Ok(()); - } - if asset.size > max_bytes { - totals.skipped += 1; - self.rep - .log( - "warn", - format!( - "asset `{}` skipped: larger than the upload limit", - asset.name - ), - ) - .await; - return Ok(()); - } - self.rep - .log("info", format!("Downloading asset {}", asset.name)) - .await; - let stream = match self.api.download(asset, max_bytes).await { - Ok(stream) => stream, - Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => { - return Err(e.to_string()); - } - Err(e) => { - totals.skipped += 1; - self.rep - .log("warn", format!("asset `{}` skipped: {e}", asset.name)) - .await; - return Ok(()); - } - }; - let name = asset_name(&asset.name); - let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str()); - match crate::release_ops::put_asset( - self.state, - self.repo, - release, - self.user, - &name, - content_type, - stream, - max_bytes, - ) - .await - { - Ok((stored, _)) => { - self.record("asset", &ext, &stored.id, &rel.author, &asset.url) - .await; - totals.assets += 1; - } - Err(e) => { - totals.skipped += 1; - self.rep - .log( - "warn", - format!("asset `{}` skipped: {}", asset.name, e.message()), - ) - .await; - } - } - Ok(()) - } -} - -pub async fn on_boot(state: &AppState) { - match state.store.fail_interrupted_imports().await { - Ok(0) => {} - Ok(n) => tracing::warn!(count = n, "import: marked interrupted jobs as failed"), - Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"), - } -} diff --git a/crates/forge-web-app/src/importer/remote.rs b/crates/forge-web-app/src/importer/remote.rs deleted file mode 100644 index a321b57..0000000 --- a/crates/forge-web-app/src/importer/remote.rs +++ /dev/null @@ -1,174 +0,0 @@ -use std::time::Duration; - -use super::Source; -use super::api::{self, Auth, Forgejo, GitHub, GitLab, Http, Notice}; -use crate::mirrors::policy; -use crate::state::AppState; -use crate::webhooks::client::{policy_client, validate_url}; - -fn client(state: &AppState) -> Result { - policy_client(policy(state), Duration::from_secs(60), "forge-import/1") - .map_err(|e| format!("could not build the HTTP client: {e}")) -} - -fn instance_host<'a>(state: &AppState, instance: &'a str) -> Result<(&'a str, String), String> { - let instance = instance.trim_end_matches('/'); - let host = validate_url(instance, &policy(state)) - .map_err(|e| format!("instance address refused: {e}"))? - .host_str() - .unwrap_or_default() - .to_ascii_lowercase(); - Ok((instance, host)) -} - -pub fn make_github( - state: &AppState, - token: Option, - notice: Notice, -) -> Result { - let client = client(state)?; - Ok(GitHub::new(Http::new( - client, - policy(state), - token, - Auth::GitHub, - "api.github.com".into(), - notice, - ))) -} - -pub fn make_gitlab( - state: &AppState, - instance: &str, - token: Option, - notice: Notice, -) -> Result { - let (instance, host) = instance_host(state, instance)?; - let client = client(state)?; - Ok(GitLab::new( - Http::new(client, policy(state), token, Auth::GitLab, host, notice), - instance, - )) -} - -pub fn make_forgejo( - state: &AppState, - instance: &str, - token: Option, - notice: Notice, -) -> Result { - let (instance, host) = instance_host(state, instance)?; - let client = client(state)?; - Ok(Forgejo::new( - Http::new(client, policy(state), token, Auth::Forgejo, host, notice), - instance, - )) -} - -pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> { - let text = text.trim(); - match source { - Source::Git => (text.starts_with("https://") || text.starts_with("http://")) - .then(|| (text.to_owned(), String::new())), - Source::GitHub => { - let path = text - .strip_prefix("https://github.com/") - .unwrap_or(text) - .trim_end_matches('/'); - let path = path.strip_suffix(".git").unwrap_or(path); - api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new())) - } - Source::GitLab | Source::Forgejo => { - let max = if source == Source::GitLab { 20 } else { 2 }; - if let Some((scheme, rest)) = text - .strip_prefix("https://") - .map(|r| ("https", r)) - .or_else(|| text.strip_prefix("http://").map(|r| ("http", r))) - { - let (host, path) = rest.split_once('/')?; - let path = path.trim_end_matches('/'); - let path = path.strip_suffix(".git").unwrap_or(path); - if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, max) { - return None; - } - return Some((path.to_owned(), format!("{scheme}://{host}"))); - } - let instance = instance.trim().trim_end_matches('/'); - let path = text.trim_matches('/'); - let path = path.strip_suffix(".git").unwrap_or(path); - let host = instance - .strip_prefix("https://") - .or_else(|| instance.strip_prefix("http://"))?; - let ok = !host.is_empty() - && !host.contains('@') - && !host.contains('/') - && api::valid_path(path, 2, max); - ok.then(|| (path.to_owned(), instance.to_owned())) - } - } -} - -pub fn source_ref(source: Source, remote: &str, instance: &str) -> String { - match source { - Source::GitLab | Source::Forgejo => { - format!("{}/{}", instance.trim_end_matches('/'), remote) - } - _ => remote.to_owned(), - } -} - -pub fn default_name(remote: &str) -> String { - remote - .trim_end_matches('/') - .rsplit('/') - .next() - .unwrap_or_default() - .trim_end_matches(".git") - .to_owned() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn github_accepts_owner_name_or_url() { - let ok = |t: &str| parse_remote(Source::GitHub, t, "").map(|r| r.0); - assert_eq!(ok("tahinli/forge").as_deref(), Some("tahinli/forge")); - assert_eq!( - ok("https://github.com/tahinli/forge.git").as_deref(), - Some("tahinli/forge") - ); - assert_eq!(ok("tahinli").as_deref(), None); - assert_eq!(ok("a/b/c").as_deref(), None); - assert_eq!(ok("../etc").as_deref(), None); - } - - #[test] - fn gitlab_takes_a_url_or_a_path_with_an_instance() { - let url = parse_remote(Source::GitLab, "https://gl.example.org/grp/sub/proj", ""); - assert_eq!( - url, - Some(("grp/sub/proj".into(), "https://gl.example.org".into())) - ); - let bare = parse_remote(Source::GitLab, "grp/proj", "https://gitlab.com/"); - assert_eq!(bare, Some(("grp/proj".into(), "https://gitlab.com".into()))); - assert_eq!(parse_remote(Source::GitLab, "grp/proj", ""), None); - assert_eq!( - parse_remote(Source::GitLab, "https://u:p@host/a/b", ""), - None - ); - } - - #[test] - fn git_needs_http_scheme_and_names_default_from_the_path() { - assert!(parse_remote(Source::Git, "file:///etc", "").is_none()); - assert!(parse_remote(Source::Git, "https://example.org/x/y.git", "").is_some()); - assert_eq!(default_name("https://example.org/x/y.git"), "y"); - assert_eq!(default_name("grp/proj"), "proj"); - assert_eq!( - source_ref(Source::GitLab, "g/p", "https://gitlab.com"), - "https://gitlab.com/g/p" - ); - } -} diff --git a/crates/forge-web-app/src/lib.rs b/crates/forge-web-app/src/lib.rs index b0ca366..336629f 100644 --- a/crates/forge-web-app/src/lib.rs +++ b/crates/forge-web-app/src/lib.rs @@ -15,11 +15,9 @@ pub mod automerge; pub mod backup; pub mod ci; pub mod client_ip; -pub mod exporter; pub mod git_auth; pub mod git_http; pub mod hook_cmd; -pub mod importer; pub mod internal; pub mod layers; pub mod lfs; diff --git a/crates/forge-web-app/src/live.rs b/crates/forge-web-app/src/live.rs index ea1f8a0..15bf3f7 100644 --- a/crates/forge-web-app/src/live.rs +++ b/crates/forge-web-app/src/live.rs @@ -25,7 +25,6 @@ pub enum Topic { User(String), Inbox(String), ReviewRequests(String), - Imports(String), Explore, Org(String), AdminUsers, diff --git a/crates/forge-web-app/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs index c3cf462..c9c9918 100644 --- a/crates/forge-web-app/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -37,7 +37,6 @@ use crate::i18n::authoring::{self as au, K as AuK}; use crate::i18n::browse as br; use crate::i18n::code::{self as g, K}; use crate::i18n::link::{self as lk, K as LinkKey}; -use crate::i18n::migrate::{self as mg, K as MGK}; use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::orgs::{self as o, K as OK}; use crate::i18n::s; @@ -101,7 +100,6 @@ const TOP_LEVEL_PAGES: &[&str] = &[ "logout", "register", "forgot", - "import", "review-requests", "setup", "needs-you", @@ -865,7 +863,6 @@ pub fn global_items(lang: Lang, can_create_org: bool) -> Vec { crate::i18n::needs::t(lang, crate::i18n::needs::K::NeedsYou), ), item("new", "/new", t(lang, Key::NewRepository)), - item("import", "/new/import", mg::t(lang, MGK::ImportTitle)), ]; if can_create_org { items.push(item("new-org", "/org/new", o::t(lang, OK::NewOrganization))); @@ -894,7 +891,6 @@ pub fn settings_items(lang: Lang) -> Vec { ), item("security", "/settings/security", t(lang, Key::Security)), item("keys", "/settings/keys", pk(lang, "Keys", "Anahtarlar")), - item("export", "/settings/export", pk(lang, "Data", "Veri")), ] } diff --git a/crates/forge-web-base/src/i18n/audit_names.rs b/crates/forge-web-base/src/i18n/audit_names.rs index a0d9d2d..b7b00df 100644 --- a/crates/forge-web-base/src/i18n/audit_names.rs +++ b/crates/forge-web-base/src/i18n/audit_names.rs @@ -308,8 +308,6 @@ pub fn detail_key_name(lang: Lang, key: &str) -> Option<&'static str> { ("members_can_create_repos", Lang::Tr) => Some("üyeler depo oluşturabilir"), ("invite", Lang::En) => Some("invite"), ("invite", Lang::Tr) => Some("davet"), - ("import", Lang::En) => Some("import"), - ("import", Lang::Tr) => Some("içe aktarma"), ("host", Lang::En) => Some("host"), ("host", Lang::Tr) => Some("sunucu adresi"), ("fork_of", Lang::En) => Some("fork of"), diff --git a/crates/forge-web-base/src/i18n/migrate.rs b/crates/forge-web-base/src/i18n/migrate.rs deleted file mode 100644 index 8715c68..0000000 --- a/crates/forge-web-base/src/i18n/migrate.rs +++ /dev/null @@ -1,119 +0,0 @@ -use super::Lang; - -strings! { - K; - TabCreate => "Create", "Oluştur"; - TabImport => "Import", "İçe aktar"; - ImportTitle => "Import a repository", "Depo içe aktar"; - SrcGit => "Git URL", "Git URL'si"; - SrcGitHub => "GitHub", "GitHub"; - SrcGitLab => "GitLab", "GitLab"; - SrcForgejo => "Forgejo / Gitea", "Forgejo / Gitea"; - GitUrl => "Repository URL", "Depo URL'si"; - GitUser => "Username (optional)", "Kullanıcı adı (isteğe bağlı)"; - GitPassword => "Password or token (optional)", "Parola veya belirteç (isteğe bağlı)"; - GitHubRepo => "Repository (owner/name)", "Depo (sahip/ad)"; - GitLabInstance => "GitLab address", "GitLab adresi"; - GitLabProject => "Project path", "Proje yolu"; - ForgejoInstance => "Forgejo or Gitea address (Codeberg works too)", "Forgejo veya Gitea adresi (Codeberg da olur)"; - TokenOptional => "Access token (optional)", "Erişim belirteci (isteğe bağlı)"; - TargetOwner => "Owner", "Sahip"; - TargetName => "New repository name", "Yeni depo adı"; - Description => "Description (optional)", "Açıklama (isteğe bağlı)"; - WhatToImport => "Also import", "Şunları da içe aktar"; - OptLabels => "Labels and milestones", "Etiketler ve kilometre taşları"; - OptIssues => "Issues and comments", "Konular ve yorumlar"; - OptPulls => "Pull requests (as issues)", "Çekme istekleri (konu olarak)"; - OptReleases => "Releases and their files", "Sürümler ve dosyaları"; - StartImport => "Start import", "İçe aktarmayı başlat"; - BulkLink => "Import several repositories", "Birden çok depoyu içe aktar"; - BulkLinkButton => "Choose repositories", "Depoları seç"; - BulkTitle => "Import several repositories", "Birden çok depoyu içe aktar"; - BulkOwnerGitHub => "GitHub user or organization", "GitHub kullanıcısı veya kuruluşu"; - BulkOwnerForgejo => "User or organization (empty with a token lists your own)", "Kullanıcı veya kuruluş (belirteçle boş bırakırsanız kendi depolarınız listelenir)"; - BulkOwnerGitLab => "GitLab user or group", "GitLab kullanıcısı veya grubu"; - BulkListButton => "List repositories", "Depoları listele"; - BulkSelectHeading => "Select the repositories to import", "İçe aktarılacak depoları seçin"; - BulkSelectAll => "Select all", "Tümünü seç"; - BulkImportSelected => "Import selected", "Seçilenleri içe aktar"; - BulkNone => "No repositories found.", "Depo bulunamadı."; - BulkPrivate => "private", "özel"; - BulkFork => "fork", "çatal"; - BulkArchived => "archived", "arşivlenmiş"; - JobsTitle => "Import history", "İçe aktarma geçmişi"; - NoJobs => "No imports yet.", "Henüz içe aktarma yok."; - JobQueued => "Queued", "Sırada"; - JobRunning => "Running", "Çalışıyor"; - JobDone => "Done", "Bitti"; - JobFailed => "Failed", "Başarısız"; - JobRetry => "Retry", "Yeniden dene"; - JobOpenRepo => "Open repository", "Depoyu aç"; - JobProgress => "Progress", "İlerleme"; - JobNoLog => "Nothing yet.", "Henüz bir şey yok."; - JobStarted => "Started", "Başladı"; - RetryFailedTitle => "Retry failed imports", "Başarısız içe aktarmaları yeniden dene"; - RetrySelected => "Retry selected", "Seçilenleri yeniden dene"; - RetryNone => "No failed imports", "Başarısız içe aktarma yok"; - StageGit => "Git data", "Git verisi"; - StageLabels => "Labels", "Etiketler"; - StageMilestones => "Milestones", "Kilometre taşları"; - StageIssues => "Issues and pull requests", "Konular ve çekme istekleri"; - StageReleases => "Releases", "Sürümler"; - StageDone => "Finished", "Tamamlandı"; - ErrBadRemote => "That repository address is not valid.", "Bu depo adresi geçerli değil."; - ErrBadInstance => "That instance address is not valid.", "Bu sunucu adresi geçerli değil."; - ErrBadOwner => "That user or organization name is not valid.", "Bu kullanıcı veya kuruluş adı geçerli değil."; - ErrNothingSelected => "Select at least one repository.", "En az bir depo seçin."; - ErrTooMany => "Too many repositories selected at once.", "Bir seferde çok fazla depo seçildi."; - SettingsExport => "Data export", "Veri dışa aktarımı"; - ExportTitle => "Export your data", "Verilerinizi dışa aktarın"; - ExportRequest => "Request an export", "Dışa aktarım iste"; - ExportBuilding => "Building", "Hazırlanıyor"; - ExportReady => "Ready", "Hazır"; - ExportFailed => "Failed", "Başarısız"; - ExportDownload => "Download", "İndir"; - ExportNone => "No exports yet.", "Henüz dışa aktarım yok."; - ExportRequested => "Requested", "İstendi"; - ExportSize => "Size", "Boyut"; -} - -pub fn expires_label(lang: Lang) -> &'static str { - match lang { - Lang::En => "Expires", - Lang::Tr => "Son geçerlilik", - } -} - -pub fn bulk_skipped(lang: Lang, list: &str) -> String { - match lang { - Lang::En => format!("Not imported: {list}. Import them one by one to choose another name."), - Lang::Tr => format!( - "İçe aktarılmayanlar: {list}. Başka bir ad seçmek için onları tek tek içe aktarın." - ), - } -} - -pub fn progress_of(done: i64, total: i64) -> String { - format!("{done} / {total}") -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_variant_has_both_languages() { - for key in ALL { - assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English"); - assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish"); - assert!( - !t(Lang::En, *key).contains('\u{2014}'), - "{key:?} has an em dash" - ); - assert!( - !t(Lang::Tr, *key).contains('\u{2014}'), - "{key:?} has an em dash" - ); - } - } -} diff --git a/crates/forge-web-base/src/i18n/mod.rs b/crates/forge-web-base/src/i18n/mod.rs index 57399cb..3ba1a21 100644 --- a/crates/forge-web-base/src/i18n/mod.rs +++ b/crates/forge-web-base/src/i18n/mod.rs @@ -40,7 +40,6 @@ pub mod integrations; pub mod issues; pub mod link; pub mod merge_queue; -pub mod migrate; pub mod misc; pub mod needs; pub mod orgs; diff --git a/crates/forge-web-pages/Cargo.toml b/crates/forge-web-pages/Cargo.toml index 5752129..207d430 100644 --- a/crates/forge-web-pages/Cargo.toml +++ b/crates/forge-web-pages/Cargo.toml @@ -33,7 +33,6 @@ reqwest = { workspace = true } similar = { workspace = true } multer.workspace = true zip = { workspace = true } -tar.workspace = true tempfile = { workspace = true, optional = true } diff --git a/crates/forge-web-repo/Cargo.toml b/crates/forge-web-repo/Cargo.toml index ba7b0de..6182a8f 100644 --- a/crates/forge-web-repo/Cargo.toml +++ b/crates/forge-web-repo/Cargo.toml @@ -33,7 +33,6 @@ reqwest = { workspace = true } multer.workspace = true ulid.workspace = true zip = { workspace = true } -tar.workspace = true [dev-dependencies] diff --git a/crates/forge-web/Cargo.toml b/crates/forge-web/Cargo.toml index 480e717..60baccd 100644 --- a/crates/forge-web/Cargo.toml +++ b/crates/forge-web/Cargo.toml @@ -36,8 +36,6 @@ nix = { workspace = true } time.workspace = true reqwest = { workspace = true } forge-runner = { workspace = true } -zip = { workspace = true } -tar.workspace = true [dev-dependencies] forge-web-pages = { workspace = true, features = ["test-support"] } diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index fd320cb..8c9a41b 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -1193,18 +1193,6 @@ field.dispatchEvent(new Event('input', { bubbles: true })); }); - // A checkbox marked data-select-all="" ticks or clears every checkbox inside the first - // element that matches the selector (the bulk import list). - document.addEventListener('change', function (e) { - var all = e.target && e.target.closest ? e.target.closest('[data-select-all]') : null; - if (!all) { return; } - var scope = document.querySelector(all.getAttribute('data-select-all')); - if (!scope) { return; } - Array.prototype.forEach.call(scope.querySelectorAll('input[type="checkbox"]'), function (box) { - box.checked = all.checked; - }); - }); - // Filter controls submit their form on change. document.addEventListener('change', function (e) { var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 9aeeb6b..df81c36 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -133,8 +133,6 @@ pub async fn serve( if let Err(e) = forge_web_app::signatures::rebuild_gpg_keyring(&state).await { tracing::error!(error = %e, "rebuilding the GPG keyring failed"); } - forge_web_app::importer::on_boot(&state).await; - forge_web_app::exporter::on_boot(&state).await; forge_web_app::webhooks::worker::spawn(state.clone()); forge_web_app::mirrors::worker::spawn(state.clone()); forge_web_app::mail::worker::spawn(state.clone()); diff --git a/crates/forge-web/src/forgejo_tests.rs b/crates/forge-web/src/forgejo_tests.rs deleted file mode 100644 index 57ec3a6..0000000 --- a/crates/forge-web/src/forgejo_tests.rs +++ /dev/null @@ -1,404 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use serde_json::{Value, json}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::TcpListener; - -use super::*; -use forge_web_app::importer::api::{Auth, Forgejo, Http}; - -type Reply = (Vec<(String, String)>, Vec); -type Log = Arc)>>>; - -async fn bind() -> (TcpListener, String) { - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let base = format!("http://{}", listener.local_addr().expect("addr")); - (listener, base) -} - -fn serve(listener: TcpListener, handler: F) -> Log -where - F: Fn(&str) -> Option + Send + Sync + 'static, -{ - let log: Log = Arc::default(); - let seen = log.clone(); - let handler = Arc::new(handler); - tokio::spawn(async move { - loop { - let Ok((mut sock, _)) = listener.accept().await else { - return; - }; - let handler = handler.clone(); - let seen = seen.clone(); - tokio::spawn(async move { - let mut buf = Vec::new(); - let mut chunk = [0u8; 2048]; - while !buf.windows(4).any(|w| w == b"\r\n\r\n") { - match sock.read(&mut chunk).await { - Ok(0) | Err(_) => return, - Ok(n) => buf.extend_from_slice(&chunk[..n]), - } - } - let text = String::from_utf8_lossy(&buf).into_owned(); - let target = text - .lines() - .next() - .and_then(|l| l.split_whitespace().nth(1)) - .unwrap_or("/") - .to_owned(); - let auth = text.lines().find_map(|l| { - let (k, v) = l.split_once(':')?; - k.eq_ignore_ascii_case("authorization") - .then(|| v.trim().to_owned()) - }); - seen.lock().unwrap().push((target.clone(), auth)); - let out = match handler(&target) { - Some((headers, body)) => { - let mut head = format!( - "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n", - body.len() - ); - for (k, v) in headers { - head.push_str(&format!("{k}: {v}\r\n")); - } - head.push_str("\r\n"); - let mut out = head.into_bytes(); - out.extend(body); - out - } - None => { - b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" - .to_vec() - } - }; - let _ = sock.write_all(&out).await; - let _ = sock.shutdown().await; - }); - } - }); - log -} - -fn json_reply(headers: Vec<(&str, String)>, body: &Value) -> Option { - let mut all = vec![("content-type".to_owned(), "application/json".to_owned())]; - all.extend(headers.into_iter().map(|(k, v)| (k.to_owned(), v))); - Some((all, body.to_string().into_bytes())) -} - -fn page_of(target: &str) -> usize { - target - .split(['?', '&']) - .find_map(|p| p.strip_prefix("page=")) - .and_then(|v| v.parse().ok()) - .unwrap_or(1) -} - -fn client(base: &str, token: Option<&str>) -> Forgejo { - let notice: forge_web_app::importer::api::Notice = Arc::new(|_| {}); - let open = forge_web_app::webhooks::client::WebhookPolicy::from_config( - &forge_core::config::WebhookConfig { - allow_http: true, - allowed_hosts: vec!["127.0.0.1".into()], - }, - ) - .expect("policy"); - let http = Http::new( - reqwest::Client::new(), - open, - token.map(str::to_owned), - Auth::Forgejo, - "127.0.0.1".into(), - notice, - ); - Forgejo::new(http, base) -} - -fn issue_json(n: i64, state: &str) -> Value { - json!({ - "number": n, "title": format!("Issue {n}"), "body": "text", "state": state, - "user": {"login": "hubot"}, "labels": [{"name": "bug", "color": "d73a4a"}], - "milestone": null, "created_at": "2020-01-02T03:04:05Z", - "html_url": format!("https://codeberg.example/tahinli/project/issues/{n}"), - }) -} - -#[tokio::test] -async fn pagination_follows_the_link_header_with_a_limit_of_fifty() { - let (listener, base) = bind().await; - let log = serve(listener, |target| { - if !target.starts_with("/api/v1/repos/tahinli/project/issues?type=issues") { - return json_reply(vec![], &json!([])); - } - match page_of(target) { - 1 => json_reply( - vec![ - ("x-total-count", "52".into()), - ( - "link", - "; rel=\"next\", ; rel=\"last\"" - .into(), - ), - ], - &Value::Array((1..=50).map(|n| issue_json(n, "open")).collect()), - ), - 2 => json_reply( - vec![ - ("x-total-count", "52".into()), - ("link", "; rel=\"prev\"".into()), - ], - &Value::Array((51..=52).map(|n| issue_json(n, "closed")).collect()), - ), - _ => json_reply(vec![], &json!([])), - } - }); - let api = client(&base, Some("abc123")); - let issues = api.issues("tahinli/project").await.unwrap(); - let plain: Vec<_> = issues.iter().filter(|i| !i.is_pr).collect(); - assert_eq!(plain.len(), 52, "both pages were read"); - assert!(plain[51].closed && !plain[0].closed); - assert_eq!(plain[0].author, "hubot"); - assert_eq!(plain[0].labels, vec!["bug"]); - - let log = log.lock().unwrap(); - let issue_calls: Vec<_> = log - .iter() - .filter(|(t, _)| t.contains("type=issues")) - .collect(); - assert_eq!(issue_calls.len(), 2, "stopped when the link had no next"); - assert!(issue_calls[0].0.contains("limit=50")); - assert!(issue_calls[0].0.contains("page=1") && issue_calls[1].0.contains("page=2")); - assert!( - log.iter() - .all(|(_, auth)| auth.as_deref() == Some("token abc123")), - "every request carries the token header" - ); -} - -#[tokio::test] -async fn the_total_count_stops_a_listing_with_no_link_header() { - let (listener, base) = bind().await; - let log = serve(listener, |target| { - json_reply( - vec![("x-total-count", "50".into())], - &Value::Array( - (0..50) - .map(|i| json!({"name": format!("l{i}"), "color": "00aabb"})) - .collect(), - ), - ) - .filter(|_| target.contains("/labels")) - }); - let api = client(&base, None); - let labels = api.labels("tahinli/project").await.unwrap(); - assert_eq!(labels.len(), 50); - assert_eq!(labels[0].color, "#00aabb"); - assert_eq!( - log.lock().unwrap().len(), - 1, - "a full page of exactly the total is the end" - ); - assert!( - log.lock().unwrap()[0].1.is_none(), - "no token, no Authorization header" - ); -} - -#[tokio::test] -async fn pulls_map_merged_closed_and_open() { - let (listener, base) = bind().await; - serve(listener, |target| { - if target.contains("/pulls?") { - let mut merged = issue_json(2, "closed"); - merged["merged"] = json!(true); - let closed = issue_json(3, "closed"); - let mut open = issue_json(4, "open"); - open["milestone"] = json!({"title": "v1"}); - json_reply(vec![], &json!([merged, closed, open])) - } else if target.contains("/issues?") { - json_reply(vec![], &json!([issue_json(1, "open")])) - } else { - None - } - }); - let api = client(&base, None); - let all = api.issues("tahinli/project").await.unwrap(); - assert_eq!(all.len(), 4); - assert!(!all[0].is_pr); - let pulls: Vec<_> = all.iter().filter(|i| i.is_pr).collect(); - assert!(pulls[0].closed && pulls[0].merged); - assert!(pulls[1].closed && !pulls[1].merged); - assert!(!pulls[2].closed); - assert_eq!(pulls[2].milestone.as_deref(), Some("v1")); -} - -#[tokio::test] -async fn bulk_listing_tries_the_org_then_the_user_and_supports_own_repos() { - let (listener, base) = bind().await; - let repo = |name: &str, private: bool| { - json!({"name": name, "full_name": format!("tahinli/{name}"), "private": private, - "fork": false, "archived": false, "default_branch": "main", "description": null}) - }; - let log = serve(listener, move |target| { - if target.starts_with("/api/v1/users/tahinli/repos") { - json_reply(vec![], &json!([repo("a", false)])) - } else if target.starts_with("/api/v1/user/repos") { - json_reply(vec![], &json!([repo("a", false), repo("b", true)])) - } else { - None - } - }); - let api = client(&base, Some("t")); - let public = api.list_repos("tahinli").await.unwrap(); - assert_eq!(public.len(), 1); - assert_eq!(public[0].full_name, "tahinli/a"); - assert!( - log.lock().unwrap()[0] - .0 - .starts_with("/api/v1/orgs/tahinli/repos"), - "the org is tried first" - ); - let mine = api.list_repos("").await.unwrap(); - assert_eq!(mine.len(), 2); - assert!(mine[1].private); -} - -#[tokio::test] -async fn a_bad_asset_address_is_refused_before_any_request() { - let (listener, base) = bind().await; - let log = serve(listener, |_| None); - let api = client(&base, Some("t")); - let asset = ExtAsset { - url: "https://elsewhere.example/a.bin".into(), - ..ExtAsset::default() - }; - assert!(api.download(&asset, 100).await.is_err()); - assert!(log.lock().unwrap().is_empty()); -} - -#[tokio::test] -async fn full_forgejo_import_maps_issues_pulls_comments_labels_and_releases() { - let fx = fixture().await; - let (listener, base) = bind().await; - let origin = base.clone(); - serve(listener, move |target| { - let path = target.split('?').next().unwrap_or_default(); - match path { - "/api/v1/repos/tahinli/project/labels" => json_reply( - vec![], - &json!([{"name": "bug", "color": "d73a4a", "description": "Broken"}]), - ), - "/api/v1/repos/tahinli/project/milestones" => json_reply( - vec![], - &json!([{"id": 9, "title": "v1", "description": "", "state": "closed", - "due_on": "2020-05-06T00:00:00Z"}]), - ), - "/api/v1/repos/tahinli/project/issues" => { - json_reply(vec![], &json!([issue_json(1, "closed")])) - } - "/api/v1/repos/tahinli/project/pulls" => { - let mut pr = issue_json(2, "closed"); - pr["title"] = json!("Add the thing"); - pr["merged"] = json!(true); - json_reply(vec![], &json!([pr])) - } - "/api/v1/repos/tahinli/project/issues/1/comments" => json_reply( - vec![], - &json!([{"id": 11, "body": "same here", "user": {"login": "hubot"}, - "created_at": "2020-01-03T00:00:00Z", - "html_url": "https://codeberg.example/c/11"}]), - ), - "/api/v1/repos/tahinli/project/issues/2/comments" => json_reply(vec![], &json!([])), - "/api/v1/repos/tahinli/project/releases" => json_reply( - vec![], - &json!([{"id": 5, "tag_name": "v1", "name": "", "body": "notes", "draft": false, - "prerelease": false, "author": {"login": "hubot"}, - "created_at": "2021-01-01T00:00:00Z", - "html_url": "https://codeberg.example/r/5", - "assets": [{"id": 1, "name": "app.tar.gz", "size": 5, - "browser_download_url": format!("{origin}/attachments/uuid-1")}]}]), - ), - "/attachments/uuid-1" => Some((vec![], b"hello".to_vec())), - _ => None, - } - }); - let api = client(&base, Some(TOKEN)); - let job = new_job(&fx, Source::Forgejo).await; - let mut spec = spec(Source::Forgejo, everything()); - spec.instance = base.clone(); - run_job( - &fx.state, - &job, - &spec, - Some(&api), - &Transport::Local(fx.upstream.clone()), - ) - .await; - - let store = &fx.state.store; - let job = store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); - - let all = IssueFilter { - state: None, - per_page: 100, - ..IssueFilter::default() - }; - let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); - assert_eq!(total, 2); - let issue = items.iter().find(|i| i.issue.title == "Issue 1").unwrap(); - assert_eq!(issue.issue.state, IssueState::Closed); - assert!( - issue - .issue - .body - .starts_with("> Originally by \\@hubot on Forgejo, 2020-01-02"), - "{}", - issue.issue.body - ); - assert!(issue.labels.iter().any(|l| l.name == "bug")); - let pull = items - .iter() - .find(|i| i.issue.title == "Add the thing") - .unwrap(); - assert!(pull.issue.body.contains("Imported pull request (merged)")); - let comments = store.list_comments(&issue.issue.id).await.unwrap(); - assert_eq!(comments.len(), 1); - assert!(comments[0].body.ends_with("same here")); - - let release = store - .release_by_tag(&fx.repo.id, "v1") - .await - .unwrap() - .unwrap(); - assert!(release.body.contains("notes")); - let assets = store.list_release_assets(&release.id).await.unwrap(); - assert_eq!(assets.len(), 1); - assert_eq!(assets[0].name, "app.tar.gz"); - assert_eq!(assets[0].size, 5); -} - -#[test] -fn forgejo_remotes_take_a_url_or_a_path_with_an_instance() { - use forge_web_app::importer::parse_remote; - assert_eq!( - parse_remote( - Source::Forgejo, - "https://codeberg.org/tahinli/forge.git", - "" - ), - Some(("tahinli/forge".into(), "https://codeberg.org".into())) - ); - assert_eq!( - parse_remote(Source::Forgejo, "tahinli/forge", "https://codeberg.org/"), - Some(("tahinli/forge".into(), "https://codeberg.org".into())) - ); - assert_eq!( - parse_remote(Source::Forgejo, "a/b/c", "https://codeberg.org"), - None - ); - assert_eq!(parse_remote(Source::Forgejo, "tahinli/forge", ""), None); - assert_eq!(Source::parse("gitea"), Some(Source::Forgejo)); - let mut s = spec(Source::Forgejo, ImportOptions::default()); - s.instance = "https://codeberg.org/".into(); - assert_eq!(s.clone_url(), "https://codeberg.org/tahinli/project.git"); -} diff --git a/crates/forge-web/src/importer_route_tests.rs b/crates/forge-web/src/importer_route_tests.rs deleted file mode 100644 index 8454cba..0000000 --- a/crates/forge-web/src/importer_route_tests.rs +++ /dev/null @@ -1,599 +0,0 @@ -use std::collections::HashMap; -use std::path::Path; -use std::sync::Mutex; - -use forge_core::issues::IssueFilter; -use forge_core::store::imports::{ImportJob, ImportState}; -use forge_core::{IssueState, Visibility}; -use topcoat::router::request::Request; -use topcoat::router::{Body, to_bytes}; - -use forge_web_app::auth::SESSION_COOKIE; -use forge_web_app::importer::api::{ - ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, - ExtRelease, ExtRepo, RemoteApi, -}; -use forge_web_app::importer::{ - ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note, -}; -use forge_web_app::state::AppState; -use forge_web_app::test_support::{app_router, create_session, test_state}; - -const TOKEN: &str = "ghp_supersecret_token_value"; - -fn all_issues() -> IssueFilter { - IssueFilter { - state: None, - per_page: 100, - ..IssueFilter::default() - } -} - -#[derive(Default)] -struct Fake { - labels: Vec, - milestones: Vec, - issues: Vec, - comments: HashMap>, - releases: Vec, - files: HashMap>, - comment_failures: Mutex>, - comment_calls: Mutex, -} - -impl RemoteApi for Fake { - async fn list_repos(&self, _owner: &str) -> ApiResult> { - Ok(vec![ExtRepo { - name: "project".into(), - full_name: "tahinli/project".into(), - ..ExtRepo::default() - }]) - } - - async fn labels(&self, _repo: &str) -> ApiResult> { - Ok(self.labels.clone()) - } - - async fn milestones(&self, _repo: &str) -> ApiResult> { - Ok(self.milestones.clone()) - } - - async fn issues(&self, _repo: &str) -> ApiResult> { - Ok(self.issues.clone()) - } - - async fn comments(&self, _repo: &str, issue: &ExtIssue) -> ApiResult> { - *self.comment_calls.lock().unwrap() += 1; - if let Some(e) = self.comment_failures.lock().unwrap().pop() { - return Err(e); - } - Ok(self - .comments - .get(&issue.number) - .cloned() - .unwrap_or_default()) - } - - async fn releases(&self, _repo: &str) -> ApiResult> { - Ok(self.releases.clone()) - } - - async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult { - let bytes = self - .files - .get(&asset.url) - .cloned() - .ok_or_else(|| ApiError::NotFound("asset".into()))?; - Ok(Box::pin(futures_util::stream::once(async move { - Ok::<_, std::io::Error>(bytes::Bytes::from(bytes)) - }))) - } -} - -fn plumbing(git_dir: &Path, args: &[&str]) -> String { - let out = std::process::Command::new("git") - .arg(format!("--git-dir={}", git_dir.display())) - .args(args) - .env("GIT_AUTHOR_NAME", "t") - .env("GIT_AUTHOR_EMAIL", "t@example.com") - .env("GIT_COMMITTER_NAME", "t") - .env("GIT_COMMITTER_EMAIL", "t@example.com") - .output() - .expect("git runs"); - assert!(out.status.success(), "git {args:?}: {out:?}"); - String::from_utf8_lossy(&out.stdout).trim().to_string() -} - -fn commit_to(git_dir: &Path, refname: &str, message: &str) { - let tree = plumbing(git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]); - let commit = plumbing(git_dir, &["commit-tree", &tree, "-m", message]); - plumbing(git_dir, &["update-ref", refname, &commit]); -} - -fn upstream(dir: &Path) -> String { - let path = dir.join("upstream.git"); - let out = std::process::Command::new("git") - .args(["init", "--bare", "-q"]) - .arg(&path) - .output() - .expect("git init"); - assert!(out.status.success()); - plumbing(&path, &["symbolic-ref", "HEAD", "refs/heads/master"]); - commit_to(&path, "refs/heads/master", "one"); - commit_to(&path, "refs/heads/dev", "dev work"); - commit_to(&path, "refs/tags/v1", "tagged"); - path.display().to_string() -} - -struct Fixture { - state: AppState, - repo: forge_core::Repo, - user: forge_core::User, - _dir: tempfile::TempDir, - upstream: String, -} - -async fn fixture() -> Fixture { - let dir = tempfile::tempdir().expect("tempdir"); - let state = test_state(dir.path()).await; - let user = state - .store - .create_user("tahinli", None, "unused", false) - .await - .expect("user"); - let repo = state - .store - .create_repo(&user.id, "project", "", Visibility::Public, "main") - .await - .expect("repo"); - let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path"); - forge_git::repo::init_bare(&state.git, &bare, "main") - .await - .expect("init bare"); - let upstream = upstream(dir.path()); - Fixture { - state, - repo, - user, - _dir: dir, - upstream, - } -} - -fn spec(source: Source, options: ImportOptions) -> JobSpec { - JobSpec { - source, - remote: "tahinli/project".into(), - instance: String::new(), - token: Some(TOKEN.into()), - git_user: String::new(), - options, - } -} - -async fn new_job(fx: &Fixture, source: Source) -> ImportJob { - fx.state - .store - .create_import_job( - &fx.user.id, - &fx.repo.id, - source.as_str(), - "tahinli/project", - "{}", - ) - .await - .expect("job") -} - -fn everything() -> ImportOptions { - ImportOptions { - labels: true, - issues: true, - pulls: true, - releases: true, - } -} - -fn fake() -> Fake { - let mut fake = Fake { - labels: vec![ExtLabel { - name: "bug".into(), - color: "#d73a4a".into(), - description: "Broken".into(), - }], - milestones: vec![ExtMilestone { - id: "1".into(), - title: "v1".into(), - closed: true, - due_on: Some("2020-05-06".into()), - ..ExtMilestone::default() - }], - issues: vec![ - ExtIssue { - number: 1, - title: "It breaks".into(), - body: "steps".into(), - closed: true, - author: "octocat".into(), - labels: vec!["bug".into()], - milestone: Some("v1".into()), - created_at: "2020-01-02T03:04:05Z".into(), - url: "https://github.com/tahinli/project/issues/1".into(), - ..ExtIssue::default() - }, - ExtIssue { - number: 2, - title: "Add the thing".into(), - body: "patch".into(), - closed: true, - merged: true, - is_pr: true, - author: "hubot".into(), - created_at: "2020-02-02T00:00:00Z".into(), - url: "https://github.com/tahinli/project/pull/2".into(), - ..ExtIssue::default() - }, - ], - releases: vec![ExtRelease { - id: "7".into(), - tag: "v1".into(), - title: "First".into(), - body: "notes".into(), - author: "octocat".into(), - assets: vec![ExtAsset { - id: "9".into(), - name: "app 1.tar.gz".into(), - size: 5, - content_type: "application/gzip".into(), - url: "https://api.github.com/assets/9".into(), - }], - ..ExtRelease::default() - }], - ..Fake::default() - }; - fake.comments.insert( - 1, - vec![ExtComment { - id: "100".into(), - author: "hubot".into(), - body: "same here".into(), - created_at: "2020-01-03T00:00:00Z".into(), - url: "https://github.com/tahinli/project/issues/1#c100".into(), - }], - ); - fake.files - .insert("https://api.github.com/assets/9".into(), b"hello".to_vec()); - fake -} - -#[tokio::test] -async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() { - let fx = fixture().await; - let job = new_job(&fx, Source::Git).await; - let git_spec = spec(Source::Git, ImportOptions::default()); - run_job::( - &fx.state, - &job, - &git_spec, - None, - &Transport::Local(fx.upstream.clone()), - ) - .await; - - let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); - let dir = forge_git::repo::repo_path(&fx.state.git.data_dir, &fx.repo.id).unwrap(); - let refs = forge_web_app::mirrors::ref_snapshot(&fx.state, &dir) - .await - .unwrap(); - assert!(refs.contains_key("refs/heads/master")); - assert!(refs.contains_key("refs/heads/dev")); - assert!(refs.contains_key("refs/tags/v1")); - let repo = fx - .state - .store - .repo_by_id(&fx.repo.id) - .await - .unwrap() - .unwrap(); - assert_eq!(repo.default_branch, "master"); - assert!( - fx.state - .store - .pull_mirror(&fx.repo.id) - .await - .unwrap() - .is_none() - ); - - let bad_job = new_job(&fx, Source::Git).await; - let bad_spec = spec(Source::Git, ImportOptions::default()); - run_job::( - &fx.state, - &bad_job, - &bad_spec, - None, - &Transport::Local("/nonexistent/path.git".into()), - ) - .await; - let bad_job = fx - .state - .store - .import_job(&bad_job.id) - .await - .unwrap() - .unwrap(); - assert_eq!(bad_job.state, ImportState::Failed); - assert!(bad_job.error.is_some()); -} - -#[tokio::test] -async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() { - let fx = fixture().await; - let api = fake(); - let job = new_job(&fx, Source::GitHub).await; - let spec = spec(Source::GitHub, everything()); - run_job( - &fx.state, - &job, - &spec, - Some(&api), - &Transport::Local(fx.upstream.clone()), - ) - .await; - - let store = &fx.state.store; - let job = store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); - - let (items, total) = store.list_issues(&fx.repo.id, &all_issues()).await.unwrap(); - assert_eq!(total, 2); - let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); - assert_eq!(issue.issue.state, IssueState::Closed); - assert_eq!( - issue.issue.author_id, fx.user.id, - "the importer owns the row" - ); - assert!( - issue - .issue - .body - .starts_with("> Originally by \\@octocat on GitHub, 2020-01-02"), - "{}", - issue.issue.body - ); - assert!(issue.labels.iter().any(|l| l.name == "bug")); - assert!(issue.issue.milestone_id.is_some()); - - let pull = items - .iter() - .find(|i| i.issue.title == "Add the thing") - .unwrap(); - assert!(pull.labels.iter().any(|l| l.name == "imported PR")); - assert!(pull.issue.body.contains("Imported pull request (merged)")); - assert!(pull.issue.body.contains("Originally by \\@hubot")); - - let comments = store.list_comments(&issue.issue.id).await.unwrap(); - assert_eq!(comments.len(), 1); - assert!( - comments[0] - .body - .contains("Originally by \\@hubot on GitHub") - ); - assert!(comments[0].body.ends_with("same here")); - - let release = store - .release_by_tag(&fx.repo.id, "v1") - .await - .unwrap() - .unwrap(); - assert!(release.body.contains("notes")); - let assets = store.list_release_assets(&release.id).await.unwrap(); - assert_eq!(assets.len(), 1); - assert_eq!(assets[0].name, "app_1.tar.gz"); - assert_eq!(assets[0].size, 5); - - let again = new_job(&fx, Source::GitHub).await; - run_job( - &fx.state, - &again, - &spec, - Some(&api), - &Transport::Local(fx.upstream.clone()), - ) - .await; - let again = store.import_job(&again.id).await.unwrap().unwrap(); - assert_eq!(again.state, ImportState::Done, "{:?}", again.error); - let (items, total) = store.list_issues(&fx.repo.id, &all_issues()).await.unwrap(); - assert_eq!(total, 2); - let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); - assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1); - assert_eq!(store.list_releases(&fx.repo.id).await.unwrap().len(), 1); - let release = store - .release_by_tag(&fx.repo.id, "v1") - .await - .unwrap() - .unwrap(); - assert_eq!( - store.list_release_assets(&release.id).await.unwrap().len(), - 1 - ); - let labels = store.list_labels(&fx.repo.id).await.unwrap(); - assert_eq!(labels.iter().filter(|l| l.name == "bug").count(), 1); -} - -#[tokio::test] -async fn a_rate_limit_fails_the_job_clearly_and_a_retry_finishes_it() { - let fx = fixture().await; - let api = fake(); - api.comment_failures - .lock() - .unwrap() - .push(ApiError::RateLimited { wait_secs: 3600 }); - let job = new_job(&fx, Source::GitHub).await; - let spec = spec(Source::GitHub, everything()); - let transport = Transport::Local(fx.upstream.clone()); - run_job(&fx.state, &job, &spec, Some(&api), &transport).await; - - let failed = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(failed.state, ImportState::Failed); - let message = failed.error.clone().unwrap(); - assert!(message.contains("rate limit"), "{message}"); - let events = fx - .state - .store - .list_import_events(&job.id, 50) - .await - .unwrap(); - assert!(events.iter().any(|e| e.level == "error")); - - run_job(&fx.state, &job, &spec, Some(&api), &transport).await; - let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(done.state, ImportState::Done, "{:?}", done.error); - assert!(done.error.is_none()); - let (_, total) = fx - .state - .store - .list_issues(&fx.repo.id, &all_issues()) - .await - .unwrap(); - assert_eq!(total, 2); -} - -#[tokio::test] -async fn the_token_is_never_written_to_the_database() { - let fx = fixture().await; - let api = fake(); - api.comment_failures - .lock() - .unwrap() - .push(ApiError::Http(format!("boom {}", "x"))); - let job = new_job(&fx, Source::GitHub).await; - let spec = spec(Source::GitHub, everything()); - run_job( - &fx.state, - &job, - &spec, - Some(&api), - &Transport::Local(fx.upstream.clone()), - ) - .await; - let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - let events = fx - .state - .store - .list_import_events(&job.id, 500) - .await - .unwrap(); - let mut text = format!("{job:?}"); - for e in events { - text.push_str(&e.message); - } - assert!( - !text.contains(TOKEN), - "the token leaked into stored job data" - ); - assert!( - !format!("{spec:?}").contains(TOKEN), - "Debug prints the token" - ); -} - -#[tokio::test] -async fn retry_submit_leaves_another_users_failed_job_alone() { - let fx = fixture().await; - let other = fx - .state - .store - .create_user("mallory", None, "unused", false) - .await - .unwrap(); - let job = new_job(&fx, Source::GitHub).await; - fx.state - .store - .set_import_state(&job.id, ImportState::Failed, Some("rate limit")) - .await - .unwrap(); - create_session( - &fx.state.store, - &other.id, - "retry-other-session", - "retry-csrf", - ) - .await; - - let router = app_router(fx.state.clone()); - let cookie = format!("__Host-{SESSION_COOKIE}=retry-other-session"); - - let page = router - .handle( - Request::builder() - .method("GET") - .uri("/import/retry") - .header("cookie", cookie.as_str()) - .body(Body::empty()) - .unwrap(), - ) - .await; - assert_eq!(page.status().as_u16(), 200); - let bytes = to_bytes(page.into_body(), usize::MAX).await.unwrap(); - assert!(String::from_utf8_lossy(&bytes).contains("No failed imports")); - - let form = format!("csrf=retry-csrf&token=&sel_0={}", job.id); - let res = router - .handle( - Request::builder() - .method("POST") - .uri("/import/retry") - .header("cookie", cookie.as_str()) - .header("content-type", "application/x-www-form-urlencoded") - .body(Body::from(form)) - .unwrap(), - ) - .await; - assert_eq!(res.status().as_u16(), 303); - let _ = to_bytes(res.into_body(), usize::MAX).await.unwrap(); - - let after = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); - assert_eq!(after.state, ImportState::Failed); - assert_eq!(after.error.as_deref(), Some("rate limit")); -} - -#[test] -fn the_origin_note_escapes_the_mention_and_cleans_the_name() { - let note = origin_note( - "GitHub", - "evil @tahinli\n", - "2021-03-04T00:00:00Z", - "https://github.com/o/r/issues/1", - ); - assert!(note.starts_with("> Originally by \\@eviltahinli on GitHub, 2021-03-04")); - assert!(note.contains("[original](https://github.com/o/r/issues/1)")); - assert!(note.ends_with("\n\n")); - let none = origin_note("GitHub", "", "", "javascript:alert(1)"); - assert!(none.contains("\\@unknown")); - assert!(!none.contains("javascript")); -} - -#[test] -fn bodies_are_cut_at_the_limit_on_a_char_boundary() { - let long = "\u{e9}".repeat(forge_core::issues::MAX_BODY); - let text = with_note("> note\n\n", &long); - assert!(text.len() <= forge_core::issues::MAX_BODY); - assert!(text.ends_with("(cut)")); -} - -#[test] -fn asset_names_are_made_safe() { - assert_eq!(asset_name("app 1.tar.gz"), "app_1.tar.gz"); - assert_eq!(asset_name("../../etc/passwd"), "_.._etc_passwd"); - assert_eq!(asset_name(".hidden"), "hidden"); - assert_eq!(asset_name("###"), "___"); - assert_eq!(asset_name(""), "asset"); - assert!(forge_core::releases::valid_asset_name(&asset_name( - "a b/c?d" - ))); -} - -#[path = "forgejo_tests.rs"] -mod forgejo; diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 41a410c..2f1c753 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -9,8 +9,6 @@ mod boot; #[cfg(test)] mod compression_route_tests; #[cfg(test)] -mod importer_route_tests; -#[cfg(test)] mod page_route_tests; #[cfg(test)] mod route_list_tests; diff --git a/crates/forge-web/src/routes.snap b/crates/forge-web/src/routes.snap index 83b29e8..e52fee8 100644 --- a/crates/forge-web/src/routes.snap +++ b/crates/forge-web/src/routes.snap @@ -27,9 +27,6 @@ page /admin/users/{user_id}/unsuspend Only([POST]) page /explore Only([GET]) page /forgot Only([GET]) page /forgot Only([POST]) -page /import Only([GET]) -page /import/retry Only([GET]) -page /import/{job_id} Only([GET]) page /login Only([GET]) page /login Only([POST]) page /login/2fa Only([GET]) @@ -37,10 +34,6 @@ page /login/2fa Only([POST]) page /needs-you Only([GET]) page /new Only([GET]) page /new Only([POST]) -page /new/import Only([GET]) -page /new/import Only([POST]) -page /new/import/bulk Only([GET]) -page /new/import/bulk Only([POST]) page /notifications Only([GET]) page /org/new Only([GET]) page /org/new Only([POST]) @@ -54,7 +47,6 @@ page /reset/{token} Only([GET]) page /reset/{token} Only([POST]) page /review-requests Only([GET]) page /settings/appearance Only([GET]) -page /settings/export Only([GET]) page /settings/gpg Only([GET]) page /settings/gpg Only([POST]) page /settings/keys Only([GET]) @@ -245,10 +237,6 @@ route /attachments/{id}/{name} Only([GET]) route /avatars/{username} Only([GET]) route /explore/events Only([GET]) route /healthz Only([GET]) -route /import/events Only([GET]) -route /import/retry Only([POST]) -route /import/{job_id}/events Only([GET]) -route /import/{job_id}/retry Only([POST]) route /login/passkey/begin Only([POST]) route /login/passkey/finish Only([POST]) route /logout Only([POST]) @@ -284,10 +272,6 @@ route /org/{org}/teams/{team}/update Only([POST]) route /review-requests/events Only([GET]) route /settings/appearance Only([POST]) route /settings/events Only([GET]) -route /settings/export Only([POST]) -route /settings/export/events Only([GET]) -route /settings/export/{export_id}/delete Only([POST]) -route /settings/export/{export_id}/download Only([GET]) route /settings/gpg/delete Only([POST]) route /settings/keys/delete Only([POST]) route /settings/notifications Only([POST]) diff --git a/docs/architecture.md b/docs/architecture.md index c304348..0b88e14 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -277,7 +277,7 @@ Pages update without a reload. A write that changes what a page shows calls `Liv | Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot | | Admin health `/admin/health` | `/admin/health/events` | the alerts, the counts and the mail queue. The disk and tree probes are read when the page renders, not on each change | | Admin server `/admin/server` | `/admin/server/events` | saved or reset settings. A page waiting for a restart gets one event when a new process answers | -| Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance, export) | `/settings/events` (the section sidebar) | the viewer's own account topic: a setting, key, token, passkey or session changed, a sign-in or key use happened, or a suspension or account deletion. A revoked current session leaves for the login page on the next re-read | +| Settings `/settings/...` (profile, keys, GPG, tokens, sessions, security, passkeys, notifications, appearance) | `/settings/events` (the section sidebar) | the viewer's own account topic: a setting, key, token, passkey or session changed, a sign-in or key use happened, or a suspension or account deletion. A revoked current session leaves for the login page on the next re-read | | Every signed-in page (`/-/alive`, the stream every page holds) | the viewer's account topic. A `theme` event carries the appearance attributes (theme, accents, base, sidebar side) when they change, and `nav.js` applies them with no reload. The stream is one connection, shared with the restart check | | Repo settings `/{owner}/{repo}/settings/...`, transfer `/{owner}/{repo}/transfer` | `/{owner}/{repo}/settings/live` (admins only), `/{owner}/{repo}/transfer/live` | the repo settings topic: a settings POST, a webhook delivery queued or sent, a mirror sync that finished, a transfer accepted, declined or cancelled. The settings stream also follows the repo refs for the branch picker | diff --git a/docs/ui-language.md b/docs/ui-language.md index 0aa453c..4b9167a 100644 --- a/docs/ui-language.md +++ b/docs/ui-language.md @@ -206,7 +206,7 @@ Turkish page shows no English, an English page no Turkish. - Every control has one focus ring: 2px in `--focus`, inside its own edge (`outline-offset: -2px`), so no sheet, row or scrolling list cuts it. - A tab's own pages sit in its rail: the Security log is a Security rail item, not a page of its own. -- No page is an orphan. A page that makes or shows something of yours (a new repository, an import, a +- No page is an orphan. A page that makes or shows something of yours (a new repository, a new organization) shows your profile tabs with the area it belongs to marked, and the inbox pages (Notifications, Needs you, Review requests) share one rail, so a mouse reaches every neighbour. - An action a server cannot carry out shows as unavailable: no "send again" when mail is not set up. diff --git a/style/_import.scss b/style/_import.scss deleted file mode 100644 index b9e49d2..0000000 --- a/style/_import.scss +++ /dev/null @@ -1,81 +0,0 @@ - - -.import-pick-list { - max-height: 60vh; - margin: 0; - padding: 0; - overflow-y: auto; - list-style: none; - -} - -.import-job { - display: flex; - flex-direction: column; - gap: 16px; - max-width: 960px; - min-width: 0; -} - -.import-progress { - width: 100%; - height: 8px; - border-radius: var(--radius-full); - overflow: hidden; -} - -.badge.import-running { - background: var(--accent-soft, var(--surface-2)); - color: var(--accent-ink); -} - -.badge.import-failed { - background: var(--danger-bg); - color: var(--alert-text); -} - -.import-log-title { - margin: 0; - font-size: 0.9375rem; -} - -.import-log { - display: flex; - flex-direction: column; - gap: 2px; - max-height: 46vh; - margin: 0; - padding: 0; - overflow-y: auto; - list-style: none; - font-family: var(--mono); - font-size: 0.8125rem; -} - -.import-log-line { - overflow-wrap: anywhere; - color: var(--text-2); - - &.import-log-warn { - color: var(--warn); - } - - &.import-log-error { - color: var(--danger); - } -} - -.export-page { - display: flex; - flex-direction: column; - gap: 16px; - max-width: 960px; -} - -.export-progress { - width: 120px; -} - -@media (max-width: 560px) { - -} diff --git a/style/_look.scss b/style/_look.scss index 552becc..2ff4aab 100644 --- a/style/_look.scss +++ b/style/_look.scss @@ -41,7 +41,6 @@ th, .ci-side-title, .ci-art-title, .ci-warnings-title, -.import-log-title, .row-title, .mx-caption, .card > .muted.small:first-child:has(+ .table-wrap, + .table, + ul, + ol) { diff --git a/style/_min_settings.scss b/style/_min_settings.scss index beb102d..bc5f352 100644 --- a/style/_min_settings.scss +++ b/style/_min_settings.scss @@ -53,30 +53,7 @@ } } -// Data export: each archive is one flat line (when, state, Download, Delete); a building one adds its -// progress and an error under the line. -.export-row { - display: block; - margin: 0 -18px; - border-bottom: 1px solid var(--border); - - &:last-child { - border-bottom: 0; - } - - > .line { - padding-left: 18px; - padding-right: 18px; - border-bottom: 0; - } - - > progress, - > .alert { - margin: 0 18px 10px; - } -} - -// A request that cannot be sent right now (an export is building). +// A request that cannot be sent right now. button.act:disabled, button.act:disabled:hover { color: var(--muted); diff --git a/style/main.scss b/style/main.scss index 2a430be..79c0e80 100644 --- a/style/main.scss +++ b/style/main.scss @@ -5451,7 +5451,6 @@ button.ci-job-last { @import "pull"; @import "dashboard"; @import "browse"; -@import "import"; @import "authoring"; // Code inside cards, notices and settings panels must stay inside the card. Long tokens and