🔥 remove: importer (GitHub, GitLab, Forgejo, git URL) and per-user data export; account deletion moves to Security
Browse files at this commit0621a31c4497ece5d783004612ae0e24e90674bcParent: cd4373f42 changed files +119 -7085
- Cargo.lock +0 -7
- crates/forge-core/src/store/exports.rs +0 -150
- crates/forge-core/src/store/imports.rs +0 -340
- crates/forge-core/src/store/mod.rs +0 -2
- crates/forge-e2e/Cargo.toml +0 -1
- crates/forge-e2e/tests/e2e/section_nav_e2e.rs +0 -1
- crates/forge-web-account/src/lib.rs +2 -2
- crates/forge-web-account/src/pages/home.rs +0 -3
- crates/forge-web-account/src/pages/import.rs +0 -1420
- crates/forge-web-account/src/pages/import_tests.rs +0 -157
- crates/forge-web-account/src/pages/mod.rs +0 -4
- crates/forge-web-account/src/pages/new_repo.rs +14 -2
- crates/forge-web-account/src/pages/palette.rs +0 -9
- crates/forge-web-account/src/pages/settings_export.rs +0 -372
- crates/forge-web-account/src/pages/settings_security.rs +100 -9
- crates/forge-web-app/Cargo.toml +0 -2
- crates/forge-web-app/src/exporter.rs +0 -412
- crates/forge-web-app/src/exporter/tests.rs +0 -171
- crates/forge-web-app/src/importer/api.rs +0 -1482
- crates/forge-web-app/src/importer/mod.rs +0 -1088
- crates/forge-web-app/src/importer/remote.rs +0 -174
- crates/forge-web-app/src/lib.rs +0 -2
- crates/forge-web-app/src/live.rs +0 -1
- crates/forge-web-app/src/views/mod.rs +0 -4
- crates/forge-web-base/src/i18n/audit_names.rs +0 -2
- crates/forge-web-base/src/i18n/migrate.rs +0 -119
- crates/forge-web-base/src/i18n/mod.rs +0 -1
- crates/forge-web-pages/Cargo.toml +0 -1
- crates/forge-web-repo/Cargo.toml +0 -1
- crates/forge-web/Cargo.toml +0 -2
- crates/forge-web/assets/nav.js +0 -12
- crates/forge-web/src/boot.rs +0 -2
- crates/forge-web/src/forgejo_tests.rs +0 -404
- crates/forge-web/src/importer_route_tests.rs +0 -599
- crates/forge-web/src/main.rs +0 -2
- crates/forge-web/src/routes.snap +0 -16
- docs/architecture.md +1 -1
- docs/ui-language.md +1 -1
- style/_import.scss +0 -81
- style/_look.scss +0 -1
- style/_min_settings.scss +1 -24
- style/main.scss +0 -1
Cargo.lockmodified+0 -7
| @@ -2025,7 +2025,6 @@ dependencies = [ | ||
| 2025 | 2025 | "tempfile", |
| 2026 | 2026 | "tokio", |
| 2027 | 2027 | "tokio-util", |
| 2028 | - "zip", | |
| 2029 | 2028 | ] |
| 2030 | 2029 | |
| 2031 | 2030 | [[package]] |
| @@ -2117,14 +2116,12 @@ dependencies = [ | ||
| 2117 | 2116 | "reqwest", |
| 2118 | 2117 | "rpassword", |
| 2119 | 2118 | "serde_json", |
| 2120 | - "tar", | |
| 2121 | 2119 | "tempfile", |
| 2122 | 2120 | "time", |
| 2123 | 2121 | "tokio", |
| 2124 | 2122 | "topcoat", |
| 2125 | 2123 | "tracing", |
| 2126 | 2124 | "tracing-subscriber", |
| 2127 | - "zip", | |
| 2128 | 2125 | ] |
| 2129 | 2126 | |
| 2130 | 2127 | [[package]] |
| @@ -2168,7 +2165,6 @@ dependencies = [ | ||
| 2168 | 2165 | "async-compression", |
| 2169 | 2166 | "base64 0.23.1", |
| 2170 | 2167 | "bytes", |
| 2171 | - "flate2", | |
| 2172 | 2168 | "forge-ci", |
| 2173 | 2169 | "forge-core", |
| 2174 | 2170 | "forge-git", |
| @@ -2192,7 +2188,6 @@ dependencies = [ | ||
| 2192 | 2188 | "serde_json", |
| 2193 | 2189 | "sha2 0.11.1", |
| 2194 | 2190 | "similar", |
| 2195 | - "tar", | |
| 2196 | 2191 | "tempfile", |
| 2197 | 2192 | "time", |
| 2198 | 2193 | "tokio", |
| @@ -2252,7 +2247,6 @@ dependencies = [ | ||
| 2252 | 2247 | "serde", |
| 2253 | 2248 | "serde_json", |
| 2254 | 2249 | "similar", |
| 2255 | - "tar", | |
| 2256 | 2250 | "tempfile", |
| 2257 | 2251 | "time", |
| 2258 | 2252 | "tokio", |
| @@ -2286,7 +2280,6 @@ dependencies = [ | ||
| 2286 | 2280 | "serde", |
| 2287 | 2281 | "serde_json", |
| 2288 | 2282 | "sha2 0.11.1", |
| 2289 | - "tar", | |
| 2290 | 2283 | "tempfile", |
| 2291 | 2284 | "time", |
| 2292 | 2285 | "tokio", |
crates/forge-core/src/store/exports.rsdeleted+0 -150
| @@ -1,150 +0,0 @@ | ||
| 1 | -use std::time::Duration; | |
| 2 | - | |
| 3 | -use turso::{Row, Value}; | |
| 4 | - | |
| 5 | -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; | |
| 6 | -use crate::error::Result; | |
| 7 | -use crate::time::{now_stamp, stamp_after}; | |
| 8 | - | |
| 9 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 10 | -pub enum ExportState { | |
| 11 | - Building, | |
| 12 | - Ready, | |
| 13 | - Failed, | |
| 14 | -} | |
| 15 | - | |
| 16 | -string_enum!(ExportState { | |
| 17 | - Building = "building", | |
| 18 | - Ready = "ready", | |
| 19 | - Failed = "failed", | |
| 20 | -}); | |
| 21 | - | |
| 22 | -#[derive(Debug, Clone, PartialEq)] | |
| 23 | -pub struct DataExport { | |
| 24 | - pub id: String, | |
| 25 | - pub user_id: String, | |
| 26 | - pub state: ExportState, | |
| 27 | - pub size: i64, | |
| 28 | - pub error: Option<String>, | |
| 29 | - pub created_at: String, | |
| 30 | - pub ready_at: Option<String>, | |
| 31 | - pub expires_at: String, | |
| 32 | -} | |
| 33 | - | |
| 34 | -const COLS: &str = "id, user_id, state, size, error, created_at, ready_at, expires_at"; | |
| 35 | - | |
| 36 | -fn map_export(row: &Row) -> Result<DataExport> { | |
| 37 | - Ok(DataExport { | |
| 38 | - id: col_text(row, 0)?, | |
| 39 | - user_id: col_text(row, 1)?, | |
| 40 | - state: col_text(row, 2)? | |
| 41 | - .parse::<ExportState>() | |
| 42 | - .unwrap_or(ExportState::Building), | |
| 43 | - size: col_int(row, 3)?, | |
| 44 | - error: col_opt_text(row, 4)?, | |
| 45 | - created_at: col_text(row, 5)?, | |
| 46 | - ready_at: col_opt_text(row, 6)?, | |
| 47 | - expires_at: col_text(row, 7)?, | |
| 48 | - }) | |
| 49 | -} | |
| 50 | - | |
| 51 | -impl Store { | |
| 52 | - pub async fn create_export(&self, user_id: &str, ttl: Duration) -> Result<DataExport> { | |
| 53 | - let id = new_id(); | |
| 54 | - let now = now_stamp(); | |
| 55 | - let expires = stamp_after(ttl); | |
| 56 | - { | |
| 57 | - let conn = self.inner.conn.lock().await; | |
| 58 | - conn.execute( | |
| 59 | - "INSERT INTO data_exports (id, user_id, created_at, expires_at) \ | |
| 60 | - VALUES (?1, ?2, ?3, ?4)", | |
| 61 | - (id.clone(), user_id.to_owned(), now, expires), | |
| 62 | - ) | |
| 63 | - .await | |
| 64 | - .map_err(db_err)?; | |
| 65 | - } | |
| 66 | - self.data_export(&id).await?.ok_or_else(super::missing_row) | |
| 67 | - } | |
| 68 | - | |
| 69 | - pub async fn data_export(&self, id: &str) -> Result<Option<DataExport>> { | |
| 70 | - let conn = self.inner.conn.lock().await; | |
| 71 | - fetch_opt( | |
| 72 | - &conn, | |
| 73 | - &format!("SELECT {COLS} FROM data_exports WHERE id = ?1"), | |
| 74 | - (id.to_owned(),), | |
| 75 | - map_export, | |
| 76 | - ) | |
| 77 | - .await | |
| 78 | - } | |
| 79 | - | |
| 80 | - pub async fn list_exports(&self, user_id: &str) -> Result<Vec<DataExport>> { | |
| 81 | - let conn = self.inner.conn.lock().await; | |
| 82 | - fetch_all( | |
| 83 | - &conn, | |
| 84 | - &format!( | |
| 85 | - "SELECT {COLS} FROM data_exports WHERE user_id = ?1 ORDER BY created_at DESC, id DESC" | |
| 86 | - ), | |
| 87 | - (user_id.to_owned(),), | |
| 88 | - map_export, | |
| 89 | - ) | |
| 90 | - .await | |
| 91 | - } | |
| 92 | - | |
| 93 | - pub async fn mark_export_ready(&self, id: &str, size: i64, ttl: Duration) -> Result<()> { | |
| 94 | - let conn = self.inner.conn.lock().await; | |
| 95 | - conn.execute( | |
| 96 | - "UPDATE data_exports SET state = 'ready', size = ?2, ready_at = ?3, expires_at = ?4 \ | |
| 97 | - WHERE id = ?1", | |
| 98 | - vec![ | |
| 99 | - Value::Text(id.to_owned()), | |
| 100 | - Value::Integer(size), | |
| 101 | - Value::Text(now_stamp()), | |
| 102 | - Value::Text(stamp_after(ttl)), | |
| 103 | - ], | |
| 104 | - ) | |
| 105 | - .await | |
| 106 | - .map_err(db_err)?; | |
| 107 | - Ok(()) | |
| 108 | - } | |
| 109 | - | |
| 110 | - pub async fn mark_export_failed(&self, id: &str, error: &str) -> Result<()> { | |
| 111 | - let conn = self.inner.conn.lock().await; | |
| 112 | - conn.execute( | |
| 113 | - "UPDATE data_exports SET state = 'failed', error = ?2 WHERE id = ?1", | |
| 114 | - (id.to_owned(), error.to_owned()), | |
| 115 | - ) | |
| 116 | - .await | |
| 117 | - .map_err(db_err)?; | |
| 118 | - Ok(()) | |
| 119 | - } | |
| 120 | - | |
| 121 | - pub async fn expired_exports(&self, now: &str) -> Result<Vec<DataExport>> { | |
| 122 | - let conn = self.inner.conn.lock().await; | |
| 123 | - fetch_all( | |
| 124 | - &conn, | |
| 125 | - &format!("SELECT {COLS} FROM data_exports WHERE expires_at <= ?1"), | |
| 126 | - (now.to_owned(),), | |
| 127 | - map_export, | |
| 128 | - ) | |
| 129 | - .await | |
| 130 | - } | |
| 131 | - | |
| 132 | - pub async fn delete_export(&self, id: &str) -> Result<()> { | |
| 133 | - let conn = self.inner.conn.lock().await; | |
| 134 | - conn.execute("DELETE FROM data_exports WHERE id = ?1", (id.to_owned(),)) | |
| 135 | - .await | |
| 136 | - .map_err(db_err)?; | |
| 137 | - Ok(()) | |
| 138 | - } | |
| 139 | - | |
| 140 | - pub async fn fail_interrupted_exports(&self) -> Result<u64> { | |
| 141 | - let conn = self.inner.conn.lock().await; | |
| 142 | - conn.execute( | |
| 143 | - "UPDATE data_exports SET state = 'failed', error = 'interrupted by a server restart' \ | |
| 144 | - WHERE state = 'building'", | |
| 145 | - (), | |
| 146 | - ) | |
| 147 | - .await | |
| 148 | - .map_err(db_err) | |
| 149 | - } | |
| 150 | -} |
crates/forge-core/src/store/imports.rsdeleted+0 -340
| @@ -1,340 +0,0 @@ | ||
| 1 | -use turso::{Row, Value}; | |
| 2 | - | |
| 3 | -use super::issues::parse_db; | |
| 4 | -use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id, text}; | |
| 5 | -use crate::error::Result; | |
| 6 | -use crate::time::now_stamp; | |
| 7 | - | |
| 8 | -pub const MAX_EVENTS: i64 = 500; | |
| 9 | - | |
| 10 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 11 | -pub enum ImportState { | |
| 12 | - Queued, | |
| 13 | - Running, | |
| 14 | - Done, | |
| 15 | - Failed, | |
| 16 | -} | |
| 17 | - | |
| 18 | -string_enum!(ImportState { | |
| 19 | - Queued = "queued", | |
| 20 | - Running = "running", | |
| 21 | - Done = "done", | |
| 22 | - Failed = "failed", | |
| 23 | -}); | |
| 24 | - | |
| 25 | -impl ImportState { | |
| 26 | - pub fn is_finished(self) -> bool { | |
| 27 | - matches!(self, ImportState::Done | ImportState::Failed) | |
| 28 | - } | |
| 29 | -} | |
| 30 | - | |
| 31 | -#[derive(Debug, Clone, PartialEq)] | |
| 32 | -pub struct ImportJob { | |
| 33 | - pub id: String, | |
| 34 | - pub user_id: String, | |
| 35 | - pub repo_id: Option<String>, | |
| 36 | - pub source: String, | |
| 37 | - pub source_ref: String, | |
| 38 | - pub options: String, | |
| 39 | - pub state: ImportState, | |
| 40 | - pub stage: String, | |
| 41 | - pub done: i64, | |
| 42 | - pub total: i64, | |
| 43 | - pub error: Option<String>, | |
| 44 | - pub created_at: String, | |
| 45 | - pub updated_at: String, | |
| 46 | - pub finished_at: Option<String>, | |
| 47 | -} | |
| 48 | - | |
| 49 | -#[derive(Debug, Clone, PartialEq)] | |
| 50 | -pub struct ImportEvent { | |
| 51 | - pub seq: i64, | |
| 52 | - pub level: String, | |
| 53 | - pub message: String, | |
| 54 | - pub created_at: String, | |
| 55 | -} | |
| 56 | - | |
| 57 | -#[derive(Debug, Clone, PartialEq)] | |
| 58 | -pub struct ImportOrigin { | |
| 59 | - pub local_id: String, | |
| 60 | - pub author: String, | |
| 61 | - pub url: String, | |
| 62 | -} | |
| 63 | - | |
| 64 | -const JOB_COLS: &str = "id, user_id, repo_id, source, source_ref, options, state, stage, done, \ | |
| 65 | - total, error, created_at, updated_at, finished_at"; | |
| 66 | - | |
| 67 | -fn map_job(row: &Row) -> Result<ImportJob> { | |
| 68 | - Ok(ImportJob { | |
| 69 | - id: col_text(row, 0)?, | |
| 70 | - user_id: col_text(row, 1)?, | |
| 71 | - repo_id: col_opt_text(row, 2)?, | |
| 72 | - source: col_text(row, 3)?, | |
| 73 | - source_ref: col_text(row, 4)?, | |
| 74 | - options: col_text(row, 5)?, | |
| 75 | - state: parse_db(&col_text(row, 6)?)?, | |
| 76 | - stage: col_text(row, 7)?, | |
| 77 | - done: col_int(row, 8)?, | |
| 78 | - total: col_int(row, 9)?, | |
| 79 | - error: col_opt_text(row, 10)?, | |
| 80 | - created_at: col_text(row, 11)?, | |
| 81 | - updated_at: col_text(row, 12)?, | |
| 82 | - finished_at: col_opt_text(row, 13)?, | |
| 83 | - }) | |
| 84 | -} | |
| 85 | - | |
| 86 | -impl Store { | |
| 87 | - pub async fn create_import_job( | |
| 88 | - &self, | |
| 89 | - user_id: &str, | |
| 90 | - repo_id: &str, | |
| 91 | - source: &str, | |
| 92 | - source_ref: &str, | |
| 93 | - options: &str, | |
| 94 | - ) -> Result<ImportJob> { | |
| 95 | - let id = new_id(); | |
| 96 | - let now = now_stamp(); | |
| 97 | - { | |
| 98 | - let conn = self.inner.conn.lock().await; | |
| 99 | - conn.execute( | |
| 100 | - "INSERT INTO import_jobs (id, user_id, repo_id, source, source_ref, options, \ | |
| 101 | - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)", | |
| 102 | - vec![ | |
| 103 | - text(&id), | |
| 104 | - text(user_id), | |
| 105 | - text(repo_id), | |
| 106 | - text(source), | |
| 107 | - text(source_ref), | |
| 108 | - text(options), | |
| 109 | - text(&now), | |
| 110 | - ], | |
| 111 | - ) | |
| 112 | - .await | |
| 113 | - .map_err(db_err)?; | |
| 114 | - } | |
| 115 | - self.import_job(&id).await?.ok_or_else(super::missing_row) | |
| 116 | - } | |
| 117 | - | |
| 118 | - pub async fn import_job(&self, id: &str) -> Result<Option<ImportJob>> { | |
| 119 | - let conn = self.inner.conn.lock().await; | |
| 120 | - fetch_opt( | |
| 121 | - &conn, | |
| 122 | - &format!("SELECT {JOB_COLS} FROM import_jobs WHERE id = ?1"), | |
| 123 | - (id.to_owned(),), | |
| 124 | - map_job, | |
| 125 | - ) | |
| 126 | - .await | |
| 127 | - } | |
| 128 | - | |
| 129 | - pub async fn list_import_jobs(&self, user_id: &str, limit: u32) -> Result<Vec<ImportJob>> { | |
| 130 | - let conn = self.inner.conn.lock().await; | |
| 131 | - fetch_all( | |
| 132 | - &conn, | |
| 133 | - &format!( | |
| 134 | - "SELECT {JOB_COLS} FROM import_jobs WHERE user_id = ?1 \ | |
| 135 | - ORDER BY created_at DESC, id DESC LIMIT ?2" | |
| 136 | - ), | |
| 137 | - (user_id.to_owned(), i64::from(limit.clamp(1, 200))), | |
| 138 | - map_job, | |
| 139 | - ) | |
| 140 | - .await | |
| 141 | - } | |
| 142 | - | |
| 143 | - pub async fn active_import_for_repo(&self, repo_id: &str) -> Result<Option<ImportJob>> { | |
| 144 | - let conn = self.inner.conn.lock().await; | |
| 145 | - fetch_opt( | |
| 146 | - &conn, | |
| 147 | - &format!( | |
| 148 | - "SELECT {JOB_COLS} FROM import_jobs WHERE repo_id = ?1 \ | |
| 149 | - AND state IN ('queued', 'running') LIMIT 1" | |
| 150 | - ), | |
| 151 | - (repo_id.to_owned(),), | |
| 152 | - map_job, | |
| 153 | - ) | |
| 154 | - .await | |
| 155 | - } | |
| 156 | - | |
| 157 | - pub async fn set_import_state( | |
| 158 | - &self, | |
| 159 | - id: &str, | |
| 160 | - state: ImportState, | |
| 161 | - error: Option<&str>, | |
| 162 | - ) -> Result<()> { | |
| 163 | - let now = now_stamp(); | |
| 164 | - let finished = if state.is_finished() { | |
| 165 | - text(&now) | |
| 166 | - } else { | |
| 167 | - Value::Null | |
| 168 | - }; | |
| 169 | - let conn = self.inner.conn.lock().await; | |
| 170 | - conn.execute( | |
| 171 | - "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \ | |
| 172 | - WHERE id = ?1", | |
| 173 | - vec![ | |
| 174 | - text(id), | |
| 175 | - text(state.as_str()), | |
| 176 | - error.map_or(Value::Null, text), | |
| 177 | - text(&now), | |
| 178 | - finished, | |
| 179 | - ], | |
| 180 | - ) | |
| 181 | - .await | |
| 182 | - .map_err(db_err)?; | |
| 183 | - Ok(()) | |
| 184 | - } | |
| 185 | - | |
| 186 | - pub async fn requeue_failed_import(&self, id: &str) -> Result<bool> { | |
| 187 | - let conn = self.inner.conn.lock().await; | |
| 188 | - let changed = conn | |
| 189 | - .execute( | |
| 190 | - "UPDATE import_jobs SET state = 'queued', error = NULL, finished_at = NULL, \ | |
| 191 | - updated_at = ?2 WHERE id = ?1 AND state = 'failed' AND NOT EXISTS (\ | |
| 192 | - SELECT 1 FROM import_jobs other WHERE other.repo_id = \ | |
| 193 | - (SELECT repo_id FROM import_jobs WHERE id = ?1) \ | |
| 194 | - AND other.state IN ('queued', 'running'))", | |
| 195 | - vec![text(id), text(&now_stamp())], | |
| 196 | - ) | |
| 197 | - .await | |
| 198 | - .map_err(db_err)?; | |
| 199 | - Ok(changed > 0) | |
| 200 | - } | |
| 201 | - | |
| 202 | - pub async fn set_import_progress( | |
| 203 | - &self, | |
| 204 | - id: &str, | |
| 205 | - stage: &str, | |
| 206 | - done: i64, | |
| 207 | - total: i64, | |
| 208 | - ) -> Result<()> { | |
| 209 | - let conn = self.inner.conn.lock().await; | |
| 210 | - conn.execute( | |
| 211 | - "UPDATE import_jobs SET stage = ?2, done = ?3, total = ?4, updated_at = ?5 WHERE id = ?1", | |
| 212 | - vec![ | |
| 213 | - text(id), | |
| 214 | - text(stage), | |
| 215 | - Value::Integer(done), | |
| 216 | - Value::Integer(total), | |
| 217 | - text(&now_stamp()), | |
| 218 | - ], | |
| 219 | - ) | |
| 220 | - .await | |
| 221 | - .map_err(db_err)?; | |
| 222 | - Ok(()) | |
| 223 | - } | |
| 224 | - | |
| 225 | - pub async fn add_import_event(&self, job_id: &str, level: &str, message: &str) -> Result<()> { | |
| 226 | - let conn = self.inner.conn.lock().await; | |
| 227 | - let next = fetch_opt( | |
| 228 | - &conn, | |
| 229 | - "SELECT COALESCE(MAX(seq), 0) + 1 FROM import_events WHERE job_id = ?1", | |
| 230 | - (job_id.to_owned(),), | |
| 231 | - |row| col_int(row, 0), | |
| 232 | - ) | |
| 233 | - .await? | |
| 234 | - .unwrap_or(1); | |
| 235 | - conn.execute( | |
| 236 | - "INSERT INTO import_events (job_id, seq, level, message, created_at) \ | |
| 237 | - VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 238 | - vec![ | |
| 239 | - text(job_id), | |
| 240 | - Value::Integer(next), | |
| 241 | - text(level), | |
| 242 | - text(message), | |
| 243 | - text(&now_stamp()), | |
| 244 | - ], | |
| 245 | - ) | |
| 246 | - .await | |
| 247 | - .map_err(db_err)?; | |
| 248 | - conn.execute( | |
| 249 | - "DELETE FROM import_events WHERE job_id = ?1 AND seq <= ?2", | |
| 250 | - (job_id.to_owned(), next - MAX_EVENTS), | |
| 251 | - ) | |
| 252 | - .await | |
| 253 | - .map_err(db_err)?; | |
| 254 | - Ok(()) | |
| 255 | - } | |
| 256 | - | |
| 257 | - pub async fn list_import_events(&self, job_id: &str, limit: u32) -> Result<Vec<ImportEvent>> { | |
| 258 | - let conn = self.inner.conn.lock().await; | |
| 259 | - let mut rows = fetch_all( | |
| 260 | - &conn, | |
| 261 | - "SELECT seq, level, message, created_at FROM import_events WHERE job_id = ?1 \ | |
| 262 | - ORDER BY seq DESC LIMIT ?2", | |
| 263 | - (job_id.to_owned(), i64::from(limit.clamp(1, 500))), | |
| 264 | - |row| { | |
| 265 | - Ok(ImportEvent { | |
| 266 | - seq: col_int(row, 0)?, | |
| 267 | - level: col_text(row, 1)?, | |
| 268 | - message: col_text(row, 2)?, | |
| 269 | - created_at: col_text(row, 3)?, | |
| 270 | - }) | |
| 271 | - }, | |
| 272 | - ) | |
| 273 | - .await?; | |
| 274 | - rows.reverse(); | |
| 275 | - Ok(rows) | |
| 276 | - } | |
| 277 | - | |
| 278 | - pub async fn import_origin( | |
| 279 | - &self, | |
| 280 | - repo_id: &str, | |
| 281 | - kind: &str, | |
| 282 | - ext_id: &str, | |
| 283 | - ) -> Result<Option<ImportOrigin>> { | |
| 284 | - let conn = self.inner.conn.lock().await; | |
| 285 | - fetch_opt( | |
| 286 | - &conn, | |
| 287 | - "SELECT local_id, orig_author, orig_url FROM import_map \ | |
| 288 | - WHERE repo_id = ?1 AND kind = ?2 AND ext_id = ?3", | |
| 289 | - (repo_id.to_owned(), kind.to_owned(), ext_id.to_owned()), | |
| 290 | - |row| { | |
| 291 | - Ok(ImportOrigin { | |
| 292 | - local_id: col_text(row, 0)?, | |
| 293 | - author: col_text(row, 1)?, | |
| 294 | - url: col_text(row, 2)?, | |
| 295 | - }) | |
| 296 | - }, | |
| 297 | - ) | |
| 298 | - .await | |
| 299 | - } | |
| 300 | - | |
| 301 | - pub async fn record_import_origin( | |
| 302 | - &self, | |
| 303 | - repo_id: &str, | |
| 304 | - kind: &str, | |
| 305 | - ext_id: &str, | |
| 306 | - origin: &ImportOrigin, | |
| 307 | - ) -> Result<()> { | |
| 308 | - let conn = self.inner.conn.lock().await; | |
| 309 | - conn.execute( | |
| 310 | - "INSERT INTO import_map (repo_id, kind, ext_id, local_id, orig_author, orig_url) \ | |
| 311 | - VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(repo_id, kind, ext_id) DO UPDATE SET \ | |
| 312 | - local_id = excluded.local_id, orig_author = excluded.orig_author, \ | |
| 313 | - orig_url = excluded.orig_url", | |
| 314 | - vec![ | |
| 315 | - text(repo_id), | |
| 316 | - text(kind), | |
| 317 | - text(ext_id), | |
| 318 | - text(&origin.local_id), | |
| 319 | - text(&origin.author), | |
| 320 | - text(&origin.url), | |
| 321 | - ], | |
| 322 | - ) | |
| 323 | - .await | |
| 324 | - .map_err(db_err)?; | |
| 325 | - Ok(()) | |
| 326 | - } | |
| 327 | - | |
| 328 | - pub async fn fail_interrupted_imports(&self) -> Result<u64> { | |
| 329 | - let now = now_stamp(); | |
| 330 | - let conn = self.inner.conn.lock().await; | |
| 331 | - conn.execute( | |
| 332 | - "UPDATE import_jobs SET state = 'failed', updated_at = ?1, finished_at = ?1, \ | |
| 333 | - error = 'interrupted by a server restart, retry to continue' \ | |
| 334 | - WHERE state IN ('queued', 'running')", | |
| 335 | - (now,), | |
| 336 | - ) | |
| 337 | - .await | |
| 338 | - .map_err(db_err) | |
| 339 | - } | |
| 340 | -} |
crates/forge-core/src/store/mod.rsmodified+0 -2
| @@ -7,9 +7,7 @@ pub mod ci; | ||
| 7 | 7 | pub mod commit_status; |
| 8 | 8 | pub mod contributions; |
| 9 | 9 | pub mod edit_history_read; |
| 10 | -pub mod exports; | |
| 11 | 10 | pub mod health; |
| 12 | -pub mod imports; | |
| 13 | 11 | pub mod issues; |
| 14 | 12 | pub mod labels; |
| 15 | 13 | pub mod lfs; |
crates/forge-e2e/Cargo.tomlmodified+0 -1
| @@ -19,7 +19,6 @@ tokio.workspace = true | ||
| 19 | 19 | tokio-util = { workspace = true, features = ["io"] } |
| 20 | 20 | reqwest.workspace = true |
| 21 | 21 | serde_json.workspace = true |
| 22 | -zip = { workspace = true } | |
| 23 | 22 | tempfile.workspace = true |
| 24 | 23 | scraper = { workspace = true } |
| 25 | 24 |
crates/forge-e2e/tests/e2e/section_nav_e2e.rsmodified+0 -1
| @@ -90,7 +90,6 @@ async fn settings_pages_get_the_settings_tabs() { | ||
| 90 | 90 | "/settings/notifications", |
| 91 | 91 | "/settings/security", |
| 92 | 92 | "/settings/keys", |
| 93 | - "/settings/export", | |
| 94 | 93 | ]; |
| 95 | 94 | let pages = [ |
| 96 | 95 | ("/settings/profile", "/settings/profile"), |
crates/forge-web-account/src/lib.rsmodified+2 -2
| @@ -3,8 +3,8 @@ | ||
| 3 | 3 | #[cfg(test)] |
| 4 | 4 | pub(crate) use forge_web_app::test_support; |
| 5 | 5 | pub(crate) use forge_web_app::{ |
| 6 | - accent, alerts, api, audit, auth, backup, client_ip, custom_colour, exporter, i18n, importer, | |
| 7 | - live, mail, mirrors, render, self_update, signatures, state, theme, throttle, views, webhooks, | |
| 6 | + accent, alerts, api, audit, auth, backup, client_ip, custom_colour, i18n, live, mail, render, | |
| 7 | + self_update, signatures, state, theme, throttle, views, | |
| 8 | 8 | }; |
| 9 | 9 | #[cfg(test)] |
| 10 | 10 | pub(crate) use forge_web_app::{blobs, release_ops, replication}; |
crates/forge-web-account/src/pages/home.rsmodified+0 -3
| @@ -9,7 +9,6 @@ use topcoat::view::{View, component, view}; | ||
| 9 | 9 | |
| 10 | 10 | use crate::auth::current_user; |
| 11 | 11 | use crate::i18n::authoring::{self as ga}; |
| 12 | -use crate::i18n::migrate::{self as mg, K as MGK}; | |
| 13 | 12 | use crate::i18n::needs::{self as ni, K as NK}; |
| 14 | 13 | use crate::i18n::orgs::{self as g, K}; |
| 15 | 14 | use crate::i18n::s; |
| @@ -192,11 +191,9 @@ async fn signed_home(cx: &Cx, lang: Lang, data: SignedHome, may_org: bool) -> Re | ||
| 192 | 191 | let repos_heading = s(lang, "Your repositories", "Depolarınız"); |
| 193 | 192 | let all = s(lang, "View all", "Tümünü gör"); |
| 194 | 193 | let no_repos = s(lang, "You have no repositories yet.", "Henüz deponuz yok."); |
| 195 | - let import_label = mg::t(lang, MGK::TabImport); | |
| 196 | 194 | Ok(view! { |
| 197 | 195 | head(title: g::t(lang, K::Home), |
| 198 | 196 | <a class="button primary" href="/new">(g::t(lang, K::NewRepository))</a> |
| 199 | - <a class="button" href="/new/import">(import_label)</a> | |
| 200 | 197 | if may_org { |
| 201 | 198 | <a class="button" href="/org/new">(g::t(lang, K::NewOrganization))</a> |
| 202 | 199 | } |
crates/forge-web-account/src/pages/import.rsdeleted+0 -1420
| @@ -1,1420 +0,0 @@ | ||
| 1 | -use std::collections::HashMap; | |
| 2 | - | |
| 3 | -use forge_core::store::imports::{ImportJob, ImportState}; | |
| 4 | -use forge_core::{AuditAction, Repo, User, Visibility}; | |
| 5 | -use forge_git::repo::{init_bare, repo_path}; | |
| 6 | -use futures_util::stream; | |
| 7 | -use serde::Deserialize; | |
| 8 | -use topcoat::Result; | |
| 9 | -use topcoat::context::{Cx, context}; | |
| 10 | -use topcoat::router::content::Form; | |
| 11 | -use topcoat::router::error::{SeeOther, not_found, see_other}; | |
| 12 | -use topcoat::router::response::Response; | |
| 13 | -use topcoat::router::{page, path_param, query_params, route}; | |
| 14 | -use topcoat::view::{View, component, view}; | |
| 15 | - | |
| 16 | -use crate::audit::{self, Actor, Target}; | |
| 17 | -use crate::auth::{require_csrf, require_user}; | |
| 18 | -use crate::i18n::migrate::{self as g, K}; | |
| 19 | -use crate::i18n::{self, Lang}; | |
| 20 | -use crate::importer::api::{ApiError, ExtRepo, RemoteApi}; | |
| 21 | -use crate::importer::{ | |
| 22 | - self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, | |
| 23 | - parse_remote, source_ref, | |
| 24 | -}; | |
| 25 | -use crate::live::{Topic, stream_changes}; | |
| 26 | -use crate::live::{changed_event, events_response}; | |
| 27 | -use crate::pages::new_repo::{owner_choices, repo_owner}; | |
| 28 | -use crate::pages::repo_ctx::still_readable; | |
| 29 | -use crate::state::AppState; | |
| 30 | -use crate::views::paging::{paginate, requested_page}; | |
| 31 | -use crate::views::parts::{SubPart, head}; | |
| 32 | -use crate::views::repo_list::{PageLink, pager, pager_links}; | |
| 33 | -use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message}; | |
| 34 | - | |
| 35 | -path_param!(job_id); | |
| 36 | - | |
| 37 | -const MAX_BULK: usize = 50; | |
| 38 | -const DEFAULT_BRANCH: &str = "main"; | |
| 39 | - | |
| 40 | -#[derive(Deserialize, Default)] | |
| 41 | -struct ImportForm { | |
| 42 | - #[serde(default)] | |
| 43 | - csrf: String, | |
| 44 | - #[serde(default)] | |
| 45 | - source: String, | |
| 46 | - #[serde(default)] | |
| 47 | - remote: String, | |
| 48 | - #[serde(default)] | |
| 49 | - instance: String, | |
| 50 | - #[serde(default)] | |
| 51 | - token: String, | |
| 52 | - #[serde(default)] | |
| 53 | - git_user: String, | |
| 54 | - #[serde(default)] | |
| 55 | - owner: String, | |
| 56 | - #[serde(default)] | |
| 57 | - name: String, | |
| 58 | - #[serde(default)] | |
| 59 | - description: String, | |
| 60 | - #[serde(default)] | |
| 61 | - visibility: String, | |
| 62 | - #[serde(default)] | |
| 63 | - opt_labels: String, | |
| 64 | - #[serde(default)] | |
| 65 | - opt_issues: String, | |
| 66 | - #[serde(default)] | |
| 67 | - opt_pulls: String, | |
| 68 | - #[serde(default)] | |
| 69 | - opt_releases: String, | |
| 70 | -} | |
| 71 | - | |
| 72 | -#[derive(Deserialize, Default)] | |
| 73 | -struct BulkForm { | |
| 74 | - #[serde(default)] | |
| 75 | - csrf: String, | |
| 76 | - #[serde(default)] | |
| 77 | - stage: String, | |
| 78 | - #[serde(default)] | |
| 79 | - source: String, | |
| 80 | - #[serde(default)] | |
| 81 | - instance: String, | |
| 82 | - #[serde(default)] | |
| 83 | - token: String, | |
| 84 | - #[serde(default)] | |
| 85 | - from: String, | |
| 86 | - #[serde(default)] | |
| 87 | - owner: String, | |
| 88 | - #[serde(default)] | |
| 89 | - visibility: String, | |
| 90 | - #[serde(default)] | |
| 91 | - opt_labels: String, | |
| 92 | - #[serde(default)] | |
| 93 | - opt_issues: String, | |
| 94 | - #[serde(default)] | |
| 95 | - opt_pulls: String, | |
| 96 | - #[serde(default)] | |
| 97 | - opt_releases: String, | |
| 98 | - #[serde(flatten)] | |
| 99 | - extra: HashMap<String, String>, | |
| 100 | -} | |
| 101 | - | |
| 102 | -#[query_params(error = bad_request)] | |
| 103 | -struct SourceQuery { | |
| 104 | - source: Option<String>, | |
| 105 | - error: Option<String>, | |
| 106 | -} | |
| 107 | - | |
| 108 | -#[query_params(error = bad_request)] | |
| 109 | -struct JobsQuery { | |
| 110 | - skipped: Option<String>, | |
| 111 | - page: Option<String>, | |
| 112 | -} | |
| 113 | - | |
| 114 | -#[query_params(error = bad_request)] | |
| 115 | -struct SeenQuery { | |
| 116 | - v: Option<String>, | |
| 117 | -} | |
| 118 | - | |
| 119 | -fn options_of(labels: &str, issues: &str, pulls: &str, releases: &str) -> ImportOptions { | |
| 120 | - ImportOptions { | |
| 121 | - labels: !labels.is_empty(), | |
| 122 | - issues: !issues.is_empty(), | |
| 123 | - pulls: !pulls.is_empty(), | |
| 124 | - releases: !releases.is_empty(), | |
| 125 | - } | |
| 126 | -} | |
| 127 | - | |
| 128 | -fn source_of(raw: Option<&str>) -> Source { | |
| 129 | - raw.and_then(Source::parse).unwrap_or(Source::GitHub) | |
| 130 | -} | |
| 131 | - | |
| 132 | -fn default_instance(source: Source) -> &'static str { | |
| 133 | - match source { | |
| 134 | - Source::Forgejo => "https://codeberg.org", | |
| 135 | - _ => "https://gitlab.com", | |
| 136 | - } | |
| 137 | -} | |
| 138 | - | |
| 139 | -fn has_instance(source: Source) -> bool { | |
| 140 | - matches!(source, Source::GitLab | Source::Forgejo) | |
| 141 | -} | |
| 142 | - | |
| 143 | -fn instance_label(lang: Lang, source: Source) -> &'static str { | |
| 144 | - if source == Source::Forgejo { | |
| 145 | - g::t(lang, K::ForgejoInstance) | |
| 146 | - } else { | |
| 147 | - g::t(lang, K::GitLabInstance) | |
| 148 | - } | |
| 149 | -} | |
| 150 | - | |
| 151 | -fn token_of(raw: &str) -> Option<String> { | |
| 152 | - let t = raw.trim(); | |
| 153 | - (!t.is_empty()).then(|| t.to_owned()) | |
| 154 | -} | |
| 155 | - | |
| 156 | -#[component] | |
| 157 | -pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<impl View> { | |
| 158 | - let create = active == "create"; | |
| 159 | - let import = active == "import"; | |
| 160 | - let history = active == "history"; | |
| 161 | - Ok(view! { | |
| 162 | - <nav class="tabs" aria-label=(g::t(lang, K::ImportTitle))> | |
| 163 | - <a href="/new" aria-current=(create.then_some("page"))>(g::t(lang, K::TabCreate))</a> | |
| 164 | - <a href="/new/import" aria-current=(import.then_some("page"))>(g::t(lang, K::TabImport))</a> | |
| 165 | - <a href="/import" aria-current=(history.then_some("page"))>(crate::i18n::s(lang, "Import history", "İçe aktarma geçmişi"))</a> | |
| 166 | - </nav> | |
| 167 | - }) | |
| 168 | -} | |
| 169 | - | |
| 170 | -#[component] | |
| 171 | -async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result<impl View> { | |
| 172 | - let git = format!("{base}?source=git"); | |
| 173 | - let github = format!("{base}?source=github"); | |
| 174 | - let gitlab = format!("{base}?source=gitlab"); | |
| 175 | - let forgejo = format!("{base}?source=forgejo"); | |
| 176 | - Ok(view! { | |
| 177 | - <div class="field"> | |
| 178 | - <span class="field-label">(crate::i18n::s(lang, "Source", "Kaynak"))</span> | |
| 179 | - <nav class="choice" aria-label=(g::t(lang, K::TabImport))> | |
| 180 | - <a href=(git.as_str()) aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a> | |
| 181 | - <a href=(github.as_str()) aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a> | |
| 182 | - <a href=(gitlab.as_str()) aria-current=((active == Source::GitLab).then_some("page"))>(g::t(lang, K::SrcGitLab))</a> | |
| 183 | - <a href=(forgejo.as_str()) aria-current=((active == Source::Forgejo).then_some("page"))>(g::t(lang, K::SrcForgejo))</a> | |
| 184 | - </nav> | |
| 185 | - </div> | |
| 186 | - }) | |
| 187 | -} | |
| 188 | - | |
| 189 | -#[component] | |
| 190 | -pub(crate) async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result<impl View> { | |
| 191 | - Ok(view! { | |
| 192 | - <div class="field"> | |
| 193 | - <span class="field-label">(crate::i18n::misc::t(lang, crate::i18n::misc::K::VisibilityLegend))</span> | |
| 194 | - <div class="choice" role="radiogroup" aria-label=(crate::i18n::misc::t(lang, crate::i18n::misc::K::VisibilityLegend))> | |
| 195 | - <label><input type="radio" name="visibility" value="private" checked=(private)><span>(crate::i18n::community::t(lang, crate::i18n::community::K::VisibilityPrivate))</span></label> | |
| 196 | - <label><input type="radio" name="visibility" value="public" checked=(!private)><span>(crate::i18n::community::t(lang, crate::i18n::community::K::VisibilityPublic))</span></label> | |
| 197 | - </div> | |
| 198 | - </div> | |
| 199 | - }) | |
| 200 | -} | |
| 201 | - | |
| 202 | -#[component] | |
| 203 | -async fn option_boxes(cx: &Cx, lang: Lang, opts: ImportOptions) -> Result<impl View> { | |
| 204 | - Ok(view! { | |
| 205 | - <div class="field" role="group" aria-labelledby="import-what"> | |
| 206 | - <span class="field-label" id="import-what">(g::t(lang, K::WhatToImport))</span> | |
| 207 | - <div class="checks"> | |
| 208 | - <label class="switch"><input type="checkbox" name="opt_labels" value="on" checked=(opts.labels)><span>(g::t(lang, K::OptLabels))</span></label> | |
| 209 | - <label class="switch"><input type="checkbox" name="opt_issues" value="on" checked=(opts.issues)><span>(g::t(lang, K::OptIssues))</span></label> | |
| 210 | - <label class="switch"><input type="checkbox" name="opt_pulls" value="on" checked=(opts.pulls)><span>(g::t(lang, K::OptPulls))</span></label> | |
| 211 | - <label class="switch"><input type="checkbox" name="opt_releases" value="on" checked=(opts.releases)><span>(g::t(lang, K::OptReleases))</span></label> | |
| 212 | - </div> | |
| 213 | - </div> | |
| 214 | - }) | |
| 215 | -} | |
| 216 | - | |
| 217 | -struct Draft { | |
| 218 | - source: Source, | |
| 219 | - remote: String, | |
| 220 | - instance: String, | |
| 221 | - git_user: String, | |
| 222 | - owner: String, | |
| 223 | - name: String, | |
| 224 | - description: String, | |
| 225 | - private: bool, | |
| 226 | - opts: ImportOptions, | |
| 227 | -} | |
| 228 | - | |
| 229 | -impl Draft { | |
| 230 | - fn fresh(source: Source) -> Self { | |
| 231 | - Draft { | |
| 232 | - source, | |
| 233 | - remote: String::new(), | |
| 234 | - instance: default_instance(source).into(), | |
| 235 | - git_user: String::new(), | |
| 236 | - owner: String::new(), | |
| 237 | - name: String::new(), | |
| 238 | - description: String::new(), | |
| 239 | - private: false, | |
| 240 | - opts: ImportOptions { | |
| 241 | - labels: true, | |
| 242 | - issues: true, | |
| 243 | - pulls: true, | |
| 244 | - releases: true, | |
| 245 | - }, | |
| 246 | - } | |
| 247 | - } | |
| 248 | - | |
| 249 | - fn from_form(form: &ImportForm, source: Source) -> Self { | |
| 250 | - Draft { | |
| 251 | - source, | |
| 252 | - remote: form.remote.trim().to_owned(), | |
| 253 | - instance: form.instance.trim().to_owned(), | |
| 254 | - git_user: form.git_user.trim().to_owned(), | |
| 255 | - owner: form.owner.trim().to_owned(), | |
| 256 | - name: form.name.trim().to_owned(), | |
| 257 | - description: form.description.clone(), | |
| 258 | - private: form.visibility != "public", | |
| 259 | - opts: options_of( | |
| 260 | - &form.opt_labels, | |
| 261 | - &form.opt_issues, | |
| 262 | - &form.opt_pulls, | |
| 263 | - &form.opt_releases, | |
| 264 | - ), | |
| 265 | - } | |
| 266 | - } | |
| 267 | -} | |
| 268 | - | |
| 269 | -#[component] | |
| 270 | -async fn import_form( | |
| 271 | - cx: &Cx, | |
| 272 | - lang: Lang, | |
| 273 | - username: String, | |
| 274 | - csrf: &str, | |
| 275 | - draft: Draft, | |
| 276 | - error: Option<String>, | |
| 277 | - owners: Vec<String>, | |
| 278 | -) -> Result<impl View> { | |
| 279 | - let source = draft.source; | |
| 280 | - let selected_owner = if draft.owner.is_empty() { | |
| 281 | - owners.first().cloned().unwrap_or_default() | |
| 282 | - } else { | |
| 283 | - draft.owner.clone() | |
| 284 | - }; | |
| 285 | - let source_value = source.as_str(); | |
| 286 | - let is_git = source == Source::Git; | |
| 287 | - let has_instance = has_instance(source); | |
| 288 | - let instance_label = instance_label(lang, source); | |
| 289 | - let bulk_href = if is_git { | |
| 290 | - String::new() | |
| 291 | - } else { | |
| 292 | - format!("/new/import/bulk?source={source_value}") | |
| 293 | - }; | |
| 294 | - let remote_label = match source { | |
| 295 | - Source::Git => g::t(lang, K::GitUrl), | |
| 296 | - Source::GitHub | Source::Forgejo => g::t(lang, K::GitHubRepo), | |
| 297 | - Source::GitLab => g::t(lang, K::GitLabProject), | |
| 298 | - }; | |
| 299 | - let remote_placeholder = match source { | |
| 300 | - Source::Git => "https://example.org/tahinli/project.git", | |
| 301 | - Source::GitHub => "tahinli/project", | |
| 302 | - Source::GitLab | Source::Forgejo => "tahinli/project", | |
| 303 | - }; | |
| 304 | - let token_label = if is_git { | |
| 305 | - g::t(lang, K::GitPassword) | |
| 306 | - } else { | |
| 307 | - g::t(lang, K::TokenOptional) | |
| 308 | - }; | |
| 309 | - let private = draft.private; | |
| 310 | - let opts = draft.opts; | |
| 311 | - Ok(view! { | |
| 312 | - head(title: g::t(lang, K::ImportTitle)) | |
| 313 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 314 | - newrepo_tabs(lang: lang, active: "import") | |
| 315 | - <div class="sheet fit"> | |
| 316 | - <form method="post" action="/new/import" class="fields"> | |
| 317 | - if let Some(message) = error { | |
| 318 | - alert(message: message.as_str()) | |
| 319 | - } | |
| 320 | - csrf_field(token: csrf) | |
| 321 | - <input type="hidden" name="source" value=(source_value)> | |
| 322 | - source_tabs(lang: lang, base: "/new/import", active: source) | |
| 323 | - if has_instance { | |
| 324 | - <div class="field"> | |
| 325 | - <label for="import-instance">(instance_label)</label> | |
| 326 | - <input id="import-instance" type="url" name="instance" value=(draft.instance.as_str()) autocomplete="off" spellcheck="false" maxlength="2048"> | |
| 327 | - </div> | |
| 328 | - } | |
| 329 | - <div class="field"> | |
| 330 | - <label for="import-remote">(remote_label)</label> | |
| 331 | - <input id="import-remote" type="text" name="remote" value=(draft.remote.as_str()) placeholder=(remote_placeholder) required=(true) autocomplete="off" spellcheck="false" maxlength="2048"> | |
| 332 | - </div> | |
| 333 | - if is_git { | |
| 334 | - <div class="field"> | |
| 335 | - <label for="import-git-user">(g::t(lang, K::GitUser))</label> | |
| 336 | - <input id="import-git-user" type="text" name="git_user" value=(draft.git_user.as_str()) autocomplete="off" maxlength="255"> | |
| 337 | - </div> | |
| 338 | - } | |
| 339 | - <div class="field"> | |
| 340 | - <label for="import-token">(token_label)</label> | |
| 341 | - <input id="import-token" type="password" name="token" autocomplete="new-password" maxlength="1024"> | |
| 342 | - </div> | |
| 343 | - if !is_git { | |
| 344 | - option_boxes(lang: lang, opts: opts) | |
| 345 | - } | |
| 346 | - <div class="field"> | |
| 347 | - <label for="import-owner">(g::t(lang, K::TargetOwner))</label> | |
| 348 | - <select id="import-owner" name="owner"> | |
| 349 | - for name in owners.iter() { | |
| 350 | - <option value=(name.as_str()) selected=(*name == selected_owner)>(name.as_str())</option> | |
| 351 | - } | |
| 352 | - </select> | |
| 353 | - </div> | |
| 354 | - <div class="field"> | |
| 355 | - <label for="import-name">(g::t(lang, K::TargetName))</label> | |
| 356 | - <input id="import-name" type="text" name="name" value=(draft.name.as_str()) maxlength="64" autocomplete="off"> | |
| 357 | - </div> | |
| 358 | - <div class="field"> | |
| 359 | - <label for="import-description">(g::t(lang, K::Description))</label> | |
| 360 | - <textarea id="import-description" name="description" rows="2" maxlength="350">(draft.description.as_str())</textarea> | |
| 361 | - </div> | |
| 362 | - visibility_pick(lang: lang, private: private) | |
| 363 | - <button type="submit" class="primary">(g::t(lang, K::StartImport))</button> | |
| 364 | - </form> | |
| 365 | - if !is_git { | |
| 366 | - <section class="sec"> | |
| 367 | - <h2>(g::t(lang, K::BulkLink))</h2> | |
| 368 | - <div class="acts"> | |
| 369 | - <a class="act" href=(bulk_href.as_str())>(g::t(lang, K::BulkLinkButton))</a> | |
| 370 | - </div> | |
| 371 | - </section> | |
| 372 | - } | |
| 373 | - </div> | |
| 374 | - }) | |
| 375 | -} | |
| 376 | - | |
| 377 | -#[component] | |
| 378 | -async fn import_home( | |
| 379 | - cx: &Cx, | |
| 380 | - lang: Lang, | |
| 381 | - username: String, | |
| 382 | - csrf: String, | |
| 383 | - draft: Draft, | |
| 384 | - owners: Vec<String>, | |
| 385 | -) -> Result<impl View> { | |
| 386 | - Ok(view! { | |
| 387 | - import_form(lang: lang, username: username, csrf: csrf.as_str(), draft: draft, error: None, owners: owners) | |
| 388 | - }) | |
| 389 | -} | |
| 390 | - | |
| 391 | -#[component] | |
| 392 | -async fn import_error_body( | |
| 393 | - cx: &Cx, | |
| 394 | - lang: Lang, | |
| 395 | - username: String, | |
| 396 | - csrf: String, | |
| 397 | - draft: Draft, | |
| 398 | - error: String, | |
| 399 | - owners: Vec<String>, | |
| 400 | -) -> Result<impl View> { | |
| 401 | - Ok(view! { | |
| 402 | - import_form(lang: lang, username: username, csrf: csrf.as_str(), draft: draft, error: Some(error), owners: owners) | |
| 403 | - }) | |
| 404 | -} | |
| 405 | - | |
| 406 | -#[page("/new/import")] | |
| 407 | -async fn import_page(cx: &Cx) -> Result<impl View> { | |
| 408 | - let viewer = require_user(cx).await?; | |
| 409 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 410 | - let query = query_params::<SourceQuery>(cx)?; | |
| 411 | - let source = source_of(query.source.as_deref()); | |
| 412 | - let state = context::<AppState>(cx); | |
| 413 | - let owners = owner_choices(state, &viewer.0).await?; | |
| 414 | - let csrf = viewer.1.csrf_token.clone(); | |
| 415 | - Ok(view! { | |
| 416 | - shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), | |
| 417 | - import_home(lang: lang, username: viewer.0.username.clone(), csrf: csrf, draft: Draft::fresh(source), owners: owners)) | |
| 418 | - }) | |
| 419 | -} | |
| 420 | - | |
| 421 | -#[page(POST "/new/import")] | |
| 422 | -async fn import_submit(cx: &Cx, Form(form): Form<ImportForm>) -> Result<impl View> { | |
| 423 | - let viewer = require_csrf(cx, &form.csrf).await?; | |
| 424 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 425 | - let source = source_of(Some(&form.source)); | |
| 426 | - match start_single(cx, &viewer.0, lang, source, &form).await? { | |
| 427 | - Ok(job_id) => Err(see_other(format!("/import/{job_id}")).into()), | |
| 428 | - Err(message) => { | |
| 429 | - let owners = owner_choices(context::<AppState>(cx), &viewer.0).await?; | |
| 430 | - let csrf = viewer.1.csrf_token.clone(); | |
| 431 | - let draft = Draft::from_form(&form, source); | |
| 432 | - Ok(view! { | |
| 433 | - shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), | |
| 434 | - import_error_body(lang: lang, username: viewer.0.username.clone(), csrf: csrf, draft: draft, error: message, owners: owners)) | |
| 435 | - }) | |
| 436 | - } | |
| 437 | - } | |
| 438 | -} | |
| 439 | - | |
| 440 | -async fn start_single( | |
| 441 | - cx: &Cx, | |
| 442 | - viewer: &User, | |
| 443 | - lang: Lang, | |
| 444 | - source: Source, | |
| 445 | - form: &ImportForm, | |
| 446 | -) -> Result<std::result::Result<String, String>> { | |
| 447 | - let state = context::<AppState>(cx); | |
| 448 | - let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else { | |
| 449 | - let message = if has_instance(source) && form.remote.trim().starts_with("http") { | |
| 450 | - g::t(lang, K::ErrBadInstance) | |
| 451 | - } else { | |
| 452 | - g::t(lang, K::ErrBadRemote) | |
| 453 | - }; | |
| 454 | - return Ok(Err(message.to_owned())); | |
| 455 | - }; | |
| 456 | - if source == Source::Git | |
| 457 | - && crate::webhooks::client::validate_url(&remote, &crate::mirrors::policy(state)).is_err() | |
| 458 | - { | |
| 459 | - return Ok(Err(g::t(lang, K::ErrBadRemote).to_owned())); | |
| 460 | - } | |
| 461 | - let target = match repo_owner(state, viewer, lang, &form.owner).await? { | |
| 462 | - Ok(target) => target, | |
| 463 | - Err(message) => return Ok(Err(message)), | |
| 464 | - }; | |
| 465 | - let name = match form.name.trim() { | |
| 466 | - "" => default_name(&remote), | |
| 467 | - given => given.to_owned(), | |
| 468 | - }; | |
| 469 | - let spec = JobSpec { | |
| 470 | - source, | |
| 471 | - remote: remote.clone(), | |
| 472 | - instance: instance.clone(), | |
| 473 | - token: token_of(&form.token), | |
| 474 | - git_user: form.git_user.trim().to_owned(), | |
| 475 | - options: if source == Source::Git { | |
| 476 | - ImportOptions::default() | |
| 477 | - } else { | |
| 478 | - options_of( | |
| 479 | - &form.opt_labels, | |
| 480 | - &form.opt_issues, | |
| 481 | - &form.opt_pulls, | |
| 482 | - &form.opt_releases, | |
| 483 | - ) | |
| 484 | - }, | |
| 485 | - }; | |
| 486 | - let visibility = if form.visibility == "public" { | |
| 487 | - Visibility::Public | |
| 488 | - } else { | |
| 489 | - Visibility::Private | |
| 490 | - }; | |
| 491 | - begin( | |
| 492 | - cx, | |
| 493 | - viewer, | |
| 494 | - &target, | |
| 495 | - &name, | |
| 496 | - form.description.trim(), | |
| 497 | - visibility, | |
| 498 | - spec, | |
| 499 | - ) | |
| 500 | - .await | |
| 501 | -} | |
| 502 | - | |
| 503 | -async fn begin( | |
| 504 | - cx: &Cx, | |
| 505 | - actor: &User, | |
| 506 | - target: &User, | |
| 507 | - name: &str, | |
| 508 | - description: &str, | |
| 509 | - visibility: Visibility, | |
| 510 | - spec: JobSpec, | |
| 511 | -) -> Result<std::result::Result<String, String>> { | |
| 512 | - let state = context::<AppState>(cx); | |
| 513 | - let lang = i18n::lang(cx, Some(actor)); | |
| 514 | - let name = match forge_core::names::validate_name(name) { | |
| 515 | - Ok(name) => name, | |
| 516 | - Err(e) => { | |
| 517 | - return Ok(Err(user_facing_message(&e).unwrap_or_else(|| { | |
| 518 | - crate::i18n::misc::t(lang, crate::i18n::misc::K::InvalidRepoName).to_owned() | |
| 519 | - }))); | |
| 520 | - } | |
| 521 | - }; | |
| 522 | - if description.chars().count() > 350 { | |
| 523 | - return Ok(Err(crate::i18n::misc::description_too_long(lang, 350))); | |
| 524 | - } | |
| 525 | - let repo = match state | |
| 526 | - .store | |
| 527 | - .create_repo(&target.id, &name, description, visibility, DEFAULT_BRANCH) | |
| 528 | - .await | |
| 529 | - { | |
| 530 | - Ok(repo) => { | |
| 531 | - state.live.bump_repo(&repo.owner_id, &repo.id); | |
| 532 | - repo | |
| 533 | - } | |
| 534 | - Err(e) => match user_facing_message(&e) { | |
| 535 | - Some(message) => return Ok(Err(message)), | |
| 536 | - None => return Err(e.into()), | |
| 537 | - }, | |
| 538 | - }; | |
| 539 | - let path = repo_path(&state.config.data_dir, &repo.id)?; | |
| 540 | - if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await { | |
| 541 | - state.store.delete_repo(&repo.id).await?; | |
| 542 | - return Ok(Err(crate::i18n::misc::git_init_failed(lang, e))); | |
| 543 | - } | |
| 544 | - let job = match state | |
| 545 | - .store | |
| 546 | - .create_import_job( | |
| 547 | - &actor.id, | |
| 548 | - &repo.id, | |
| 549 | - spec.source.as_str(), | |
| 550 | - &source_ref(spec.source, &spec.remote, &spec.instance), | |
| 551 | - &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()), | |
| 552 | - ) | |
| 553 | - .await | |
| 554 | - { | |
| 555 | - Ok(job) => job, | |
| 556 | - Err(e) => { | |
| 557 | - state.store.delete_repo(&repo.id).await?; | |
| 558 | - return Err(e.into()); | |
| 559 | - } | |
| 560 | - }; | |
| 561 | - let full_name = format!("{}/{}", repo.owner_name, repo.name); | |
| 562 | - audit::record( | |
| 563 | - &state.store, | |
| 564 | - Some(cx), | |
| 565 | - Actor::User(actor), | |
| 566 | - AuditAction::RepoCreated, | |
| 567 | - Target { | |
| 568 | - kind: "repo", | |
| 569 | - id: &repo.id, | |
| 570 | - name: &full_name, | |
| 571 | - }, | |
| 572 | - serde_json::json!({ "import": spec.source.as_str() }), | |
| 573 | - ) | |
| 574 | - .await; | |
| 575 | - importer::spawn_job(state.clone(), job.clone(), spec); | |
| 576 | - Ok(Ok(job.id)) | |
| 577 | -} | |
| 578 | - | |
| 579 | -#[component] | |
| 580 | -async fn bulk_form( | |
| 581 | - cx: &Cx, | |
| 582 | - lang: Lang, | |
| 583 | - username: String, | |
| 584 | - csrf: &str, | |
| 585 | - source: Source, | |
| 586 | - instance: &str, | |
| 587 | - owners: Vec<String>, | |
| 588 | - error: Option<String>, | |
| 589 | -) -> Result<impl View> { | |
| 590 | - let has_instance = has_instance(source); | |
| 591 | - let instance_label = instance_label(lang, source); | |
| 592 | - let source_value = source.as_str(); | |
| 593 | - let owner_label = match source { | |
| 594 | - Source::GitLab => g::t(lang, K::BulkOwnerGitLab), | |
| 595 | - Source::Forgejo => g::t(lang, K::BulkOwnerForgejo), | |
| 596 | - _ => g::t(lang, K::BulkOwnerGitHub), | |
| 597 | - }; | |
| 598 | - let owner_required = source != Source::Forgejo; | |
| 599 | - Ok(view! { | |
| 600 | - head(title: g::t(lang, K::BulkTitle)) | |
| 601 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 602 | - newrepo_tabs(lang: lang, active: "import") | |
| 603 | - <div class="sheet fit"> | |
| 604 | - <form method="post" action="/new/import/bulk" class="fields"> | |
| 605 | - if let Some(message) = error { | |
| 606 | - alert(message: message.as_str()) | |
| 607 | - } | |
| 608 | - csrf_field(token: csrf) | |
| 609 | - <input type="hidden" name="source" value=(source_value)> | |
| 610 | - source_tabs(lang: lang, base: "/new/import/bulk", active: source) | |
| 611 | - <input type="hidden" name="stage" value="list"> | |
| 612 | - if has_instance { | |
| 613 | - <div class="field"> | |
| 614 | - <label for="bulk-instance">(instance_label)</label> | |
| 615 | - <input id="bulk-instance" type="url" name="instance" value=(instance) autocomplete="off" spellcheck="false" maxlength="2048"> | |
| 616 | - </div> | |
| 617 | - } | |
| 618 | - <div class="field"> | |
| 619 | - <label for="bulk-from">(owner_label)</label> | |
| 620 | - <input id="bulk-from" type="text" name="from" required=(owner_required) autocomplete="off" spellcheck="false" maxlength="100"> | |
| 621 | - </div> | |
| 622 | - <div class="field"> | |
| 623 | - <label for="bulk-token">(g::t(lang, K::TokenOptional))</label> | |
| 624 | - <input id="bulk-token" type="password" name="token" autocomplete="new-password" maxlength="1024"> | |
| 625 | - </div> | |
| 626 | - <input type="hidden" name="owner" value=(owners.first().map(String::as_str).unwrap_or(""))> | |
| 627 | - <button type="submit" class="primary">(g::t(lang, K::BulkListButton))</button> | |
| 628 | - </form> | |
| 629 | - </div> | |
| 630 | - }) | |
| 631 | -} | |
| 632 | - | |
| 633 | -#[component] | |
| 634 | -async fn bulk_select( | |
| 635 | - cx: &Cx, | |
| 636 | - lang: Lang, | |
| 637 | - username: String, | |
| 638 | - csrf: &str, | |
| 639 | - form: BulkFormEcho, | |
| 640 | - repos: Vec<ExtRepo>, | |
| 641 | - owners: Vec<String>, | |
| 642 | -) -> Result<impl View> { | |
| 643 | - let count = repos.len(); | |
| 644 | - let empty = repos.is_empty(); | |
| 645 | - let selected_owner = if form.owner.is_empty() { | |
| 646 | - owners.first().cloned().unwrap_or_default() | |
| 647 | - } else { | |
| 648 | - form.owner.clone() | |
| 649 | - }; | |
| 650 | - Ok(view! { | |
| 651 | - head(title: g::t(lang, K::BulkSelectHeading)) | |
| 652 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 653 | - newrepo_tabs(lang: lang, active: "import") | |
| 654 | - <div class="sheet"> | |
| 655 | - <form method="post" action="/new/import/bulk" class="fields"> | |
| 656 | - csrf_field(token: csrf) | |
| 657 | - <input type="hidden" name="stage" value="run"> | |
| 658 | - <input type="hidden" name="source" value=(form.source.as_str())> | |
| 659 | - <input type="hidden" name="instance" value=(form.instance.as_str())> | |
| 660 | - <input type="hidden" name="token" value=(form.token.as_str())> | |
| 661 | - <input type="hidden" name="from" value=(form.from.as_str())> | |
| 662 | - if empty { | |
| 663 | - <p class="state">(g::t(lang, K::BulkNone))</p> | |
| 664 | - } else { | |
| 665 | - <div class="field"> | |
| 666 | - <label for="bulk-owner">(g::t(lang, K::TargetOwner))</label> | |
| 667 | - <select id="bulk-owner" name="owner"> | |
| 668 | - for name in owners.iter() { | |
| 669 | - <option value=(name.as_str()) selected=(*name == selected_owner)>(name.as_str())</option> | |
| 670 | - } | |
| 671 | - </select> | |
| 672 | - </div> | |
| 673 | - visibility_pick(lang: lang, private: false) | |
| 674 | - option_boxes(lang: lang, opts: ImportOptions { labels: true, issues: true, pulls: true, releases: true }) | |
| 675 | - <label class="line" data-kb-row=""> | |
| 676 | - <input type="checkbox" data-select-all=".import-pick-list"> | |
| 677 | - <span class="name">(g::t(lang, K::BulkSelectAll))</span> | |
| 678 | - <span class="val">(count)</span> | |
| 679 | - </label> | |
| 680 | - <div class="import-pick-list"> | |
| 681 | - for (i, repo) in repos.iter().enumerate() { | |
| 682 | - <label class="line" data-kb-row=""> | |
| 683 | - <input type="checkbox" name=(format!("sel_{i}")) value=(repo.full_name.as_str())> | |
| 684 | - <span class="name">(repo.name.as_str())</span> | |
| 685 | - <span class="val"> | |
| 686 | - if repo.private { | |
| 687 | - <span class="badge private">(g::t(lang, K::BulkPrivate))</span> | |
| 688 | - } | |
| 689 | - if repo.fork { | |
| 690 | - <span class="badge">(g::t(lang, K::BulkFork))</span> | |
| 691 | - } | |
| 692 | - if repo.archived { | |
| 693 | - <span class="badge">(g::t(lang, K::BulkArchived))</span> | |
| 694 | - } | |
| 695 | - (repo.description.as_str()) | |
| 696 | - </span> | |
| 697 | - </label> | |
| 698 | - } | |
| 699 | - </div> | |
| 700 | - <button type="submit" class="primary">(g::t(lang, K::BulkImportSelected))</button> | |
| 701 | - } | |
| 702 | - </form> | |
| 703 | - </div> | |
| 704 | - }) | |
| 705 | -} | |
| 706 | - | |
| 707 | -struct BulkFormEcho { | |
| 708 | - source: String, | |
| 709 | - instance: String, | |
| 710 | - token: String, | |
| 711 | - from: String, | |
| 712 | - owner: String, | |
| 713 | -} | |
| 714 | - | |
| 715 | -#[page("/new/import/bulk")] | |
| 716 | -async fn bulk_page(cx: &Cx) -> Result<impl View> { | |
| 717 | - let viewer = require_user(cx).await?; | |
| 718 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 719 | - let query = query_params::<SourceQuery>(cx)?; | |
| 720 | - let source = match source_of(query.source.as_deref()) { | |
| 721 | - Source::Git => Source::GitHub, | |
| 722 | - other => other, | |
| 723 | - }; | |
| 724 | - let owners = owner_choices(context::<AppState>(cx), &viewer.0).await?; | |
| 725 | - let csrf = viewer.1.csrf_token.clone(); | |
| 726 | - Ok(view! { | |
| 727 | - shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), | |
| 728 | - 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))) | |
| 729 | - }) | |
| 730 | -} | |
| 731 | - | |
| 732 | -async fn list_remote( | |
| 733 | - state: &AppState, | |
| 734 | - source: Source, | |
| 735 | - instance: &str, | |
| 736 | - from: &str, | |
| 737 | - token: Option<String>, | |
| 738 | -) -> std::result::Result<Vec<ExtRepo>, String> { | |
| 739 | - let notice: importer::api::Notice = std::sync::Arc::new(|_msg: String| {}); | |
| 740 | - let listed = match source { | |
| 741 | - Source::GitLab => { | |
| 742 | - make_gitlab(state, instance, token, notice)? | |
| 743 | - .list_repos(from) | |
| 744 | - .await | |
| 745 | - } | |
| 746 | - Source::Forgejo => { | |
| 747 | - make_forgejo(state, instance, token, notice)? | |
| 748 | - .list_repos(from) | |
| 749 | - .await | |
| 750 | - } | |
| 751 | - _ => make_github(state, token, notice)?.list_repos(from).await, | |
| 752 | - }; | |
| 753 | - listed.map_err(|e: ApiError| e.to_string()) | |
| 754 | -} | |
| 755 | - | |
| 756 | -#[page(POST "/new/import/bulk")] | |
| 757 | -async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> { | |
| 758 | - let viewer = require_csrf(cx, &form.csrf).await?; | |
| 759 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 760 | - let state = context::<AppState>(cx); | |
| 761 | - let source = match source_of(Some(&form.source)) { | |
| 762 | - Source::Git => Source::GitHub, | |
| 763 | - other => other, | |
| 764 | - }; | |
| 765 | - let owners = owner_choices(state, &viewer.0).await?; | |
| 766 | - let csrf = viewer.1.csrf_token.clone(); | |
| 767 | - let instance = if has_instance(source) && !form.instance.trim().is_empty() { | |
| 768 | - form.instance.trim().to_owned() | |
| 769 | - } else { | |
| 770 | - default_instance(source).to_owned() | |
| 771 | - }; | |
| 772 | - | |
| 773 | - if form.stage == "run" { | |
| 774 | - let Err(redirect) = run_bulk(cx, &viewer.0, lang, source, &instance, &form).await; | |
| 775 | - return Err(redirect); | |
| 776 | - } | |
| 777 | - | |
| 778 | - let from = form.from.trim(); | |
| 779 | - let owner_max = if source == Source::GitLab { 20 } else { 1 }; | |
| 780 | - let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some(); | |
| 781 | - let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max); | |
| 782 | - let result = if bad_owner { | |
| 783 | - Err(g::t(lang, K::ErrBadOwner).to_owned()) | |
| 784 | - } else { | |
| 785 | - list_remote(state, source, &instance, from, token_of(&form.token)).await | |
| 786 | - }; | |
| 787 | - let (error, picker) = match result { | |
| 788 | - Err(message) => (Some(message), None), | |
| 789 | - Ok(found) => { | |
| 790 | - let echo = BulkFormEcho { | |
| 791 | - source: source.as_str().to_owned(), | |
| 792 | - instance: instance.clone(), | |
| 793 | - token: form.token.trim().to_owned(), | |
| 794 | - from: from.to_owned(), | |
| 795 | - owner: form.owner.trim().to_owned(), | |
| 796 | - }; | |
| 797 | - (None, Some((echo, found))) | |
| 798 | - } | |
| 799 | - }; | |
| 800 | - Ok(view! { | |
| 801 | - shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), | |
| 802 | - 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)) | |
| 803 | - }) | |
| 804 | -} | |
| 805 | - | |
| 806 | -#[component] | |
| 807 | -async fn bulk_stage( | |
| 808 | - cx: &Cx, | |
| 809 | - lang: Lang, | |
| 810 | - username: String, | |
| 811 | - csrf: &str, | |
| 812 | - source: Source, | |
| 813 | - instance: &str, | |
| 814 | - owners: Vec<String>, | |
| 815 | - error: Option<String>, | |
| 816 | - picker: Option<(BulkFormEcho, Vec<ExtRepo>)>, | |
| 817 | -) -> Result<impl View> { | |
| 818 | - Ok(view! { | |
| 819 | - if let Some((echo, repos)) = picker { | |
| 820 | - bulk_select(lang: lang, username: username, csrf: csrf, form: echo, repos: repos, owners: owners) | |
| 821 | - } else { | |
| 822 | - bulk_form(lang: lang, username: username, csrf: csrf, source: source, instance: instance, owners: owners, error: error) | |
| 823 | - } | |
| 824 | - }) | |
| 825 | -} | |
| 826 | - | |
| 827 | -async fn run_bulk( | |
| 828 | - cx: &Cx, | |
| 829 | - viewer: &User, | |
| 830 | - lang: Lang, | |
| 831 | - source: Source, | |
| 832 | - instance: &str, | |
| 833 | - form: &BulkForm, | |
| 834 | -) -> Result<std::convert::Infallible> { | |
| 835 | - let state = context::<AppState>(cx); | |
| 836 | - let mut picked: Vec<(usize, &String)> = form | |
| 837 | - .extra | |
| 838 | - .iter() | |
| 839 | - .filter_map(|(k, v)| Some((k.strip_prefix("sel_")?.parse::<usize>().ok()?, v))) | |
| 840 | - .collect(); | |
| 841 | - picked.sort_by_key(|(i, _)| *i); | |
| 842 | - let fail = |message: &str| -> Result<std::convert::Infallible> { | |
| 843 | - Err(see_other(format!( | |
| 844 | - "/new/import/bulk?source={}&error={}", | |
| 845 | - source.as_str(), | |
| 846 | - crate::views::enc(message) | |
| 847 | - )) | |
| 848 | - .into()) | |
| 849 | - }; | |
| 850 | - if picked.is_empty() { | |
| 851 | - return fail(g::t(lang, K::ErrNothingSelected)); | |
| 852 | - } | |
| 853 | - if picked.len() > MAX_BULK { | |
| 854 | - return fail(g::t(lang, K::ErrTooMany)); | |
| 855 | - } | |
| 856 | - let target = match repo_owner(state, viewer, lang, &form.owner).await? { | |
| 857 | - Ok(target) => target, | |
| 858 | - Err(message) => return fail(&message), | |
| 859 | - }; | |
| 860 | - let options = options_of( | |
| 861 | - &form.opt_labels, | |
| 862 | - &form.opt_issues, | |
| 863 | - &form.opt_pulls, | |
| 864 | - &form.opt_releases, | |
| 865 | - ); | |
| 866 | - let visibility = if form.visibility == "public" { | |
| 867 | - Visibility::Public | |
| 868 | - } else { | |
| 869 | - Visibility::Private | |
| 870 | - }; | |
| 871 | - let failed: Vec<ImportJob> = state | |
| 872 | - .store | |
| 873 | - .list_import_jobs(&viewer.id, 200) | |
| 874 | - .await? | |
| 875 | - .into_iter() | |
| 876 | - .filter(|job| job.state == ImportState::Failed) | |
| 877 | - .collect(); | |
| 878 | - let mut skipped: Vec<String> = Vec::new(); | |
| 879 | - for (_, full_name) in picked { | |
| 880 | - let Some((remote, inst)) = parse_remote(source, full_name, instance) else { | |
| 881 | - continue; | |
| 882 | - }; | |
| 883 | - let spec = JobSpec { | |
| 884 | - source, | |
| 885 | - remote: remote.clone(), | |
| 886 | - instance: inst, | |
| 887 | - token: token_of(&form.token), | |
| 888 | - git_user: String::new(), | |
| 889 | - options, | |
| 890 | - }; | |
| 891 | - let name = default_name(&remote); | |
| 892 | - if let Some(repo) = state | |
| 893 | - .store | |
| 894 | - .repo_by_owner_and_name(&target.username, &name) | |
| 895 | - .await? | |
| 896 | - && let Some(job) = failed.iter().find(|job| { | |
| 897 | - job.repo_id.as_deref() == Some(repo.id.as_str()) && job.source == source.as_str() | |
| 898 | - }) | |
| 899 | - { | |
| 900 | - retry_job(state, job.clone(), &form.token).await?; | |
| 901 | - continue; | |
| 902 | - } | |
| 903 | - if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? { | |
| 904 | - tracing::info!(repo = %remote, %message, "bulk import: skipped a repository"); | |
| 905 | - skipped.push(format!("{name} ({message})")); | |
| 906 | - } | |
| 907 | - } | |
| 908 | - if skipped.is_empty() { | |
| 909 | - return Err(see_other("/import").into()); | |
| 910 | - } | |
| 911 | - let mut list = skipped.join(", "); | |
| 912 | - if list.len() > 1500 { | |
| 913 | - list.truncate(list.floor_char_boundary(1500)); | |
| 914 | - list.push('…'); | |
| 915 | - } | |
| 916 | - Err(see_other(format!("/import?skipped={}", crate::views::enc(&list))).into()) | |
| 917 | -} | |
| 918 | - | |
| 919 | -fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) { | |
| 920 | - match state { | |
| 921 | - ImportState::Queued => ("badge", g::t(lang, K::JobQueued)), | |
| 922 | - ImportState::Running => ("badge import-running", g::t(lang, K::JobRunning)), | |
| 923 | - ImportState::Done => ("badge public", g::t(lang, K::JobDone)), | |
| 924 | - ImportState::Failed => ("badge import-failed", g::t(lang, K::JobFailed)), | |
| 925 | - } | |
| 926 | -} | |
| 927 | - | |
| 928 | -fn stage_name(lang: Lang, stage: &str) -> &'static str { | |
| 929 | - match stage { | |
| 930 | - "git" => g::t(lang, K::StageGit), | |
| 931 | - "labels" => g::t(lang, K::StageLabels), | |
| 932 | - "milestones" => g::t(lang, K::StageMilestones), | |
| 933 | - "issues" => g::t(lang, K::StageIssues), | |
| 934 | - "releases" => g::t(lang, K::StageReleases), | |
| 935 | - "done" => g::t(lang, K::StageDone), | |
| 936 | - _ => "", | |
| 937 | - } | |
| 938 | -} | |
| 939 | - | |
| 940 | -async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Result<Option<Repo>> { | |
| 941 | - let Some(id) = &job.repo_id else { | |
| 942 | - return Ok(None); | |
| 943 | - }; | |
| 944 | - if !still_readable(&state.store, user, id).await { | |
| 945 | - return Ok(None); | |
| 946 | - } | |
| 947 | - Ok(state.store.repo_by_id(id).await?) | |
| 948 | -} | |
| 949 | - | |
| 950 | -async fn load_job_rows( | |
| 951 | - state: &AppState, | |
| 952 | - user_id: &str, | |
| 953 | - limit: u32, | |
| 954 | -) -> Result<Vec<(ImportJob, Option<Repo>)>> { | |
| 955 | - let user = state.store.user_by_id(user_id).await?; | |
| 956 | - let jobs = state.store.list_import_jobs(user_id, limit).await?; | |
| 957 | - let mut rows = Vec::with_capacity(jobs.len()); | |
| 958 | - for job in jobs { | |
| 959 | - let repo = job_repo(state, user.as_ref(), &job).await?; | |
| 960 | - rows.push((job, repo)); | |
| 961 | - } | |
| 962 | - Ok(rows) | |
| 963 | -} | |
| 964 | - | |
| 965 | -#[component] | |
| 966 | -async fn job_rows(cx: &Cx, lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<impl View> { | |
| 967 | - Ok(view! { | |
| 968 | - <div> | |
| 969 | - for (job, repo) in jobs.iter() { | |
| 970 | - <div class="line" data-kb-row=""> | |
| 971 | - <a class="name" href=(format!("/import/{}", job.id))>(job.source_ref.as_str())</a> | |
| 972 | - <span class="val"> | |
| 973 | - <span class=(state_badge(lang, job.state).0)>(state_badge(lang, job.state).1)</span> | |
| 974 | - " · " (g::t(lang, K::JobStarted)) " " rel_time(lang: lang, stamp: job.created_at.as_str()) | |
| 975 | - if let Some(repo) = repo { | |
| 976 | - " · " <a class="act" href=(format!("/{}/{}", repo.owner_name, repo.name))>(format!("{}/{}", repo.owner_name, repo.name))</a> | |
| 977 | - } | |
| 978 | - </span> | |
| 979 | - </div> | |
| 980 | - } | |
| 981 | - </div> | |
| 982 | - }) | |
| 983 | -} | |
| 984 | - | |
| 985 | -#[component] | |
| 986 | -async fn jobs_list( | |
| 987 | - cx: &Cx, | |
| 988 | - lang: Lang, | |
| 989 | - username: String, | |
| 990 | - jobs: Vec<(ImportJob, Option<Repo>)>, | |
| 991 | - skipped: Option<String>, | |
| 992 | - page: u64, | |
| 993 | - pages: u64, | |
| 994 | - nav: (Vec<PageLink>, Option<String>, Option<String>), | |
| 995 | -) -> Result<impl View> { | |
| 996 | - let (links, prev, next) = nav; | |
| 997 | - let empty = jobs.is_empty(); | |
| 998 | - let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed); | |
| 999 | - Ok(view! { | |
| 1000 | - head(title: g::t(lang, K::JobsTitle), live: Some("/import/events")) | |
| 1001 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 1002 | - newrepo_tabs(lang: lang, active: "history") | |
| 1003 | - <div class="sheet"> | |
| 1004 | - if retry { | |
| 1005 | - <div class="sheet-tools"> | |
| 1006 | - <a class="act" href="/import/retry">(g::t(lang, K::RetryFailedTitle))</a> | |
| 1007 | - </div> | |
| 1008 | - } | |
| 1009 | - if let Some(message) = skipped { | |
| 1010 | - alert(message: message.as_str()) | |
| 1011 | - } | |
| 1012 | - if empty { | |
| 1013 | - <p class="state">(g::t(lang, K::NoJobs))</p> | |
| 1014 | - <div class="acts"> | |
| 1015 | - <a class="act" href="/new/import">(g::t(lang, K::ImportTitle))</a> | |
| 1016 | - </div> | |
| 1017 | - } else { | |
| 1018 | - job_rows(lang: lang, jobs: jobs) | |
| 1019 | - } | |
| 1020 | - pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) | |
| 1021 | - </div> | |
| 1022 | - }) | |
| 1023 | -} | |
| 1024 | - | |
| 1025 | -async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> { | |
| 1026 | - let rows = load_job_rows(state, user_id, 50).await?; | |
| 1027 | - Ok(rows | |
| 1028 | - .iter() | |
| 1029 | - .map(|(job, repo)| { | |
| 1030 | - let repo = repo.as_ref().map_or(String::new(), |repo| { | |
| 1031 | - format!("{}/{}", repo.owner_name, repo.name) | |
| 1032 | - }); | |
| 1033 | - format!( | |
| 1034 | - "{} {} {} {repo}", | |
| 1035 | - job.id, | |
| 1036 | - job.state.as_str(), | |
| 1037 | - job.source_ref | |
| 1038 | - ) | |
| 1039 | - }) | |
| 1040 | - .collect::<Vec<_>>() | |
| 1041 | - .join("\n")) | |
| 1042 | -} | |
| 1043 | - | |
| 1044 | -#[route(GET "/import/events")] | |
| 1045 | -async fn jobs_events(cx: &Cx) -> Result<Response> { | |
| 1046 | - let viewer = require_user(cx).await?; | |
| 1047 | - let state = context::<AppState>(cx).clone(); | |
| 1048 | - let user_id = viewer.0.id.clone(); | |
| 1049 | - stream_changes( | |
| 1050 | - cx, | |
| 1051 | - &state.live.clone(), | |
| 1052 | - &[Topic::Imports(user_id.clone())], | |
| 1053 | - move || { | |
| 1054 | - let state = state.clone(); | |
| 1055 | - let user_id = user_id.clone(); | |
| 1056 | - async move { jobs_fingerprint(&state, &user_id).await } | |
| 1057 | - }, | |
| 1058 | - ) | |
| 1059 | - .await | |
| 1060 | -} | |
| 1061 | - | |
| 1062 | -const HISTORY_ROWS: u64 = 10; | |
| 1063 | - | |
| 1064 | -#[page("/import")] | |
| 1065 | -async fn jobs_page(cx: &Cx) -> Result<impl View> { | |
| 1066 | - let viewer = require_user(cx).await?; | |
| 1067 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 1068 | - let state = context::<AppState>(cx); | |
| 1069 | - let query = query_params::<JobsQuery>(cx)?; | |
| 1070 | - let all = state.store.list_import_jobs(&viewer.0.id, 1000).await?; | |
| 1071 | - let (shown, page, pages) = paginate(all, requested_page(query.page.as_deref()), HISTORY_ROWS); | |
| 1072 | - let user = state.store.user_by_id(&viewer.0.id).await?; | |
| 1073 | - let mut rows = Vec::new(); | |
| 1074 | - for job in shown { | |
| 1075 | - let repo = job_repo(state, user.as_ref(), &job).await?; | |
| 1076 | - rows.push((job, repo)); | |
| 1077 | - } | |
| 1078 | - let nav = pager_links(page, pages, |n| format!("/import?page={n}")); | |
| 1079 | - let skipped = query | |
| 1080 | - .skipped | |
| 1081 | - .clone() | |
| 1082 | - .filter(|s| !s.is_empty() && s.len() < 2000) | |
| 1083 | - .map(|s| g::bulk_skipped(lang, &s)); | |
| 1084 | - Ok(view! { | |
| 1085 | - 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)) | |
| 1086 | - }) | |
| 1087 | -} | |
| 1088 | - | |
| 1089 | -#[component] | |
| 1090 | -async fn job_view( | |
| 1091 | - cx: &Cx, | |
| 1092 | - lang: Lang, | |
| 1093 | - username: String, | |
| 1094 | - csrf: &str, | |
| 1095 | - job: ImportJob, | |
| 1096 | - repo: Option<Repo>, | |
| 1097 | - log: Vec<forge_core::store::imports::ImportEvent>, | |
| 1098 | -) -> Result<impl View> { | |
| 1099 | - let (badge_class, badge_text) = state_badge(lang, job.state); | |
| 1100 | - let live = (!job.state.is_finished()).then(|| { | |
| 1101 | - format!( | |
| 1102 | - "/import/{}/events?v={}", | |
| 1103 | - job.id, | |
| 1104 | - crate::views::enc(&job.updated_at) | |
| 1105 | - ) | |
| 1106 | - }); | |
| 1107 | - let stage = stage_name(lang, &job.stage); | |
| 1108 | - let has_progress = job.total > 0 && !job.state.is_finished(); | |
| 1109 | - let progress_text = g::progress_of(job.done, job.total); | |
| 1110 | - let failed = job.state == ImportState::Failed; | |
| 1111 | - let done = job.state == ImportState::Done; | |
| 1112 | - let repo_href = repo | |
| 1113 | - .as_ref() | |
| 1114 | - .map(|r| format!("/{}/{}", r.owner_name, r.name)); | |
| 1115 | - let retry_action = format!("/import/{}/retry", job.id); | |
| 1116 | - let error = job.error.clone(); | |
| 1117 | - let state_word = job.state.as_str(); | |
| 1118 | - let empty_log = log.is_empty(); | |
| 1119 | - let sub = vec![SubPart { | |
| 1120 | - text: badge_text.to_owned(), | |
| 1121 | - class: badge_class, | |
| 1122 | - ..SubPart::default() | |
| 1123 | - }]; | |
| 1124 | - Ok(view! { | |
| 1125 | - head(title: job.source_ref.as_str(), sub: sub, live: live.as_deref()) | |
| 1126 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 1127 | - newrepo_tabs(lang: lang, active: "history") | |
| 1128 | - <div class="sheet import-job" data-live-state=(state_word)> | |
| 1129 | - <section class="sec"> | |
| 1130 | - if !stage.is_empty() { | |
| 1131 | - <p class="state"> | |
| 1132 | - (stage) | |
| 1133 | - if has_progress { | |
| 1134 | - " · " (progress_text.as_str()) | |
| 1135 | - } | |
| 1136 | - </p> | |
| 1137 | - } | |
| 1138 | - if has_progress { | |
| 1139 | - <progress class="import-progress" value=(job.done) max=(job.total)></progress> | |
| 1140 | - } else if !job.state.is_finished() { | |
| 1141 | - <progress class="import-progress"></progress> | |
| 1142 | - } | |
| 1143 | - if let Some(message) = error { | |
| 1144 | - alert(message: message.as_str()) | |
| 1145 | - } | |
| 1146 | - if let Some(href) = repo_href.as_ref() { | |
| 1147 | - if done { | |
| 1148 | - <div class="acts"> | |
| 1149 | - <a class="act" href=(href.as_str())>(g::t(lang, K::JobOpenRepo))</a> | |
| 1150 | - </div> | |
| 1151 | - } | |
| 1152 | - } | |
| 1153 | - </section> | |
| 1154 | - if failed { | |
| 1155 | - <section class="sec"> | |
| 1156 | - <form method="post" action=(retry_action.as_str()) class="fields"> | |
| 1157 | - csrf_field(token: csrf) | |
| 1158 | - <div class="field"> | |
| 1159 | - <label for="retry-token">(g::t(lang, K::TokenOptional))</label> | |
| 1160 | - <input id="retry-token" type="password" name="token" autocomplete="new-password" maxlength="1024"> | |
| 1161 | - </div> | |
| 1162 | - <button type="submit" class="primary">(g::t(lang, K::JobRetry))</button> | |
| 1163 | - </form> | |
| 1164 | - </section> | |
| 1165 | - } | |
| 1166 | - <section class="sec"> | |
| 1167 | - <h2>(g::t(lang, K::JobProgress))</h2> | |
| 1168 | - if empty_log { | |
| 1169 | - <p class="hint">(g::t(lang, K::JobNoLog))</p> | |
| 1170 | - } else { | |
| 1171 | - <ol class="import-log"> | |
| 1172 | - for line in log.iter() { | |
| 1173 | - <li class=(format!("import-log-line import-log-{}", line.level))>(line.message.as_str())</li> | |
| 1174 | - } | |
| 1175 | - </ol> | |
| 1176 | - } | |
| 1177 | - </section> | |
| 1178 | - </div> | |
| 1179 | - }) | |
| 1180 | -} | |
| 1181 | - | |
| 1182 | -async fn owned_job(cx: &Cx, viewer: &User) -> Result<ImportJob> { | |
| 1183 | - let id = job_id(cx).to_owned(); | |
| 1184 | - let state = context::<AppState>(cx); | |
| 1185 | - match state.store.import_job(&id).await? { | |
| 1186 | - Some(job) if job.user_id == viewer.id => Ok(job), | |
| 1187 | - _ => Err(not_found().into()), | |
| 1188 | - } | |
| 1189 | -} | |
| 1190 | - | |
| 1191 | -#[page("/import/{job_id}")] | |
| 1192 | -async fn job_page(cx: &Cx) -> Result<impl View> { | |
| 1193 | - let viewer = require_user(cx).await?; | |
| 1194 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 1195 | - let state = context::<AppState>(cx); | |
| 1196 | - let job = owned_job(cx, &viewer.0).await?; | |
| 1197 | - let repo = job_repo(state, Some(&viewer.0), &job).await?; | |
| 1198 | - let log = state.store.list_import_events(&job.id, 200).await?; | |
| 1199 | - let csrf = viewer.1.csrf_token.clone(); | |
| 1200 | - let title = job.source_ref.clone(); | |
| 1201 | - Ok(view! { | |
| 1202 | - shell(title: title.as_str(), viewer: Some(&viewer), | |
| 1203 | - job_view(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), job: job, repo: repo, log: log)) | |
| 1204 | - }) | |
| 1205 | -} | |
| 1206 | - | |
| 1207 | -#[route(GET "/import/{job_id}/events")] | |
| 1208 | -async fn job_events(cx: &Cx) -> Result<Response> { | |
| 1209 | - let viewer = require_user(cx).await?; | |
| 1210 | - let job = owned_job(cx, &viewer.0).await?; | |
| 1211 | - let query = query_params::<SeenQuery>(cx)?; | |
| 1212 | - let state = context::<AppState>(cx); | |
| 1213 | - let seen = query.v.clone().unwrap_or_default(); | |
| 1214 | - let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id)); | |
| 1215 | - let store = state.store.clone(); | |
| 1216 | - let id = job.id.clone(); | |
| 1217 | - let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| { | |
| 1218 | - let store = store.clone(); | |
| 1219 | - let id = id.clone(); | |
| 1220 | - async move { | |
| 1221 | - if ended { | |
| 1222 | - return None; | |
| 1223 | - } | |
| 1224 | - loop { | |
| 1225 | - let job = store.import_job(&id).await.ok().flatten()?; | |
| 1226 | - if job.updated_at != seen { | |
| 1227 | - seen = job.updated_at.clone(); | |
| 1228 | - let finished = job.state.is_finished(); | |
| 1229 | - return Some(( | |
| 1230 | - changed_event(job.state.as_str().to_owned()), | |
| 1231 | - (wake, seen, finished), | |
| 1232 | - )); | |
| 1233 | - } | |
| 1234 | - if job.state.is_finished() { | |
| 1235 | - return None; | |
| 1236 | - } | |
| 1237 | - let rx = wake.as_mut()?; | |
| 1238 | - rx.changed().await.ok()?; | |
| 1239 | - } | |
| 1240 | - } | |
| 1241 | - }); | |
| 1242 | - events_response(cx, events) | |
| 1243 | -} | |
| 1244 | - | |
| 1245 | -#[derive(Deserialize)] | |
| 1246 | -struct RetryForm { | |
| 1247 | - #[serde(default)] | |
| 1248 | - csrf: String, | |
| 1249 | - #[serde(default)] | |
| 1250 | - token: String, | |
| 1251 | -} | |
| 1252 | - | |
| 1253 | -async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool> { | |
| 1254 | - if job.state != ImportState::Failed { | |
| 1255 | - return Ok(false); | |
| 1256 | - } | |
| 1257 | - let Some(source) = Source::parse(&job.source) else { | |
| 1258 | - return Ok(false); | |
| 1259 | - }; | |
| 1260 | - let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else { | |
| 1261 | - return Ok(false); | |
| 1262 | - }; | |
| 1263 | - let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default(); | |
| 1264 | - if !state.store.requeue_failed_import(&job.id).await? { | |
| 1265 | - return Ok(false); | |
| 1266 | - } | |
| 1267 | - state | |
| 1268 | - .store | |
| 1269 | - .add_import_event( | |
| 1270 | - &job.id, | |
| 1271 | - "info", | |
| 1272 | - "Retrying; what was imported before is skipped", | |
| 1273 | - ) | |
| 1274 | - .await?; | |
| 1275 | - let spec = JobSpec { | |
| 1276 | - source, | |
| 1277 | - remote, | |
| 1278 | - instance, | |
| 1279 | - token: token_of(token), | |
| 1280 | - git_user: String::new(), | |
| 1281 | - options, | |
| 1282 | - }; | |
| 1283 | - importer::spawn_job(state.clone(), job, spec); | |
| 1284 | - Ok(true) | |
| 1285 | -} | |
| 1286 | - | |
| 1287 | -#[route(POST "/import/{job_id}/retry")] | |
| 1288 | -async fn job_retry(cx: &Cx, Form(form): Form<RetryForm>) -> Result<SeeOther> { | |
| 1289 | - let viewer = require_csrf(cx, &form.csrf).await?; | |
| 1290 | - let state = context::<AppState>(cx); | |
| 1291 | - let job = owned_job(cx, &viewer.0).await?; | |
| 1292 | - let href = format!("/import/{}", job.id); | |
| 1293 | - retry_job(state, job, &form.token).await?; | |
| 1294 | - Err(see_other(href).into()) | |
| 1295 | -} | |
| 1296 | - | |
| 1297 | -async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(ImportJob, Repo)>> { | |
| 1298 | - let mut rows = Vec::new(); | |
| 1299 | - for job in state.store.list_import_jobs(&viewer.id, 200).await? { | |
| 1300 | - if job.state != ImportState::Failed { | |
| 1301 | - continue; | |
| 1302 | - } | |
| 1303 | - let Some(repo) = job_repo(state, Some(viewer), &job).await? else { | |
| 1304 | - continue; | |
| 1305 | - }; | |
| 1306 | - if state | |
| 1307 | - .store | |
| 1308 | - .active_import_for_repo(&repo.id) | |
| 1309 | - .await? | |
| 1310 | - .is_some() | |
| 1311 | - { | |
| 1312 | - continue; | |
| 1313 | - } | |
| 1314 | - rows.push((job, repo)); | |
| 1315 | - } | |
| 1316 | - Ok(rows) | |
| 1317 | -} | |
| 1318 | - | |
| 1319 | -fn source_label(raw: &str) -> &'static str { | |
| 1320 | - Source::parse(raw).map_or("", Source::label) | |
| 1321 | -} | |
| 1322 | - | |
| 1323 | -#[component] | |
| 1324 | -async fn retry_list( | |
| 1325 | - cx: &Cx, | |
| 1326 | - lang: Lang, | |
| 1327 | - username: String, | |
| 1328 | - csrf: &str, | |
| 1329 | - rows: Vec<(ImportJob, Repo)>, | |
| 1330 | -) -> Result<impl View> { | |
| 1331 | - let count = rows.len(); | |
| 1332 | - let empty = rows.is_empty(); | |
| 1333 | - Ok(view! { | |
| 1334 | - head(title: g::t(lang, K::RetryFailedTitle)) | |
| 1335 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 1336 | - newrepo_tabs(lang: lang, active: "history") | |
| 1337 | - <div class="sheet"> | |
| 1338 | - <form method="post" action="/import/retry" class="fields"> | |
| 1339 | - csrf_field(token: csrf) | |
| 1340 | - if empty { | |
| 1341 | - <p class="state">(g::t(lang, K::RetryNone))</p> | |
| 1342 | - } else { | |
| 1343 | - <div class="field"> | |
| 1344 | - <label for="retry-token">(g::t(lang, K::TokenOptional))</label> | |
| 1345 | - <input id="retry-token" type="password" name="token" autocomplete="new-password" maxlength="1024"> | |
| 1346 | - </div> | |
| 1347 | - <label class="line" data-kb-row=""> | |
| 1348 | - <input type="checkbox" data-select-all=".import-pick-list"> | |
| 1349 | - <span class="name">(g::t(lang, K::BulkSelectAll))</span> | |
| 1350 | - <span class="val">(count)</span> | |
| 1351 | - </label> | |
| 1352 | - <div class="import-pick-list"> | |
| 1353 | - for (i, (job, repo)) in rows.iter().enumerate() { | |
| 1354 | - <label class="line" data-kb-row=""> | |
| 1355 | - <input type="checkbox" name=(format!("sel_{i}")) value=(job.id.as_str())> | |
| 1356 | - <span class="name">(format!("{}/{}", repo.owner_name, repo.name))</span> | |
| 1357 | - <span class="val"> | |
| 1358 | - <span class="badge">(source_label(&job.source))</span> | |
| 1359 | - " " (job.source_ref.as_str()) | |
| 1360 | - if let Some(message) = job.error.as_ref() { | |
| 1361 | - " · " (message.as_str()) | |
| 1362 | - } | |
| 1363 | - </span> | |
| 1364 | - </label> | |
| 1365 | - } | |
| 1366 | - </div> | |
| 1367 | - <button type="submit" class="primary">(g::t(lang, K::RetrySelected))</button> | |
| 1368 | - } | |
| 1369 | - </form> | |
| 1370 | - </div> | |
| 1371 | - }) | |
| 1372 | -} | |
| 1373 | - | |
| 1374 | -#[page("/import/retry")] | |
| 1375 | -async fn retry_page(cx: &Cx) -> Result<impl View> { | |
| 1376 | - let viewer = require_user(cx).await?; | |
| 1377 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 1378 | - let state = context::<AppState>(cx); | |
| 1379 | - let rows = retry_candidates(state, &viewer.0).await?; | |
| 1380 | - let csrf = viewer.1.csrf_token.clone(); | |
| 1381 | - Ok(view! { | |
| 1382 | - shell(title: g::t(lang, K::RetryFailedTitle), viewer: Some(&viewer), | |
| 1383 | - retry_list(lang: lang, username: viewer.0.username.clone(), csrf: csrf.as_str(), rows: rows)) | |
| 1384 | - }) | |
| 1385 | -} | |
| 1386 | - | |
| 1387 | -#[derive(Deserialize)] | |
| 1388 | -struct RetrySelectedForm { | |
| 1389 | - #[serde(default)] | |
| 1390 | - csrf: String, | |
| 1391 | - #[serde(default)] | |
| 1392 | - token: String, | |
| 1393 | - #[serde(flatten)] | |
| 1394 | - extra: HashMap<String, String>, | |
| 1395 | -} | |
| 1396 | - | |
| 1397 | -#[route(POST "/import/retry")] | |
| 1398 | -async fn retry_submit(cx: &Cx, Form(form): Form<RetrySelectedForm>) -> Result<SeeOther> { | |
| 1399 | - let viewer = require_csrf(cx, &form.csrf).await?; | |
| 1400 | - let state = context::<AppState>(cx); | |
| 1401 | - let mut picked: Vec<(usize, &String)> = form | |
| 1402 | - .extra | |
| 1403 | - .iter() | |
| 1404 | - .filter_map(|(k, v)| Some((k.strip_prefix("sel_")?.parse::<usize>().ok()?, v))) | |
| 1405 | - .collect(); | |
| 1406 | - picked.sort_by_key(|(i, _)| *i); | |
| 1407 | - if picked.is_empty() { | |
| 1408 | - return Err(see_other("/import/retry").into()); | |
| 1409 | - } | |
| 1410 | - for (_, id) in picked { | |
| 1411 | - let Some(job) = state.store.import_job(id).await? else { | |
| 1412 | - continue; | |
| 1413 | - }; | |
| 1414 | - if job.user_id != viewer.0.id { | |
| 1415 | - continue; | |
| 1416 | - } | |
| 1417 | - retry_job(state, job, &form.token).await?; | |
| 1418 | - } | |
| 1419 | - Err(see_other("/import").into()) | |
| 1420 | -} |
crates/forge-web-account/src/pages/import_tests.rsdeleted+0 -157
| @@ -1,157 +0,0 @@ | ||
| 1 | -use forge_core::Store; | |
| 2 | -use topcoat::router::Router; | |
| 3 | - | |
| 4 | -use crate::auth::SESSION_COOKIE; | |
| 5 | -use crate::test_support::fixture::{send, send_form}; | |
| 6 | -use crate::test_support::{app_router, create_session, test_state}; | |
| 7 | - | |
| 8 | -const TOKEN: &str = "import-session"; | |
| 9 | -const CSRF: &str = "import-csrf"; | |
| 10 | -const OTHER: &str = "other-session"; | |
| 11 | - | |
| 12 | -struct Fixture { | |
| 13 | - _dir: tempfile::TempDir, | |
| 14 | - router: Router, | |
| 15 | - store: Store, | |
| 16 | - user_id: String, | |
| 17 | -} | |
| 18 | - | |
| 19 | -async fn fixture() -> Fixture { | |
| 20 | - let dir = tempfile::tempdir().expect("tempdir"); | |
| 21 | - let data_dir = dir.path().join("data"); | |
| 22 | - std::fs::create_dir_all(&data_dir).expect("data dir"); | |
| 23 | - let state = test_state(&data_dir).await; | |
| 24 | - let owner = state | |
| 25 | - .store | |
| 26 | - .create_user("tahinli", None, "h", false) | |
| 27 | - .await | |
| 28 | - .expect("user"); | |
| 29 | - let other = state | |
| 30 | - .store | |
| 31 | - .create_user("nina", None, "h", false) | |
| 32 | - .await | |
| 33 | - .expect("user"); | |
| 34 | - create_session(&state.store, &owner.id, TOKEN, CSRF).await; | |
| 35 | - create_session(&state.store, &other.id, OTHER, "other-csrf").await; | |
| 36 | - Fixture { | |
| 37 | - _dir: dir, | |
| 38 | - router: app_router(state.clone()), | |
| 39 | - store: state.store.clone(), | |
| 40 | - user_id: owner.id, | |
| 41 | - } | |
| 42 | -} | |
| 43 | - | |
| 44 | -fn session_cookie(token: &str) -> String { | |
| 45 | - format!("__Host-{SESSION_COOKIE}={token}") | |
| 46 | -} | |
| 47 | - | |
| 48 | -async fn scenario_pages_render(fx: &Fixture) { | |
| 49 | - let cookie = session_cookie(TOKEN); | |
| 50 | - for (uri, needle) in [ | |
| 51 | - ("/new/import?source=git", "Import a repository"), | |
| 52 | - ("/new/import?source=github", "Import a repository"), | |
| 53 | - ("/new/import?source=gitlab", "Import a repository"), | |
| 54 | - ( | |
| 55 | - "/new/import/bulk?source=github", | |
| 56 | - "Import several repositories", | |
| 57 | - ), | |
| 58 | - ("/import", "Import history"), | |
| 59 | - ("/settings/export", "Export your data"), | |
| 60 | - ] { | |
| 61 | - let reply = send(&fx.router, "GET", uri, Some(&cookie), None).await; | |
| 62 | - assert_eq!(reply.status, 200, "{uri}: {}", reply.body); | |
| 63 | - assert!(reply.body.contains(needle), "{uri} lacks {needle}"); | |
| 64 | - } | |
| 65 | -} | |
| 66 | - | |
| 67 | -async fn scenario_need_session(fx: &Fixture) { | |
| 68 | - for uri in [ | |
| 69 | - "/new/import", | |
| 70 | - "/new/import/bulk", | |
| 71 | - "/import", | |
| 72 | - "/settings/export", | |
| 73 | - ] { | |
| 74 | - let reply = send(&fx.router, "GET", uri, None, None).await; | |
| 75 | - assert_ne!(reply.status, 200, "{uri}: {}", reply.body); | |
| 76 | - } | |
| 77 | -} | |
| 78 | - | |
| 79 | -async fn scenario_csrf(fx: &Fixture) { | |
| 80 | - let cookie = session_cookie(TOKEN); | |
| 81 | - let form = "source=git&remote=https%3A%2F%2Fexample.org%2Fa.git&csrf=wrong".to_owned(); | |
| 82 | - let reply = send_form(&fx.router, "POST", "/new/import", Some(&cookie), Some(form)).await; | |
| 83 | - assert_ne!(reply.status, 303, "a bad token must not redirect to a job"); | |
| 84 | - assert!( | |
| 85 | - fx.store | |
| 86 | - .list_import_jobs(&fx.user_id, 10) | |
| 87 | - .await | |
| 88 | - .expect("jobs") | |
| 89 | - .is_empty() | |
| 90 | - ); | |
| 91 | - let reply = send_form( | |
| 92 | - &fx.router, | |
| 93 | - "POST", | |
| 94 | - "/settings/export", | |
| 95 | - Some(&cookie), | |
| 96 | - Some("csrf=wrong".into()), | |
| 97 | - ) | |
| 98 | - .await; | |
| 99 | - assert_ne!(reply.status, 303); | |
| 100 | - assert!( | |
| 101 | - fx.store | |
| 102 | - .list_exports(&fx.user_id) | |
| 103 | - .await | |
| 104 | - .expect("exports") | |
| 105 | - .is_empty() | |
| 106 | - ); | |
| 107 | -} | |
| 108 | - | |
| 109 | -async fn scenario_private_address(fx: &Fixture) { | |
| 110 | - let cookie = session_cookie(TOKEN); | |
| 111 | - let form = format!( | |
| 112 | - "csrf={CSRF}&source=git&remote=https%3A%2F%2F127.0.0.1%2Fa.git&owner=tahinli&visibility=private" | |
| 113 | - ); | |
| 114 | - let reply = send_form(&fx.router, "POST", "/new/import", Some(&cookie), Some(form)).await; | |
| 115 | - assert_ne!(reply.status, 500, "{}", reply.body); | |
| 116 | - assert!( | |
| 117 | - fx.store | |
| 118 | - .list_import_jobs(&fx.user_id, 10) | |
| 119 | - .await | |
| 120 | - .expect("jobs") | |
| 121 | - .is_empty(), | |
| 122 | - "no job for a refused address" | |
| 123 | - ); | |
| 124 | -} | |
| 125 | - | |
| 126 | -async fn scenario_archive(fx: &Fixture) { | |
| 127 | - let export = fx | |
| 128 | - .store | |
| 129 | - .create_export(&fx.user_id, std::time::Duration::from_secs(3600)) | |
| 130 | - .await | |
| 131 | - .expect("export"); | |
| 132 | - fx.store | |
| 133 | - .mark_export_ready(&export.id, 10, std::time::Duration::from_secs(3600)) | |
| 134 | - .await | |
| 135 | - .expect("ready"); | |
| 136 | - let uri = format!("/settings/export/{}/download", export.id); | |
| 137 | - let other = session_cookie(OTHER); | |
| 138 | - let reply = send(&fx.router, "GET", &uri, Some(&other), None).await; | |
| 139 | - assert_eq!(reply.status, 404, "a stranger gets not found"); | |
| 140 | - let reply = send(&fx.router, "GET", &uri, None, None).await; | |
| 141 | - assert_ne!(reply.status, 200); | |
| 142 | -} | |
| 143 | - | |
| 144 | -#[tokio::test] | |
| 145 | -async fn import_and_export_pages_render_and_need_a_session() { | |
| 146 | - let fx = fixture().await; | |
| 147 | - scenario_pages_render(&fx).await; | |
| 148 | - scenario_need_session(&fx).await; | |
| 149 | -} | |
| 150 | - | |
| 151 | -#[tokio::test] | |
| 152 | -async fn import_and_export_writes_are_refused_or_scoped() { | |
| 153 | - let fx = fixture().await; | |
| 154 | - scenario_csrf(&fx).await; | |
| 155 | - scenario_private_address(&fx).await; | |
| 156 | - scenario_archive(&fx).await; | |
| 157 | -} |
crates/forge-web-account/src/pages/mod.rsmodified+0 -4
| @@ -18,9 +18,6 @@ pub mod banner; | ||
| 18 | 18 | pub mod explore; |
| 19 | 19 | pub mod forgot; |
| 20 | 20 | pub mod home; |
| 21 | -pub mod import; | |
| 22 | -#[cfg(test)] | |
| 23 | -mod import_tests; | |
| 24 | 21 | pub mod invites; |
| 25 | 22 | pub mod login; |
| 26 | 23 | pub mod needs_you; |
| @@ -43,7 +40,6 @@ pub mod register; | ||
| 43 | 40 | #[cfg(test)] |
| 44 | 41 | mod releases_tests; |
| 45 | 42 | pub mod settings_appearance; |
| 46 | -pub mod settings_export; | |
| 47 | 43 | pub mod settings_gpg; |
| 48 | 44 | #[cfg(test)] |
| 49 | 45 | mod settings_gpg_tests; |
crates/forge-web-account/src/pages/new_repo.rsmodified+14 -2
| @@ -222,7 +222,6 @@ async fn new_repo_form( | ||
| 222 | 222 | Ok(view! { |
| 223 | 223 | head(title: i18n::t(lang, Key::NewRepository)) |
| 224 | 224 | crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) |
| 225 | - crate::pages::import::newrepo_tabs(lang: lang, active: "create") | |
| 226 | 225 | <div class="sheet fit"> |
| 227 | 226 | <form method="post" action="/new" class="fields"> |
| 228 | 227 | if let Some(message) = error { |
| @@ -253,7 +252,7 @@ async fn new_repo_form( | ||
| 253 | 252 | <input type="checkbox" name="default_labels" value="on" checked=(default_labels)> |
| 254 | 253 | <span>(g::t(lang, K::AddDefaultLabels))</span> |
| 255 | 254 | </label> |
| 256 | - crate::pages::import::visibility_pick(lang: lang, private: private) | |
| 255 | + visibility_pick(lang: lang, private: private) | |
| 257 | 256 | <label class="switch"> |
| 258 | 257 | <input type="checkbox" name="add_readme" value="on" checked=(add_readme)> |
| 259 | 258 | <span>(g::t(lang, K::ReadmeLabel))</span> |
| @@ -291,6 +290,19 @@ async fn new_repo_form( | ||
| 291 | 290 | }) |
| 292 | 291 | } |
| 293 | 292 | |
| 293 | +#[component] | |
| 294 | +async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result<impl View> { | |
| 295 | + Ok(view! { | |
| 296 | + <div class="field"> | |
| 297 | + <span class="field-label">(crate::i18n::misc::t(lang, crate::i18n::misc::K::VisibilityLegend))</span> | |
| 298 | + <div class="choice" role="radiogroup" aria-label=(crate::i18n::misc::t(lang, crate::i18n::misc::K::VisibilityLegend))> | |
| 299 | + <label><input type="radio" name="visibility" value="private" checked=(private)><span>(crate::i18n::community::t(lang, crate::i18n::community::K::VisibilityPrivate))</span></label> | |
| 300 | + <label><input type="radio" name="visibility" value="public" checked=(!private)><span>(crate::i18n::community::t(lang, crate::i18n::community::K::VisibilityPublic))</span></label> | |
| 301 | + </div> | |
| 302 | + </div> | |
| 303 | + }) | |
| 304 | +} | |
| 305 | + | |
| 294 | 306 | pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> { |
| 295 | 307 | let mut names = vec![viewer.username.clone()]; |
| 296 | 308 | for (org, _) in state.store.orgs_for_user(&viewer.id).await? { |
crates/forge-web-account/src/pages/palette.rsmodified+0 -9
| @@ -121,15 +121,6 @@ const SETTINGS_TERMS: &[(&str, &[&str])] = &[ | ||
| 121 | 121 | "Tones", |
| 122 | 122 | ], |
| 123 | 123 | ), |
| 124 | - ( | |
| 125 | - "/settings/export", | |
| 126 | - &[ | |
| 127 | - "Download my data", | |
| 128 | - "Verilerimi indir", | |
| 129 | - "Archive", | |
| 130 | - "Dışa aktar", | |
| 131 | - ], | |
| 132 | - ), | |
| 133 | 124 | ]; |
| 134 | 125 | |
| 135 | 126 | const ADMIN_TERMS: &[(&str, &[&str])] = &[ |
crates/forge-web-account/src/pages/settings_export.rsdeleted+0 -372
| @@ -1,372 +0,0 @@ | ||
| 1 | -use std::time::Duration; | |
| 2 | - | |
| 3 | -use forge_core::store::exports::{DataExport, ExportState}; | |
| 4 | -use forge_core::{Session, User}; | |
| 5 | -use futures_util::{TryStreamExt, stream}; | |
| 6 | -use http::header::{ | |
| 7 | - CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, RETRY_AFTER, | |
| 8 | - X_CONTENT_TYPE_OPTIONS, | |
| 9 | -}; | |
| 10 | -use http_body::Frame; | |
| 11 | -use http_body_util::StreamBody; | |
| 12 | -use tokio_util::io::ReaderStream; | |
| 13 | -use topcoat::Result; | |
| 14 | -use topcoat::context::{Cx, context}; | |
| 15 | -use topcoat::router::content::Form; | |
| 16 | -use topcoat::router::error::{SeeOther, not_found, see_other}; | |
| 17 | -use topcoat::router::response::Response; | |
| 18 | -use topcoat::router::{Body, HeaderMap, StatusCode, page, path_param, query_params, route}; | |
| 19 | -use topcoat::view::{View, component, view}; | |
| 20 | - | |
| 21 | -use crate::auth::{CsrfForm, require_csrf, require_user, two_factor_enabled}; | |
| 22 | -use crate::exporter; | |
| 23 | -use crate::i18n::migrate::{self as g, K}; | |
| 24 | -use crate::i18n::{self, Key, Lang}; | |
| 25 | -use crate::live::{changed_event, events_response}; | |
| 26 | -use crate::state::AppState; | |
| 27 | -use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail}; | |
| 28 | -use crate::views::{alert, csrf_field, human_size, rel_time, shell}; | |
| 29 | - | |
| 30 | -path_param!(export_id); | |
| 31 | - | |
| 32 | -#[query_params(error = bad_request)] | |
| 33 | -struct SeenQuery { | |
| 34 | - v: Option<String>, | |
| 35 | -} | |
| 36 | - | |
| 37 | -#[query_params(error = bad_request)] | |
| 38 | -struct TopicQuery { | |
| 39 | - part: Option<String>, | |
| 40 | -} | |
| 41 | - | |
| 42 | -fn signature(exports: &[DataExport]) -> String { | |
| 43 | - exports | |
| 44 | - .iter() | |
| 45 | - .map(|e| format!("{}:{}", e.id, e.state.as_str())) | |
| 46 | - .collect::<Vec<_>>() | |
| 47 | - .join(",") | |
| 48 | -} | |
| 49 | - | |
| 50 | -fn is_building(exports: &[DataExport]) -> bool { | |
| 51 | - exports.iter().any(|e| e.state == ExportState::Building) | |
| 52 | -} | |
| 53 | - | |
| 54 | -fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> { | |
| 55 | - vec![ | |
| 56 | - RailItem { | |
| 57 | - name: crate::i18n::s(lang, "Export", "Dışa aktar").to_owned(), | |
| 58 | - val: String::new(), | |
| 59 | - href: "/settings/export".to_owned(), | |
| 60 | - current: !delete, | |
| 61 | - }, | |
| 62 | - RailItem { | |
| 63 | - name: i18n::t(lang, Key::DeleteAccount).to_owned(), | |
| 64 | - val: String::new(), | |
| 65 | - href: "/settings/export?part=delete".to_owned(), | |
| 66 | - current: delete, | |
| 67 | - }, | |
| 68 | - ] | |
| 69 | -} | |
| 70 | - | |
| 71 | -#[component] | |
| 72 | -async fn export_sheet( | |
| 73 | - cx: &Cx, | |
| 74 | - lang: Lang, | |
| 75 | - csrf: &str, | |
| 76 | - exports: Vec<DataExport>, | |
| 77 | -) -> Result<impl View> { | |
| 78 | - let building = is_building(&exports); | |
| 79 | - let live = building.then(|| { | |
| 80 | - format!( | |
| 81 | - "/settings/export/events?v={}", | |
| 82 | - crate::views::enc(&signature(&exports)) | |
| 83 | - ) | |
| 84 | - }); | |
| 85 | - let empty = exports.is_empty(); | |
| 86 | - Ok(view! { | |
| 87 | - <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })> | |
| 88 | - <section class="sec"> | |
| 89 | - <h2>(crate::i18n::s(lang, "Your archives", "Arşivleriniz"))</h2> | |
| 90 | - if empty { | |
| 91 | - <p class="state">(g::t(lang, K::ExportNone))</p> | |
| 92 | - } | |
| 93 | - for export in exports.iter() { | |
| 94 | - let delete = format!("/settings/export/{}/delete", export.id); | |
| 95 | - <div class="export-row"> | |
| 96 | - <div class="line"> | |
| 97 | - <span class="name">(g::t(lang, K::ExportRequested)) " " rel_time(lang: lang, stamp: export.created_at.as_str())</span> | |
| 98 | - <span class="val"> | |
| 99 | - if export.state == ExportState::Ready { | |
| 100 | - (g::t(lang, K::ExportReady)) " · " (g::t(lang, K::ExportSize)) ": " (human_size(lang, u64::try_from(export.size).unwrap_or(0))) | |
| 101 | - " · " (g::expires_label(lang)) " " rel_time(lang: lang, stamp: export.expires_at.as_str()) | |
| 102 | - } | |
| 103 | - if export.state == ExportState::Building { | |
| 104 | - (g::t(lang, K::ExportBuilding)) | |
| 105 | - } | |
| 106 | - if export.state == ExportState::Failed { | |
| 107 | - (g::t(lang, K::ExportFailed)) | |
| 108 | - } | |
| 109 | - </span> | |
| 110 | - if export.state == ExportState::Ready { | |
| 111 | - <a class="act" href=(format!("/settings/export/{}/download", export.id))>(g::t(lang, K::ExportDownload))</a> | |
| 112 | - } | |
| 113 | - if export.state != ExportState::Building { | |
| 114 | - confirm_act(lang: lang, label: crate::i18n::s(lang, "Delete", "Sil"), action: delete.as_str(), csrf: csrf) | |
| 115 | - } | |
| 116 | - </div> | |
| 117 | - if export.state == ExportState::Building { | |
| 118 | - <progress class="import-progress export-progress"></progress> | |
| 119 | - } | |
| 120 | - if let Some(message) = export.error.as_ref() { | |
| 121 | - alert(message: message.as_str()) | |
| 122 | - } | |
| 123 | - </div> | |
| 124 | - } | |
| 125 | - </section> | |
| 126 | - </div> | |
| 127 | - }) | |
| 128 | -} | |
| 129 | - | |
| 130 | -#[component] | |
| 131 | -async fn delete_sheet( | |
| 132 | - cx: &Cx, | |
| 133 | - lang: Lang, | |
| 134 | - csrf: &str, | |
| 135 | - two_factor_on: bool, | |
| 136 | - owned_repos: Vec<String>, | |
| 137 | - error: Option<String>, | |
| 138 | -) -> Result<impl View> { | |
| 139 | - let blocked = !owned_repos.is_empty(); | |
| 140 | - let open = error.is_some(); | |
| 141 | - Ok(view! { | |
| 142 | - <div class="sheet"> | |
| 143 | - <section class="sec" id="danger"> | |
| 144 | - <h2>(i18n::t(lang, Key::DangerZone))</h2> | |
| 145 | - if blocked { | |
| 146 | - <p class="state">(i18n::t(lang, Key::TransferOrDeleteRepos))</p> | |
| 147 | - <ul class="topic-list"> | |
| 148 | - for name in owned_repos.iter() { | |
| 149 | - <li class="line"><span class="name">(name.as_str())</span></li> | |
| 150 | - } | |
| 151 | - </ul> | |
| 152 | - } else { | |
| 153 | - <div class="acts"> | |
| 154 | - <details class="reveal" open=(open)> | |
| 155 | - <summary class="act danger">(i18n::t(lang, Key::DeleteAccount))</summary> | |
| 156 | - <div class="opened"> | |
| 157 | - if let Some(message) = error.as_deref() { | |
| 158 | - alert(message: message) | |
| 159 | - } | |
| 160 | - <form data-hard="true" method="post" action="/settings/security/delete" class="fields"> | |
| 161 | - <input type="hidden" name="csrf" value=(csrf)> | |
| 162 | - <div class="field"> | |
| 163 | - <label for="delete-password">(i18n::t(lang, Key::CurrentPassword))</label> | |
| 164 | - <input id="delete-password" type="password" name="current_password" autocomplete="current-password" required=(true)> | |
| 165 | - </div> | |
| 166 | - if two_factor_on { | |
| 167 | - <div class="field"> | |
| 168 | - <label for="delete-code">(i18n::t(lang, Key::Code))</label> | |
| 169 | - <input id="delete-code" type="text" name="code" autocomplete="one-time-code" required=(true)> | |
| 170 | - </div> | |
| 171 | - } | |
| 172 | - <div class="field"> | |
| 173 | - <label for="delete-username">(i18n::t(lang, Key::TypeUsernameToConfirm))</label> | |
| 174 | - <input id="delete-username" type="text" name="confirm_username" autocomplete="off" required=(true)> | |
| 175 | - </div> | |
| 176 | - <button type="submit" class="act danger">(i18n::t(lang, Key::DeleteAccount))</button> | |
| 177 | - </form> | |
| 178 | - </div> | |
| 179 | - </details> | |
| 180 | - </div> | |
| 181 | - } | |
| 182 | - </section> | |
| 183 | - </div> | |
| 184 | - }) | |
| 185 | -} | |
| 186 | - | |
| 187 | -#[component] | |
| 188 | -async fn data_body( | |
| 189 | - cx: &Cx, | |
| 190 | - lang: Lang, | |
| 191 | - csrf: &str, | |
| 192 | - delete: bool, | |
| 193 | - exports: Vec<DataExport>, | |
| 194 | - two_factor_on: bool, | |
| 195 | - owned_repos: Vec<String>, | |
| 196 | - delete_error: Option<String>, | |
| 197 | -) -> Result<impl View> { | |
| 198 | - let items = data_rail_items(lang, delete); | |
| 199 | - let title = if delete { | |
| 200 | - i18n::t(lang, Key::DeleteAccount) | |
| 201 | - } else { | |
| 202 | - g::t(lang, K::ExportTitle) | |
| 203 | - }; | |
| 204 | - let building = is_building(&exports); | |
| 205 | - Ok(view! { | |
| 206 | - head(title: title, sub: Vec::<SubPart>::new(), | |
| 207 | - if !delete { | |
| 208 | - <form method="post" action="/settings/export"> | |
| 209 | - csrf_field(token: csrf) | |
| 210 | - <button type="submit" class="primary" disabled=(building)>(g::t(lang, K::ExportRequest))</button> | |
| 211 | - </form> | |
| 212 | - } | |
| 213 | - ) | |
| 214 | - <div class="work"> | |
| 215 | - rail(label: crate::i18n::s(lang, "Data", "Veri"), items: items) | |
| 216 | - if delete { | |
| 217 | - delete_sheet(lang: lang, csrf: csrf, two_factor_on: two_factor_on, owned_repos: owned_repos, error: delete_error) | |
| 218 | - } else { | |
| 219 | - export_sheet(lang: lang, csrf: csrf, exports: exports) | |
| 220 | - } | |
| 221 | - </div> | |
| 222 | - }) | |
| 223 | -} | |
| 224 | - | |
| 225 | -async fn page_view( | |
| 226 | - cx: &Cx, | |
| 227 | - viewer: (User, Session), | |
| 228 | - delete: bool, | |
| 229 | - delete_error: Option<String>, | |
| 230 | - throttled: Option<Duration>, | |
| 231 | -) -> Result<impl View> { | |
| 232 | - let state = context::<AppState>(cx); | |
| 233 | - let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 234 | - let user_id = viewer.0.id.clone(); | |
| 235 | - let exports = state.store.list_exports(&user_id).await?; | |
| 236 | - let two_factor_on = two_factor_enabled(&state.store, &user_id).await?; | |
| 237 | - let owned_repos: Vec<String> = state | |
| 238 | - .store | |
| 239 | - .list_repos_by_owner(&user_id) | |
| 240 | - .await? | |
| 241 | - .into_iter() | |
| 242 | - .map(|repo| format!("{}/{}", repo.owner_name, repo.name)) | |
| 243 | - .collect(); | |
| 244 | - let mut headers = HeaderMap::new(); | |
| 245 | - let status = match throttled { | |
| 246 | - Some(retry) => { | |
| 247 | - headers.insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1))); | |
| 248 | - StatusCode::TOO_MANY_REQUESTS | |
| 249 | - } | |
| 250 | - None => StatusCode::OK, | |
| 251 | - }; | |
| 252 | - let csrf = viewer.1.csrf_token.clone(); | |
| 253 | - Ok(view! { | |
| 254 | - (status) | |
| 255 | - (headers) | |
| 256 | - shell(title: g::t(lang, K::SettingsExport), viewer: Some(&viewer), | |
| 257 | - data_body(lang: lang, csrf: csrf.as_str(), delete: delete, exports: exports, | |
| 258 | - two_factor_on: two_factor_on, owned_repos: owned_repos, delete_error: delete_error)) | |
| 259 | - }) | |
| 260 | -} | |
| 261 | - | |
| 262 | -pub(crate) async fn respond_delete( | |
| 263 | - cx: &Cx, | |
| 264 | - viewer: (User, Session), | |
| 265 | - error: Option<String>, | |
| 266 | - throttled: Option<Duration>, | |
| 267 | -) -> Result<impl View> { | |
| 268 | - page_view(cx, viewer, true, error, throttled).await | |
| 269 | -} | |
| 270 | - | |
| 271 | -#[page("/settings/export")] | |
| 272 | -async fn export_page(cx: &Cx) -> Result<impl View> { | |
| 273 | - let viewer = require_user(cx).await?; | |
| 274 | - let state = context::<AppState>(cx); | |
| 275 | - exporter::sweep_expired(state).await; | |
| 276 | - let query = query_params::<TopicQuery>(cx)?; | |
| 277 | - page_view( | |
| 278 | - cx, | |
| 279 | - viewer, | |
| 280 | - query.part.as_deref() == Some("delete"), | |
| 281 | - None, | |
| 282 | - None, | |
| 283 | - ) | |
| 284 | - .await | |
| 285 | -} | |
| 286 | - | |
| 287 | -#[route(POST "/settings/export")] | |
| 288 | -async fn export_request(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 289 | - let viewer = require_csrf(cx, &form.csrf).await?; | |
| 290 | - let state = context::<AppState>(cx); | |
| 291 | - exporter::start(state, &viewer.0).await?; | |
| 292 | - Err(see_other("/settings/export").into()) | |
| 293 | -} | |
| 294 | - | |
| 295 | -#[route(POST "/settings/export/{export_id}/delete")] | |
| 296 | -async fn export_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |
| 297 | - let viewer = require_csrf(cx, &form.csrf).await?; | |
| 298 | - let id = export_id(cx).to_owned(); | |
| 299 | - let state = context::<AppState>(cx); | |
| 300 | - let export = match state.store.data_export(&id).await? { | |
| 301 | - Some(e) if e.user_id == viewer.0.id && e.state != ExportState::Building => e, | |
| 302 | - _ => return Err(not_found().into()), | |
| 303 | - }; | |
| 304 | - exporter::delete_one(state, &export).await?; | |
| 305 | - Err(see_other("/settings/export").into()) | |
| 306 | -} | |
| 307 | - | |
| 308 | -#[route(GET "/settings/export/events")] | |
| 309 | -async fn export_events(cx: &Cx) -> Result<Response> { | |
| 310 | - let viewer = require_user(cx).await?; | |
| 311 | - let query = query_params::<SeenQuery>(cx)?; | |
| 312 | - let state = context::<AppState>(cx); | |
| 313 | - let user_id = viewer.0.id.clone(); | |
| 314 | - let wake = exporter::subscribe(&user_id); | |
| 315 | - let store = state.store.clone(); | |
| 316 | - let seen = query.v.clone().unwrap_or_default(); | |
| 317 | - let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| { | |
| 318 | - let store = store.clone(); | |
| 319 | - let user_id = user_id.clone(); | |
| 320 | - async move { | |
| 321 | - if ended { | |
| 322 | - return None; | |
| 323 | - } | |
| 324 | - loop { | |
| 325 | - let exports = store.list_exports(&user_id).await.ok()?; | |
| 326 | - let sig = signature(&exports); | |
| 327 | - let building = is_building(&exports); | |
| 328 | - if sig != seen { | |
| 329 | - seen = sig; | |
| 330 | - return Some((changed_event("export".to_owned()), (wake, seen, !building))); | |
| 331 | - } | |
| 332 | - if !building { | |
| 333 | - return None; | |
| 334 | - } | |
| 335 | - wake.changed().await.ok()?; | |
| 336 | - } | |
| 337 | - } | |
| 338 | - }); | |
| 339 | - events_response(cx, events) | |
| 340 | -} | |
| 341 | - | |
| 342 | -#[route(GET "/settings/export/{export_id}/download")] | |
| 343 | -async fn export_download(cx: &Cx) -> Result<Response> { | |
| 344 | - let viewer = require_user(cx).await?; | |
| 345 | - let id = export_id(cx).to_owned(); | |
| 346 | - let state = context::<AppState>(cx); | |
| 347 | - exporter::sweep_expired(state).await; | |
| 348 | - let export = match state.store.data_export(&id).await? { | |
| 349 | - Some(e) if e.user_id == viewer.0.id && e.state == ExportState::Ready => e, | |
| 350 | - _ => return Err(not_found().into()), | |
| 351 | - }; | |
| 352 | - let file = match tokio::fs::File::open(exporter::archive_path(state, &export.id)).await { | |
| 353 | - Ok(file) => file, | |
| 354 | - Err(_) => return Err(not_found().into()), | |
| 355 | - }; | |
| 356 | - let len = file.metadata().await?.len(); | |
| 357 | - let chunks = ReaderStream::new(file).map_ok(Frame::data); | |
| 358 | - let mut res = Response::new(Body::new(StreamBody::new(chunks))); | |
| 359 | - let headers = res.headers_mut(); | |
| 360 | - headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/gzip")); | |
| 361 | - headers.insert( | |
| 362 | - CONTENT_DISPOSITION, | |
| 363 | - HeaderValue::from_str(&format!( | |
| 364 | - "attachment; filename=\"forge-export-{}.tar.gz\"", | |
| 365 | - viewer.0.username | |
| 366 | - ))?, | |
| 367 | - ); | |
| 368 | - headers.insert(CONTENT_LENGTH, HeaderValue::from(len)); | |
| 369 | - headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); | |
| 370 | - headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-store")); | |
| 371 | - Ok(res) | |
| 372 | -} |
crates/forge-web-account/src/pages/settings_security.rsmodified+100 -9
| @@ -23,7 +23,6 @@ use crate::i18n::s; | ||
| 23 | 23 | use crate::i18n::{self, Key, Lang, t}; |
| 24 | 24 | use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel}; |
| 25 | 25 | use crate::pages::register::check_new_password; |
| 26 | -use crate::pages::settings_export; | |
| 27 | 26 | use crate::pages::settings_sessions::session_label; |
| 28 | 27 | use crate::state::AppState; |
| 29 | 28 | use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT}; |
| @@ -115,6 +114,7 @@ struct Shown { | ||
| 115 | 114 | codes: Option<Vec<String>>, |
| 116 | 115 | throttled: Option<Duration>, |
| 117 | 116 | part: Option<String>, |
| 117 | + delete_error: Option<String>, | |
| 118 | 118 | } |
| 119 | 119 | |
| 120 | 120 | #[derive(Clone, Copy, Default, PartialEq, Eq)] |
| @@ -147,6 +147,7 @@ struct SecurityPage { | ||
| 147 | 147 | passkeys: PasskeyPanel, |
| 148 | 148 | sessions: Vec<Session>, |
| 149 | 149 | current_session_id: String, |
| 150 | + owned_repos: Vec<String>, | |
| 150 | 151 | shown: Shown, |
| 151 | 152 | } |
| 152 | 153 | |
| @@ -199,6 +200,12 @@ pub(crate) fn security_rail_items( | ||
| 199 | 200 | href: "/settings/security/log".to_owned(), |
| 200 | 201 | current: active == "log", |
| 201 | 202 | }, |
| 203 | + RailItem { | |
| 204 | + name: t(lang, Key::DeleteAccount).to_owned(), | |
| 205 | + val: String::new(), | |
| 206 | + href: "/settings/security?part=danger".to_owned(), | |
| 207 | + current: active == "danger", | |
| 208 | + }, | |
| 202 | 209 | ] |
| 203 | 210 | } |
| 204 | 211 | |
| @@ -220,6 +227,61 @@ pub(crate) async fn security_rail_for( | ||
| 220 | 227 | )) |
| 221 | 228 | } |
| 222 | 229 | |
| 230 | +#[component] | |
| 231 | +async fn danger_zone( | |
| 232 | + cx: &Cx, | |
| 233 | + lang: Lang, | |
| 234 | + csrf: &str, | |
| 235 | + two_factor_on: bool, | |
| 236 | + owned_repos: Vec<String>, | |
| 237 | + error: Option<String>, | |
| 238 | +) -> Result<impl View> { | |
| 239 | + let blocked = !owned_repos.is_empty(); | |
| 240 | + let open = error.is_some(); | |
| 241 | + Ok(view! { | |
| 242 | + <section class="sec" id="danger"> | |
| 243 | + <h2>(t(lang, Key::DangerZone))</h2> | |
| 244 | + if blocked { | |
| 245 | + <p class="state">(t(lang, Key::TransferOrDeleteRepos))</p> | |
| 246 | + <ul class="topic-list"> | |
| 247 | + for name in owned_repos.iter() { | |
| 248 | + <li class="line"><span class="name">(name.as_str())</span></li> | |
| 249 | + } | |
| 250 | + </ul> | |
| 251 | + } else { | |
| 252 | + <div class="acts"> | |
| 253 | + <details class="reveal" open=(open)> | |
| 254 | + <summary class="act danger">(t(lang, Key::DeleteAccount))</summary> | |
| 255 | + <div class="opened"> | |
| 256 | + if let Some(message) = error.as_deref() { | |
| 257 | + alert(message: message) | |
| 258 | + } | |
| 259 | + <form data-hard="true" method="post" action="/settings/security/delete" class="fields"> | |
| 260 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 261 | + <div class="field"> | |
| 262 | + <label for="delete-password">(t(lang, Key::CurrentPassword))</label> | |
| 263 | + <input id="delete-password" type="password" name="current_password" autocomplete="current-password" required=(true)> | |
| 264 | + </div> | |
| 265 | + if two_factor_on { | |
| 266 | + <div class="field"> | |
| 267 | + <label for="delete-code">(t(lang, Key::Code))</label> | |
| 268 | + <input id="delete-code" type="text" name="code" autocomplete="one-time-code" required=(true)> | |
| 269 | + </div> | |
| 270 | + } | |
| 271 | + <div class="field"> | |
| 272 | + <label for="delete-username">(t(lang, Key::TypeUsernameToConfirm))</label> | |
| 273 | + <input id="delete-username" type="text" name="confirm_username" autocomplete="off" required=(true)> | |
| 274 | + </div> | |
| 275 | + <button type="submit" class="act danger">(t(lang, Key::DeleteAccount))</button> | |
| 276 | + </form> | |
| 277 | + </div> | |
| 278 | + </details> | |
| 279 | + </div> | |
| 280 | + } | |
| 281 | + </section> | |
| 282 | + }) | |
| 283 | +} | |
| 284 | + | |
| 223 | 285 | #[component] |
| 224 | 286 | async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl View> { |
| 225 | 287 | let SecurityPage { |
| @@ -236,6 +298,7 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | ||
| 236 | 298 | passkeys, |
| 237 | 299 | sessions, |
| 238 | 300 | current_session_id, |
| 301 | + owned_repos, | |
| 239 | 302 | shown, |
| 240 | 303 | } = page; |
| 241 | 304 | let Shown { |
| @@ -246,6 +309,7 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | ||
| 246 | 309 | two_factor_panel, |
| 247 | 310 | codes, |
| 248 | 311 | part, |
| 312 | + delete_error, | |
| 249 | 313 | .. |
| 250 | 314 | } = shown; |
| 251 | 315 | let two_factor_on = two_factor.is_some(); |
| @@ -267,7 +331,14 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | ||
| 267 | 331 | }; |
| 268 | 332 | let regenerate_open = regenerate_error.is_some(); |
| 269 | 333 | let disable_open = disable_error.is_some(); |
| 270 | - const TOPICS: [&str; 5] = ["password", "email", "two-factor", "passkeys", "sessions"]; | |
| 334 | + const TOPICS: [&str; 6] = [ | |
| 335 | + "password", | |
| 336 | + "email", | |
| 337 | + "two-factor", | |
| 338 | + "passkeys", | |
| 339 | + "sessions", | |
| 340 | + "danger", | |
| 341 | + ]; | |
| 271 | 342 | let active: &'static str = if password_open { |
| 272 | 343 | "password" |
| 273 | 344 | } else if email_open { |
| @@ -469,6 +540,7 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | ||
| 469 | 540 | </div> |
| 470 | 541 | } |
| 471 | 542 | </section> |
| 543 | + danger_zone(lang: lang, csrf: csrf, two_factor_on: two_factor_on, owned_repos: owned_repos, error: delete_error) | |
| 472 | 544 | </div> |
| 473 | 545 | </div> |
| 474 | 546 | }) |
| @@ -590,10 +662,32 @@ async fn build_page( | ||
| 590 | 662 | two_factor, |
| 591 | 663 | sessions: state.store.list_sessions(&viewer.0.id).await?, |
| 592 | 664 | current_session_id: viewer.1.id.clone(), |
| 665 | + owned_repos: state | |
| 666 | + .store | |
| 667 | + .list_repos_by_owner(&viewer.0.id) | |
| 668 | + .await? | |
| 669 | + .into_iter() | |
| 670 | + .map(|repo| format!("{}/{}", repo.owner_name, repo.name)) | |
| 671 | + .collect(), | |
| 593 | 672 | shown, |
| 594 | 673 | }) |
| 595 | 674 | } |
| 596 | 675 | |
| 676 | +async fn respond_delete( | |
| 677 | + cx: &Cx, | |
| 678 | + viewer: (User, Session), | |
| 679 | + error: Option<String>, | |
| 680 | + throttled: Option<Duration>, | |
| 681 | +) -> Result<impl View> { | |
| 682 | + let shown = Shown { | |
| 683 | + part: Some("danger".to_owned()), | |
| 684 | + delete_error: error, | |
| 685 | + throttled, | |
| 686 | + ..Shown::default() | |
| 687 | + }; | |
| 688 | + respond(cx, viewer, shown).await | |
| 689 | +} | |
| 690 | + | |
| 597 | 691 | async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result<impl View> { |
| 598 | 692 | let state = context::<AppState>(cx); |
| 599 | 693 | let mut headers = HeaderMap::new(); |
| @@ -691,9 +785,6 @@ async fn security_page(cx: &Cx) -> Result<impl View> { | ||
| 691 | 785 | let viewer = require_user(cx).await?; |
| 692 | 786 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 693 | 787 | let query = query_params::<SecurityQuery>(cx)?; |
| 694 | - if query.part.as_deref() == Some("danger") { | |
| 695 | - return Err(see_other("/settings/export?part=delete").into()); | |
| 696 | - } | |
| 697 | 788 | let saved = query.saved.clone(); |
| 698 | 789 | let part = query.part.clone().or_else(|| { |
| 699 | 790 | saved.as_deref().map(|saved| { |
| @@ -912,16 +1003,16 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result< | ||
| 912 | 1003 | let user_id = viewer.0.id.clone(); |
| 913 | 1004 | if form.confirm_username != viewer.0.username { |
| 914 | 1005 | let error = Some(t(lang, Key::ErrConfirmUsername).into()); |
| 915 | - return settings_export::respond_delete(cx, viewer, error, None).await; | |
| 1006 | + return respond_delete(cx, viewer, error, None).await; | |
| 916 | 1007 | } |
| 917 | 1008 | if let Err(refused) = require_password(lang, state, &viewer.0, &form.current_password).await? { |
| 918 | 1009 | let error = Some(refused.message.into()); |
| 919 | - return settings_export::respond_delete(cx, viewer, error, refused.retry).await; | |
| 1010 | + return respond_delete(cx, viewer, error, refused.retry).await; | |
| 920 | 1011 | } |
| 921 | 1012 | if two_factor_enabled(&state.store, &user_id).await? { |
| 922 | 1013 | if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? { |
| 923 | 1014 | let error = Some(refused.message.into()); |
| 924 | - return settings_export::respond_delete(cx, viewer, error, refused.retry).await; | |
| 1015 | + return respond_delete(cx, viewer, error, refused.retry).await; | |
| 925 | 1016 | } |
| 926 | 1017 | } |
| 927 | 1018 | let ghost = state.store.ensure_ghost_user().await?; |
| @@ -945,7 +1036,7 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result< | ||
| 945 | 1036 | Err(see_other("/").into()) |
| 946 | 1037 | } |
| 947 | 1038 | Err(e) => match user_facing_message(&e) { |
| 948 | - Some(message) => settings_export::respond_delete(cx, viewer, Some(message), None).await, | |
| 1039 | + Some(message) => respond_delete(cx, viewer, Some(message), None).await, | |
| 949 | 1040 | None => Err(e.into()), |
| 950 | 1041 | }, |
| 951 | 1042 | } |
crates/forge-web-app/Cargo.tomlmodified+0 -2
| @@ -40,8 +40,6 @@ hmac.workspace = true | ||
| 40 | 40 | similar = { workspace = true } |
| 41 | 41 | ulid.workspace = true |
| 42 | 42 | lettre.workspace = true |
| 43 | -tar.workspace = true | |
| 44 | -flate2.workspace = true | |
| 45 | 43 | |
| 46 | 44 | tempfile = { workspace = true, optional = true } |
| 47 | 45 |
crates/forge-web-app/src/exporter.rsdeleted+0 -412
| @@ -1,412 +0,0 @@ | ||
| 1 | -use std::collections::HashMap; | |
| 2 | -use std::io::{BufWriter, Write}; | |
| 3 | -use std::path::{Path, PathBuf}; | |
| 4 | -use std::sync::{LazyLock, Mutex, PoisonError}; | |
| 5 | -use std::time::Duration; | |
| 6 | - | |
| 7 | -use forge_core::issues::IssueFilter; | |
| 8 | -use forge_core::store::exports::{DataExport, ExportState}; | |
| 9 | -use forge_core::time::now_stamp; | |
| 10 | -use forge_core::{IssueSort, Repo, User}; | |
| 11 | -use forge_git::backup::bundle_create; | |
| 12 | -use serde_json::{Value, json}; | |
| 13 | -use tokio::sync::watch; | |
| 14 | - | |
| 15 | -use crate::state::AppState; | |
| 16 | - | |
| 17 | -pub const EXPORT_TTL_DAYS: u64 = 7; | |
| 18 | -pub const EXPORT_TTL: Duration = Duration::from_secs(EXPORT_TTL_DAYS * 24 * 60 * 60); | |
| 19 | -const PAGE: u32 = 100; | |
| 20 | - | |
| 21 | -static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> = | |
| 22 | - LazyLock::new(|| Mutex::new(HashMap::new())); | |
| 23 | -static START: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); | |
| 24 | - | |
| 25 | -pub fn subscribe(user_id: &str) -> watch::Receiver<u64> { | |
| 26 | - let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); | |
| 27 | - hub.retain(|_, tx| tx.receiver_count() > 0); | |
| 28 | - hub.entry(user_id.to_owned()) | |
| 29 | - .or_insert_with(|| watch::channel(0).0) | |
| 30 | - .subscribe() | |
| 31 | -} | |
| 32 | - | |
| 33 | -fn bump(user_id: &str) { | |
| 34 | - let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); | |
| 35 | - if let Some(tx) = hub.get(user_id) { | |
| 36 | - tx.send_modify(|n| *n = n.wrapping_add(1)); | |
| 37 | - if tx.receiver_count() == 0 { | |
| 38 | - hub.remove(user_id); | |
| 39 | - } | |
| 40 | - } | |
| 41 | -} | |
| 42 | - | |
| 43 | -fn export_dir(state: &AppState) -> PathBuf { | |
| 44 | - state.config.data_dir.join("exports") | |
| 45 | -} | |
| 46 | - | |
| 47 | -pub fn archive_path(state: &AppState, id: &str) -> PathBuf { | |
| 48 | - export_dir(state).join(format!("{id}.tar.gz")) | |
| 49 | -} | |
| 50 | - | |
| 51 | -fn partial_path(state: &AppState, id: &str) -> PathBuf { | |
| 52 | - export_dir(state).join(format!("{id}.tar.part")) | |
| 53 | -} | |
| 54 | - | |
| 55 | -async fn remove_archive(state: &AppState, id: &str) -> std::io::Result<()> { | |
| 56 | - for path in [archive_path(state, id), partial_path(state, id)] { | |
| 57 | - match tokio::fs::remove_file(&path).await { | |
| 58 | - Ok(()) => {} | |
| 59 | - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} | |
| 60 | - Err(e) => return Err(e), | |
| 61 | - } | |
| 62 | - } | |
| 63 | - Ok(()) | |
| 64 | -} | |
| 65 | - | |
| 66 | -pub async fn start(state: &AppState, user: &User) -> forge_core::Result<DataExport> { | |
| 67 | - sweep_expired(state).await; | |
| 68 | - let _guard = START.lock().await; | |
| 69 | - if let Some(running) = state | |
| 70 | - .store | |
| 71 | - .list_exports(&user.id) | |
| 72 | - .await? | |
| 73 | - .into_iter() | |
| 74 | - .find(|e| e.state == ExportState::Building) | |
| 75 | - { | |
| 76 | - return Ok(running); | |
| 77 | - } | |
| 78 | - let export = state.store.create_export(&user.id, EXPORT_TTL).await?; | |
| 79 | - let task_state = state.clone(); | |
| 80 | - let task_user = user.clone(); | |
| 81 | - let id = export.id.clone(); | |
| 82 | - tokio::spawn(async move { | |
| 83 | - run(&task_state, &task_user, &id).await; | |
| 84 | - }); | |
| 85 | - Ok(export) | |
| 86 | -} | |
| 87 | - | |
| 88 | -async fn run(state: &AppState, user: &User, id: &str) { | |
| 89 | - let outcome = build(state, user, id).await; | |
| 90 | - match outcome { | |
| 91 | - Ok(size) => { | |
| 92 | - if let Err(e) = state | |
| 93 | - .store | |
| 94 | - .mark_export_ready(id, i64::try_from(size).unwrap_or(i64::MAX), EXPORT_TTL) | |
| 95 | - .await | |
| 96 | - { | |
| 97 | - tracing::error!(error = %e, "export: could not mark the export ready"); | |
| 98 | - } | |
| 99 | - notify_ready(state, user, id).await; | |
| 100 | - } | |
| 101 | - Err(message) => { | |
| 102 | - tracing::error!(error = %message, export_id = id, "export failed"); | |
| 103 | - let _ = remove_archive(state, id).await; | |
| 104 | - if let Err(e) = state.store.mark_export_failed(id, &message).await { | |
| 105 | - tracing::error!(error = %e, "export: could not record a failure"); | |
| 106 | - } | |
| 107 | - } | |
| 108 | - } | |
| 109 | - bump(&user.id); | |
| 110 | -} | |
| 111 | - | |
| 112 | -async fn notify_ready(state: &AppState, user: &User, id: &str) { | |
| 113 | - let Some(email) = user.email.as_deref().filter(|e| !e.is_empty()) else { | |
| 114 | - return; | |
| 115 | - }; | |
| 116 | - let base = state.config.base_url.trim_end_matches('/'); | |
| 117 | - let body = format!( | |
| 118 | - "Your data export is ready.\n\nDownload it at {base}/settings/export (you must be signed in). \ | |
| 119 | - It is removed after {EXPORT_TTL_DAYS} days.\n" | |
| 120 | - ); | |
| 121 | - if let Err(e) = crate::mail::enqueue( | |
| 122 | - state, | |
| 123 | - &format!("export:{id}"), | |
| 124 | - forge_core::mail::MailKind::Other, | |
| 125 | - Some(&user.id), | |
| 126 | - email, | |
| 127 | - "Your data export is ready", | |
| 128 | - &body, | |
| 129 | - ) | |
| 130 | - .await | |
| 131 | - { | |
| 132 | - tracing::warn!(error = %e, "export: could not queue the ready mail"); | |
| 133 | - } | |
| 134 | -} | |
| 135 | - | |
| 136 | -async fn build(state: &AppState, user: &User, id: &str) -> Result<u64, String> { | |
| 137 | - let dir = export_dir(state); | |
| 138 | - tokio::fs::create_dir_all(&dir) | |
| 139 | - .await | |
| 140 | - .map_err(|e| e.to_string())?; | |
| 141 | - let work = dir.join(format!("{id}.work")); | |
| 142 | - let _ = tokio::fs::remove_dir_all(&work).await; | |
| 143 | - tokio::fs::create_dir_all(work.join("repos")) | |
| 144 | - .await | |
| 145 | - .map_err(|e| e.to_string())?; | |
| 146 | - let result = stage_and_pack(state, user, id, &work).await; | |
| 147 | - let _ = tokio::fs::remove_dir_all(&work).await; | |
| 148 | - result | |
| 149 | -} | |
| 150 | - | |
| 151 | -async fn stage_and_pack( | |
| 152 | - state: &AppState, | |
| 153 | - user: &User, | |
| 154 | - id: &str, | |
| 155 | - work: &Path, | |
| 156 | -) -> Result<u64, String> { | |
| 157 | - write_json(&work.join("profile.json"), &profile_json(user)).await?; | |
| 158 | - let repos = state | |
| 159 | - .store | |
| 160 | - .list_repos_by_owner(&user.id) | |
| 161 | - .await | |
| 162 | - .map_err(|e| e.to_string())?; | |
| 163 | - for repo in &repos { | |
| 164 | - let repo_dir = work.join("repos").join(&repo.name); | |
| 165 | - tokio::fs::create_dir_all(&repo_dir) | |
| 166 | - .await | |
| 167 | - .map_err(|e| e.to_string())?; | |
| 168 | - stage_repo(state, repo, &repo_dir).await?; | |
| 169 | - } | |
| 170 | - let target = archive_path(state, id); | |
| 171 | - let partial = partial_path(state, id); | |
| 172 | - let (work_buf, partial_buf, name) = ( | |
| 173 | - work.to_path_buf(), | |
| 174 | - partial.clone(), | |
| 175 | - format!("forge-export-{}", user.username), | |
| 176 | - ); | |
| 177 | - tokio::task::spawn_blocking(move || pack(&work_buf, &partial_buf, &name)) | |
| 178 | - .await | |
| 179 | - .map_err(|e| e.to_string())??; | |
| 180 | - tokio::fs::rename(&partial, &target) | |
| 181 | - .await | |
| 182 | - .map_err(|e| e.to_string())?; | |
| 183 | - let meta = tokio::fs::metadata(&target) | |
| 184 | - .await | |
| 185 | - .map_err(|e| e.to_string())?; | |
| 186 | - Ok(meta.len()) | |
| 187 | -} | |
| 188 | - | |
| 189 | -fn pack(work: &Path, out: &Path, top: &str) -> Result<(), String> { | |
| 190 | - use std::os::unix::fs::OpenOptionsExt; | |
| 191 | - let file = std::fs::OpenOptions::new() | |
| 192 | - .write(true) | |
| 193 | - .create(true) | |
| 194 | - .truncate(true) | |
| 195 | - .mode(0o600) | |
| 196 | - .open(out) | |
| 197 | - .map_err(|e| e.to_string())?; | |
| 198 | - let gz = flate2::write::GzEncoder::new(file, flate2::Compression::default()); | |
| 199 | - let mut tar = tar::Builder::new(gz); | |
| 200 | - tar.append_dir_all(top, work).map_err(|e| e.to_string())?; | |
| 201 | - let gz = tar.into_inner().map_err(|e| e.to_string())?; | |
| 202 | - gz.finish().map_err(|e| e.to_string())?; | |
| 203 | - Ok(()) | |
| 204 | -} | |
| 205 | - | |
| 206 | -async fn write_json(path: &Path, value: &Value) -> Result<(), String> { | |
| 207 | - let text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?; | |
| 208 | - tokio::fs::write(path, text) | |
| 209 | - .await | |
| 210 | - .map_err(|e| e.to_string()) | |
| 211 | -} | |
| 212 | - | |
| 213 | -fn write_array_item( | |
| 214 | - out: &mut impl Write, | |
| 215 | - written: &mut usize, | |
| 216 | - value: &Value, | |
| 217 | -) -> Result<(), String> { | |
| 218 | - let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; | |
| 219 | - let lead: &[u8] = if *written == 0 { b"[\n " } else { b",\n " }; | |
| 220 | - out.write_all(lead) | |
| 221 | - .and_then(|()| out.write_all(text.replace('\n', "\n ").as_bytes())) | |
| 222 | - .map_err(|e| e.to_string())?; | |
| 223 | - *written += 1; | |
| 224 | - Ok(()) | |
| 225 | -} | |
| 226 | - | |
| 227 | -fn profile_json(user: &User) -> Value { | |
| 228 | - json!({ | |
| 229 | - "username": user.username, | |
| 230 | - "display_name": user.display_name, | |
| 231 | - "email": user.email, | |
| 232 | - "about": user.about, | |
| 233 | - "created_at": user.created_at, | |
| 234 | - "timezone": user.timezone, | |
| 235 | - "language": user.language, | |
| 236 | - "theme": user.theme, | |
| 237 | - "exported_at": now_stamp(), | |
| 238 | - }) | |
| 239 | -} | |
| 240 | - | |
| 241 | -async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), String> { | |
| 242 | - let git_dir = | |
| 243 | - forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; | |
| 244 | - let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle")) | |
| 245 | - .await | |
| 246 | - .map_err(|e| format!("bundling {}: {e}", repo.name))?; | |
| 247 | - | |
| 248 | - let labels = state | |
| 249 | - .store | |
| 250 | - .list_labels(&repo.id) | |
| 251 | - .await | |
| 252 | - .map_err(|e| e.to_string())?; | |
| 253 | - let milestones = state | |
| 254 | - .store | |
| 255 | - .list_milestones(&repo.id, None) | |
| 256 | - .await | |
| 257 | - .map_err(|e| e.to_string())?; | |
| 258 | - let meta = json!({ | |
| 259 | - "name": repo.name, | |
| 260 | - "description": repo.description, | |
| 261 | - "visibility": repo.visibility.as_str(), | |
| 262 | - "default_branch": repo.default_branch, | |
| 263 | - "created_at": repo.created_at, | |
| 264 | - "archived": repo.archived, | |
| 265 | - "has_bundle": bundled, | |
| 266 | - "labels": labels.iter().map(|l| json!({"name": l.name, "color": l.color, "description": l.description})).collect::<Vec<_>>(), | |
| 267 | - "milestones": milestones.iter().map(|m| json!({ | |
| 268 | - "title": m.title, "description": m.description, "due_on": m.due_on, | |
| 269 | - "state": m.state.as_str(), "created_at": m.created_at, "closed_at": m.closed_at, | |
| 270 | - })).collect::<Vec<_>>(), | |
| 271 | - }); | |
| 272 | - write_json(&dir.join("repo.json"), &meta).await?; | |
| 273 | - | |
| 274 | - let mut out = | |
| 275 | - BufWriter::new(std::fs::File::create(dir.join("issues.json")).map_err(|e| e.to_string())?); | |
| 276 | - let mut written = 0usize; | |
| 277 | - let mut page = 1; | |
| 278 | - loop { | |
| 279 | - let filter = IssueFilter { | |
| 280 | - state: None, | |
| 281 | - sort: IssueSort::Oldest, | |
| 282 | - page, | |
| 283 | - per_page: PAGE, | |
| 284 | - ..IssueFilter::default() | |
| 285 | - }; | |
| 286 | - let (items, total) = state | |
| 287 | - .store | |
| 288 | - .list_issues(&repo.id, &filter) | |
| 289 | - .await | |
| 290 | - .map_err(|e| e.to_string())?; | |
| 291 | - let got = items.len(); | |
| 292 | - for item in items { | |
| 293 | - let comments = state | |
| 294 | - .store | |
| 295 | - .list_comments(&item.issue.id) | |
| 296 | - .await | |
| 297 | - .map_err(|e| e.to_string())?; | |
| 298 | - let names = state | |
| 299 | - .store | |
| 300 | - .usernames_by_ids( | |
| 301 | - &comments | |
| 302 | - .iter() | |
| 303 | - .map(|c| c.author_id.clone()) | |
| 304 | - .collect::<Vec<_>>(), | |
| 305 | - ) | |
| 306 | - .await | |
| 307 | - .map_err(|e| e.to_string())?; | |
| 308 | - let names: HashMap<String, String> = | |
| 309 | - names.into_iter().map(|(k, (name, _))| (k, name)).collect(); | |
| 310 | - write_array_item( | |
| 311 | - &mut out, | |
| 312 | - &mut written, | |
| 313 | - &issue_json(&item, &comments, &names), | |
| 314 | - )?; | |
| 315 | - } | |
| 316 | - if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total { | |
| 317 | - break; | |
| 318 | - } | |
| 319 | - page += 1; | |
| 320 | - } | |
| 321 | - out.write_all(if written == 0 { b"[]" } else { b"\n]" }) | |
| 322 | - .and_then(|()| out.flush()) | |
| 323 | - .map_err(|e| e.to_string())?; | |
| 324 | - | |
| 325 | - let releases = state | |
| 326 | - .store | |
| 327 | - .list_releases(&repo.id) | |
| 328 | - .await | |
| 329 | - .map_err(|e| e.to_string())?; | |
| 330 | - let mut out = Vec::new(); | |
| 331 | - for r in releases { | |
| 332 | - let assets = state | |
| 333 | - .store | |
| 334 | - .list_release_assets(&r.id) | |
| 335 | - .await | |
| 336 | - .map_err(|e| e.to_string())?; | |
| 337 | - out.push(json!({ | |
| 338 | - "tag": r.tag, "title": r.title, "body": r.body, "draft": r.draft, | |
| 339 | - "prerelease": r.prerelease, "author": r.author_name, "target_oid": r.target_oid, | |
| 340 | - "created_at": r.created_at, "published_at": r.published_at, | |
| 341 | - "assets": assets.iter().map(|a| json!({ | |
| 342 | - "name": a.name, "size": a.size, "sha256": a.sha256, | |
| 343 | - "content_type": a.content_type, "downloads": a.download_count, | |
| 344 | - })).collect::<Vec<_>>(), | |
| 345 | - })); | |
| 346 | - } | |
| 347 | - write_json(&dir.join("releases.json"), &Value::Array(out)).await | |
| 348 | -} | |
| 349 | - | |
| 350 | -fn issue_json( | |
| 351 | - item: &forge_core::IssueListItem, | |
| 352 | - comments: &[forge_core::Comment], | |
| 353 | - names: &HashMap<String, String>, | |
| 354 | -) -> Value { | |
| 355 | - let i = &item.issue; | |
| 356 | - json!({ | |
| 357 | - "number": i.number, | |
| 358 | - "title": i.title, | |
| 359 | - "body": i.body, | |
| 360 | - "state": i.state.as_str(), | |
| 361 | - "author": item.author, | |
| 362 | - "labels": item.labels.iter().map(|l| l.name.clone()).collect::<Vec<_>>(), | |
| 363 | - "assignees": item.assignees, | |
| 364 | - "created_at": i.created_at, | |
| 365 | - "closed_at": i.closed_at, | |
| 366 | - "comments": comments.iter().map(|c| json!({ | |
| 367 | - "author": names.get(&c.author_id).cloned().unwrap_or_default(), | |
| 368 | - "body": c.body, | |
| 369 | - "created_at": c.created_at, | |
| 370 | - })).collect::<Vec<_>>(), | |
| 371 | - }) | |
| 372 | -} | |
| 373 | - | |
| 374 | -pub async fn sweep_expired(state: &AppState) { | |
| 375 | - let expired = match state.store.expired_exports(&now_stamp()).await { | |
| 376 | - Ok(rows) => rows, | |
| 377 | - Err(e) => { | |
| 378 | - tracing::warn!(error = %e, "export: could not list expired exports"); | |
| 379 | - return; | |
| 380 | - } | |
| 381 | - }; | |
| 382 | - for export in expired { | |
| 383 | - if let Err(e) = remove_archive(state, &export.id).await { | |
| 384 | - tracing::warn!(error = %e, "export: could not remove an expired archive"); | |
| 385 | - continue; | |
| 386 | - } | |
| 387 | - if let Err(e) = state.store.delete_export(&export.id).await { | |
| 388 | - tracing::warn!(error = %e, "export: could not delete an expired export row"); | |
| 389 | - } | |
| 390 | - bump(&export.user_id); | |
| 391 | - } | |
| 392 | -} | |
| 393 | - | |
| 394 | -pub async fn delete_one(state: &AppState, export: &DataExport) -> forge_core::Result<()> { | |
| 395 | - if let Err(e) = remove_archive(state, &export.id).await { | |
| 396 | - tracing::warn!(error = %e, "export: could not remove an archive"); | |
| 397 | - return Err(e.into()); | |
| 398 | - } | |
| 399 | - state.store.delete_export(&export.id).await?; | |
| 400 | - bump(&export.user_id); | |
| 401 | - Ok(()) | |
| 402 | -} | |
| 403 | - | |
| 404 | -pub async fn on_boot(state: &AppState) { | |
| 405 | - if let Err(e) = state.store.fail_interrupted_exports().await { | |
| 406 | - tracing::error!(error = %e, "export: could not clean up interrupted exports"); | |
| 407 | - } | |
| 408 | - sweep_expired(state).await; | |
| 409 | -} | |
| 410 | - | |
| 411 | -#[cfg(test)] | |
| 412 | -mod tests; |
crates/forge-web-app/src/exporter/tests.rsdeleted+0 -171
| @@ -1,171 +0,0 @@ | ||
| 1 | -use std::io::Read; | |
| 2 | - | |
| 3 | -use forge_core::Visibility; | |
| 4 | -use forge_core::store::exports::ExportState; | |
| 5 | - | |
| 6 | -use super::*; | |
| 7 | -use crate::test_support::test_state; | |
| 8 | - | |
| 9 | -fn entries(path: &Path) -> Vec<(String, Vec<u8>)> { | |
| 10 | - let file = std::fs::File::open(path).expect("archive opens"); | |
| 11 | - let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(file)); | |
| 12 | - let mut out = Vec::new(); | |
| 13 | - for entry in archive.entries().expect("entries") { | |
| 14 | - let mut entry = entry.expect("entry"); | |
| 15 | - let name = entry.path().expect("path").display().to_string(); | |
| 16 | - let mut bytes = Vec::new(); | |
| 17 | - entry.read_to_end(&mut bytes).expect("read"); | |
| 18 | - out.push((name, bytes)); | |
| 19 | - } | |
| 20 | - out | |
| 21 | -} | |
| 22 | - | |
| 23 | -async fn setup() -> (AppState, User, Repo, tempfile::TempDir) { | |
| 24 | - let dir = tempfile::tempdir().expect("tempdir"); | |
| 25 | - let state = test_state(dir.path()).await; | |
| 26 | - let user = state | |
| 27 | - .store | |
| 28 | - .create_user("tahinli", Some("tahinli@example.com"), "unused", false) | |
| 29 | - .await | |
| 30 | - .expect("user"); | |
| 31 | - let repo = state | |
| 32 | - .store | |
| 33 | - .create_repo(&user.id, "project", "A project", Visibility::Public, "main") | |
| 34 | - .await | |
| 35 | - .expect("repo"); | |
| 36 | - let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path"); | |
| 37 | - forge_git::repo::init_bare(&state.git, &bare, "main") | |
| 38 | - .await | |
| 39 | - .expect("init"); | |
| 40 | - let run = |args: &[&str]| { | |
| 41 | - let out = std::process::Command::new("git") | |
| 42 | - .arg(format!("--git-dir={}", bare.display())) | |
| 43 | - .args(args) | |
| 44 | - .env("GIT_AUTHOR_NAME", "t") | |
| 45 | - .env("GIT_AUTHOR_EMAIL", "t@example.com") | |
| 46 | - .env("GIT_COMMITTER_NAME", "t") | |
| 47 | - .env("GIT_COMMITTER_EMAIL", "t@example.com") | |
| 48 | - .output() | |
| 49 | - .expect("git"); | |
| 50 | - assert!(out.status.success(), "{out:?}"); | |
| 51 | - String::from_utf8_lossy(&out.stdout).trim().to_string() | |
| 52 | - }; | |
| 53 | - let tree = run(&["hash-object", "-t", "tree", "-w", "--stdin"]); | |
| 54 | - let commit = run(&["commit-tree", &tree, "-m", "first"]); | |
| 55 | - run(&["update-ref", "refs/heads/main", &commit]); | |
| 56 | - let issue = state | |
| 57 | - .store | |
| 58 | - .create_issue(&repo.id, &user.id, "It breaks", "steps") | |
| 59 | - .await | |
| 60 | - .expect("issue"); | |
| 61 | - state | |
| 62 | - .store | |
| 63 | - .add_comment(&issue.id, &user.id, "same here") | |
| 64 | - .await | |
| 65 | - .expect("comment"); | |
| 66 | - (state, user, repo, dir) | |
| 67 | -} | |
| 68 | - | |
| 69 | -#[tokio::test] | |
| 70 | -async fn the_archive_holds_the_profile_bundles_issues_and_releases() { | |
| 71 | - let (state, user, _repo, _dir) = setup().await; | |
| 72 | - let export = start(&state, &user).await.expect("start"); | |
| 73 | - let mut wake = subscribe(&user.id); | |
| 74 | - loop { | |
| 75 | - let row = state.store.data_export(&export.id).await.unwrap().unwrap(); | |
| 76 | - if row.state != ExportState::Building { | |
| 77 | - assert_eq!(row.state, ExportState::Ready, "{:?}", row.error); | |
| 78 | - assert!(row.size > 0); | |
| 79 | - break; | |
| 80 | - } | |
| 81 | - tokio::time::timeout(Duration::from_secs(60), wake.changed()) | |
| 82 | - .await | |
| 83 | - .expect("the export finishes") | |
| 84 | - .expect("signal open"); | |
| 85 | - } | |
| 86 | - | |
| 87 | - let files = entries(&archive_path(&state, &export.id)); | |
| 88 | - let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); | |
| 89 | - let has = |suffix: &str| names.iter().any(|n| n.ends_with(suffix)); | |
| 90 | - assert!(has("profile.json"), "{names:?}"); | |
| 91 | - assert!(has("repos/project/repo.bundle"), "{names:?}"); | |
| 92 | - assert!(has("repos/project/repo.json")); | |
| 93 | - assert!(has("repos/project/issues.json")); | |
| 94 | - assert!(has("repos/project/releases.json")); | |
| 95 | - | |
| 96 | - let read = |suffix: &str| { | |
| 97 | - let (_, bytes) = files.iter().find(|(n, _)| n.ends_with(suffix)).unwrap(); | |
| 98 | - String::from_utf8_lossy(bytes).into_owned() | |
| 99 | - }; | |
| 100 | - let profile = read("profile.json"); | |
| 101 | - assert!(profile.contains("tahinli@example.com")); | |
| 102 | - assert!( | |
| 103 | - !profile.contains("password"), | |
| 104 | - "no credential in the profile" | |
| 105 | - ); | |
| 106 | - let issues: serde_json::Value = serde_json::from_str(&read("issues.json")).unwrap(); | |
| 107 | - assert_eq!(issues[0]["title"], "It breaks"); | |
| 108 | - assert_eq!(issues[0]["comments"][0]["body"], "same here"); | |
| 109 | - assert_eq!(issues[0]["comments"][0]["author"], "tahinli"); | |
| 110 | - let bundle = files | |
| 111 | - .iter() | |
| 112 | - .find(|(n, _)| n.ends_with("repo.bundle")) | |
| 113 | - .unwrap(); | |
| 114 | - assert!(bundle.1.starts_with(b"# v2 git bundle") || bundle.1.starts_with(b"# v3 git bundle")); | |
| 115 | -} | |
| 116 | - | |
| 117 | -#[tokio::test] | |
| 118 | -async fn an_expired_export_is_removed_with_its_file() { | |
| 119 | - let (state, user, _repo, _dir) = setup().await; | |
| 120 | - let export = state | |
| 121 | - .store | |
| 122 | - .create_export(&user.id, Duration::from_secs(0)) | |
| 123 | - .await | |
| 124 | - .expect("export"); | |
| 125 | - let path = archive_path(&state, &export.id); | |
| 126 | - tokio::fs::create_dir_all(path.parent().unwrap()) | |
| 127 | - .await | |
| 128 | - .unwrap(); | |
| 129 | - tokio::fs::write(&path, b"x").await.unwrap(); | |
| 130 | - sweep_expired(&state).await; | |
| 131 | - assert!(state.store.data_export(&export.id).await.unwrap().is_none()); | |
| 132 | - assert!(!path.exists()); | |
| 133 | -} | |
| 134 | - | |
| 135 | -#[tokio::test] | |
| 136 | -async fn a_fresh_export_survives_the_sweep() { | |
| 137 | - let (state, user, _repo, _dir) = setup().await; | |
| 138 | - let export = state | |
| 139 | - .store | |
| 140 | - .create_export(&user.id, EXPORT_TTL) | |
| 141 | - .await | |
| 142 | - .unwrap(); | |
| 143 | - sweep_expired(&state).await; | |
| 144 | - assert!(state.store.data_export(&export.id).await.unwrap().is_some()); | |
| 145 | -} | |
| 146 | - | |
| 147 | -#[tokio::test] | |
| 148 | -async fn a_second_request_while_building_returns_the_running_export() { | |
| 149 | - let (state, user, _repo, _dir) = setup().await; | |
| 150 | - let running = state | |
| 151 | - .store | |
| 152 | - .create_export(&user.id, EXPORT_TTL) | |
| 153 | - .await | |
| 154 | - .unwrap(); | |
| 155 | - let again = start(&state, &user).await.unwrap(); | |
| 156 | - assert_eq!(again.id, running.id); | |
| 157 | -} | |
| 158 | - | |
| 159 | -#[tokio::test] | |
| 160 | -async fn ready_mail_is_queued_for_an_account_with_an_address() { | |
| 161 | - let (state, user, _repo, _dir) = setup().await; | |
| 162 | - notify_ready(&state, &user, "abc").await; | |
| 163 | - notify_ready(&state, &user, "abc").await; | |
| 164 | - let queued = state | |
| 165 | - .store | |
| 166 | - .list_mail(None, "9999-12-31T00:00:00Z", 10) | |
| 167 | - .await | |
| 168 | - .expect("mail list") | |
| 169 | - .len(); | |
| 170 | - assert_eq!(queued, 1, "one mail, however often the ready step runs"); | |
| 171 | -} |
crates/forge-web-app/src/importer/api.rsdeleted+0 -1482
| @@ -1,1482 +0,0 @@ | ||
| 1 | -use std::fmt; | |
| 2 | -use std::future::Future; | |
| 3 | -use std::io; | |
| 4 | -use std::sync::Arc; | |
| 5 | -use std::time::Duration; | |
| 6 | - | |
| 7 | -use bytes::Bytes; | |
| 8 | -use futures_util::stream::{BoxStream, StreamExt}; | |
| 9 | -use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER}; | |
| 10 | -use serde::Deserialize; | |
| 11 | -use serde::de::DeserializeOwned; | |
| 12 | - | |
| 13 | -use crate::webhooks::client::{WebhookPolicy, validate_url}; | |
| 14 | - | |
| 15 | -pub type AssetStream = BoxStream<'static, io::Result<Bytes>>; | |
| 16 | - | |
| 17 | -const PER_PAGE: usize = 100; | |
| 18 | -const FORGEJO_LIMIT: usize = 50; | |
| 19 | -const MAX_PAGES: usize = 500; | |
| 20 | -const MAX_RATE_WAIT: u64 = 15 * 60; | |
| 21 | -const MAX_JSON_BYTES: usize = 32 * 1024 * 1024; | |
| 22 | -const MAX_REDIRECTS: usize = 5; | |
| 23 | - | |
| 24 | -#[derive(Debug, Clone, PartialEq, Eq)] | |
| 25 | -pub enum ApiError { | |
| 26 | - NotFound(String), | |
| 27 | - Unauthorized(String), | |
| 28 | - RateLimited { wait_secs: u64 }, | |
| 29 | - TooLarge, | |
| 30 | - Http(String), | |
| 31 | - Parse(String), | |
| 32 | -} | |
| 33 | - | |
| 34 | -impl fmt::Display for ApiError { | |
| 35 | - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 36 | - match self { | |
| 37 | - ApiError::NotFound(what) => write!(f, "not found: {what}"), | |
| 38 | - ApiError::Unauthorized(what) => write!(f, "access denied: {what}"), | |
| 39 | - ApiError::RateLimited { wait_secs } => write!( | |
| 40 | - f, | |
| 41 | - "the rate limit is used up and resets in {}; retry then, nothing imported is lost", | |
| 42 | - wait_text(*wait_secs) | |
| 43 | - ), | |
| 44 | - ApiError::TooLarge => write!(f, "the file is larger than the allowed size"), | |
| 45 | - ApiError::Http(msg) => write!(f, "request failed: {msg}"), | |
| 46 | - ApiError::Parse(msg) => write!(f, "unexpected response: {msg}"), | |
| 47 | - } | |
| 48 | - } | |
| 49 | -} | |
| 50 | - | |
| 51 | -fn wait_text(secs: u64) -> String { | |
| 52 | - let plural = |n: u64| if n == 1 { "" } else { "s" }; | |
| 53 | - if secs < 60 { | |
| 54 | - return format!("{secs} second{}", plural(secs)); | |
| 55 | - } | |
| 56 | - let minutes = secs.div_ceil(60); | |
| 57 | - let (hours, rest) = (minutes / 60, minutes % 60); | |
| 58 | - match (hours, rest) { | |
| 59 | - (0, m) => format!("{m} minute{}", plural(m)), | |
| 60 | - (h, 0) => format!("{h} hour{}", plural(h)), | |
| 61 | - (h, m) => format!("{h} hour{} {m} minute{}", plural(h), plural(m)), | |
| 62 | - } | |
| 63 | -} | |
| 64 | - | |
| 65 | -pub type ApiResult<T> = Result<T, ApiError>; | |
| 66 | - | |
| 67 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 68 | -pub struct ExtLabel { | |
| 69 | - pub name: String, | |
| 70 | - pub color: String, | |
| 71 | - pub description: String, | |
| 72 | -} | |
| 73 | - | |
| 74 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 75 | -pub struct ExtMilestone { | |
| 76 | - pub id: String, | |
| 77 | - pub title: String, | |
| 78 | - pub description: String, | |
| 79 | - pub closed: bool, | |
| 80 | - pub due_on: Option<String>, | |
| 81 | -} | |
| 82 | - | |
| 83 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 84 | -pub struct ExtIssue { | |
| 85 | - pub number: i64, | |
| 86 | - pub title: String, | |
| 87 | - pub body: String, | |
| 88 | - pub closed: bool, | |
| 89 | - pub not_planned: bool, | |
| 90 | - pub merged: bool, | |
| 91 | - pub author: String, | |
| 92 | - pub labels: Vec<String>, | |
| 93 | - pub milestone: Option<String>, | |
| 94 | - pub created_at: String, | |
| 95 | - pub url: String, | |
| 96 | - pub is_pr: bool, | |
| 97 | -} | |
| 98 | - | |
| 99 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 100 | -pub struct ExtComment { | |
| 101 | - pub id: String, | |
| 102 | - pub author: String, | |
| 103 | - pub body: String, | |
| 104 | - pub created_at: String, | |
| 105 | - pub url: String, | |
| 106 | -} | |
| 107 | - | |
| 108 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 109 | -pub struct ExtAsset { | |
| 110 | - pub id: String, | |
| 111 | - pub name: String, | |
| 112 | - pub size: u64, | |
| 113 | - pub content_type: String, | |
| 114 | - pub url: String, | |
| 115 | -} | |
| 116 | - | |
| 117 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 118 | -pub struct ExtRelease { | |
| 119 | - pub id: String, | |
| 120 | - pub tag: String, | |
| 121 | - pub title: String, | |
| 122 | - pub body: String, | |
| 123 | - pub draft: bool, | |
| 124 | - pub prerelease: bool, | |
| 125 | - pub author: String, | |
| 126 | - pub created_at: String, | |
| 127 | - pub url: String, | |
| 128 | - pub assets: Vec<ExtAsset>, | |
| 129 | -} | |
| 130 | - | |
| 131 | -#[derive(Debug, Clone, PartialEq, Eq, Default)] | |
| 132 | -pub struct ExtRepo { | |
| 133 | - pub name: String, | |
| 134 | - pub full_name: String, | |
| 135 | - pub description: String, | |
| 136 | - pub private: bool, | |
| 137 | - pub fork: bool, | |
| 138 | - pub archived: bool, | |
| 139 | - pub default_branch: String, | |
| 140 | - pub web_url: String, | |
| 141 | -} | |
| 142 | - | |
| 143 | -pub trait RemoteApi: Send + Sync { | |
| 144 | - fn list_repos(&self, owner: &str) -> impl Future<Output = ApiResult<Vec<ExtRepo>>> + Send; | |
| 145 | - fn labels(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtLabel>>> + Send; | |
| 146 | - fn milestones(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtMilestone>>> + Send; | |
| 147 | - fn issues(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtIssue>>> + Send; | |
| 148 | - fn comments( | |
| 149 | - &self, | |
| 150 | - repo: &str, | |
| 151 | - issue: &ExtIssue, | |
| 152 | - ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send; | |
| 153 | - fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send; | |
| 154 | - fn download( | |
| 155 | - &self, | |
| 156 | - asset: &ExtAsset, | |
| 157 | - max_bytes: u64, | |
| 158 | - ) -> impl Future<Output = ApiResult<AssetStream>> + Send; | |
| 159 | -} | |
| 160 | - | |
| 161 | -pub fn valid_segment(s: &str) -> bool { | |
| 162 | - !s.is_empty() | |
| 163 | - && s.len() <= 100 | |
| 164 | - && s != "." | |
| 165 | - && s != ".." | |
| 166 | - && s.bytes() | |
| 167 | - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) | |
| 168 | -} | |
| 169 | - | |
| 170 | -pub fn valid_path(path: &str, min: usize, max: usize) -> bool { | |
| 171 | - let parts: Vec<&str> = path.split('/').collect(); | |
| 172 | - (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p)) | |
| 173 | -} | |
| 174 | - | |
| 175 | -pub fn rate_wait( | |
| 176 | - retry_after: Option<&str>, | |
| 177 | - remaining: Option<&str>, | |
| 178 | - reset_unix: Option<&str>, | |
| 179 | - now_unix: i64, | |
| 180 | -) -> Option<u64> { | |
| 181 | - if let Some(secs) = retry_after.and_then(|v| v.trim().parse::<u64>().ok()) { | |
| 182 | - return Some(secs.max(1)); | |
| 183 | - } | |
| 184 | - if remaining.map(str::trim) == Some("0") { | |
| 185 | - let reset = reset_unix.and_then(|v| v.trim().parse::<i64>().ok())?; | |
| 186 | - return Some(u64::try_from(reset - now_unix).unwrap_or(0).max(1)); | |
| 187 | - } | |
| 188 | - None | |
| 189 | -} | |
| 190 | - | |
| 191 | -pub type Notice = Arc<dyn Fn(String) + Send + Sync>; | |
| 192 | - | |
| 193 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 194 | -pub enum Auth { | |
| 195 | - GitHub, | |
| 196 | - GitLab, | |
| 197 | - Forgejo, | |
| 198 | -} | |
| 199 | - | |
| 200 | -pub struct Http { | |
| 201 | - client: reqwest::Client, | |
| 202 | - policy: WebhookPolicy, | |
| 203 | - token: Option<String>, | |
| 204 | - auth: Auth, | |
| 205 | - auth_host: String, | |
| 206 | - notice: Notice, | |
| 207 | -} | |
| 208 | - | |
| 209 | -impl Http { | |
| 210 | - pub fn new( | |
| 211 | - client: reqwest::Client, | |
| 212 | - policy: WebhookPolicy, | |
| 213 | - token: Option<String>, | |
| 214 | - auth: Auth, | |
| 215 | - auth_host: String, | |
| 216 | - notice: Notice, | |
| 217 | - ) -> Self { | |
| 218 | - let token = token.filter(|t| !t.trim().is_empty()); | |
| 219 | - Http { | |
| 220 | - client, | |
| 221 | - policy, | |
| 222 | - token, | |
| 223 | - auth, | |
| 224 | - auth_host, | |
| 225 | - notice, | |
| 226 | - } | |
| 227 | - } | |
| 228 | - | |
| 229 | - fn host_of(url: &str) -> String { | |
| 230 | - reqwest::Url::parse(url) | |
| 231 | - .ok() | |
| 232 | - .and_then(|u| u.host_str().map(str::to_ascii_lowercase)) | |
| 233 | - .unwrap_or_default() | |
| 234 | - } | |
| 235 | - | |
| 236 | - fn request(&self, url: &str, accept: &str, authed: bool) -> reqwest::RequestBuilder { | |
| 237 | - let mut req = self.client.get(url).header(ACCEPT, accept); | |
| 238 | - if authed | |
| 239 | - && Self::host_of(url) == self.auth_host | |
| 240 | - && let Some(token) = &self.token | |
| 241 | - { | |
| 242 | - req = match self.auth { | |
| 243 | - Auth::GitLab => req.header("PRIVATE-TOKEN", token), | |
| 244 | - Auth::GitHub => req | |
| 245 | - .header(AUTHORIZATION, format!("Bearer {token}")) | |
| 246 | - .header("X-GitHub-Api-Version", "2022-11-28"), | |
| 247 | - Auth::Forgejo => req.header(AUTHORIZATION, format!("token {token}")), | |
| 248 | - }; | |
| 249 | - } | |
| 250 | - req | |
| 251 | - } | |
| 252 | - | |
| 253 | - fn header(headers: &HeaderMap, name: &str) -> Option<String> { | |
| 254 | - headers | |
| 255 | - .get(name) | |
| 256 | - .and_then(|v| v.to_str().ok()) | |
| 257 | - .map(str::to_owned) | |
| 258 | - } | |
| 259 | - | |
| 260 | - async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> { | |
| 261 | - validate_url(url, &self.policy) | |
| 262 | - .map_err(|e| ApiError::Http(format!("address refused: {e}")))?; | |
| 263 | - let mut attempt = 0u32; | |
| 264 | - loop { | |
| 265 | - attempt += 1; | |
| 266 | - let resp = self | |
| 267 | - .request(url, accept, authed) | |
| 268 | - .send() | |
| 269 | - .await | |
| 270 | - .map_err(|e| ApiError::Http(e.without_url().to_string()))?; | |
| 271 | - let status = resp.status(); | |
| 272 | - if status.is_success() || status.is_redirection() { | |
| 273 | - return Ok(resp); | |
| 274 | - } | |
| 275 | - let headers = resp.headers(); | |
| 276 | - match status.as_u16() { | |
| 277 | - 401 => return Err(ApiError::Unauthorized("the token was refused".into())), | |
| 278 | - 404 => return Err(ApiError::NotFound(Self::host_of(url))), | |
| 279 | - 403 | 429 => { | |
| 280 | - let wait = rate_wait( | |
| 281 | - Self::header(headers, RETRY_AFTER.as_str()).as_deref(), | |
| 282 | - Self::header(headers, "x-ratelimit-remaining").as_deref(), | |
| 283 | - Self::header(headers, "x-ratelimit-reset").as_deref(), | |
| 284 | - jiff::Timestamp::now().as_second(), | |
| 285 | - ) | |
| 286 | - .or_else(|| (status.as_u16() == 429).then_some(60)); | |
| 287 | - let Some(wait) = wait else { | |
| 288 | - return Err(ApiError::Unauthorized( | |
| 289 | - "the server refused the request (is the token valid and allowed to read this?)" | |
| 290 | - .into(), | |
| 291 | - )); | |
| 292 | - }; | |
| 293 | - if wait > MAX_RATE_WAIT || attempt > 4 { | |
| 294 | - return Err(ApiError::RateLimited { wait_secs: wait }); | |
| 295 | - } | |
| 296 | - (self.notice)(format!("Rate limited, waiting {wait} seconds")); | |
| 297 | - tokio::time::sleep(Duration::from_secs(wait)).await; | |
| 298 | - } | |
| 299 | - 500..=599 if attempt <= 3 => { | |
| 300 | - tokio::time::sleep(Duration::from_secs(u64::from(attempt) * 2)).await; | |
| 301 | - } | |
| 302 | - code => return Err(ApiError::Http(format!("status {code}"))), | |
| 303 | - } | |
| 304 | - } | |
| 305 | - } | |
| 306 | - | |
| 307 | - async fn body(resp: reqwest::Response, max: usize) -> ApiResult<Vec<u8>> { | |
| 308 | - let mut resp = resp; | |
| 309 | - let mut out = Vec::new(); | |
| 310 | - while let Some(chunk) = resp | |
| 311 | - .chunk() | |
| 312 | - .await | |
| 313 | - .map_err(|e| ApiError::Http(e.without_url().to_string()))? | |
| 314 | - { | |
| 315 | - if out.len() + chunk.len() > max { | |
| 316 | - return Err(ApiError::TooLarge); | |
| 317 | - } | |
| 318 | - out.extend_from_slice(&chunk); | |
| 319 | - } | |
| 320 | - Ok(out) | |
| 321 | - } | |
| 322 | - | |
| 323 | - pub async fn json<T: DeserializeOwned>(&self, url: &str) -> ApiResult<T> { | |
| 324 | - let resp = self.send(url, "application/json", true).await?; | |
| 325 | - let bytes = Self::body(resp, MAX_JSON_BYTES).await?; | |
| 326 | - serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string())) | |
| 327 | - } | |
| 328 | - | |
| 329 | - pub async fn pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> { | |
| 330 | - let sep = if base.contains('?') { '&' } else { '?' }; | |
| 331 | - let mut out = Vec::new(); | |
| 332 | - for page in 1..=MAX_PAGES { | |
| 333 | - let url = format!("{base}{sep}per_page={PER_PAGE}&page={page}"); | |
| 334 | - let items: Vec<T> = self.json(&url).await?; | |
| 335 | - let short = items.len() < PER_PAGE; | |
| 336 | - out.extend(items); | |
| 337 | - if short { | |
| 338 | - return Ok(out); | |
| 339 | - } | |
| 340 | - } | |
| 341 | - Err(ApiError::TooLarge) | |
| 342 | - } | |
| 343 | - | |
| 344 | - pub async fn limit_pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> { | |
| 345 | - let sep = if base.contains('?') { '&' } else { '?' }; | |
| 346 | - let mut out: Vec<T> = Vec::new(); | |
| 347 | - for page in 1..=MAX_PAGES { | |
| 348 | - let url = format!("{base}{sep}limit={FORGEJO_LIMIT}&page={page}"); | |
| 349 | - let resp = self.send(&url, "application/json", true).await?; | |
| 350 | - let link = Self::header(resp.headers(), "link"); | |
| 351 | - let total = Self::header(resp.headers(), "x-total-count") | |
| 352 | - .and_then(|v| v.trim().parse::<usize>().ok()); | |
| 353 | - let bytes = Self::body(resp, MAX_JSON_BYTES).await?; | |
| 354 | - let items: Vec<T> = | |
| 355 | - serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))?; | |
| 356 | - let got = items.len(); | |
| 357 | - out.extend(items); | |
| 358 | - let done = got == 0 | |
| 359 | - || match (&link, total) { | |
| 360 | - (Some(l), _) => !l.contains("rel=\"next\""), | |
| 361 | - (None, Some(total)) => out.len() >= total, | |
| 362 | - (None, None) => got < FORGEJO_LIMIT, | |
| 363 | - }; | |
| 364 | - if done { | |
| 365 | - return Ok(out); | |
| 366 | - } | |
| 367 | - } | |
| 368 | - Err(ApiError::TooLarge) | |
| 369 | - } | |
| 370 | - | |
| 371 | - pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<AssetStream> { | |
| 372 | - let mut current = url.to_owned(); | |
| 373 | - for _ in 0..=MAX_REDIRECTS { | |
| 374 | - let resp = self | |
| 375 | - .send(¤t, "application/octet-stream", true) | |
| 376 | - .await?; | |
| 377 | - if resp.status().is_redirection() { | |
| 378 | - let next = resp | |
| 379 | - .headers() | |
| 380 | - .get(LOCATION) | |
| 381 | - .and_then(|v| v.to_str().ok()) | |
| 382 | - .ok_or_else(|| ApiError::Http("redirect without a location".into()))?; | |
| 383 | - let base = | |
| 384 | - reqwest::Url::parse(¤t).map_err(|e| ApiError::Http(e.to_string()))?; | |
| 385 | - current = base | |
| 386 | - .join(next) | |
| 387 | - .map_err(|e| ApiError::Http(e.to_string()))? | |
| 388 | - .to_string(); | |
| 389 | - if !current.starts_with("https://") { | |
| 390 | - return Err(ApiError::Http("redirect to a non-https address".into())); | |
| 391 | - } | |
| 392 | - continue; | |
| 393 | - } | |
| 394 | - if let Some(len) = resp.content_length() | |
| 395 | - && len > max_bytes | |
| 396 | - { | |
| 397 | - return Err(ApiError::TooLarge); | |
| 398 | - } | |
| 399 | - return Ok(Self::stream(resp, max_bytes)); | |
| 400 | - } | |
| 401 | - Err(ApiError::Http("too many redirects".into())) | |
| 402 | - } | |
| 403 | - | |
| 404 | - fn stream(resp: reqwest::Response, max: u64) -> AssetStream { | |
| 405 | - let mut seen: u64 = 0; | |
| 406 | - Box::pin(resp.bytes_stream().map(move |chunk| { | |
| 407 | - let chunk: reqwest::Result<Bytes> = chunk; | |
| 408 | - let chunk = chunk.map_err(|e| io::Error::other(e.without_url().to_string()))?; | |
| 409 | - seen = seen.saturating_add(u64::try_from(chunk.len()).unwrap_or(u64::MAX)); | |
| 410 | - if seen > max { | |
| 411 | - return Err(io::Error::new( | |
| 412 | - io::ErrorKind::InvalidData, | |
| 413 | - "the file is larger than the allowed size", | |
| 414 | - )); | |
| 415 | - } | |
| 416 | - Ok(chunk) | |
| 417 | - })) | |
| 418 | - } | |
| 419 | -} | |
| 420 | - | |
| 421 | -fn day(stamp: &str) -> Option<String> { | |
| 422 | - let d = stamp.get(..10)?; | |
| 423 | - let ok = d.as_bytes().iter().enumerate().all(|(i, b)| match i { | |
| 424 | - 4 | 7 => *b == b'-', | |
| 425 | - _ => b.is_ascii_digit(), | |
| 426 | - }); | |
| 427 | - ok.then(|| d.to_owned()) | |
| 428 | -} | |
| 429 | - | |
| 430 | -fn s(v: Option<String>) -> String { | |
| 431 | - v.unwrap_or_default() | |
| 432 | -} | |
| 433 | - | |
| 434 | -pub struct GitHub { | |
| 435 | - http: Http, | |
| 436 | - base: String, | |
| 437 | -} | |
| 438 | - | |
| 439 | -impl GitHub { | |
| 440 | - pub fn new(http: Http) -> Self { | |
| 441 | - GitHub { | |
| 442 | - http, | |
| 443 | - base: "https://api.github.com".into(), | |
| 444 | - } | |
| 445 | - } | |
| 446 | -} | |
| 447 | - | |
| 448 | -#[derive(Deserialize)] | |
| 449 | -struct GhUser { | |
| 450 | - login: Option<String>, | |
| 451 | -} | |
| 452 | - | |
| 453 | -#[derive(Deserialize)] | |
| 454 | -struct GhLabel { | |
| 455 | - name: String, | |
| 456 | - color: Option<String>, | |
| 457 | - description: Option<String>, | |
| 458 | -} | |
| 459 | - | |
| 460 | -#[derive(Deserialize)] | |
| 461 | -struct GhMilestone { | |
| 462 | - number: i64, | |
| 463 | - title: String, | |
| 464 | - description: Option<String>, | |
| 465 | - state: String, | |
| 466 | - due_on: Option<String>, | |
| 467 | -} | |
| 468 | - | |
| 469 | -#[derive(Deserialize)] | |
| 470 | -struct GhPull { | |
| 471 | - merged_at: Option<String>, | |
| 472 | -} | |
| 473 | - | |
| 474 | -#[derive(Deserialize)] | |
| 475 | -struct GhIssue { | |
| 476 | - number: i64, | |
| 477 | - title: String, | |
| 478 | - body: Option<String>, | |
| 479 | - state: String, | |
| 480 | - state_reason: Option<String>, | |
| 481 | - user: Option<GhUser>, | |
| 482 | - #[serde(default)] | |
| 483 | - labels: Vec<GhLabel>, | |
| 484 | - milestone: Option<GhMilestoneRef>, | |
| 485 | - created_at: Option<String>, | |
| 486 | - html_url: Option<String>, | |
| 487 | - pull_request: Option<GhPull>, | |
| 488 | -} | |
| 489 | - | |
| 490 | -#[derive(Deserialize)] | |
| 491 | -struct GhMilestoneRef { | |
| 492 | - title: String, | |
| 493 | -} | |
| 494 | - | |
| 495 | -#[derive(Deserialize)] | |
| 496 | -struct GhComment { | |
| 497 | - id: i64, | |
| 498 | - body: Option<String>, | |
| 499 | - user: Option<GhUser>, | |
| 500 | - created_at: Option<String>, | |
| 501 | - html_url: Option<String>, | |
| 502 | -} | |
| 503 | - | |
| 504 | -#[derive(Deserialize)] | |
| 505 | -struct GhAsset { | |
| 506 | - id: i64, | |
| 507 | - name: String, | |
| 508 | - size: Option<u64>, | |
| 509 | - content_type: Option<String>, | |
| 510 | - url: String, | |
| 511 | -} | |
| 512 | - | |
| 513 | -#[derive(Deserialize)] | |
| 514 | -struct GhRelease { | |
| 515 | - id: i64, | |
| 516 | - tag_name: String, | |
| 517 | - name: Option<String>, | |
| 518 | - body: Option<String>, | |
| 519 | - #[serde(default)] | |
| 520 | - draft: bool, | |
| 521 | - #[serde(default)] | |
| 522 | - prerelease: bool, | |
| 523 | - author: Option<GhUser>, | |
| 524 | - created_at: Option<String>, | |
| 525 | - html_url: Option<String>, | |
| 526 | - #[serde(default)] | |
| 527 | - assets: Vec<GhAsset>, | |
| 528 | -} | |
| 529 | - | |
| 530 | -#[derive(Deserialize)] | |
| 531 | -struct GhRepo { | |
| 532 | - name: String, | |
| 533 | - full_name: String, | |
| 534 | - description: Option<String>, | |
| 535 | - #[serde(default)] | |
| 536 | - private: bool, | |
| 537 | - #[serde(default)] | |
| 538 | - fork: bool, | |
| 539 | - #[serde(default)] | |
| 540 | - archived: bool, | |
| 541 | - default_branch: Option<String>, | |
| 542 | - html_url: Option<String>, | |
| 543 | -} | |
| 544 | - | |
| 545 | -fn login(u: Option<GhUser>) -> String { | |
| 546 | - u.and_then(|u| u.login).unwrap_or_default() | |
| 547 | -} | |
| 548 | - | |
| 549 | -fn release_title(name: Option<String>, tag: &str) -> String { | |
| 550 | - name.filter(|n| !n.is_empty()) | |
| 551 | - .unwrap_or_else(|| tag.to_owned()) | |
| 552 | -} | |
| 553 | - | |
| 554 | -async fn or_user<T>( | |
| 555 | - org: ApiResult<Vec<T>>, | |
| 556 | - user: impl Future<Output = ApiResult<Vec<T>>>, | |
| 557 | -) -> ApiResult<Vec<T>> { | |
| 558 | - match org { | |
| 559 | - Err(ApiError::NotFound(_)) => user.await, | |
| 560 | - other => other, | |
| 561 | - } | |
| 562 | -} | |
| 563 | - | |
| 564 | -#[cfg(test)] | |
| 565 | -fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> { | |
| 566 | - let raw: Vec<GhLabel> = from_json(json)?; | |
| 567 | - Ok(raw.into_iter().map(label_of).collect()) | |
| 568 | -} | |
| 569 | - | |
| 570 | -fn label_of(l: GhLabel) -> ExtLabel { | |
| 571 | - ExtLabel { | |
| 572 | - name: l.name, | |
| 573 | - color: format!("#{}", s(l.color).trim_start_matches('#')), | |
| 574 | - description: s(l.description), | |
| 575 | - } | |
| 576 | -} | |
| 577 | - | |
| 578 | -#[cfg(test)] | |
| 579 | -fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> { | |
| 580 | - serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string())) | |
| 581 | -} | |
| 582 | - | |
| 583 | -#[cfg(test)] | |
| 584 | -fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> { | |
| 585 | - let raw: Vec<GhIssue> = from_json(json)?; | |
| 586 | - Ok(raw.into_iter().map(gh_issue).collect()) | |
| 587 | -} | |
| 588 | - | |
| 589 | -fn gh_issue(i: GhIssue) -> ExtIssue { | |
| 590 | - let merged = i | |
| 591 | - .pull_request | |
| 592 | - .as_ref() | |
| 593 | - .is_some_and(|p| p.merged_at.is_some()); | |
| 594 | - ExtIssue { | |
| 595 | - number: i.number, | |
| 596 | - title: i.title, | |
| 597 | - body: s(i.body), | |
| 598 | - closed: i.state == "closed", | |
| 599 | - not_planned: i.state_reason.as_deref() == Some("not_planned"), | |
| 600 | - merged, | |
| 601 | - author: login(i.user), | |
| 602 | - labels: i.labels.into_iter().map(|l| l.name).collect(), | |
| 603 | - milestone: i.milestone.map(|m| m.title), | |
| 604 | - created_at: s(i.created_at), | |
| 605 | - url: s(i.html_url), | |
| 606 | - is_pr: i.pull_request.is_some(), | |
| 607 | - } | |
| 608 | -} | |
| 609 | - | |
| 610 | -#[cfg(test)] | |
| 611 | -fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> { | |
| 612 | - let raw: Vec<GhRelease> = from_json(json)?; | |
| 613 | - Ok(raw | |
| 614 | - .into_iter() | |
| 615 | - .map(|r| ExtRelease { | |
| 616 | - id: r.id.to_string(), | |
| 617 | - title: r | |
| 618 | - .name | |
| 619 | - .filter(|n| !n.is_empty()) | |
| 620 | - .unwrap_or_else(|| r.tag_name.clone()), | |
| 621 | - tag: r.tag_name, | |
| 622 | - body: s(r.body), | |
| 623 | - draft: r.draft, | |
| 624 | - prerelease: r.prerelease, | |
| 625 | - author: login(r.author), | |
| 626 | - created_at: s(r.created_at), | |
| 627 | - url: s(r.html_url), | |
| 628 | - assets: r | |
| 629 | - .assets | |
| 630 | - .into_iter() | |
| 631 | - .map(|a| ExtAsset { | |
| 632 | - id: a.id.to_string(), | |
| 633 | - name: a.name, | |
| 634 | - size: a.size.unwrap_or(0), | |
| 635 | - content_type: s(a.content_type), | |
| 636 | - url: a.url, | |
| 637 | - }) | |
| 638 | - .collect(), | |
| 639 | - }) | |
| 640 | - .collect()) | |
| 641 | -} | |
| 642 | - | |
| 643 | -impl RemoteApi for GitHub { | |
| 644 | - async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> { | |
| 645 | - if !valid_segment(owner) { | |
| 646 | - return Err(ApiError::NotFound("owner".into())); | |
| 647 | - } | |
| 648 | - let org: ApiResult<Vec<GhRepo>> = self | |
| 649 | - .http | |
| 650 | - .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base)) | |
| 651 | - .await; | |
| 652 | - let raw = or_user( | |
| 653 | - org, | |
| 654 | - self.http | |
| 655 | - .pages(&format!("{}/users/{owner}/repos?type=owner", self.base)), | |
| 656 | - ) | |
| 657 | - .await?; | |
| 658 | - Ok(raw | |
| 659 | - .into_iter() | |
| 660 | - .map(|r| ExtRepo { | |
| 661 | - name: r.name, | |
| 662 | - full_name: r.full_name, | |
| 663 | - description: s(r.description), | |
| 664 | - private: r.private, | |
| 665 | - fork: r.fork, | |
| 666 | - archived: r.archived, | |
| 667 | - default_branch: s(r.default_branch), | |
| 668 | - web_url: s(r.html_url), | |
| 669 | - }) | |
| 670 | - .collect()) | |
| 671 | - } | |
| 672 | - | |
| 673 | - async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> { | |
| 674 | - check_repo(repo, 2, 2)?; | |
| 675 | - let raw: Vec<GhLabel> = self | |
| 676 | - .http | |
| 677 | - .pages(&format!("{}/repos/{repo}/labels", self.base)) | |
| 678 | - .await?; | |
| 679 | - Ok(raw.into_iter().map(label_of).collect()) | |
| 680 | - } | |
| 681 | - | |
| 682 | - async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> { | |
| 683 | - check_repo(repo, 2, 2)?; | |
| 684 | - let raw: Vec<GhMilestone> = self | |
| 685 | - .http | |
| 686 | - .pages(&format!("{}/repos/{repo}/milestones?state=all", self.base)) | |
| 687 | - .await?; | |
| 688 | - Ok(raw | |
| 689 | - .into_iter() | |
| 690 | - .map(|m| ExtMilestone { | |
| 691 | - id: m.number.to_string(), | |
| 692 | - title: m.title, | |
| 693 | - description: s(m.description), | |
| 694 | - closed: m.state == "closed", | |
| 695 | - due_on: m.due_on.as_deref().and_then(day), | |
| 696 | - }) | |
| 697 | - .collect()) | |
| 698 | - } | |
| 699 | - | |
| 700 | - async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> { | |
| 701 | - check_repo(repo, 2, 2)?; | |
| 702 | - let raw: Vec<GhIssue> = self | |
| 703 | - .http | |
| 704 | - .pages(&format!( | |
| 705 | - "{}/repos/{repo}/issues?state=all&sort=created&direction=asc", | |
| 706 | - self.base | |
| 707 | - )) | |
| 708 | - .await?; | |
| 709 | - Ok(raw.into_iter().map(gh_issue).collect()) | |
| 710 | - } | |
| 711 | - | |
| 712 | - async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> { | |
| 713 | - check_repo(repo, 2, 2)?; | |
| 714 | - let raw: Vec<GhComment> = self | |
| 715 | - .http | |
| 716 | - .pages(&format!( | |
| 717 | - "{}/repos/{repo}/issues/{}/comments", | |
| 718 | - self.base, issue.number | |
| 719 | - )) | |
| 720 | - .await?; | |
| 721 | - Ok(raw | |
| 722 | - .into_iter() | |
| 723 | - .map(|c| ExtComment { | |
| 724 | - id: c.id.to_string(), | |
| 725 | - author: login(c.user), | |
| 726 | - body: s(c.body), | |
| 727 | - created_at: s(c.created_at), | |
| 728 | - url: s(c.html_url), | |
| 729 | - }) | |
| 730 | - .collect()) | |
| 731 | - } | |
| 732 | - | |
| 733 | - async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> { | |
| 734 | - check_repo(repo, 2, 2)?; | |
| 735 | - let raw: Vec<GhRelease> = self | |
| 736 | - .http | |
| 737 | - .pages(&format!("{}/repos/{repo}/releases", self.base)) | |
| 738 | - .await?; | |
| 739 | - Ok(raw.into_iter().map(gh_release).collect()) | |
| 740 | - } | |
| 741 | - | |
| 742 | - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> { | |
| 743 | - if !asset.url.starts_with("https://api.github.com/") { | |
| 744 | - return Err(ApiError::Http("unexpected asset address".into())); | |
| 745 | - } | |
| 746 | - self.http.download(&asset.url, max_bytes).await | |
| 747 | - } | |
| 748 | -} | |
| 749 | - | |
| 750 | -fn gh_release(r: GhRelease) -> ExtRelease { | |
| 751 | - ExtRelease { | |
| 752 | - id: r.id.to_string(), | |
| 753 | - title: release_title(r.name, &r.tag_name), | |
| 754 | - tag: r.tag_name, | |
| 755 | - body: s(r.body), | |
| 756 | - draft: r.draft, | |
| 757 | - prerelease: r.prerelease, | |
| 758 | - author: login(r.author), | |
| 759 | - created_at: s(r.created_at), | |
| 760 | - url: s(r.html_url), | |
| 761 | - assets: r | |
| 762 | - .assets | |
| 763 | - .into_iter() | |
| 764 | - .map(|a| ExtAsset { | |
| 765 | - id: a.id.to_string(), | |
| 766 | - name: a.name, | |
| 767 | - size: a.size.unwrap_or(0), | |
| 768 | - content_type: s(a.content_type), | |
| 769 | - url: a.url, | |
| 770 | - }) | |
| 771 | - .collect(), | |
| 772 | - } | |
| 773 | -} | |
| 774 | - | |
| 775 | -fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> { | |
| 776 | - if valid_path(repo, min, max) { | |
| 777 | - Ok(()) | |
| 778 | - } else { | |
| 779 | - Err(ApiError::NotFound("repository path".into())) | |
| 780 | - } | |
| 781 | -} | |
| 782 | - | |
| 783 | -pub struct GitLab { | |
| 784 | - http: Http, | |
| 785 | - base: String, | |
| 786 | -} | |
| 787 | - | |
| 788 | -impl GitLab { | |
| 789 | - pub fn new(http: Http, instance: &str) -> Self { | |
| 790 | - GitLab { | |
| 791 | - http, | |
| 792 | - base: format!("{}/api/v4", instance.trim_end_matches('/')), | |
| 793 | - } | |
| 794 | - } | |
| 795 | - | |
| 796 | - fn project(&self, repo: &str) -> ApiResult<String> { | |
| 797 | - check_repo(repo, 2, 20)?; | |
| 798 | - Ok(format!( | |
| 799 | - "{}/projects/{}", | |
| 800 | - self.base, | |
| 801 | - repo.replace('/', "%2F") | |
| 802 | - )) | |
| 803 | - } | |
| 804 | -} | |
| 805 | - | |
| 806 | -#[derive(Deserialize)] | |
| 807 | -struct GlUser { | |
| 808 | - username: Option<String>, | |
| 809 | -} | |
| 810 | - | |
| 811 | -#[derive(Deserialize)] | |
| 812 | -struct GlLabel { | |
| 813 | - name: String, | |
| 814 | - color: Option<String>, | |
| 815 | - description: Option<String>, | |
| 816 | -} | |
| 817 | - | |
| 818 | -#[derive(Deserialize)] | |
| 819 | -struct GlMilestone { | |
| 820 | - id: i64, | |
| 821 | - title: String, | |
| 822 | - description: Option<String>, | |
| 823 | - state: String, | |
| 824 | - due_date: Option<String>, | |
| 825 | -} | |
| 826 | - | |
| 827 | -#[derive(Deserialize)] | |
| 828 | -struct GlMilestoneRef { | |
| 829 | - title: String, | |
| 830 | -} | |
| 831 | - | |
| 832 | -#[derive(Deserialize)] | |
| 833 | -struct GlIssue { | |
| 834 | - iid: i64, | |
| 835 | - title: String, | |
| 836 | - description: Option<String>, | |
| 837 | - state: String, | |
| 838 | - author: Option<GlUser>, | |
| 839 | - #[serde(default)] | |
| 840 | - labels: Vec<String>, | |
| 841 | - milestone: Option<GlMilestoneRef>, | |
| 842 | - created_at: Option<String>, | |
| 843 | - web_url: Option<String>, | |
| 844 | -} | |
| 845 | - | |
| 846 | -#[derive(Deserialize)] | |
| 847 | -struct GlNote { | |
| 848 | - id: i64, | |
| 849 | - body: Option<String>, | |
| 850 | - author: Option<GlUser>, | |
| 851 | - created_at: Option<String>, | |
| 852 | - #[serde(default)] | |
| 853 | - system: bool, | |
| 854 | -} | |
| 855 | - | |
| 856 | -#[derive(Deserialize)] | |
| 857 | -struct GlLink { | |
| 858 | - id: i64, | |
| 859 | - name: String, | |
| 860 | - url: String, | |
| 861 | - direct_asset_url: Option<String>, | |
| 862 | -} | |
| 863 | - | |
| 864 | -#[derive(Deserialize, Default)] | |
| 865 | -struct GlAssets { | |
| 866 | - #[serde(default)] | |
| 867 | - links: Vec<GlLink>, | |
| 868 | -} | |
| 869 | - | |
| 870 | -#[derive(Deserialize)] | |
| 871 | -struct GlRelease { | |
| 872 | - tag_name: String, | |
| 873 | - name: Option<String>, | |
| 874 | - description: Option<String>, | |
| 875 | - created_at: Option<String>, | |
| 876 | - #[serde(default)] | |
| 877 | - upcoming_release: bool, | |
| 878 | - author: Option<GlUser>, | |
| 879 | - #[serde(default)] | |
| 880 | - assets: GlAssets, | |
| 881 | - #[serde(rename = "_links")] | |
| 882 | - links: Option<GlSelf>, | |
| 883 | -} | |
| 884 | - | |
| 885 | -#[derive(Deserialize)] | |
| 886 | -struct GlSelf { | |
| 887 | - #[serde(rename = "self")] | |
| 888 | - self_url: Option<String>, | |
| 889 | -} | |
| 890 | - | |
| 891 | -#[derive(Deserialize)] | |
| 892 | -struct GlProject { | |
| 893 | - path: String, | |
| 894 | - path_with_namespace: String, | |
| 895 | - description: Option<String>, | |
| 896 | - visibility: Option<String>, | |
| 897 | - default_branch: Option<String>, | |
| 898 | - web_url: Option<String>, | |
| 899 | - #[serde(default)] | |
| 900 | - archived: bool, | |
| 901 | - forked_from_project: Option<serde_json::Value>, | |
| 902 | -} | |
| 903 | - | |
| 904 | -fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue { | |
| 905 | - ExtIssue { | |
| 906 | - number: i.iid, | |
| 907 | - title: i.title, | |
| 908 | - body: s(i.description), | |
| 909 | - closed: i.state != "opened", | |
| 910 | - not_planned: false, | |
| 911 | - merged: i.state == "merged", | |
| 912 | - author: i.author.and_then(|a| a.username).unwrap_or_default(), | |
| 913 | - labels: i.labels, | |
| 914 | - milestone: i.milestone.map(|m| m.title), | |
| 915 | - created_at: s(i.created_at), | |
| 916 | - url: s(i.web_url), | |
| 917 | - is_pr, | |
| 918 | - } | |
| 919 | -} | |
| 920 | - | |
| 921 | -#[cfg(test)] | |
| 922 | -fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> { | |
| 923 | - let raw: Vec<GlIssue> = from_json(json)?; | |
| 924 | - Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect()) | |
| 925 | -} | |
| 926 | - | |
| 927 | -#[cfg(test)] | |
| 928 | -fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> { | |
| 929 | - let raw: Vec<GlRelease> = from_json(json)?; | |
| 930 | - Ok(raw.into_iter().map(gl_release).collect()) | |
| 931 | -} | |
| 932 | - | |
| 933 | -fn gl_release(r: GlRelease) -> ExtRelease { | |
| 934 | - ExtRelease { | |
| 935 | - id: r.tag_name.clone(), | |
| 936 | - title: release_title(r.name, &r.tag_name), | |
| 937 | - tag: r.tag_name, | |
| 938 | - body: s(r.description), | |
| 939 | - draft: r.upcoming_release, | |
| 940 | - prerelease: false, | |
| 941 | - author: r.author.and_then(|a| a.username).unwrap_or_default(), | |
| 942 | - created_at: s(r.created_at), | |
| 943 | - url: r.links.and_then(|l| l.self_url).unwrap_or_default(), | |
| 944 | - assets: r | |
| 945 | - .assets | |
| 946 | - .links | |
| 947 | - .into_iter() | |
| 948 | - .map(|l| ExtAsset { | |
| 949 | - id: l.id.to_string(), | |
| 950 | - name: l.name, | |
| 951 | - size: 0, | |
| 952 | - content_type: String::new(), | |
| 953 | - url: l | |
| 954 | - .direct_asset_url | |
| 955 | - .filter(|u| !u.is_empty()) | |
| 956 | - .unwrap_or(l.url), | |
| 957 | - }) | |
| 958 | - .collect(), | |
| 959 | - } | |
| 960 | -} | |
| 961 | - | |
| 962 | -impl RemoteApi for GitLab { | |
| 963 | - async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> { | |
| 964 | - check_repo(owner, 1, 20)?; | |
| 965 | - let enc = owner.replace('/', "%2F"); | |
| 966 | - let group: ApiResult<Vec<GlProject>> = self | |
| 967 | - .http | |
| 968 | - .pages(&format!( | |
| 969 | - "{}/groups/{enc}/projects?include_subgroups=false&simple=false", | |
| 970 | - self.base | |
| 971 | - )) | |
| 972 | - .await; | |
| 973 | - let raw = or_user( | |
| 974 | - group, | |
| 975 | - self.http | |
| 976 | - .pages(&format!("{}/users/{enc}/projects", self.base)), | |
| 977 | - ) | |
| 978 | - .await?; | |
| 979 | - Ok(raw | |
| 980 | - .into_iter() | |
| 981 | - .map(|p| ExtRepo { | |
| 982 | - name: p.path, | |
| 983 | - full_name: p.path_with_namespace, | |
| 984 | - description: s(p.description), | |
| 985 | - private: p.visibility.as_deref() != Some("public"), | |
| 986 | - fork: p.forked_from_project.is_some(), | |
| 987 | - archived: p.archived, | |
| 988 | - default_branch: s(p.default_branch), | |
| 989 | - web_url: s(p.web_url), | |
| 990 | - }) | |
| 991 | - .collect()) | |
| 992 | - } | |
| 993 | - | |
| 994 | - async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> { | |
| 995 | - let raw: Vec<GlLabel> = self | |
| 996 | - .http | |
| 997 | - .pages(&format!("{}/labels", self.project(repo)?)) | |
| 998 | - .await?; | |
| 999 | - Ok(raw | |
| 1000 | - .into_iter() | |
| 1001 | - .map(|l| ExtLabel { | |
| 1002 | - name: l.name, | |
| 1003 | - color: s(l.color), | |
| 1004 | - description: s(l.description), | |
| 1005 | - }) | |
| 1006 | - .collect()) | |
| 1007 | - } | |
| 1008 | - | |
| 1009 | - async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> { | |
| 1010 | - let raw: Vec<GlMilestone> = self | |
| 1011 | - .http | |
| 1012 | - .pages(&format!("{}/milestones", self.project(repo)?)) | |
| 1013 | - .await?; | |
| 1014 | - Ok(raw | |
| 1015 | - .into_iter() | |
| 1016 | - .map(|m| ExtMilestone { | |
| 1017 | - id: m.id.to_string(), | |
| 1018 | - title: m.title, | |
| 1019 | - description: s(m.description), | |
| 1020 | - closed: m.state == "closed", | |
| 1021 | - due_on: m.due_date.as_deref().and_then(day), | |
| 1022 | - }) | |
| 1023 | - .collect()) | |
| 1024 | - } | |
| 1025 | - | |
| 1026 | - async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> { | |
| 1027 | - let project = self.project(repo)?; | |
| 1028 | - let issues: Vec<GlIssue> = self | |
| 1029 | - .http | |
| 1030 | - .pages(&format!( | |
| 1031 | - "{project}/issues?state=all&order_by=created_at&sort=asc" | |
| 1032 | - )) | |
| 1033 | - .await?; | |
| 1034 | - let pulls: Vec<GlIssue> = self | |
| 1035 | - .http | |
| 1036 | - .pages(&format!( | |
| 1037 | - "{project}/merge_requests?state=all&order_by=created_at&sort=asc" | |
| 1038 | - )) | |
| 1039 | - .await?; | |
| 1040 | - let mut out: Vec<ExtIssue> = issues.into_iter().map(|i| gl_issue(i, false)).collect(); | |
| 1041 | - out.extend(pulls.into_iter().map(|i| gl_issue(i, true))); | |
| 1042 | - Ok(out) | |
| 1043 | - } | |
| 1044 | - | |
| 1045 | - async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> { | |
| 1046 | - let kind = if issue.is_pr { | |
| 1047 | - "merge_requests" | |
| 1048 | - } else { | |
| 1049 | - "issues" | |
| 1050 | - }; | |
| 1051 | - let raw: Vec<GlNote> = self | |
| 1052 | - .http | |
| 1053 | - .pages(&format!( | |
| 1054 | - "{}/{kind}/{}/notes?sort=asc&order_by=created_at", | |
| 1055 | - self.project(repo)?, | |
| 1056 | - issue.number | |
| 1057 | - )) | |
| 1058 | - .await?; | |
| 1059 | - Ok(raw | |
| 1060 | - .into_iter() | |
| 1061 | - .filter(|n| !n.system) | |
| 1062 | - .map(|n| ExtComment { | |
| 1063 | - id: n.id.to_string(), | |
| 1064 | - author: n.author.and_then(|a| a.username).unwrap_or_default(), | |
| 1065 | - body: s(n.body), | |
| 1066 | - created_at: s(n.created_at), | |
| 1067 | - url: format!("{}#note_{}", issue.url, n.id), | |
| 1068 | - }) | |
| 1069 | - .collect()) | |
| 1070 | - } | |
| 1071 | - | |
| 1072 | - async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> { | |
| 1073 | - let raw: Vec<GlRelease> = self | |
| 1074 | - .http | |
| 1075 | - .pages(&format!("{}/releases", self.project(repo)?)) | |
| 1076 | - .await?; | |
| 1077 | - Ok(raw.into_iter().map(gl_release).collect()) | |
| 1078 | - } | |
| 1079 | - | |
| 1080 | - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> { | |
| 1081 | - if !asset.url.starts_with("https://") { | |
| 1082 | - return Err(ApiError::Http("unexpected asset address".into())); | |
| 1083 | - } | |
| 1084 | - self.http.download(&asset.url, max_bytes).await | |
| 1085 | - } | |
| 1086 | -} | |
| 1087 | - | |
| 1088 | -pub struct Forgejo { | |
| 1089 | - http: Http, | |
| 1090 | - origin: String, | |
| 1091 | - base: String, | |
| 1092 | -} | |
| 1093 | - | |
| 1094 | -impl Forgejo { | |
| 1095 | - pub fn new(http: Http, instance: &str) -> Self { | |
| 1096 | - let origin = instance.trim_end_matches('/').to_owned(); | |
| 1097 | - Forgejo { | |
| 1098 | - http, | |
| 1099 | - base: format!("{origin}/api/v1"), | |
| 1100 | - origin, | |
| 1101 | - } | |
| 1102 | - } | |
| 1103 | -} | |
| 1104 | - | |
| 1105 | -#[derive(Deserialize)] | |
| 1106 | -struct FjUser { | |
| 1107 | - login: Option<String>, | |
| 1108 | - username: Option<String>, | |
| 1109 | -} | |
| 1110 | - | |
| 1111 | -fn fj_user(u: Option<FjUser>) -> String { | |
| 1112 | - u.and_then(|u| u.login.filter(|l| !l.is_empty()).or(u.username)) | |
| 1113 | - .unwrap_or_default() | |
| 1114 | -} | |
| 1115 | - | |
| 1116 | -#[derive(Deserialize)] | |
| 1117 | -struct FjLabel { | |
| 1118 | - name: String, | |
| 1119 | - color: Option<String>, | |
| 1120 | - description: Option<String>, | |
| 1121 | -} | |
| 1122 | - | |
| 1123 | -#[derive(Deserialize)] | |
| 1124 | -struct FjMilestone { | |
| 1125 | - id: i64, | |
| 1126 | - title: String, | |
| 1127 | - description: Option<String>, | |
| 1128 | - state: String, | |
| 1129 | - due_on: Option<String>, | |
| 1130 | -} | |
| 1131 | - | |
| 1132 | -#[derive(Deserialize)] | |
| 1133 | -struct FjMilestoneRef { | |
| 1134 | - title: String, | |
| 1135 | -} | |
| 1136 | - | |
| 1137 | -#[derive(Deserialize)] | |
| 1138 | -struct FjIssue { | |
| 1139 | - number: i64, | |
| 1140 | - title: String, | |
| 1141 | - body: Option<String>, | |
| 1142 | - state: String, | |
| 1143 | - user: Option<FjUser>, | |
| 1144 | - #[serde(default)] | |
| 1145 | - labels: Vec<FjLabel>, | |
| 1146 | - milestone: Option<FjMilestoneRef>, | |
| 1147 | - created_at: Option<String>, | |
| 1148 | - html_url: Option<String>, | |
| 1149 | - #[serde(default)] | |
| 1150 | - merged: bool, | |
| 1151 | -} | |
| 1152 | - | |
| 1153 | -#[derive(Deserialize)] | |
| 1154 | -struct FjComment { | |
| 1155 | - id: i64, | |
| 1156 | - body: Option<String>, | |
| 1157 | - user: Option<FjUser>, | |
| 1158 | - created_at: Option<String>, | |
| 1159 | - html_url: Option<String>, | |
| 1160 | -} | |
| 1161 | - | |
| 1162 | -#[derive(Deserialize)] | |
| 1163 | -struct FjAsset { | |
| 1164 | - id: i64, | |
| 1165 | - name: String, | |
| 1166 | - size: Option<u64>, | |
| 1167 | - browser_download_url: String, | |
| 1168 | -} | |
| 1169 | - | |
| 1170 | -#[derive(Deserialize)] | |
| 1171 | -struct FjRelease { | |
| 1172 | - id: i64, | |
| 1173 | - tag_name: String, | |
| 1174 | - name: Option<String>, | |
| 1175 | - body: Option<String>, | |
| 1176 | - #[serde(default)] | |
| 1177 | - draft: bool, | |
| 1178 | - #[serde(default)] | |
| 1179 | - prerelease: bool, | |
| 1180 | - author: Option<FjUser>, | |
| 1181 | - created_at: Option<String>, | |
| 1182 | - html_url: Option<String>, | |
| 1183 | - #[serde(default)] | |
| 1184 | - assets: Vec<FjAsset>, | |
| 1185 | -} | |
| 1186 | - | |
| 1187 | -#[derive(Deserialize)] | |
| 1188 | -struct FjRepo { | |
| 1189 | - name: String, | |
| 1190 | - full_name: String, | |
| 1191 | - description: Option<String>, | |
| 1192 | - #[serde(default)] | |
| 1193 | - private: bool, | |
| 1194 | - #[serde(default)] | |
| 1195 | - fork: bool, | |
| 1196 | - #[serde(default)] | |
| 1197 | - archived: bool, | |
| 1198 | - default_branch: Option<String>, | |
| 1199 | - html_url: Option<String>, | |
| 1200 | -} | |
| 1201 | - | |
| 1202 | -fn fj_issue(i: FjIssue, is_pr: bool) -> ExtIssue { | |
| 1203 | - ExtIssue { | |
| 1204 | - number: i.number, | |
| 1205 | - title: i.title, | |
| 1206 | - body: s(i.body), | |
| 1207 | - closed: i.state != "open", | |
| 1208 | - not_planned: false, | |
| 1209 | - merged: is_pr && i.merged, | |
| 1210 | - author: fj_user(i.user), | |
| 1211 | - labels: i.labels.into_iter().map(|l| l.name).collect(), | |
| 1212 | - milestone: i.milestone.map(|m| m.title), | |
| 1213 | - created_at: s(i.created_at), | |
| 1214 | - url: s(i.html_url), | |
| 1215 | - is_pr, | |
| 1216 | - } | |
| 1217 | -} | |
| 1218 | - | |
| 1219 | -fn fj_release(r: FjRelease) -> ExtRelease { | |
| 1220 | - ExtRelease { | |
| 1221 | - id: r.id.to_string(), | |
| 1222 | - title: release_title(r.name, &r.tag_name), | |
| 1223 | - tag: r.tag_name, | |
| 1224 | - body: s(r.body), | |
| 1225 | - draft: r.draft, | |
| 1226 | - prerelease: r.prerelease, | |
| 1227 | - author: fj_user(r.author), | |
| 1228 | - created_at: s(r.created_at), | |
| 1229 | - url: s(r.html_url), | |
| 1230 | - assets: r | |
| 1231 | - .assets | |
| 1232 | - .into_iter() | |
| 1233 | - .map(|a| ExtAsset { | |
| 1234 | - id: a.id.to_string(), | |
| 1235 | - name: a.name, | |
| 1236 | - size: a.size.unwrap_or(0), | |
| 1237 | - content_type: String::new(), | |
| 1238 | - url: a.browser_download_url, | |
| 1239 | - }) | |
| 1240 | - .collect(), | |
| 1241 | - } | |
| 1242 | -} | |
| 1243 | - | |
| 1244 | -impl RemoteApi for Forgejo { | |
| 1245 | - async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> { | |
| 1246 | - let raw: Vec<FjRepo> = if owner.is_empty() { | |
| 1247 | - self.http | |
| 1248 | - .limit_pages(&format!("{}/user/repos", self.base)) | |
| 1249 | - .await? | |
| 1250 | - } else { | |
| 1251 | - if !valid_segment(owner) { | |
| 1252 | - return Err(ApiError::NotFound("owner".into())); | |
| 1253 | - } | |
| 1254 | - let org: ApiResult<Vec<FjRepo>> = self | |
| 1255 | - .http | |
| 1256 | - .limit_pages(&format!("{}/orgs/{owner}/repos", self.base)) | |
| 1257 | - .await; | |
| 1258 | - or_user( | |
| 1259 | - org, | |
| 1260 | - self.http | |
| 1261 | - .limit_pages(&format!("{}/users/{owner}/repos", self.base)), | |
| 1262 | - ) | |
| 1263 | - .await? | |
| 1264 | - }; | |
| 1265 | - Ok(raw | |
| 1266 | - .into_iter() | |
| 1267 | - .map(|r| ExtRepo { | |
| 1268 | - name: r.name, | |
| 1269 | - full_name: r.full_name, | |
| 1270 | - description: s(r.description), | |
| 1271 | - private: r.private, | |
| 1272 | - fork: r.fork, | |
| 1273 | - archived: r.archived, | |
| 1274 | - default_branch: s(r.default_branch), | |
| 1275 | - web_url: s(r.html_url), | |
| 1276 | - }) | |
| 1277 | - .collect()) | |
| 1278 | - } | |
| 1279 | - | |
| 1280 | - async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> { | |
| 1281 | - check_repo(repo, 2, 2)?; | |
| 1282 | - let raw: Vec<FjLabel> = self | |
| 1283 | - .http | |
| 1284 | - .limit_pages(&format!("{}/repos/{repo}/labels", self.base)) | |
| 1285 | - .await?; | |
| 1286 | - Ok(raw | |
| 1287 | - .into_iter() | |
| 1288 | - .map(|l| ExtLabel { | |
| 1289 | - name: l.name, | |
| 1290 | - color: format!("#{}", s(l.color).trim_start_matches('#')), | |
| 1291 | - description: s(l.description), | |
| 1292 | - }) | |
| 1293 | - .collect()) | |
| 1294 | - } | |
| 1295 | - | |
| 1296 | - async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> { | |
| 1297 | - check_repo(repo, 2, 2)?; | |
| 1298 | - let raw: Vec<FjMilestone> = self | |
| 1299 | - .http | |
| 1300 | - .limit_pages(&format!("{}/repos/{repo}/milestones?state=all", self.base)) | |
| 1301 | - .await?; | |
| 1302 | - Ok(raw | |
| 1303 | - .into_iter() | |
| 1304 | - .map(|m| ExtMilestone { | |
| 1305 | - id: m.id.to_string(), | |
| 1306 | - title: m.title, | |
| 1307 | - description: s(m.description), | |
| 1308 | - closed: m.state == "closed", | |
| 1309 | - due_on: m.due_on.as_deref().and_then(day), | |
| 1310 | - }) | |
| 1311 | - .collect()) | |
| 1312 | - } | |
| 1313 | - | |
| 1314 | - async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> { | |
| 1315 | - check_repo(repo, 2, 2)?; | |
| 1316 | - let issues: Vec<FjIssue> = self | |
| 1317 | - .http | |
| 1318 | - .limit_pages(&format!( | |
| 1319 | - "{}/repos/{repo}/issues?type=issues&state=all&sort=oldest", | |
| 1320 | - self.base | |
| 1321 | - )) | |
| 1322 | - .await?; | |
| 1323 | - let pulls: Vec<FjIssue> = self | |
| 1324 | - .http | |
| 1325 | - .limit_pages(&format!( | |
| 1326 | - "{}/repos/{repo}/pulls?state=all&sort=oldest", | |
| 1327 | - self.base | |
| 1328 | - )) | |
| 1329 | - .await?; | |
| 1330 | - let mut out: Vec<ExtIssue> = issues.into_iter().map(|i| fj_issue(i, false)).collect(); | |
| 1331 | - out.extend(pulls.into_iter().map(|i| fj_issue(i, true))); | |
| 1332 | - Ok(out) | |
| 1333 | - } | |
| 1334 | - | |
| 1335 | - async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> { | |
| 1336 | - check_repo(repo, 2, 2)?; | |
| 1337 | - let raw: Vec<FjComment> = self | |
| 1338 | - .http | |
| 1339 | - .limit_pages(&format!( | |
| 1340 | - "{}/repos/{repo}/issues/{}/comments", | |
| 1341 | - self.base, issue.number | |
| 1342 | - )) | |
| 1343 | - .await?; | |
| 1344 | - Ok(raw | |
| 1345 | - .into_iter() | |
| 1346 | - .map(|c| ExtComment { | |
| 1347 | - id: c.id.to_string(), | |
| 1348 | - author: fj_user(c.user), | |
| 1349 | - body: s(c.body), | |
| 1350 | - created_at: s(c.created_at), | |
| 1351 | - url: s(c.html_url), | |
| 1352 | - }) | |
| 1353 | - .collect()) | |
| 1354 | - } | |
| 1355 | - | |
| 1356 | - async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> { | |
| 1357 | - check_repo(repo, 2, 2)?; | |
| 1358 | - let raw: Vec<FjRelease> = self | |
| 1359 | - .http | |
| 1360 | - .limit_pages(&format!("{}/repos/{repo}/releases", self.base)) | |
| 1361 | - .await?; | |
| 1362 | - Ok(raw.into_iter().map(fj_release).collect()) | |
| 1363 | - } | |
| 1364 | - | |
| 1365 | - async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<AssetStream> { | |
| 1366 | - if !asset.url.starts_with(&format!("{}/", self.origin)) { | |
| 1367 | - return Err(ApiError::Http("unexpected asset address".into())); | |
| 1368 | - } | |
| 1369 | - self.http.download(&asset.url, max_bytes).await | |
| 1370 | - } | |
| 1371 | -} | |
| 1372 | - | |
| 1373 | -#[cfg(test)] | |
| 1374 | -mod tests { | |
| 1375 | - use super::*; | |
| 1376 | - | |
| 1377 | - #[test] | |
| 1378 | - fn segments_reject_traversal_and_separators() { | |
| 1379 | - assert!(valid_segment("tahinli")); | |
| 1380 | - assert!(valid_segment("my-repo_1.rs")); | |
| 1381 | - assert!(!valid_segment("..")); | |
| 1382 | - assert!(!valid_segment("a/b")); | |
| 1383 | - assert!(!valid_segment("a?b")); | |
| 1384 | - assert!(!valid_segment("")); | |
| 1385 | - assert!(valid_path("tahinli/forge", 2, 2)); | |
| 1386 | - assert!(!valid_path("tahinli", 2, 2)); | |
| 1387 | - assert!(!valid_path("a/b/c", 2, 2)); | |
| 1388 | - assert!(valid_path("grp/sub/proj", 2, 20)); | |
| 1389 | - } | |
| 1390 | - | |
| 1391 | - #[test] | |
| 1392 | - fn wait_text_reads_naturally() { | |
| 1393 | - assert_eq!(wait_text(45), "45 seconds"); | |
| 1394 | - assert_eq!(wait_text(60), "1 minute"); | |
| 1395 | - assert_eq!(wait_text(3188), "54 minutes"); | |
| 1396 | - assert_eq!(wait_text(3600), "1 hour"); | |
| 1397 | - assert_eq!(wait_text(3661), "1 hour 2 minutes"); | |
| 1398 | - } | |
| 1399 | - | |
| 1400 | - #[test] | |
| 1401 | - fn rate_limit_waits_follow_the_headers() { | |
| 1402 | - assert_eq!(rate_wait(Some("30"), None, None, 100), Some(30)); | |
| 1403 | - assert_eq!(rate_wait(None, Some("0"), Some("160"), 100), Some(60)); | |
| 1404 | - assert_eq!(rate_wait(None, Some("0"), Some("90"), 100), Some(1)); | |
| 1405 | - assert_eq!(rate_wait(None, Some("12"), Some("160"), 100), None); | |
| 1406 | - assert_eq!(rate_wait(None, None, None, 100), None); | |
| 1407 | - assert_eq!(rate_wait(None, Some("0"), None, 100), None); | |
| 1408 | - } | |
| 1409 | - | |
| 1410 | - #[test] | |
| 1411 | - fn github_issues_and_pulls_parse() { | |
| 1412 | - let json = br##"[ | |
| 1413 | - {"number":1,"title":"Bug","body":"it breaks","state":"closed","state_reason":"not_planned", | |
| 1414 | - "user":{"login":"octocat"},"labels":[{"name":"bug","color":"d73a4a"}], | |
| 1415 | - "milestone":{"title":"v1"},"created_at":"2020-01-02T03:04:05Z", | |
| 1416 | - "html_url":"https://github.com/o/r/issues/1"}, | |
| 1417 | - {"number":2,"title":"Add x","body":null,"state":"closed","user":{"login":"hubot"}, | |
| 1418 | - "labels":[],"milestone":null,"created_at":"2020-02-02T00:00:00Z", | |
| 1419 | - "html_url":"https://github.com/o/r/pull/2","pull_request":{"merged_at":"2020-02-03T00:00:00Z"}} | |
| 1420 | - ]"##; | |
| 1421 | - let items = parse_github_issues(json).unwrap(); | |
| 1422 | - assert_eq!(items.len(), 2); | |
| 1423 | - assert!(items[0].closed && items[0].not_planned && !items[0].is_pr); | |
| 1424 | - assert_eq!(items[0].labels, vec!["bug"]); | |
| 1425 | - assert_eq!(items[0].milestone.as_deref(), Some("v1")); | |
| 1426 | - assert!(items[1].is_pr && items[1].merged); | |
| 1427 | - assert_eq!(items[1].body, ""); | |
| 1428 | - assert_eq!(items[1].author, "hubot"); | |
| 1429 | - } | |
| 1430 | - | |
| 1431 | - #[test] | |
| 1432 | - fn github_labels_get_a_hash() { | |
| 1433 | - let labels = | |
| 1434 | - parse_github_labels(br#"[{"name":"bug","color":"d73a4a","description":null}]"#) | |
| 1435 | - .unwrap(); | |
| 1436 | - assert_eq!(labels[0].color, "#d73a4a"); | |
| 1437 | - assert_eq!(labels[0].description, ""); | |
| 1438 | - } | |
| 1439 | - | |
| 1440 | - #[test] | |
| 1441 | - fn github_releases_carry_assets() { | |
| 1442 | - let json = br#"[{"id":7,"tag_name":"v1.0","name":"","body":"notes","draft":false, | |
| 1443 | - "prerelease":true,"author":{"login":"octocat"},"created_at":"2021-01-01T00:00:00Z", | |
| 1444 | - "html_url":"https://github.com/o/r/releases/tag/v1.0", | |
| 1445 | - "assets":[{"id":9,"name":"app.tar.gz","size":12,"content_type":"application/gzip", | |
| 1446 | - "url":"https://api.github.com/repos/o/r/releases/assets/9"}]}]"#; | |
| 1447 | - let rel = parse_github_releases(json).unwrap(); | |
| 1448 | - assert_eq!(rel[0].title, "v1.0", "a blank name falls back to the tag"); | |
| 1449 | - assert!(rel[0].prerelease); | |
| 1450 | - assert_eq!(rel[0].assets[0].name, "app.tar.gz"); | |
| 1451 | - assert_eq!(rel[0].assets[0].size, 12); | |
| 1452 | - } | |
| 1453 | - | |
| 1454 | - #[test] | |
| 1455 | - fn gitlab_states_map() { | |
| 1456 | - let json = br#"[ | |
| 1457 | - {"iid":3,"title":"MR","description":"d","state":"merged","author":{"username":"tahinli"}, | |
| 1458 | - "labels":["x"],"milestone":null,"created_at":"2022-01-01T00:00:00Z","web_url":"https://gl/x/-/merge_requests/3"}, | |
| 1459 | - {"iid":4,"title":"open","description":null,"state":"opened","author":null,"labels":[], | |
| 1460 | - "created_at":null,"web_url":null}]"#; | |
| 1461 | - let items = parse_gitlab_issues(json, true).unwrap(); | |
| 1462 | - assert!(items[0].closed && items[0].merged && items[0].is_pr); | |
| 1463 | - assert!(!items[1].closed); | |
| 1464 | - assert_eq!(items[1].author, ""); | |
| 1465 | - } | |
| 1466 | - | |
| 1467 | - #[test] | |
| 1468 | - fn gitlab_release_links_become_assets() { | |
| 1469 | - let json = br#"[{"tag_name":"v2","name":"Two","description":"n","created_at":"2022-01-01T00:00:00Z", | |
| 1470 | - "assets":{"links":[{"id":1,"name":"bin","url":"https://x/a","direct_asset_url":"https://x/direct"}]}}]"#; | |
| 1471 | - let rel = parse_gitlab_releases(json).unwrap(); | |
| 1472 | - assert_eq!(rel[0].assets[0].url, "https://x/direct"); | |
| 1473 | - assert_eq!(rel[0].tag, "v2"); | |
| 1474 | - } | |
| 1475 | - | |
| 1476 | - #[test] | |
| 1477 | - fn day_keeps_only_a_valid_date_prefix() { | |
| 1478 | - assert_eq!(day("2020-05-06T00:00:00Z").as_deref(), Some("2020-05-06")); | |
| 1479 | - assert_eq!(day("garbage!!!").as_deref(), None); | |
| 1480 | - assert_eq!(day("x").as_deref(), None); | |
| 1481 | - } | |
| 1482 | -} |
crates/forge-web-app/src/importer/mod.rsdeleted+0 -1088
| @@ -1,1088 +0,0 @@ | ||
| 1 | -pub mod api; | |
| 2 | -pub mod remote; | |
| 3 | - | |
| 4 | -use std::collections::HashMap; | |
| 5 | -use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError}; | |
| 6 | -use std::time::Duration; | |
| 7 | - | |
| 8 | -use forge_core::issues::{IssueState, MAX_BODY, MAX_TITLE, StateReason}; | |
| 9 | -use forge_core::releases::{MAX_ASSET_NAME_LEN, NewRelease}; | |
| 10 | -use forge_core::store::imports::{ImportJob, ImportOrigin, ImportState}; | |
| 11 | -use forge_core::{Repo, Store, User}; | |
| 12 | -use forge_git::mirror::{RemoteAuth, mirror_fetch}; | |
| 13 | -use serde::{Deserialize, Serialize}; | |
| 14 | -use tokio::sync::{Semaphore, watch}; | |
| 15 | - | |
| 16 | -use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi}; | |
| 17 | -pub use self::remote::{ | |
| 18 | - default_name, make_forgejo, make_github, make_gitlab, parse_remote, source_ref, | |
| 19 | -}; | |
| 20 | -use crate::live::Topic; | |
| 21 | -use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; | |
| 22 | -use crate::state::AppState; | |
| 23 | - | |
| 24 | -const GIT_TIMEOUT: Duration = Duration::from_secs(60 * 60); | |
| 25 | -static SLOTS: Semaphore = Semaphore::const_new(2); | |
| 26 | -const IMPORTED_PR_LABEL: &str = "imported PR"; | |
| 27 | -const IMPORTED_PR_COLOR: &str = "#8b7bd8"; | |
| 28 | -const FALLBACK_LABEL_COLOR: &str = "#8b949e"; | |
| 29 | -const IMPORT_BUMP_BATCH: usize = 25; | |
| 30 | - | |
| 31 | -#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 32 | -pub enum Source { | |
| 33 | - Git, | |
| 34 | - GitHub, | |
| 35 | - GitLab, | |
| 36 | - Forgejo, | |
| 37 | -} | |
| 38 | - | |
| 39 | -impl Source { | |
| 40 | - pub fn as_str(self) -> &'static str { | |
| 41 | - match self { | |
| 42 | - Source::Git => "git", | |
| 43 | - Source::GitHub => "github", | |
| 44 | - Source::GitLab => "gitlab", | |
| 45 | - Source::Forgejo => "forgejo", | |
| 46 | - } | |
| 47 | - } | |
| 48 | - | |
| 49 | - pub fn parse(s: &str) -> Option<Self> { | |
| 50 | - match s { | |
| 51 | - "git" => Some(Source::Git), | |
| 52 | - "github" => Some(Source::GitHub), | |
| 53 | - "gitlab" => Some(Source::GitLab), | |
| 54 | - "forgejo" | "gitea" => Some(Source::Forgejo), | |
| 55 | - _ => None, | |
| 56 | - } | |
| 57 | - } | |
| 58 | - | |
| 59 | - pub fn label(self) -> &'static str { | |
| 60 | - match self { | |
| 61 | - Source::Git => "git", | |
| 62 | - Source::GitHub => "GitHub", | |
| 63 | - Source::GitLab => "GitLab", | |
| 64 | - Source::Forgejo => "Forgejo", | |
| 65 | - } | |
| 66 | - } | |
| 67 | -} | |
| 68 | - | |
| 69 | -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] | |
| 70 | -pub struct ImportOptions { | |
| 71 | - #[serde(default)] | |
| 72 | - pub labels: bool, | |
| 73 | - #[serde(default)] | |
| 74 | - pub issues: bool, | |
| 75 | - #[serde(default)] | |
| 76 | - pub pulls: bool, | |
| 77 | - #[serde(default)] | |
| 78 | - pub releases: bool, | |
| 79 | -} | |
| 80 | - | |
| 81 | -impl ImportOptions { | |
| 82 | - pub fn any_api(&self) -> bool { | |
| 83 | - self.labels || self.issues || self.pulls || self.releases | |
| 84 | - } | |
| 85 | -} | |
| 86 | - | |
| 87 | -#[derive(Clone)] | |
| 88 | -pub struct JobSpec { | |
| 89 | - pub source: Source, | |
| 90 | - pub remote: String, | |
| 91 | - pub instance: String, | |
| 92 | - pub token: Option<String>, | |
| 93 | - pub git_user: String, | |
| 94 | - pub options: ImportOptions, | |
| 95 | -} | |
| 96 | - | |
| 97 | -impl std::fmt::Debug for JobSpec { | |
| 98 | - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| 99 | - f.debug_struct("JobSpec") | |
| 100 | - .field("source", &self.source) | |
| 101 | - .field("remote", &self.remote) | |
| 102 | - .field("token", &self.token.as_ref().map(|_| "[redacted]")) | |
| 103 | - .finish() | |
| 104 | - } | |
| 105 | -} | |
| 106 | - | |
| 107 | -impl JobSpec { | |
| 108 | - pub fn clone_url(&self) -> String { | |
| 109 | - match self.source { | |
| 110 | - Source::Git => self.remote.clone(), | |
| 111 | - Source::GitHub => format!("https://github.com/{}.git", self.remote), | |
| 112 | - Source::GitLab | Source::Forgejo => format!( | |
| 113 | - "{}/{}.git", | |
| 114 | - self.instance.trim_end_matches('/'), | |
| 115 | - self.remote | |
| 116 | - ), | |
| 117 | - } | |
| 118 | - } | |
| 119 | - | |
| 120 | - fn auth(&self) -> Option<RemoteAuth> { | |
| 121 | - let token = self.token.as_ref().filter(|t| !t.is_empty())?; | |
| 122 | - let username = match self.source { | |
| 123 | - Source::GitHub => "x-access-token".to_owned(), | |
| 124 | - Source::GitLab | Source::Forgejo => "oauth2".to_owned(), | |
| 125 | - Source::Git if self.git_user.is_empty() => "git".to_owned(), | |
| 126 | - Source::Git => self.git_user.clone(), | |
| 127 | - }; | |
| 128 | - Some(RemoteAuth { | |
| 129 | - username, | |
| 130 | - secret: token.clone().into_bytes(), | |
| 131 | - }) | |
| 132 | - } | |
| 133 | -} | |
| 134 | - | |
| 135 | -#[derive(Clone)] | |
| 136 | -pub enum Transport { | |
| 137 | - Net, | |
| 138 | - #[cfg(any(test, feature = "test-support"))] | |
| 139 | - Local(String), | |
| 140 | -} | |
| 141 | - | |
| 142 | -static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> = | |
| 143 | - LazyLock::new(|| Mutex::new(HashMap::new())); | |
| 144 | - | |
| 145 | -fn hub() -> MutexGuard<'static, HashMap<String, watch::Sender<u64>>> { | |
| 146 | - HUB.lock().unwrap_or_else(PoisonError::into_inner) | |
| 147 | -} | |
| 148 | - | |
| 149 | -pub fn subscribe(job_id: &str) -> watch::Receiver<u64> { | |
| 150 | - hub() | |
| 151 | - .entry(job_id.to_owned()) | |
| 152 | - .or_insert_with(|| watch::channel(0).0) | |
| 153 | - .subscribe() | |
| 154 | -} | |
| 155 | - | |
| 156 | -fn bump(job_id: &str) { | |
| 157 | - let mut hub = hub(); | |
| 158 | - if let Some(tx) = hub.get(job_id) { | |
| 159 | - tx.send_modify(|n| *n = n.wrapping_add(1)); | |
| 160 | - if tx.receiver_count() == 0 { | |
| 161 | - hub.remove(job_id); | |
| 162 | - } | |
| 163 | - } | |
| 164 | -} | |
| 165 | - | |
| 166 | -fn close(job_id: &str) { | |
| 167 | - if let Some(tx) = hub().remove(job_id) { | |
| 168 | - tx.send_modify(|n| *n = n.wrapping_add(1)); | |
| 169 | - } | |
| 170 | -} | |
| 171 | - | |
| 172 | -#[derive(Clone)] | |
| 173 | -struct Reporter { | |
| 174 | - store: Store, | |
| 175 | - job_id: String, | |
| 176 | -} | |
| 177 | - | |
| 178 | -impl Reporter { | |
| 179 | - async fn log(&self, level: &str, message: impl AsRef<str>) { | |
| 180 | - if let Err(e) = self | |
| 181 | - .store | |
| 182 | - .add_import_event(&self.job_id, level, message.as_ref()) | |
| 183 | - .await | |
| 184 | - { | |
| 185 | - tracing::warn!(error = %e, "import: could not record a progress line"); | |
| 186 | - } | |
| 187 | - bump(&self.job_id); | |
| 188 | - } | |
| 189 | - | |
| 190 | - async fn stage(&self, stage: &str, done: usize, total: usize) { | |
| 191 | - let (done, total) = (done as i64, total as i64); | |
| 192 | - if let Err(e) = self | |
| 193 | - .store | |
| 194 | - .set_import_progress(&self.job_id, stage, done, total) | |
| 195 | - .await | |
| 196 | - { | |
| 197 | - tracing::warn!(error = %e, "import: could not record progress"); | |
| 198 | - } | |
| 199 | - bump(&self.job_id); | |
| 200 | - } | |
| 201 | -} | |
| 202 | - | |
| 203 | -pub fn origin_note(source: &str, author: &str, created: &str, url: &str) -> String { | |
| 204 | - let clean: String = author | |
| 205 | - .chars() | |
| 206 | - .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) | |
| 207 | - .take(60) | |
| 208 | - .collect(); | |
| 209 | - let who = if clean.is_empty() { "unknown" } else { &clean }; | |
| 210 | - let date: String = created.chars().take(10).collect(); | |
| 211 | - let mut line = format!("> Originally by \\@{who} on {source}"); | |
| 212 | - if !date.is_empty() && date.bytes().all(|b| b.is_ascii_digit() || b == b'-') { | |
| 213 | - line.push_str(", "); | |
| 214 | - line.push_str(&date); | |
| 215 | - } | |
| 216 | - let safe_url = url.starts_with("https://") | |
| 217 | - && !url | |
| 218 | - .chars() | |
| 219 | - .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ')' | '(' | '<' | '>')); | |
| 220 | - if safe_url { | |
| 221 | - line.push_str(&format!(", [original]({url})")); | |
| 222 | - } | |
| 223 | - line.push_str("\n\n"); | |
| 224 | - line | |
| 225 | -} | |
| 226 | - | |
| 227 | -pub fn with_note(note: &str, body: &str) -> String { | |
| 228 | - let mut text = format!("{note}{body}"); | |
| 229 | - if text.len() > MAX_BODY { | |
| 230 | - let mut end = MAX_BODY - 16; | |
| 231 | - while !text.is_char_boundary(end) { | |
| 232 | - end -= 1; | |
| 233 | - } | |
| 234 | - text.truncate(end); | |
| 235 | - text.push_str("\n\n(cut)"); | |
| 236 | - } | |
| 237 | - text | |
| 238 | -} | |
| 239 | - | |
| 240 | -fn clip_title(title: &str) -> String { | |
| 241 | - let t: String = title | |
| 242 | - .chars() | |
| 243 | - .filter(|c| !c.is_control()) | |
| 244 | - .take(MAX_TITLE) | |
| 245 | - .collect(); | |
| 246 | - let t = t.trim(); | |
| 247 | - if t.is_empty() { | |
| 248 | - "(untitled)".to_owned() | |
| 249 | - } else { | |
| 250 | - t.to_owned() | |
| 251 | - } | |
| 252 | -} | |
| 253 | - | |
| 254 | -pub fn asset_name(name: &str) -> String { | |
| 255 | - let cleaned: String = name | |
| 256 | - .chars() | |
| 257 | - .map(|c| { | |
| 258 | - if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') { | |
| 259 | - c | |
| 260 | - } else { | |
| 261 | - '_' | |
| 262 | - } | |
| 263 | - }) | |
| 264 | - .collect(); | |
| 265 | - let mut out = cleaned.trim_start_matches('.').to_owned(); | |
| 266 | - out.truncate(MAX_ASSET_NAME_LEN); | |
| 267 | - if out.is_empty() { | |
| 268 | - "asset".to_owned() | |
| 269 | - } else { | |
| 270 | - out | |
| 271 | - } | |
| 272 | -} | |
| 273 | - | |
| 274 | -pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { | |
| 275 | - state.live.bump(&Topic::Imports(job.user_id.clone())); | |
| 276 | - tokio::spawn(async move { | |
| 277 | - let Ok(_slot) = SLOTS.acquire().await else { | |
| 278 | - return; | |
| 279 | - }; | |
| 280 | - run_production(&state, &job, &spec).await; | |
| 281 | - state.live.bump(&Topic::Imports(job.user_id.clone())); | |
| 282 | - }); | |
| 283 | -} | |
| 284 | - | |
| 285 | -async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { | |
| 286 | - let rep = Reporter { | |
| 287 | - store: state.store.clone(), | |
| 288 | - job_id: job.id.clone(), | |
| 289 | - }; | |
| 290 | - let notice: Notice = { | |
| 291 | - let rep = rep.clone(); | |
| 292 | - std::sync::Arc::new(move |msg: String| { | |
| 293 | - let rep = rep.clone(); | |
| 294 | - tokio::spawn(async move { rep.log("warn", msg).await }); | |
| 295 | - }) | |
| 296 | - }; | |
| 297 | - let wants_api = spec.options.any_api() && spec.source != Source::Git; | |
| 298 | - if !wants_api { | |
| 299 | - run_job::<GitHub>(state, job, spec, None, &Transport::Net).await; | |
| 300 | - return; | |
| 301 | - } | |
| 302 | - match spec.source { | |
| 303 | - Source::GitHub => match make_github(state, spec.token.clone(), notice) { | |
| 304 | - Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, | |
| 305 | - Err(e) => fail(state, &rep, &e).await, | |
| 306 | - }, | |
| 307 | - Source::GitLab => match make_gitlab(state, &spec.instance, spec.token.clone(), notice) { | |
| 308 | - Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, | |
| 309 | - Err(e) => fail(state, &rep, &e).await, | |
| 310 | - }, | |
| 311 | - Source::Forgejo => match make_forgejo(state, &spec.instance, spec.token.clone(), notice) { | |
| 312 | - Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, | |
| 313 | - Err(e) => fail(state, &rep, &e).await, | |
| 314 | - }, | |
| 315 | - Source::Git => run_job::<GitHub>(state, job, spec, None, &Transport::Net).await, | |
| 316 | - } | |
| 317 | -} | |
| 318 | - | |
| 319 | -async fn fail(state: &AppState, rep: &Reporter, message: &str) { | |
| 320 | - tracing::warn!(job = %rep.job_id, %message, "import failed"); | |
| 321 | - rep.log("error", message).await; | |
| 322 | - if let Err(e) = state | |
| 323 | - .store | |
| 324 | - .set_import_state(&rep.job_id, ImportState::Failed, Some(message)) | |
| 325 | - .await | |
| 326 | - { | |
| 327 | - tracing::error!(error = %e, "import: could not record a failure"); | |
| 328 | - } | |
| 329 | - close(&rep.job_id); | |
| 330 | -} | |
| 331 | - | |
| 332 | -pub async fn run_job<A: RemoteApi>( | |
| 333 | - state: &AppState, | |
| 334 | - job: &ImportJob, | |
| 335 | - spec: &JobSpec, | |
| 336 | - api: Option<&A>, | |
| 337 | - transport: &Transport, | |
| 338 | -) { | |
| 339 | - let rep = Reporter { | |
| 340 | - store: state.store.clone(), | |
| 341 | - job_id: job.id.clone(), | |
| 342 | - }; | |
| 343 | - if let Err(e) = state | |
| 344 | - .store | |
| 345 | - .set_import_state(&job.id, ImportState::Running, None) | |
| 346 | - .await | |
| 347 | - { | |
| 348 | - tracing::error!(error = %e, "import: could not start the job"); | |
| 349 | - return; | |
| 350 | - } | |
| 351 | - bump(&job.id); | |
| 352 | - state.live.bump(&Topic::Imports(job.user_id.clone())); | |
| 353 | - match run_steps(state, job, spec, api, transport, &rep).await { | |
| 354 | - Ok(summary) => { | |
| 355 | - rep.log("info", summary).await; | |
| 356 | - rep.stage("done", 0, 0).await; | |
| 357 | - if let Err(e) = state | |
| 358 | - .store | |
| 359 | - .set_import_state(&job.id, ImportState::Done, None) | |
| 360 | - .await | |
| 361 | - { | |
| 362 | - tracing::error!(error = %e, "import: could not finish the job"); | |
| 363 | - } | |
| 364 | - close(&job.id); | |
| 365 | - } | |
| 366 | - Err(message) => fail(state, &rep, &message).await, | |
| 367 | - } | |
| 368 | -} | |
| 369 | - | |
| 370 | -async fn run_steps<A: RemoteApi>( | |
| 371 | - state: &AppState, | |
| 372 | - job: &ImportJob, | |
| 373 | - spec: &JobSpec, | |
| 374 | - api: Option<&A>, | |
| 375 | - transport: &Transport, | |
| 376 | - rep: &Reporter, | |
| 377 | -) -> Result<String, String> { | |
| 378 | - let repo_id = job.repo_id.clone().ok_or("the repository is gone")?; | |
| 379 | - let repo = state | |
| 380 | - .store | |
| 381 | - .repo_by_id(&repo_id) | |
| 382 | - .await | |
| 383 | - .map_err(|e| e.to_string())? | |
| 384 | - .ok_or("the repository is gone")?; | |
| 385 | - let user = state | |
| 386 | - .store | |
| 387 | - .user_by_id(&job.user_id) | |
| 388 | - .await | |
| 389 | - .map_err(|e| e.to_string())? | |
| 390 | - .ok_or("the importing user is gone")?; | |
| 391 | - | |
| 392 | - rep.stage("git", 0, 0).await; | |
| 393 | - rep.log("info", "Fetching branches and tags").await; | |
| 394 | - fetch_git(state, &repo, spec, transport).await?; | |
| 395 | - let repo = sync_default_branch(state, repo, rep).await; | |
| 396 | - rep.log("info", "Git data imported").await; | |
| 397 | - | |
| 398 | - let (Some(api), true) = (api, spec.options.any_api()) else { | |
| 399 | - return Ok("Import finished".to_owned()); | |
| 400 | - }; | |
| 401 | - let run = Run { | |
| 402 | - state, | |
| 403 | - rep, | |
| 404 | - repo: &repo, | |
| 405 | - user: &user, | |
| 406 | - api, | |
| 407 | - spec, | |
| 408 | - }; | |
| 409 | - let mut totals = Totals::default(); | |
| 410 | - if spec.options.labels { | |
| 411 | - run.labels(&mut totals).await?; | |
| 412 | - run.milestones(&mut totals).await?; | |
| 413 | - } | |
| 414 | - if spec.options.issues || spec.options.pulls { | |
| 415 | - run.issues(&mut totals).await?; | |
| 416 | - } | |
| 417 | - if spec.options.releases { | |
| 418 | - run.releases(&mut totals).await?; | |
| 419 | - } | |
| 420 | - Ok(format!( | |
| 421 | - "Import finished: {} labels, {} milestones, {} issues, {} pull requests, {} comments, {} releases, {} assets{}", | |
| 422 | - totals.labels, | |
| 423 | - totals.milestones, | |
| 424 | - totals.issues, | |
| 425 | - totals.pulls, | |
| 426 | - totals.comments, | |
| 427 | - totals.releases, | |
| 428 | - totals.assets, | |
| 429 | - if totals.skipped > 0 { | |
| 430 | - format!(", {} skipped", totals.skipped) | |
| 431 | - } else { | |
| 432 | - String::new() | |
| 433 | - } | |
| 434 | - )) | |
| 435 | -} | |
| 436 | - | |
| 437 | -async fn fetch_git( | |
| 438 | - state: &AppState, | |
| 439 | - repo: &Repo, | |
| 440 | - spec: &JobSpec, | |
| 441 | - transport: &Transport, | |
| 442 | -) -> Result<(), String> { | |
| 443 | - let repo_dir = | |
| 444 | - forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; | |
| 445 | - let url = spec.clone_url(); | |
| 446 | - let fetch = async { | |
| 447 | - match transport { | |
| 448 | - Transport::Net => { | |
| 449 | - let policy = policy(state); | |
| 450 | - let pin = check_remote(&url, &policy).await?; | |
| 451 | - let auth = spec.auth(); | |
| 452 | - mirror_fetch( | |
| 453 | - &state.git, | |
| 454 | - &repo_dir, | |
| 455 | - &url, | |
| 456 | - auth.as_ref(), | |
| 457 | - policy.allow_http, | |
| 458 | - pin.as_ref(), | |
| 459 | - GIT_TIMEOUT, | |
| 460 | - ) | |
| 461 | - .await | |
| 462 | - .map_err(|e| e.to_string()) | |
| 463 | - } | |
| 464 | - #[cfg(any(test, feature = "test-support"))] | |
| 465 | - Transport::Local(path) => { | |
| 466 | - forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT) | |
| 467 | - .await | |
| 468 | - .map_err(|e| e.to_string()) | |
| 469 | - } | |
| 470 | - } | |
| 471 | - }; | |
| 472 | - pull_refs(state, repo, fetch).await.map(|_| ()) | |
| 473 | -} | |
| 474 | - | |
| 475 | -async fn sync_default_branch(state: &AppState, repo: Repo, rep: &Reporter) -> Repo { | |
| 476 | - let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) else { | |
| 477 | - return repo; | |
| 478 | - }; | |
| 479 | - let head = forge_git::command::GitCommand::new(&state.git, "symbolic-ref") | |
| 480 | - .git_dir(&dir) | |
| 481 | - .arg("--short") | |
| 482 | - .arg("HEAD") | |
| 483 | - .output() | |
| 484 | - .await | |
| 485 | - .ok() | |
| 486 | - .map(|out| String::from_utf8_lossy(&out).trim().to_owned()) | |
| 487 | - .filter(|b| !b.is_empty()); | |
| 488 | - let Some(head) = head else { | |
| 489 | - return repo; | |
| 490 | - }; | |
| 491 | - if head == repo.default_branch { | |
| 492 | - return repo; | |
| 493 | - } | |
| 494 | - if let Err(e) = state | |
| 495 | - .store | |
| 496 | - .update_repo_general(&repo.id, &repo.description, &head) | |
| 497 | - .await | |
| 498 | - { | |
| 499 | - rep.log("warn", format!("could not set the default branch: {e}")) | |
| 500 | - .await; | |
| 501 | - return repo; | |
| 502 | - } | |
| 503 | - state | |
| 504 | - .store | |
| 505 | - .repo_by_id(&repo.id) | |
| 506 | - .await | |
| 507 | - .ok() | |
| 508 | - .flatten() | |
| 509 | - .unwrap_or(repo) | |
| 510 | -} | |
| 511 | - | |
| 512 | -#[derive(Default)] | |
| 513 | -struct Totals { | |
| 514 | - labels: usize, | |
| 515 | - milestones: usize, | |
| 516 | - issues: usize, | |
| 517 | - pulls: usize, | |
| 518 | - comments: usize, | |
| 519 | - releases: usize, | |
| 520 | - assets: usize, | |
| 521 | - skipped: usize, | |
| 522 | -} | |
| 523 | - | |
| 524 | -struct Run<'a, A> { | |
| 525 | - state: &'a AppState, | |
| 526 | - rep: &'a Reporter, | |
| 527 | - repo: &'a Repo, | |
| 528 | - user: &'a User, | |
| 529 | - api: &'a A, | |
| 530 | - spec: &'a JobSpec, | |
| 531 | -} | |
| 532 | - | |
| 533 | -impl<A: RemoteApi> Run<'_, A> { | |
| 534 | - fn store(&self) -> &Store { | |
| 535 | - &self.state.store | |
| 536 | - } | |
| 537 | - | |
| 538 | - fn bump_issues(&self) { | |
| 539 | - self.state.live.bump_repo_issues(&self.repo.id); | |
| 540 | - } | |
| 541 | - | |
| 542 | - async fn mapped(&self, kind: &str, ext: &str) -> Result<Option<ImportOrigin>, String> { | |
| 543 | - self.store() | |
| 544 | - .import_origin(&self.repo.id, kind, ext) | |
| 545 | - .await | |
| 546 | - .map_err(|e| e.to_string()) | |
| 547 | - } | |
| 548 | - | |
| 549 | - async fn record(&self, kind: &str, ext: &str, local: &str, author: &str, url: &str) { | |
| 550 | - let origin = ImportOrigin { | |
| 551 | - local_id: local.to_owned(), | |
| 552 | - author: author.to_owned(), | |
| 553 | - url: url.to_owned(), | |
| 554 | - }; | |
| 555 | - if let Err(e) = self | |
| 556 | - .store() | |
| 557 | - .record_import_origin(&self.repo.id, kind, ext, &origin) | |
| 558 | - .await | |
| 559 | - { | |
| 560 | - tracing::warn!(error = %e, "import: could not record an id mapping"); | |
| 561 | - } | |
| 562 | - } | |
| 563 | - | |
| 564 | - async fn labels(&self, totals: &mut Totals) -> Result<(), String> { | |
| 565 | - self.rep.stage("labels", 0, 0).await; | |
| 566 | - let labels = self | |
| 567 | - .api | |
| 568 | - .labels(&self.spec.remote) | |
| 569 | - .await | |
| 570 | - .map_err(|e| e.to_string())?; | |
| 571 | - let total = labels.len(); | |
| 572 | - for (i, label) in labels.into_iter().enumerate() { | |
| 573 | - self.rep.stage("labels", i, total).await; | |
| 574 | - let key = label.name.to_lowercase(); | |
| 575 | - if self.mapped("label", &key).await?.is_some() { | |
| 576 | - continue; | |
| 577 | - } | |
| 578 | - let description: String = label | |
| 579 | - .description | |
| 580 | - .chars() | |
| 581 | - .take(forge_core::issues::MAX_LABEL_DESCRIPTION) | |
| 582 | - .collect(); | |
| 583 | - match self | |
| 584 | - .store() | |
| 585 | - .create_label(&self.repo.id, &label.name, &label.color, &description) | |
| 586 | - .await | |
| 587 | - { | |
| 588 | - Ok(created) => { | |
| 589 | - self.record("label", &key, &created.id, "", "").await; | |
| 590 | - totals.labels += 1; | |
| 591 | - } | |
| 592 | - Err(forge_core::Error::Conflict(_)) => {} | |
| 593 | - Err(e) => { | |
| 594 | - totals.skipped += 1; | |
| 595 | - self.rep | |
| 596 | - .log("warn", format!("label `{}` skipped: {e}", label.name)) | |
| 597 | - .await; | |
| 598 | - } | |
| 599 | - } | |
| 600 | - } | |
| 601 | - self.bump_issues(); | |
| 602 | - self.rep.log("info", format!("{total} labels read")).await; | |
| 603 | - Ok(()) | |
| 604 | - } | |
| 605 | - | |
| 606 | - async fn milestones(&self, totals: &mut Totals) -> Result<(), String> { | |
| 607 | - self.rep.stage("milestones", 0, 0).await; | |
| 608 | - let items = self | |
| 609 | - .api | |
| 610 | - .milestones(&self.spec.remote) | |
| 611 | - .await | |
| 612 | - .map_err(|e| e.to_string())?; | |
| 613 | - let total = items.len(); | |
| 614 | - for (i, m) in items.into_iter().enumerate() { | |
| 615 | - self.rep.stage("milestones", i, total).await; | |
| 616 | - if self.mapped("milestone", &m.id).await?.is_some() { | |
| 617 | - continue; | |
| 618 | - } | |
| 619 | - let created = match self | |
| 620 | - .store() | |
| 621 | - .create_milestone(&self.repo.id, &m.title, &m.description, m.due_on.as_deref()) | |
| 622 | - .await | |
| 623 | - { | |
| 624 | - Ok(created) => created, | |
| 625 | - Err(e) => { | |
| 626 | - totals.skipped += 1; | |
| 627 | - self.rep | |
| 628 | - .log("warn", format!("milestone `{}` skipped: {e}", m.title)) | |
| 629 | - .await; | |
| 630 | - continue; | |
| 631 | - } | |
| 632 | - }; | |
| 633 | - if m.closed | |
| 634 | - && let Err(e) = self | |
| 635 | - .store() | |
| 636 | - .update_milestone( | |
| 637 | - &self.repo.id, | |
| 638 | - &created.id, | |
| 639 | - &created.title, | |
| 640 | - &created.description, | |
| 641 | - created.due_on.as_deref(), | |
| 642 | - IssueState::Closed, | |
| 643 | - ) | |
| 644 | - .await | |
| 645 | - { | |
| 646 | - self.rep | |
| 647 | - .log("warn", format!("milestone `{}` stays open: {e}", m.title)) | |
| 648 | - .await; | |
| 649 | - } | |
| 650 | - self.record("milestone", &m.id, &created.id, "", "").await; | |
| 651 | - totals.milestones += 1; | |
| 652 | - } | |
| 653 | - self.bump_issues(); | |
| 654 | - Ok(()) | |
| 655 | - } | |
| 656 | - | |
| 657 | - async fn label_id( | |
| 658 | - &self, | |
| 659 | - cache: &mut HashMap<String, String>, | |
| 660 | - name: &str, | |
| 661 | - color: &str, | |
| 662 | - ) -> Option<String> { | |
| 663 | - let key = name.trim().to_lowercase(); | |
| 664 | - if let Some(id) = cache.get(&key) { | |
| 665 | - return Some(id.clone()); | |
| 666 | - } | |
| 667 | - match self | |
| 668 | - .store() | |
| 669 | - .create_label(&self.repo.id, name, color, "") | |
| 670 | - .await | |
| 671 | - { | |
| 672 | - Ok(label) => { | |
| 673 | - cache.insert(key, label.id.clone()); | |
| 674 | - Some(label.id) | |
| 675 | - } | |
| 676 | - Err(e) => { | |
| 677 | - self.rep | |
| 678 | - .log("warn", format!("label `{name}` not set: {e}")) | |
| 679 | - .await; | |
| 680 | - None | |
| 681 | - } | |
| 682 | - } | |
| 683 | - } | |
| 684 | - | |
| 685 | - async fn issues(&self, totals: &mut Totals) -> Result<(), String> { | |
| 686 | - self.rep.stage("issues", 0, 0).await; | |
| 687 | - let mut items: Vec<ExtIssue> = self | |
| 688 | - .api | |
| 689 | - .issues(&self.spec.remote) | |
| 690 | - .await | |
| 691 | - .map_err(|e| e.to_string())? | |
| 692 | - .into_iter() | |
| 693 | - .filter(|i| { | |
| 694 | - if i.is_pr { | |
| 695 | - self.spec.options.pulls | |
| 696 | - } else { | |
| 697 | - self.spec.options.issues | |
| 698 | - } | |
| 699 | - }) | |
| 700 | - .collect(); | |
| 701 | - if matches!(self.spec.source, Source::GitHub | Source::Forgejo) { | |
| 702 | - items.sort_by_key(|i| i.number); | |
| 703 | - } else { | |
| 704 | - items.sort_by_key(|i| (i.is_pr, i.number)); | |
| 705 | - } | |
| 706 | - let total = items.len(); | |
| 707 | - let mut labels: HashMap<String, String> = self | |
| 708 | - .store() | |
| 709 | - .list_labels(&self.repo.id) | |
| 710 | - .await | |
| 711 | - .map_err(|e| e.to_string())? | |
| 712 | - .into_iter() | |
| 713 | - .map(|l| (l.name.to_lowercase(), l.id)) | |
| 714 | - .collect(); | |
| 715 | - let milestones: HashMap<String, String> = self | |
| 716 | - .store() | |
| 717 | - .list_milestones(&self.repo.id, None) | |
| 718 | - .await | |
| 719 | - .map_err(|e| e.to_string())? | |
| 720 | - .into_iter() | |
| 721 | - .map(|m| (m.title.to_lowercase(), m.id)) | |
| 722 | - .collect(); | |
| 723 | - self.rep | |
| 724 | - .log( | |
| 725 | - "info", | |
| 726 | - format!("Importing {total} issues and pull requests"), | |
| 727 | - ) | |
| 728 | - .await; | |
| 729 | - let mut created_since_bump = 0usize; | |
| 730 | - for (i, item) in items.iter().enumerate() { | |
| 731 | - self.rep.stage("issues", i, total).await; | |
| 732 | - let kind = if item.is_pr { "pull" } else { "issue" }; | |
| 733 | - let ext = item.number.to_string(); | |
| 734 | - let local = match self.mapped(kind, &ext).await? { | |
| 735 | - Some(o) => o.local_id, | |
| 736 | - None => match self.create_item(item, &mut labels, &milestones).await { | |
| 737 | - Ok(id) => { | |
| 738 | - created_since_bump += 1; | |
| 739 | - if created_since_bump == IMPORT_BUMP_BATCH { | |
| 740 | - created_since_bump = 0; | |
| 741 | - self.bump_issues(); | |
| 742 | - } | |
| 743 | - if item.is_pr { | |
| 744 | - totals.pulls += 1; | |
| 745 | - } else { | |
| 746 | - totals.issues += 1; | |
| 747 | - } | |
| 748 | - id | |
| 749 | - } | |
| 750 | - Err(e) => { | |
| 751 | - totals.skipped += 1; | |
| 752 | - self.rep | |
| 753 | - .log("warn", format!("#{} skipped: {e}", item.number)) | |
| 754 | - .await; | |
| 755 | - continue; | |
| 756 | - } | |
| 757 | - }, | |
| 758 | - }; | |
| 759 | - self.import_comments(kind, &local, item, totals).await?; | |
| 760 | - } | |
| 761 | - self.rep.stage("issues", total, total).await; | |
| 762 | - self.bump_issues(); | |
| 763 | - Ok(()) | |
| 764 | - } | |
| 765 | - | |
| 766 | - async fn import_comments( | |
| 767 | - &self, | |
| 768 | - kind: &str, | |
| 769 | - local: &str, | |
| 770 | - item: &ExtIssue, | |
| 771 | - totals: &mut Totals, | |
| 772 | - ) -> Result<(), String> { | |
| 773 | - let comments = self | |
| 774 | - .api | |
| 775 | - .comments(&self.spec.remote, item) | |
| 776 | - .await | |
| 777 | - .map_err(|e| e.to_string())?; | |
| 778 | - for c in comments { | |
| 779 | - if self | |
| 780 | - .mapped("comment", &format!("{kind}:{}", c.id)) | |
| 781 | - .await? | |
| 782 | - .is_some() | |
| 783 | - { | |
| 784 | - continue; | |
| 785 | - } | |
| 786 | - let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url); | |
| 787 | - let body = with_note(¬e, &c.body); | |
| 788 | - match self.store().add_comment(local, &self.user.id, &body).await { | |
| 789 | - Ok(created) => { | |
| 790 | - self.record( | |
| 791 | - "comment", | |
| 792 | - &format!("{kind}:{}", c.id), | |
| 793 | - &created.id, | |
| 794 | - &c.author, | |
| 795 | - &c.url, | |
| 796 | - ) | |
| 797 | - .await; | |
| 798 | - totals.comments += 1; | |
| 799 | - } | |
| 800 | - Err(e) => { | |
| 801 | - totals.skipped += 1; | |
| 802 | - self.rep | |
| 803 | - .log( | |
| 804 | - "warn", | |
| 805 | - format!("a comment on #{} skipped: {e}", item.number), | |
| 806 | - ) | |
| 807 | - .await; | |
| 808 | - } | |
| 809 | - } | |
| 810 | - } | |
| 811 | - Ok(()) | |
| 812 | - } | |
| 813 | - | |
| 814 | - async fn create_item( | |
| 815 | - &self, | |
| 816 | - item: &ExtIssue, | |
| 817 | - labels: &mut HashMap<String, String>, | |
| 818 | - milestones: &HashMap<String, String>, | |
| 819 | - ) -> Result<String, forge_core::Error> { | |
| 820 | - let source = self.spec.source.label(); | |
| 821 | - let mut note = origin_note(source, &item.author, &item.created_at, &item.url); | |
| 822 | - if item.is_pr { | |
| 823 | - let how = if item.merged { | |
| 824 | - "merged" | |
| 825 | - } else if item.closed { | |
| 826 | - "closed" | |
| 827 | - } else { | |
| 828 | - "open" | |
| 829 | - }; | |
| 830 | - note.push_str(&format!( | |
| 831 | - "> Imported pull request ({how}). Its branches may no longer exist, so there is nothing to merge here.\n\n" | |
| 832 | - )); | |
| 833 | - } | |
| 834 | - let body = with_note(¬e, &item.body); | |
| 835 | - let issue = self | |
| 836 | - .store() | |
| 837 | - .create_issue( | |
| 838 | - &self.repo.id, | |
| 839 | - &self.user.id, | |
| 840 | - &clip_title(&item.title), | |
| 841 | - &body, | |
| 842 | - ) | |
| 843 | - .await?; | |
| 844 | - let kind = if item.is_pr { "pull" } else { "issue" }; | |
| 845 | - self.record( | |
| 846 | - kind, | |
| 847 | - &item.number.to_string(), | |
| 848 | - &issue.id, | |
| 849 | - &item.author, | |
| 850 | - &item.url, | |
| 851 | - ) | |
| 852 | - .await; | |
| 853 | - let mut ids = Vec::new(); | |
| 854 | - for name in &item.labels { | |
| 855 | - if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await { | |
| 856 | - ids.push(id); | |
| 857 | - } | |
| 858 | - } | |
| 859 | - if item.is_pr | |
| 860 | - && let Some(id) = self | |
| 861 | - .label_id(labels, IMPORTED_PR_LABEL, IMPORTED_PR_COLOR) | |
| 862 | - .await | |
| 863 | - { | |
| 864 | - ids.push(id); | |
| 865 | - } | |
| 866 | - if !ids.is_empty() { | |
| 867 | - self.store() | |
| 868 | - .set_issue_labels(&issue.id, &self.user.id, &ids) | |
| 869 | - .await?; | |
| 870 | - } | |
| 871 | - if let Some(id) = item | |
| 872 | - .milestone | |
| 873 | - .as_ref() | |
| 874 | - .and_then(|t| milestones.get(&t.to_lowercase())) | |
| 875 | - { | |
| 876 | - self.store() | |
| 877 | - .set_issue_milestone(&issue.id, &self.user.id, Some(id)) | |
| 878 | - .await?; | |
| 879 | - } | |
| 880 | - if item.closed { | |
| 881 | - let reason = if item.not_planned { | |
| 882 | - StateReason::NotPlanned | |
| 883 | - } else { | |
| 884 | - StateReason::Completed | |
| 885 | - }; | |
| 886 | - self.store() | |
| 887 | - .set_issue_state( | |
| 888 | - &issue.id, | |
| 889 | - Some(&self.user.id), | |
| 890 | - IssueState::Closed, | |
| 891 | - Some(reason), | |
| 892 | - serde_json::Value::Null, | |
| 893 | - ) | |
| 894 | - .await?; | |
| 895 | - } | |
| 896 | - Ok(issue.id) | |
| 897 | - } | |
| 898 | - | |
| 899 | - async fn releases(&self, totals: &mut Totals) -> Result<(), String> { | |
| 900 | - self.rep.stage("releases", 0, 0).await; | |
| 901 | - let releases = self | |
| 902 | - .api | |
| 903 | - .releases(&self.spec.remote) | |
| 904 | - .await | |
| 905 | - .map_err(|e| e.to_string())?; | |
| 906 | - let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id) | |
| 907 | - .map_err(|e| e.to_string())?; | |
| 908 | - let refs = ref_snapshot(self.state, &repo_dir).await?; | |
| 909 | - let max_bytes = self.state.live().releases.max_asset_mb * 1024 * 1024; | |
| 910 | - let total = releases.len(); | |
| 911 | - for (i, rel) in releases.iter().enumerate() { | |
| 912 | - self.rep.stage("releases", i, total).await; | |
| 913 | - let Some(release) = self.release_of(rel, &refs, totals).await? else { | |
| 914 | - continue; | |
| 915 | - }; | |
| 916 | - for asset in &rel.assets { | |
| 917 | - self.asset(&release, rel, asset, max_bytes, totals).await?; | |
| 918 | - } | |
| 919 | - } | |
| 920 | - self.rep.stage("releases", total, total).await; | |
| 921 | - Ok(()) | |
| 922 | - } | |
| 923 | - | |
| 924 | - async fn release_of( | |
| 925 | - &self, | |
| 926 | - rel: &ExtRelease, | |
| 927 | - refs: &std::collections::BTreeMap<String, String>, | |
| 928 | - totals: &mut Totals, | |
| 929 | - ) -> Result<Option<forge_core::releases::Release>, String> { | |
| 930 | - if let Some(o) = self.mapped("release", &rel.id).await? { | |
| 931 | - let found = self | |
| 932 | - .store() | |
| 933 | - .release(&o.local_id) | |
| 934 | - .await | |
| 935 | - .map_err(|e| e.to_string())?; | |
| 936 | - if found.is_none() { | |
| 937 | - totals.skipped += 1; | |
| 938 | - self.rep | |
| 939 | - .log( | |
| 940 | - "warn", | |
| 941 | - format!("release `{}` skipped: it was deleted here", rel.tag), | |
| 942 | - ) | |
| 943 | - .await; | |
| 944 | - } | |
| 945 | - return Ok(found); | |
| 946 | - } | |
| 947 | - let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else { | |
| 948 | - totals.skipped += 1; | |
| 949 | - self.rep | |
| 950 | - .log( | |
| 951 | - "warn", | |
| 952 | - format!( | |
| 953 | - "release `{}` skipped: its tag is not in the git data", | |
| 954 | - rel.tag | |
| 955 | - ), | |
| 956 | - ) | |
| 957 | - .await; | |
| 958 | - return Ok(None); | |
| 959 | - }; | |
| 960 | - if let Some(existing) = self | |
| 961 | - .store() | |
| 962 | - .release_by_tag(&self.repo.id, &rel.tag) | |
| 963 | - .await | |
| 964 | - .map_err(|e| e.to_string())? | |
| 965 | - { | |
| 966 | - self.record("release", &rel.id, &existing.id, &rel.author, &rel.url) | |
| 967 | - .await; | |
| 968 | - return Ok(Some(existing)); | |
| 969 | - } | |
| 970 | - let note = origin_note( | |
| 971 | - self.spec.source.label(), | |
| 972 | - &rel.author, | |
| 973 | - &rel.created_at, | |
| 974 | - &rel.url, | |
| 975 | - ); | |
| 976 | - let body = with_note(¬e, &rel.body); | |
| 977 | - let title = clip_title(&rel.title); | |
| 978 | - let created = self | |
| 979 | - .store() | |
| 980 | - .create_release(&NewRelease { | |
| 981 | - repo_id: &self.repo.id, | |
| 982 | - tag: &rel.tag, | |
| 983 | - target_oid: oid, | |
| 984 | - title: &title, | |
| 985 | - body: &body, | |
| 986 | - draft: rel.draft, | |
| 987 | - prerelease: rel.prerelease, | |
| 988 | - author_id: &self.user.id, | |
| 989 | - }) | |
| 990 | - .await; | |
| 991 | - match created { | |
| 992 | - Ok(release) => { | |
| 993 | - self.record("release", &rel.id, &release.id, &rel.author, &rel.url) | |
| 994 | - .await; | |
| 995 | - totals.releases += 1; | |
| 996 | - Ok(Some(release)) | |
| 997 | - } | |
| 998 | - Err(e) => { | |
| 999 | - totals.skipped += 1; | |
| 1000 | - self.rep | |
| 1001 | - .log("warn", format!("release `{}` skipped: {e}", rel.tag)) | |
| 1002 | - .await; | |
| 1003 | - Ok(None) | |
| 1004 | - } | |
| 1005 | - } | |
| 1006 | - } | |
| 1007 | - | |
| 1008 | - async fn asset( | |
| 1009 | - &self, | |
| 1010 | - release: &forge_core::releases::Release, | |
| 1011 | - rel: &ExtRelease, | |
| 1012 | - asset: &ExtAsset, | |
| 1013 | - max_bytes: u64, | |
| 1014 | - totals: &mut Totals, | |
| 1015 | - ) -> Result<(), String> { | |
| 1016 | - let ext = format!("{}:{}", rel.id, asset.id); | |
| 1017 | - if self.mapped("asset", &ext).await?.is_some() { | |
| 1018 | - return Ok(()); | |
| 1019 | - } | |
| 1020 | - if asset.size > max_bytes { | |
| 1021 | - totals.skipped += 1; | |
| 1022 | - self.rep | |
| 1023 | - .log( | |
| 1024 | - "warn", | |
| 1025 | - format!( | |
| 1026 | - "asset `{}` skipped: larger than the upload limit", | |
| 1027 | - asset.name | |
| 1028 | - ), | |
| 1029 | - ) | |
| 1030 | - .await; | |
| 1031 | - return Ok(()); | |
| 1032 | - } | |
| 1033 | - self.rep | |
| 1034 | - .log("info", format!("Downloading asset {}", asset.name)) | |
| 1035 | - .await; | |
| 1036 | - let stream = match self.api.download(asset, max_bytes).await { | |
| 1037 | - Ok(stream) => stream, | |
| 1038 | - Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => { | |
| 1039 | - return Err(e.to_string()); | |
| 1040 | - } | |
| 1041 | - Err(e) => { | |
| 1042 | - totals.skipped += 1; | |
| 1043 | - self.rep | |
| 1044 | - .log("warn", format!("asset `{}` skipped: {e}", asset.name)) | |
| 1045 | - .await; | |
| 1046 | - return Ok(()); | |
| 1047 | - } | |
| 1048 | - }; | |
| 1049 | - let name = asset_name(&asset.name); | |
| 1050 | - let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str()); | |
| 1051 | - match crate::release_ops::put_asset( | |
| 1052 | - self.state, | |
| 1053 | - self.repo, | |
| 1054 | - release, | |
| 1055 | - self.user, | |
| 1056 | - &name, | |
| 1057 | - content_type, | |
| 1058 | - stream, | |
| 1059 | - max_bytes, | |
| 1060 | - ) | |
| 1061 | - .await | |
| 1062 | - { | |
| 1063 | - Ok((stored, _)) => { | |
| 1064 | - self.record("asset", &ext, &stored.id, &rel.author, &asset.url) | |
| 1065 | - .await; | |
| 1066 | - totals.assets += 1; | |
| 1067 | - } | |
| 1068 | - Err(e) => { | |
| 1069 | - totals.skipped += 1; | |
| 1070 | - self.rep | |
| 1071 | - .log( | |
| 1072 | - "warn", | |
| 1073 | - format!("asset `{}` skipped: {}", asset.name, e.message()), | |
| 1074 | - ) | |
| 1075 | - .await; | |
| 1076 | - } | |
| 1077 | - } | |
| 1078 | - Ok(()) | |
| 1079 | - } | |
| 1080 | -} | |
| 1081 | - | |
| 1082 | -pub async fn on_boot(state: &AppState) { | |
| 1083 | - match state.store.fail_interrupted_imports().await { | |
| 1084 | - Ok(0) => {} | |
| 1085 | - Ok(n) => tracing::warn!(count = n, "import: marked interrupted jobs as failed"), | |
| 1086 | - Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"), | |
| 1087 | - } | |
| 1088 | -} |
crates/forge-web-app/src/importer/remote.rsdeleted+0 -174
| @@ -1,174 +0,0 @@ | ||
| 1 | -use std::time::Duration; | |
| 2 | - | |
| 3 | -use super::Source; | |
| 4 | -use super::api::{self, Auth, Forgejo, GitHub, GitLab, Http, Notice}; | |
| 5 | -use crate::mirrors::policy; | |
| 6 | -use crate::state::AppState; | |
| 7 | -use crate::webhooks::client::{policy_client, validate_url}; | |
| 8 | - | |
| 9 | -fn client(state: &AppState) -> Result<reqwest::Client, String> { | |
| 10 | - policy_client(policy(state), Duration::from_secs(60), "forge-import/1") | |
| 11 | - .map_err(|e| format!("could not build the HTTP client: {e}")) | |
| 12 | -} | |
| 13 | - | |
| 14 | -fn instance_host<'a>(state: &AppState, instance: &'a str) -> Result<(&'a str, String), String> { | |
| 15 | - let instance = instance.trim_end_matches('/'); | |
| 16 | - let host = validate_url(instance, &policy(state)) | |
| 17 | - .map_err(|e| format!("instance address refused: {e}"))? | |
| 18 | - .host_str() | |
| 19 | - .unwrap_or_default() | |
| 20 | - .to_ascii_lowercase(); | |
| 21 | - Ok((instance, host)) | |
| 22 | -} | |
| 23 | - | |
| 24 | -pub fn make_github( | |
| 25 | - state: &AppState, | |
| 26 | - token: Option<String>, | |
| 27 | - notice: Notice, | |
| 28 | -) -> Result<GitHub, String> { | |
| 29 | - let client = client(state)?; | |
| 30 | - Ok(GitHub::new(Http::new( | |
| 31 | - client, | |
| 32 | - policy(state), | |
| 33 | - token, | |
| 34 | - Auth::GitHub, | |
| 35 | - "api.github.com".into(), | |
| 36 | - notice, | |
| 37 | - ))) | |
| 38 | -} | |
| 39 | - | |
| 40 | -pub fn make_gitlab( | |
| 41 | - state: &AppState, | |
| 42 | - instance: &str, | |
| 43 | - token: Option<String>, | |
| 44 | - notice: Notice, | |
| 45 | -) -> Result<GitLab, String> { | |
| 46 | - let (instance, host) = instance_host(state, instance)?; | |
| 47 | - let client = client(state)?; | |
| 48 | - Ok(GitLab::new( | |
| 49 | - Http::new(client, policy(state), token, Auth::GitLab, host, notice), | |
| 50 | - instance, | |
| 51 | - )) | |
| 52 | -} | |
| 53 | - | |
| 54 | -pub fn make_forgejo( | |
| 55 | - state: &AppState, | |
| 56 | - instance: &str, | |
| 57 | - token: Option<String>, | |
| 58 | - notice: Notice, | |
| 59 | -) -> Result<Forgejo, String> { | |
| 60 | - let (instance, host) = instance_host(state, instance)?; | |
| 61 | - let client = client(state)?; | |
| 62 | - Ok(Forgejo::new( | |
| 63 | - Http::new(client, policy(state), token, Auth::Forgejo, host, notice), | |
| 64 | - instance, | |
| 65 | - )) | |
| 66 | -} | |
| 67 | - | |
| 68 | -pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> { | |
| 69 | - let text = text.trim(); | |
| 70 | - match source { | |
| 71 | - Source::Git => (text.starts_with("https://") || text.starts_with("http://")) | |
| 72 | - .then(|| (text.to_owned(), String::new())), | |
| 73 | - Source::GitHub => { | |
| 74 | - let path = text | |
| 75 | - .strip_prefix("https://github.com/") | |
| 76 | - .unwrap_or(text) | |
| 77 | - .trim_end_matches('/'); | |
| 78 | - let path = path.strip_suffix(".git").unwrap_or(path); | |
| 79 | - api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new())) | |
| 80 | - } | |
| 81 | - Source::GitLab | Source::Forgejo => { | |
| 82 | - let max = if source == Source::GitLab { 20 } else { 2 }; | |
| 83 | - if let Some((scheme, rest)) = text | |
| 84 | - .strip_prefix("https://") | |
| 85 | - .map(|r| ("https", r)) | |
| 86 | - .or_else(|| text.strip_prefix("http://").map(|r| ("http", r))) | |
| 87 | - { | |
| 88 | - let (host, path) = rest.split_once('/')?; | |
| 89 | - let path = path.trim_end_matches('/'); | |
| 90 | - let path = path.strip_suffix(".git").unwrap_or(path); | |
| 91 | - if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, max) { | |
| 92 | - return None; | |
| 93 | - } | |
| 94 | - return Some((path.to_owned(), format!("{scheme}://{host}"))); | |
| 95 | - } | |
| 96 | - let instance = instance.trim().trim_end_matches('/'); | |
| 97 | - let path = text.trim_matches('/'); | |
| 98 | - let path = path.strip_suffix(".git").unwrap_or(path); | |
| 99 | - let host = instance | |
| 100 | - .strip_prefix("https://") | |
| 101 | - .or_else(|| instance.strip_prefix("http://"))?; | |
| 102 | - let ok = !host.is_empty() | |
| 103 | - && !host.contains('@') | |
| 104 | - && !host.contains('/') | |
| 105 | - && api::valid_path(path, 2, max); | |
| 106 | - ok.then(|| (path.to_owned(), instance.to_owned())) | |
| 107 | - } | |
| 108 | - } | |
| 109 | -} | |
| 110 | - | |
| 111 | -pub fn source_ref(source: Source, remote: &str, instance: &str) -> String { | |
| 112 | - match source { | |
| 113 | - Source::GitLab | Source::Forgejo => { | |
| 114 | - format!("{}/{}", instance.trim_end_matches('/'), remote) | |
| 115 | - } | |
| 116 | - _ => remote.to_owned(), | |
| 117 | - } | |
| 118 | -} | |
| 119 | - | |
| 120 | -pub fn default_name(remote: &str) -> String { | |
| 121 | - remote | |
| 122 | - .trim_end_matches('/') | |
| 123 | - .rsplit('/') | |
| 124 | - .next() | |
| 125 | - .unwrap_or_default() | |
| 126 | - .trim_end_matches(".git") | |
| 127 | - .to_owned() | |
| 128 | -} | |
| 129 | - | |
| 130 | -#[cfg(test)] | |
| 131 | -mod tests { | |
| 132 | - use super::*; | |
| 133 | - | |
| 134 | - #[test] | |
| 135 | - fn github_accepts_owner_name_or_url() { | |
| 136 | - let ok = |t: &str| parse_remote(Source::GitHub, t, "").map(|r| r.0); | |
| 137 | - assert_eq!(ok("tahinli/forge").as_deref(), Some("tahinli/forge")); | |
| 138 | - assert_eq!( | |
| 139 | - ok("https://github.com/tahinli/forge.git").as_deref(), | |
| 140 | - Some("tahinli/forge") | |
| 141 | - ); | |
| 142 | - assert_eq!(ok("tahinli").as_deref(), None); | |
| 143 | - assert_eq!(ok("a/b/c").as_deref(), None); | |
| 144 | - assert_eq!(ok("../etc").as_deref(), None); | |
| 145 | - } | |
| 146 | - | |
| 147 | - #[test] | |
| 148 | - fn gitlab_takes_a_url_or_a_path_with_an_instance() { | |
| 149 | - let url = parse_remote(Source::GitLab, "https://gl.example.org/grp/sub/proj", ""); | |
| 150 | - assert_eq!( | |
| 151 | - url, | |
| 152 | - Some(("grp/sub/proj".into(), "https://gl.example.org".into())) | |
| 153 | - ); | |
| 154 | - let bare = parse_remote(Source::GitLab, "grp/proj", "https://gitlab.com/"); | |
| 155 | - assert_eq!(bare, Some(("grp/proj".into(), "https://gitlab.com".into()))); | |
| 156 | - assert_eq!(parse_remote(Source::GitLab, "grp/proj", ""), None); | |
| 157 | - assert_eq!( | |
| 158 | - parse_remote(Source::GitLab, "https://u:p@host/a/b", ""), | |
| 159 | - None | |
| 160 | - ); | |
| 161 | - } | |
| 162 | - | |
| 163 | - #[test] | |
| 164 | - fn git_needs_http_scheme_and_names_default_from_the_path() { | |
| 165 | - assert!(parse_remote(Source::Git, "file:///etc", "").is_none()); | |
| 166 | - assert!(parse_remote(Source::Git, "https://example.org/x/y.git", "").is_some()); | |
| 167 | - assert_eq!(default_name("https://example.org/x/y.git"), "y"); | |
| 168 | - assert_eq!(default_name("grp/proj"), "proj"); | |
| 169 | - assert_eq!( | |
| 170 | - source_ref(Source::GitLab, "g/p", "https://gitlab.com"), | |
| 171 | - "https://gitlab.com/g/p" | |
| 172 | - ); | |
| 173 | - } | |
| 174 | -} |
crates/forge-web-app/src/lib.rsmodified+0 -2
| @@ -15,11 +15,9 @@ pub mod automerge; | ||
| 15 | 15 | pub mod backup; |
| 16 | 16 | pub mod ci; |
| 17 | 17 | pub mod client_ip; |
| 18 | -pub mod exporter; | |
| 19 | 18 | pub mod git_auth; |
| 20 | 19 | pub mod git_http; |
| 21 | 20 | pub mod hook_cmd; |
| 22 | -pub mod importer; | |
| 23 | 21 | pub mod internal; |
| 24 | 22 | pub mod layers; |
| 25 | 23 | pub mod lfs; |
crates/forge-web-app/src/live.rsmodified+0 -1
| @@ -25,7 +25,6 @@ pub enum Topic { | ||
| 25 | 25 | User(String), |
| 26 | 26 | Inbox(String), |
| 27 | 27 | ReviewRequests(String), |
| 28 | - Imports(String), | |
| 29 | 28 | Explore, |
| 30 | 29 | Org(String), |
| 31 | 30 | AdminUsers, |
crates/forge-web-app/src/views/mod.rsmodified+0 -4
| @@ -37,7 +37,6 @@ use crate::i18n::authoring::{self as au, K as AuK}; | ||
| 37 | 37 | use crate::i18n::browse as br; |
| 38 | 38 | use crate::i18n::code::{self as g, K}; |
| 39 | 39 | use crate::i18n::link::{self as lk, K as LinkKey}; |
| 40 | -use crate::i18n::migrate::{self as mg, K as MGK}; | |
| 41 | 40 | use crate::i18n::misc::{self as mi, K as MK}; |
| 42 | 41 | use crate::i18n::orgs::{self as o, K as OK}; |
| 43 | 42 | use crate::i18n::s; |
| @@ -101,7 +100,6 @@ const TOP_LEVEL_PAGES: &[&str] = &[ | ||
| 101 | 100 | "logout", |
| 102 | 101 | "register", |
| 103 | 102 | "forgot", |
| 104 | - "import", | |
| 105 | 103 | "review-requests", |
| 106 | 104 | "setup", |
| 107 | 105 | "needs-you", |
| @@ -865,7 +863,6 @@ pub fn global_items(lang: Lang, can_create_org: bool) -> Vec<NavItem> { | ||
| 865 | 863 | crate::i18n::needs::t(lang, crate::i18n::needs::K::NeedsYou), |
| 866 | 864 | ), |
| 867 | 865 | item("new", "/new", t(lang, Key::NewRepository)), |
| 868 | - item("import", "/new/import", mg::t(lang, MGK::ImportTitle)), | |
| 869 | 866 | ]; |
| 870 | 867 | if can_create_org { |
| 871 | 868 | items.push(item("new-org", "/org/new", o::t(lang, OK::NewOrganization))); |
| @@ -894,7 +891,6 @@ pub fn settings_items(lang: Lang) -> Vec<NavItem> { | ||
| 894 | 891 | ), |
| 895 | 892 | item("security", "/settings/security", t(lang, Key::Security)), |
| 896 | 893 | item("keys", "/settings/keys", pk(lang, "Keys", "Anahtarlar")), |
| 897 | - item("export", "/settings/export", pk(lang, "Data", "Veri")), | |
| 898 | 894 | ] |
| 899 | 895 | } |
| 900 | 896 |
crates/forge-web-base/src/i18n/audit_names.rsmodified+0 -2
| @@ -308,8 +308,6 @@ pub fn detail_key_name(lang: Lang, key: &str) -> Option<&'static str> { | ||
| 308 | 308 | ("members_can_create_repos", Lang::Tr) => Some("üyeler depo oluşturabilir"), |
| 309 | 309 | ("invite", Lang::En) => Some("invite"), |
| 310 | 310 | ("invite", Lang::Tr) => Some("davet"), |
| 311 | - ("import", Lang::En) => Some("import"), | |
| 312 | - ("import", Lang::Tr) => Some("içe aktarma"), | |
| 313 | 311 | ("host", Lang::En) => Some("host"), |
| 314 | 312 | ("host", Lang::Tr) => Some("sunucu adresi"), |
| 315 | 313 | ("fork_of", Lang::En) => Some("fork of"), |
crates/forge-web-base/src/i18n/migrate.rsdeleted+0 -119
| @@ -1,119 +0,0 @@ | ||
| 1 | -use super::Lang; | |
| 2 | - | |
| 3 | -strings! { | |
| 4 | - K; | |
| 5 | - TabCreate => "Create", "Oluştur"; | |
| 6 | - TabImport => "Import", "İçe aktar"; | |
| 7 | - ImportTitle => "Import a repository", "Depo içe aktar"; | |
| 8 | - SrcGit => "Git URL", "Git URL'si"; | |
| 9 | - SrcGitHub => "GitHub", "GitHub"; | |
| 10 | - SrcGitLab => "GitLab", "GitLab"; | |
| 11 | - SrcForgejo => "Forgejo / Gitea", "Forgejo / Gitea"; | |
| 12 | - GitUrl => "Repository URL", "Depo URL'si"; | |
| 13 | - GitUser => "Username (optional)", "Kullanıcı adı (isteğe bağlı)"; | |
| 14 | - GitPassword => "Password or token (optional)", "Parola veya belirteç (isteğe bağlı)"; | |
| 15 | - GitHubRepo => "Repository (owner/name)", "Depo (sahip/ad)"; | |
| 16 | - GitLabInstance => "GitLab address", "GitLab adresi"; | |
| 17 | - GitLabProject => "Project path", "Proje yolu"; | |
| 18 | - ForgejoInstance => "Forgejo or Gitea address (Codeberg works too)", "Forgejo veya Gitea adresi (Codeberg da olur)"; | |
| 19 | - TokenOptional => "Access token (optional)", "Erişim belirteci (isteğe bağlı)"; | |
| 20 | - TargetOwner => "Owner", "Sahip"; | |
| 21 | - TargetName => "New repository name", "Yeni depo adı"; | |
| 22 | - Description => "Description (optional)", "Açıklama (isteğe bağlı)"; | |
| 23 | - WhatToImport => "Also import", "Şunları da içe aktar"; | |
| 24 | - OptLabels => "Labels and milestones", "Etiketler ve kilometre taşları"; | |
| 25 | - OptIssues => "Issues and comments", "Konular ve yorumlar"; | |
| 26 | - OptPulls => "Pull requests (as issues)", "Çekme istekleri (konu olarak)"; | |
| 27 | - OptReleases => "Releases and their files", "Sürümler ve dosyaları"; | |
| 28 | - StartImport => "Start import", "İçe aktarmayı başlat"; | |
| 29 | - BulkLink => "Import several repositories", "Birden çok depoyu içe aktar"; | |
| 30 | - BulkLinkButton => "Choose repositories", "Depoları seç"; | |
| 31 | - BulkTitle => "Import several repositories", "Birden çok depoyu içe aktar"; | |
| 32 | - BulkOwnerGitHub => "GitHub user or organization", "GitHub kullanıcısı veya kuruluşu"; | |
| 33 | - 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)"; | |
| 34 | - BulkOwnerGitLab => "GitLab user or group", "GitLab kullanıcısı veya grubu"; | |
| 35 | - BulkListButton => "List repositories", "Depoları listele"; | |
| 36 | - BulkSelectHeading => "Select the repositories to import", "İçe aktarılacak depoları seçin"; | |
| 37 | - BulkSelectAll => "Select all", "Tümünü seç"; | |
| 38 | - BulkImportSelected => "Import selected", "Seçilenleri içe aktar"; | |
| 39 | - BulkNone => "No repositories found.", "Depo bulunamadı."; | |
| 40 | - BulkPrivate => "private", "özel"; | |
| 41 | - BulkFork => "fork", "çatal"; | |
| 42 | - BulkArchived => "archived", "arşivlenmiş"; | |
| 43 | - JobsTitle => "Import history", "İçe aktarma geçmişi"; | |
| 44 | - NoJobs => "No imports yet.", "Henüz içe aktarma yok."; | |
| 45 | - JobQueued => "Queued", "Sırada"; | |
| 46 | - JobRunning => "Running", "Çalışıyor"; | |
| 47 | - JobDone => "Done", "Bitti"; | |
| 48 | - JobFailed => "Failed", "Başarısız"; | |
| 49 | - JobRetry => "Retry", "Yeniden dene"; | |
| 50 | - JobOpenRepo => "Open repository", "Depoyu aç"; | |
| 51 | - JobProgress => "Progress", "İlerleme"; | |
| 52 | - JobNoLog => "Nothing yet.", "Henüz bir şey yok."; | |
| 53 | - JobStarted => "Started", "Başladı"; | |
| 54 | - RetryFailedTitle => "Retry failed imports", "Başarısız içe aktarmaları yeniden dene"; | |
| 55 | - RetrySelected => "Retry selected", "Seçilenleri yeniden dene"; | |
| 56 | - RetryNone => "No failed imports", "Başarısız içe aktarma yok"; | |
| 57 | - StageGit => "Git data", "Git verisi"; | |
| 58 | - StageLabels => "Labels", "Etiketler"; | |
| 59 | - StageMilestones => "Milestones", "Kilometre taşları"; | |
| 60 | - StageIssues => "Issues and pull requests", "Konular ve çekme istekleri"; | |
| 61 | - StageReleases => "Releases", "Sürümler"; | |
| 62 | - StageDone => "Finished", "Tamamlandı"; | |
| 63 | - ErrBadRemote => "That repository address is not valid.", "Bu depo adresi geçerli değil."; | |
| 64 | - ErrBadInstance => "That instance address is not valid.", "Bu sunucu adresi geçerli değil."; | |
| 65 | - ErrBadOwner => "That user or organization name is not valid.", "Bu kullanıcı veya kuruluş adı geçerli değil."; | |
| 66 | - ErrNothingSelected => "Select at least one repository.", "En az bir depo seçin."; | |
| 67 | - ErrTooMany => "Too many repositories selected at once.", "Bir seferde çok fazla depo seçildi."; | |
| 68 | - SettingsExport => "Data export", "Veri dışa aktarımı"; | |
| 69 | - ExportTitle => "Export your data", "Verilerinizi dışa aktarın"; | |
| 70 | - ExportRequest => "Request an export", "Dışa aktarım iste"; | |
| 71 | - ExportBuilding => "Building", "Hazırlanıyor"; | |
| 72 | - ExportReady => "Ready", "Hazır"; | |
| 73 | - ExportFailed => "Failed", "Başarısız"; | |
| 74 | - ExportDownload => "Download", "İndir"; | |
| 75 | - ExportNone => "No exports yet.", "Henüz dışa aktarım yok."; | |
| 76 | - ExportRequested => "Requested", "İstendi"; | |
| 77 | - ExportSize => "Size", "Boyut"; | |
| 78 | -} | |
| 79 | - | |
| 80 | -pub fn expires_label(lang: Lang) -> &'static str { | |
| 81 | - match lang { | |
| 82 | - Lang::En => "Expires", | |
| 83 | - Lang::Tr => "Son geçerlilik", | |
| 84 | - } | |
| 85 | -} | |
| 86 | - | |
| 87 | -pub fn bulk_skipped(lang: Lang, list: &str) -> String { | |
| 88 | - match lang { | |
| 89 | - Lang::En => format!("Not imported: {list}. Import them one by one to choose another name."), | |
| 90 | - Lang::Tr => format!( | |
| 91 | - "İçe aktarılmayanlar: {list}. Başka bir ad seçmek için onları tek tek içe aktarın." | |
| 92 | - ), | |
| 93 | - } | |
| 94 | -} | |
| 95 | - | |
| 96 | -pub fn progress_of(done: i64, total: i64) -> String { | |
| 97 | - format!("{done} / {total}") | |
| 98 | -} | |
| 99 | - | |
| 100 | -#[cfg(test)] | |
| 101 | -mod tests { | |
| 102 | - use super::*; | |
| 103 | - | |
| 104 | - #[test] | |
| 105 | - fn every_variant_has_both_languages() { | |
| 106 | - for key in ALL { | |
| 107 | - assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English"); | |
| 108 | - assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish"); | |
| 109 | - assert!( | |
| 110 | - !t(Lang::En, *key).contains('\u{2014}'), | |
| 111 | - "{key:?} has an em dash" | |
| 112 | - ); | |
| 113 | - assert!( | |
| 114 | - !t(Lang::Tr, *key).contains('\u{2014}'), | |
| 115 | - "{key:?} has an em dash" | |
| 116 | - ); | |
| 117 | - } | |
| 118 | - } | |
| 119 | -} |
crates/forge-web-base/src/i18n/mod.rsmodified+0 -1
| @@ -40,7 +40,6 @@ pub mod integrations; | ||
| 40 | 40 | pub mod issues; |
| 41 | 41 | pub mod link; |
| 42 | 42 | pub mod merge_queue; |
| 43 | -pub mod migrate; | |
| 44 | 43 | pub mod misc; |
| 45 | 44 | pub mod needs; |
| 46 | 45 | pub mod orgs; |
crates/forge-web-pages/Cargo.tomlmodified+0 -1
| @@ -33,7 +33,6 @@ reqwest = { workspace = true } | ||
| 33 | 33 | similar = { workspace = true } |
| 34 | 34 | multer.workspace = true |
| 35 | 35 | zip = { workspace = true } |
| 36 | -tar.workspace = true | |
| 37 | 36 | |
| 38 | 37 | tempfile = { workspace = true, optional = true } |
| 39 | 38 |
crates/forge-web-repo/Cargo.tomlmodified+0 -1
| @@ -33,7 +33,6 @@ reqwest = { workspace = true } | ||
| 33 | 33 | multer.workspace = true |
| 34 | 34 | ulid.workspace = true |
| 35 | 35 | zip = { workspace = true } |
| 36 | -tar.workspace = true | |
| 37 | 36 | |
| 38 | 37 | |
| 39 | 38 | [dev-dependencies] |
crates/forge-web/Cargo.tomlmodified+0 -2
| @@ -36,8 +36,6 @@ nix = { workspace = true } | ||
| 36 | 36 | time.workspace = true |
| 37 | 37 | reqwest = { workspace = true } |
| 38 | 38 | forge-runner = { workspace = true } |
| 39 | -zip = { workspace = true } | |
| 40 | -tar.workspace = true | |
| 41 | 39 | |
| 42 | 40 | [dev-dependencies] |
| 43 | 41 | forge-web-pages = { workspace = true, features = ["test-support"] } |
crates/forge-web/assets/nav.jsmodified+0 -12
| @@ -1193,18 +1193,6 @@ | ||
| 1193 | 1193 | field.dispatchEvent(new Event('input', { bubbles: true })); |
| 1194 | 1194 | }); |
| 1195 | 1195 | |
| 1196 | - // A checkbox marked data-select-all="<selector>" ticks or clears every checkbox inside the first | |
| 1197 | - // element that matches the selector (the bulk import list). | |
| 1198 | - document.addEventListener('change', function (e) { | |
| 1199 | - var all = e.target && e.target.closest ? e.target.closest('[data-select-all]') : null; | |
| 1200 | - if (!all) { return; } | |
| 1201 | - var scope = document.querySelector(all.getAttribute('data-select-all')); | |
| 1202 | - if (!scope) { return; } | |
| 1203 | - Array.prototype.forEach.call(scope.querySelectorAll('input[type="checkbox"]'), function (box) { | |
| 1204 | - box.checked = all.checked; | |
| 1205 | - }); | |
| 1206 | - }); | |
| 1207 | - | |
| 1208 | 1196 | // Filter controls submit their form on change. |
| 1209 | 1197 | document.addEventListener('change', function (e) { |
| 1210 | 1198 | var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; |
crates/forge-web/src/boot.rsmodified+0 -2
| @@ -133,8 +133,6 @@ pub async fn serve( | ||
| 133 | 133 | if let Err(e) = forge_web_app::signatures::rebuild_gpg_keyring(&state).await { |
| 134 | 134 | tracing::error!(error = %e, "rebuilding the GPG keyring failed"); |
| 135 | 135 | } |
| 136 | - forge_web_app::importer::on_boot(&state).await; | |
| 137 | - forge_web_app::exporter::on_boot(&state).await; | |
| 138 | 136 | forge_web_app::webhooks::worker::spawn(state.clone()); |
| 139 | 137 | forge_web_app::mirrors::worker::spawn(state.clone()); |
| 140 | 138 | forge_web_app::mail::worker::spawn(state.clone()); |
crates/forge-web/src/forgejo_tests.rsdeleted+0 -404
| @@ -1,404 +0,0 @@ | ||
| 1 | -use std::sync::{Arc, Mutex}; | |
| 2 | - | |
| 3 | -use serde_json::{Value, json}; | |
| 4 | -use tokio::io::{AsyncReadExt, AsyncWriteExt}; | |
| 5 | -use tokio::net::TcpListener; | |
| 6 | - | |
| 7 | -use super::*; | |
| 8 | -use forge_web_app::importer::api::{Auth, Forgejo, Http}; | |
| 9 | - | |
| 10 | -type Reply = (Vec<(String, String)>, Vec<u8>); | |
| 11 | -type Log = Arc<Mutex<Vec<(String, Option<String>)>>>; | |
| 12 | - | |
| 13 | -async fn bind() -> (TcpListener, String) { | |
| 14 | - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); | |
| 15 | - let base = format!("http://{}", listener.local_addr().expect("addr")); | |
| 16 | - (listener, base) | |
| 17 | -} | |
| 18 | - | |
| 19 | -fn serve<F>(listener: TcpListener, handler: F) -> Log | |
| 20 | -where | |
| 21 | - F: Fn(&str) -> Option<Reply> + Send + Sync + 'static, | |
| 22 | -{ | |
| 23 | - let log: Log = Arc::default(); | |
| 24 | - let seen = log.clone(); | |
| 25 | - let handler = Arc::new(handler); | |
| 26 | - tokio::spawn(async move { | |
| 27 | - loop { | |
| 28 | - let Ok((mut sock, _)) = listener.accept().await else { | |
| 29 | - return; | |
| 30 | - }; | |
| 31 | - let handler = handler.clone(); | |
| 32 | - let seen = seen.clone(); | |
| 33 | - tokio::spawn(async move { | |
| 34 | - let mut buf = Vec::new(); | |
| 35 | - let mut chunk = [0u8; 2048]; | |
| 36 | - while !buf.windows(4).any(|w| w == b"\r\n\r\n") { | |
| 37 | - match sock.read(&mut chunk).await { | |
| 38 | - Ok(0) | Err(_) => return, | |
| 39 | - Ok(n) => buf.extend_from_slice(&chunk[..n]), | |
| 40 | - } | |
| 41 | - } | |
| 42 | - let text = String::from_utf8_lossy(&buf).into_owned(); | |
| 43 | - let target = text | |
| 44 | - .lines() | |
| 45 | - .next() | |
| 46 | - .and_then(|l| l.split_whitespace().nth(1)) | |
| 47 | - .unwrap_or("/") | |
| 48 | - .to_owned(); | |
| 49 | - let auth = text.lines().find_map(|l| { | |
| 50 | - let (k, v) = l.split_once(':')?; | |
| 51 | - k.eq_ignore_ascii_case("authorization") | |
| 52 | - .then(|| v.trim().to_owned()) | |
| 53 | - }); | |
| 54 | - seen.lock().unwrap().push((target.clone(), auth)); | |
| 55 | - let out = match handler(&target) { | |
| 56 | - Some((headers, body)) => { | |
| 57 | - let mut head = format!( | |
| 58 | - "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n", | |
| 59 | - body.len() | |
| 60 | - ); | |
| 61 | - for (k, v) in headers { | |
| 62 | - head.push_str(&format!("{k}: {v}\r\n")); | |
| 63 | - } | |
| 64 | - head.push_str("\r\n"); | |
| 65 | - let mut out = head.into_bytes(); | |
| 66 | - out.extend(body); | |
| 67 | - out | |
| 68 | - } | |
| 69 | - None => { | |
| 70 | - b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" | |
| 71 | - .to_vec() | |
| 72 | - } | |
| 73 | - }; | |
| 74 | - let _ = sock.write_all(&out).await; | |
| 75 | - let _ = sock.shutdown().await; | |
| 76 | - }); | |
| 77 | - } | |
| 78 | - }); | |
| 79 | - log | |
| 80 | -} | |
| 81 | - | |
| 82 | -fn json_reply(headers: Vec<(&str, String)>, body: &Value) -> Option<Reply> { | |
| 83 | - let mut all = vec![("content-type".to_owned(), "application/json".to_owned())]; | |
| 84 | - all.extend(headers.into_iter().map(|(k, v)| (k.to_owned(), v))); | |
| 85 | - Some((all, body.to_string().into_bytes())) | |
| 86 | -} | |
| 87 | - | |
| 88 | -fn page_of(target: &str) -> usize { | |
| 89 | - target | |
| 90 | - .split(['?', '&']) | |
| 91 | - .find_map(|p| p.strip_prefix("page=")) | |
| 92 | - .and_then(|v| v.parse().ok()) | |
| 93 | - .unwrap_or(1) | |
| 94 | -} | |
| 95 | - | |
| 96 | -fn client(base: &str, token: Option<&str>) -> Forgejo { | |
| 97 | - let notice: forge_web_app::importer::api::Notice = Arc::new(|_| {}); | |
| 98 | - let open = forge_web_app::webhooks::client::WebhookPolicy::from_config( | |
| 99 | - &forge_core::config::WebhookConfig { | |
| 100 | - allow_http: true, | |
| 101 | - allowed_hosts: vec!["127.0.0.1".into()], | |
| 102 | - }, | |
| 103 | - ) | |
| 104 | - .expect("policy"); | |
| 105 | - let http = Http::new( | |
| 106 | - reqwest::Client::new(), | |
| 107 | - open, | |
| 108 | - token.map(str::to_owned), | |
| 109 | - Auth::Forgejo, | |
| 110 | - "127.0.0.1".into(), | |
| 111 | - notice, | |
| 112 | - ); | |
| 113 | - Forgejo::new(http, base) | |
| 114 | -} | |
| 115 | - | |
| 116 | -fn issue_json(n: i64, state: &str) -> Value { | |
| 117 | - json!({ | |
| 118 | - "number": n, "title": format!("Issue {n}"), "body": "text", "state": state, | |
| 119 | - "user": {"login": "hubot"}, "labels": [{"name": "bug", "color": "d73a4a"}], | |
| 120 | - "milestone": null, "created_at": "2020-01-02T03:04:05Z", | |
| 121 | - "html_url": format!("https://codeberg.example/tahinli/project/issues/{n}"), | |
| 122 | - }) | |
| 123 | -} | |
| 124 | - | |
| 125 | -#[tokio::test] | |
| 126 | -async fn pagination_follows_the_link_header_with_a_limit_of_fifty() { | |
| 127 | - let (listener, base) = bind().await; | |
| 128 | - let log = serve(listener, |target| { | |
| 129 | - if !target.starts_with("/api/v1/repos/tahinli/project/issues?type=issues") { | |
| 130 | - return json_reply(vec![], &json!([])); | |
| 131 | - } | |
| 132 | - match page_of(target) { | |
| 133 | - 1 => json_reply( | |
| 134 | - vec![ | |
| 135 | - ("x-total-count", "52".into()), | |
| 136 | - ( | |
| 137 | - "link", | |
| 138 | - "<http://x/api/v1/p?page=2>; rel=\"next\", <http://x/api/v1/p?page=2>; rel=\"last\"" | |
| 139 | - .into(), | |
| 140 | - ), | |
| 141 | - ], | |
| 142 | - &Value::Array((1..=50).map(|n| issue_json(n, "open")).collect()), | |
| 143 | - ), | |
| 144 | - 2 => json_reply( | |
| 145 | - vec![ | |
| 146 | - ("x-total-count", "52".into()), | |
| 147 | - ("link", "<http://x/api/v1/p?page=1>; rel=\"prev\"".into()), | |
| 148 | - ], | |
| 149 | - &Value::Array((51..=52).map(|n| issue_json(n, "closed")).collect()), | |
| 150 | - ), | |
| 151 | - _ => json_reply(vec![], &json!([])), | |
| 152 | - } | |
| 153 | - }); | |
| 154 | - let api = client(&base, Some("abc123")); | |
| 155 | - let issues = api.issues("tahinli/project").await.unwrap(); | |
| 156 | - let plain: Vec<_> = issues.iter().filter(|i| !i.is_pr).collect(); | |
| 157 | - assert_eq!(plain.len(), 52, "both pages were read"); | |
| 158 | - assert!(plain[51].closed && !plain[0].closed); | |
| 159 | - assert_eq!(plain[0].author, "hubot"); | |
| 160 | - assert_eq!(plain[0].labels, vec!["bug"]); | |
| 161 | - | |
| 162 | - let log = log.lock().unwrap(); | |
| 163 | - let issue_calls: Vec<_> = log | |
| 164 | - .iter() | |
| 165 | - .filter(|(t, _)| t.contains("type=issues")) | |
| 166 | - .collect(); | |
| 167 | - assert_eq!(issue_calls.len(), 2, "stopped when the link had no next"); | |
| 168 | - assert!(issue_calls[0].0.contains("limit=50")); | |
| 169 | - assert!(issue_calls[0].0.contains("page=1") && issue_calls[1].0.contains("page=2")); | |
| 170 | - assert!( | |
| 171 | - log.iter() | |
| 172 | - .all(|(_, auth)| auth.as_deref() == Some("token abc123")), | |
| 173 | - "every request carries the token header" | |
| 174 | - ); | |
| 175 | -} | |
| 176 | - | |
| 177 | -#[tokio::test] | |
| 178 | -async fn the_total_count_stops_a_listing_with_no_link_header() { | |
| 179 | - let (listener, base) = bind().await; | |
| 180 | - let log = serve(listener, |target| { | |
| 181 | - json_reply( | |
| 182 | - vec![("x-total-count", "50".into())], | |
| 183 | - &Value::Array( | |
| 184 | - (0..50) | |
| 185 | - .map(|i| json!({"name": format!("l{i}"), "color": "00aabb"})) | |
| 186 | - .collect(), | |
| 187 | - ), | |
| 188 | - ) | |
| 189 | - .filter(|_| target.contains("/labels")) | |
| 190 | - }); | |
| 191 | - let api = client(&base, None); | |
| 192 | - let labels = api.labels("tahinli/project").await.unwrap(); | |
| 193 | - assert_eq!(labels.len(), 50); | |
| 194 | - assert_eq!(labels[0].color, "#00aabb"); | |
| 195 | - assert_eq!( | |
| 196 | - log.lock().unwrap().len(), | |
| 197 | - 1, | |
| 198 | - "a full page of exactly the total is the end" | |
| 199 | - ); | |
| 200 | - assert!( | |
| 201 | - log.lock().unwrap()[0].1.is_none(), | |
| 202 | - "no token, no Authorization header" | |
| 203 | - ); | |
| 204 | -} | |
| 205 | - | |
| 206 | -#[tokio::test] | |
| 207 | -async fn pulls_map_merged_closed_and_open() { | |
| 208 | - let (listener, base) = bind().await; | |
| 209 | - serve(listener, |target| { | |
| 210 | - if target.contains("/pulls?") { | |
| 211 | - let mut merged = issue_json(2, "closed"); | |
| 212 | - merged["merged"] = json!(true); | |
| 213 | - let closed = issue_json(3, "closed"); | |
| 214 | - let mut open = issue_json(4, "open"); | |
| 215 | - open["milestone"] = json!({"title": "v1"}); | |
| 216 | - json_reply(vec![], &json!([merged, closed, open])) | |
| 217 | - } else if target.contains("/issues?") { | |
| 218 | - json_reply(vec![], &json!([issue_json(1, "open")])) | |
| 219 | - } else { | |
| 220 | - None | |
| 221 | - } | |
| 222 | - }); | |
| 223 | - let api = client(&base, None); | |
| 224 | - let all = api.issues("tahinli/project").await.unwrap(); | |
| 225 | - assert_eq!(all.len(), 4); | |
| 226 | - assert!(!all[0].is_pr); | |
| 227 | - let pulls: Vec<_> = all.iter().filter(|i| i.is_pr).collect(); | |
| 228 | - assert!(pulls[0].closed && pulls[0].merged); | |
| 229 | - assert!(pulls[1].closed && !pulls[1].merged); | |
| 230 | - assert!(!pulls[2].closed); | |
| 231 | - assert_eq!(pulls[2].milestone.as_deref(), Some("v1")); | |
| 232 | -} | |
| 233 | - | |
| 234 | -#[tokio::test] | |
| 235 | -async fn bulk_listing_tries_the_org_then_the_user_and_supports_own_repos() { | |
| 236 | - let (listener, base) = bind().await; | |
| 237 | - let repo = |name: &str, private: bool| { | |
| 238 | - json!({"name": name, "full_name": format!("tahinli/{name}"), "private": private, | |
| 239 | - "fork": false, "archived": false, "default_branch": "main", "description": null}) | |
| 240 | - }; | |
| 241 | - let log = serve(listener, move |target| { | |
| 242 | - if target.starts_with("/api/v1/users/tahinli/repos") { | |
| 243 | - json_reply(vec![], &json!([repo("a", false)])) | |
| 244 | - } else if target.starts_with("/api/v1/user/repos") { | |
| 245 | - json_reply(vec![], &json!([repo("a", false), repo("b", true)])) | |
| 246 | - } else { | |
| 247 | - None | |
| 248 | - } | |
| 249 | - }); | |
| 250 | - let api = client(&base, Some("t")); | |
| 251 | - let public = api.list_repos("tahinli").await.unwrap(); | |
| 252 | - assert_eq!(public.len(), 1); | |
| 253 | - assert_eq!(public[0].full_name, "tahinli/a"); | |
| 254 | - assert!( | |
| 255 | - log.lock().unwrap()[0] | |
| 256 | - .0 | |
| 257 | - .starts_with("/api/v1/orgs/tahinli/repos"), | |
| 258 | - "the org is tried first" | |
| 259 | - ); | |
| 260 | - let mine = api.list_repos("").await.unwrap(); | |
| 261 | - assert_eq!(mine.len(), 2); | |
| 262 | - assert!(mine[1].private); | |
| 263 | -} | |
| 264 | - | |
| 265 | -#[tokio::test] | |
| 266 | -async fn a_bad_asset_address_is_refused_before_any_request() { | |
| 267 | - let (listener, base) = bind().await; | |
| 268 | - let log = serve(listener, |_| None); | |
| 269 | - let api = client(&base, Some("t")); | |
| 270 | - let asset = ExtAsset { | |
| 271 | - url: "https://elsewhere.example/a.bin".into(), | |
| 272 | - ..ExtAsset::default() | |
| 273 | - }; | |
| 274 | - assert!(api.download(&asset, 100).await.is_err()); | |
| 275 | - assert!(log.lock().unwrap().is_empty()); | |
| 276 | -} | |
| 277 | - | |
| 278 | -#[tokio::test] | |
| 279 | -async fn full_forgejo_import_maps_issues_pulls_comments_labels_and_releases() { | |
| 280 | - let fx = fixture().await; | |
| 281 | - let (listener, base) = bind().await; | |
| 282 | - let origin = base.clone(); | |
| 283 | - serve(listener, move |target| { | |
| 284 | - let path = target.split('?').next().unwrap_or_default(); | |
| 285 | - match path { | |
| 286 | - "/api/v1/repos/tahinli/project/labels" => json_reply( | |
| 287 | - vec![], | |
| 288 | - &json!([{"name": "bug", "color": "d73a4a", "description": "Broken"}]), | |
| 289 | - ), | |
| 290 | - "/api/v1/repos/tahinli/project/milestones" => json_reply( | |
| 291 | - vec![], | |
| 292 | - &json!([{"id": 9, "title": "v1", "description": "", "state": "closed", | |
| 293 | - "due_on": "2020-05-06T00:00:00Z"}]), | |
| 294 | - ), | |
| 295 | - "/api/v1/repos/tahinli/project/issues" => { | |
| 296 | - json_reply(vec![], &json!([issue_json(1, "closed")])) | |
| 297 | - } | |
| 298 | - "/api/v1/repos/tahinli/project/pulls" => { | |
| 299 | - let mut pr = issue_json(2, "closed"); | |
| 300 | - pr["title"] = json!("Add the thing"); | |
| 301 | - pr["merged"] = json!(true); | |
| 302 | - json_reply(vec![], &json!([pr])) | |
| 303 | - } | |
| 304 | - "/api/v1/repos/tahinli/project/issues/1/comments" => json_reply( | |
| 305 | - vec![], | |
| 306 | - &json!([{"id": 11, "body": "same here", "user": {"login": "hubot"}, | |
| 307 | - "created_at": "2020-01-03T00:00:00Z", | |
| 308 | - "html_url": "https://codeberg.example/c/11"}]), | |
| 309 | - ), | |
| 310 | - "/api/v1/repos/tahinli/project/issues/2/comments" => json_reply(vec![], &json!([])), | |
| 311 | - "/api/v1/repos/tahinli/project/releases" => json_reply( | |
| 312 | - vec![], | |
| 313 | - &json!([{"id": 5, "tag_name": "v1", "name": "", "body": "notes", "draft": false, | |
| 314 | - "prerelease": false, "author": {"login": "hubot"}, | |
| 315 | - "created_at": "2021-01-01T00:00:00Z", | |
| 316 | - "html_url": "https://codeberg.example/r/5", | |
| 317 | - "assets": [{"id": 1, "name": "app.tar.gz", "size": 5, | |
| 318 | - "browser_download_url": format!("{origin}/attachments/uuid-1")}]}]), | |
| 319 | - ), | |
| 320 | - "/attachments/uuid-1" => Some((vec![], b"hello".to_vec())), | |
| 321 | - _ => None, | |
| 322 | - } | |
| 323 | - }); | |
| 324 | - let api = client(&base, Some(TOKEN)); | |
| 325 | - let job = new_job(&fx, Source::Forgejo).await; | |
| 326 | - let mut spec = spec(Source::Forgejo, everything()); | |
| 327 | - spec.instance = base.clone(); | |
| 328 | - run_job( | |
| 329 | - &fx.state, | |
| 330 | - &job, | |
| 331 | - &spec, | |
| 332 | - Some(&api), | |
| 333 | - &Transport::Local(fx.upstream.clone()), | |
| 334 | - ) | |
| 335 | - .await; | |
| 336 | - | |
| 337 | - let store = &fx.state.store; | |
| 338 | - let job = store.import_job(&job.id).await.unwrap().unwrap(); | |
| 339 | - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); | |
| 340 | - | |
| 341 | - let all = IssueFilter { | |
| 342 | - state: None, | |
| 343 | - per_page: 100, | |
| 344 | - ..IssueFilter::default() | |
| 345 | - }; | |
| 346 | - let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); | |
| 347 | - assert_eq!(total, 2); | |
| 348 | - let issue = items.iter().find(|i| i.issue.title == "Issue 1").unwrap(); | |
| 349 | - assert_eq!(issue.issue.state, IssueState::Closed); | |
| 350 | - assert!( | |
| 351 | - issue | |
| 352 | - .issue | |
| 353 | - .body | |
| 354 | - .starts_with("> Originally by \\@hubot on Forgejo, 2020-01-02"), | |
| 355 | - "{}", | |
| 356 | - issue.issue.body | |
| 357 | - ); | |
| 358 | - assert!(issue.labels.iter().any(|l| l.name == "bug")); | |
| 359 | - let pull = items | |
| 360 | - .iter() | |
| 361 | - .find(|i| i.issue.title == "Add the thing") | |
| 362 | - .unwrap(); | |
| 363 | - assert!(pull.issue.body.contains("Imported pull request (merged)")); | |
| 364 | - let comments = store.list_comments(&issue.issue.id).await.unwrap(); | |
| 365 | - assert_eq!(comments.len(), 1); | |
| 366 | - assert!(comments[0].body.ends_with("same here")); | |
| 367 | - | |
| 368 | - let release = store | |
| 369 | - .release_by_tag(&fx.repo.id, "v1") | |
| 370 | - .await | |
| 371 | - .unwrap() | |
| 372 | - .unwrap(); | |
| 373 | - assert!(release.body.contains("notes")); | |
| 374 | - let assets = store.list_release_assets(&release.id).await.unwrap(); | |
| 375 | - assert_eq!(assets.len(), 1); | |
| 376 | - assert_eq!(assets[0].name, "app.tar.gz"); | |
| 377 | - assert_eq!(assets[0].size, 5); | |
| 378 | -} | |
| 379 | - | |
| 380 | -#[test] | |
| 381 | -fn forgejo_remotes_take_a_url_or_a_path_with_an_instance() { | |
| 382 | - use forge_web_app::importer::parse_remote; | |
| 383 | - assert_eq!( | |
| 384 | - parse_remote( | |
| 385 | - Source::Forgejo, | |
| 386 | - "https://codeberg.org/tahinli/forge.git", | |
| 387 | - "" | |
| 388 | - ), | |
| 389 | - Some(("tahinli/forge".into(), "https://codeberg.org".into())) | |
| 390 | - ); | |
| 391 | - assert_eq!( | |
| 392 | - parse_remote(Source::Forgejo, "tahinli/forge", "https://codeberg.org/"), | |
| 393 | - Some(("tahinli/forge".into(), "https://codeberg.org".into())) | |
| 394 | - ); | |
| 395 | - assert_eq!( | |
| 396 | - parse_remote(Source::Forgejo, "a/b/c", "https://codeberg.org"), | |
| 397 | - None | |
| 398 | - ); | |
| 399 | - assert_eq!(parse_remote(Source::Forgejo, "tahinli/forge", ""), None); | |
| 400 | - assert_eq!(Source::parse("gitea"), Some(Source::Forgejo)); | |
| 401 | - let mut s = spec(Source::Forgejo, ImportOptions::default()); | |
| 402 | - s.instance = "https://codeberg.org/".into(); | |
| 403 | - assert_eq!(s.clone_url(), "https://codeberg.org/tahinli/project.git"); | |
| 404 | -} |
crates/forge-web/src/importer_route_tests.rsdeleted+0 -599
| @@ -1,599 +0,0 @@ | ||
| 1 | -use std::collections::HashMap; | |
| 2 | -use std::path::Path; | |
| 3 | -use std::sync::Mutex; | |
| 4 | - | |
| 5 | -use forge_core::issues::IssueFilter; | |
| 6 | -use forge_core::store::imports::{ImportJob, ImportState}; | |
| 7 | -use forge_core::{IssueState, Visibility}; | |
| 8 | -use topcoat::router::request::Request; | |
| 9 | -use topcoat::router::{Body, to_bytes}; | |
| 10 | - | |
| 11 | -use forge_web_app::auth::SESSION_COOKIE; | |
| 12 | -use forge_web_app::importer::api::{ | |
| 13 | - ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, | |
| 14 | - ExtRelease, ExtRepo, RemoteApi, | |
| 15 | -}; | |
| 16 | -use forge_web_app::importer::{ | |
| 17 | - ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note, | |
| 18 | -}; | |
| 19 | -use forge_web_app::state::AppState; | |
| 20 | -use forge_web_app::test_support::{app_router, create_session, test_state}; | |
| 21 | - | |
| 22 | -const TOKEN: &str = "ghp_supersecret_token_value"; | |
| 23 | - | |
| 24 | -fn all_issues() -> IssueFilter { | |
| 25 | - IssueFilter { | |
| 26 | - state: None, | |
| 27 | - per_page: 100, | |
| 28 | - ..IssueFilter::default() | |
| 29 | - } | |
| 30 | -} | |
| 31 | - | |
| 32 | -#[derive(Default)] | |
| 33 | -struct Fake { | |
| 34 | - labels: Vec<ExtLabel>, | |
| 35 | - milestones: Vec<ExtMilestone>, | |
| 36 | - issues: Vec<ExtIssue>, | |
| 37 | - comments: HashMap<i64, Vec<ExtComment>>, | |
| 38 | - releases: Vec<ExtRelease>, | |
| 39 | - files: HashMap<String, Vec<u8>>, | |
| 40 | - comment_failures: Mutex<Vec<ApiError>>, | |
| 41 | - comment_calls: Mutex<usize>, | |
| 42 | -} | |
| 43 | - | |
| 44 | -impl RemoteApi for Fake { | |
| 45 | - async fn list_repos(&self, _owner: &str) -> ApiResult<Vec<ExtRepo>> { | |
| 46 | - Ok(vec![ExtRepo { | |
| 47 | - name: "project".into(), | |
| 48 | - full_name: "tahinli/project".into(), | |
| 49 | - ..ExtRepo::default() | |
| 50 | - }]) | |
| 51 | - } | |
| 52 | - | |
| 53 | - async fn labels(&self, _repo: &str) -> ApiResult<Vec<ExtLabel>> { | |
| 54 | - Ok(self.labels.clone()) | |
| 55 | - } | |
| 56 | - | |
| 57 | - async fn milestones(&self, _repo: &str) -> ApiResult<Vec<ExtMilestone>> { | |
| 58 | - Ok(self.milestones.clone()) | |
| 59 | - } | |
| 60 | - | |
| 61 | - async fn issues(&self, _repo: &str) -> ApiResult<Vec<ExtIssue>> { | |
| 62 | - Ok(self.issues.clone()) | |
| 63 | - } | |
| 64 | - | |
| 65 | - async fn comments(&self, _repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> { | |
| 66 | - *self.comment_calls.lock().unwrap() += 1; | |
| 67 | - if let Some(e) = self.comment_failures.lock().unwrap().pop() { | |
| 68 | - return Err(e); | |
| 69 | - } | |
| 70 | - Ok(self | |
| 71 | - .comments | |
| 72 | - .get(&issue.number) | |
| 73 | - .cloned() | |
| 74 | - .unwrap_or_default()) | |
| 75 | - } | |
| 76 | - | |
| 77 | - async fn releases(&self, _repo: &str) -> ApiResult<Vec<ExtRelease>> { | |
| 78 | - Ok(self.releases.clone()) | |
| 79 | - } | |
| 80 | - | |
| 81 | - async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult<AssetStream> { | |
| 82 | - let bytes = self | |
| 83 | - .files | |
| 84 | - .get(&asset.url) | |
| 85 | - .cloned() | |
| 86 | - .ok_or_else(|| ApiError::NotFound("asset".into()))?; | |
| 87 | - Ok(Box::pin(futures_util::stream::once(async move { | |
| 88 | - Ok::<_, std::io::Error>(bytes::Bytes::from(bytes)) | |
| 89 | - }))) | |
| 90 | - } | |
| 91 | -} | |
| 92 | - | |
| 93 | -fn plumbing(git_dir: &Path, args: &[&str]) -> String { | |
| 94 | - let out = std::process::Command::new("git") | |
| 95 | - .arg(format!("--git-dir={}", git_dir.display())) | |
| 96 | - .args(args) | |
| 97 | - .env("GIT_AUTHOR_NAME", "t") | |
| 98 | - .env("GIT_AUTHOR_EMAIL", "t@example.com") | |
| 99 | - .env("GIT_COMMITTER_NAME", "t") | |
| 100 | - .env("GIT_COMMITTER_EMAIL", "t@example.com") | |
| 101 | - .output() | |
| 102 | - .expect("git runs"); | |
| 103 | - assert!(out.status.success(), "git {args:?}: {out:?}"); | |
| 104 | - String::from_utf8_lossy(&out.stdout).trim().to_string() | |
| 105 | -} | |
| 106 | - | |
| 107 | -fn commit_to(git_dir: &Path, refname: &str, message: &str) { | |
| 108 | - let tree = plumbing(git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]); | |
| 109 | - let commit = plumbing(git_dir, &["commit-tree", &tree, "-m", message]); | |
| 110 | - plumbing(git_dir, &["update-ref", refname, &commit]); | |
| 111 | -} | |
| 112 | - | |
| 113 | -fn upstream(dir: &Path) -> String { | |
| 114 | - let path = dir.join("upstream.git"); | |
| 115 | - let out = std::process::Command::new("git") | |
| 116 | - .args(["init", "--bare", "-q"]) | |
| 117 | - .arg(&path) | |
| 118 | - .output() | |
| 119 | - .expect("git init"); | |
| 120 | - assert!(out.status.success()); | |
| 121 | - plumbing(&path, &["symbolic-ref", "HEAD", "refs/heads/master"]); | |
| 122 | - commit_to(&path, "refs/heads/master", "one"); | |
| 123 | - commit_to(&path, "refs/heads/dev", "dev work"); | |
| 124 | - commit_to(&path, "refs/tags/v1", "tagged"); | |
| 125 | - path.display().to_string() | |
| 126 | -} | |
| 127 | - | |
| 128 | -struct Fixture { | |
| 129 | - state: AppState, | |
| 130 | - repo: forge_core::Repo, | |
| 131 | - user: forge_core::User, | |
| 132 | - _dir: tempfile::TempDir, | |
| 133 | - upstream: String, | |
| 134 | -} | |
| 135 | - | |
| 136 | -async fn fixture() -> Fixture { | |
| 137 | - let dir = tempfile::tempdir().expect("tempdir"); | |
| 138 | - let state = test_state(dir.path()).await; | |
| 139 | - let user = state | |
| 140 | - .store | |
| 141 | - .create_user("tahinli", None, "unused", false) | |
| 142 | - .await | |
| 143 | - .expect("user"); | |
| 144 | - let repo = state | |
| 145 | - .store | |
| 146 | - .create_repo(&user.id, "project", "", Visibility::Public, "main") | |
| 147 | - .await | |
| 148 | - .expect("repo"); | |
| 149 | - let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path"); | |
| 150 | - forge_git::repo::init_bare(&state.git, &bare, "main") | |
| 151 | - .await | |
| 152 | - .expect("init bare"); | |
| 153 | - let upstream = upstream(dir.path()); | |
| 154 | - Fixture { | |
| 155 | - state, | |
| 156 | - repo, | |
| 157 | - user, | |
| 158 | - _dir: dir, | |
| 159 | - upstream, | |
| 160 | - } | |
| 161 | -} | |
| 162 | - | |
| 163 | -fn spec(source: Source, options: ImportOptions) -> JobSpec { | |
| 164 | - JobSpec { | |
| 165 | - source, | |
| 166 | - remote: "tahinli/project".into(), | |
| 167 | - instance: String::new(), | |
| 168 | - token: Some(TOKEN.into()), | |
| 169 | - git_user: String::new(), | |
| 170 | - options, | |
| 171 | - } | |
| 172 | -} | |
| 173 | - | |
| 174 | -async fn new_job(fx: &Fixture, source: Source) -> ImportJob { | |
| 175 | - fx.state | |
| 176 | - .store | |
| 177 | - .create_import_job( | |
| 178 | - &fx.user.id, | |
| 179 | - &fx.repo.id, | |
| 180 | - source.as_str(), | |
| 181 | - "tahinli/project", | |
| 182 | - "{}", | |
| 183 | - ) | |
| 184 | - .await | |
| 185 | - .expect("job") | |
| 186 | -} | |
| 187 | - | |
| 188 | -fn everything() -> ImportOptions { | |
| 189 | - ImportOptions { | |
| 190 | - labels: true, | |
| 191 | - issues: true, | |
| 192 | - pulls: true, | |
| 193 | - releases: true, | |
| 194 | - } | |
| 195 | -} | |
| 196 | - | |
| 197 | -fn fake() -> Fake { | |
| 198 | - let mut fake = Fake { | |
| 199 | - labels: vec![ExtLabel { | |
| 200 | - name: "bug".into(), | |
| 201 | - color: "#d73a4a".into(), | |
| 202 | - description: "Broken".into(), | |
| 203 | - }], | |
| 204 | - milestones: vec![ExtMilestone { | |
| 205 | - id: "1".into(), | |
| 206 | - title: "v1".into(), | |
| 207 | - closed: true, | |
| 208 | - due_on: Some("2020-05-06".into()), | |
| 209 | - ..ExtMilestone::default() | |
| 210 | - }], | |
| 211 | - issues: vec![ | |
| 212 | - ExtIssue { | |
| 213 | - number: 1, | |
| 214 | - title: "It breaks".into(), | |
| 215 | - body: "steps".into(), | |
| 216 | - closed: true, | |
| 217 | - author: "octocat".into(), | |
| 218 | - labels: vec!["bug".into()], | |
| 219 | - milestone: Some("v1".into()), | |
| 220 | - created_at: "2020-01-02T03:04:05Z".into(), | |
| 221 | - url: "https://github.com/tahinli/project/issues/1".into(), | |
| 222 | - ..ExtIssue::default() | |
| 223 | - }, | |
| 224 | - ExtIssue { | |
| 225 | - number: 2, | |
| 226 | - title: "Add the thing".into(), | |
| 227 | - body: "patch".into(), | |
| 228 | - closed: true, | |
| 229 | - merged: true, | |
| 230 | - is_pr: true, | |
| 231 | - author: "hubot".into(), | |
| 232 | - created_at: "2020-02-02T00:00:00Z".into(), | |
| 233 | - url: "https://github.com/tahinli/project/pull/2".into(), | |
| 234 | - ..ExtIssue::default() | |
| 235 | - }, | |
| 236 | - ], | |
| 237 | - releases: vec![ExtRelease { | |
| 238 | - id: "7".into(), | |
| 239 | - tag: "v1".into(), | |
| 240 | - title: "First".into(), | |
| 241 | - body: "notes".into(), | |
| 242 | - author: "octocat".into(), | |
| 243 | - assets: vec![ExtAsset { | |
| 244 | - id: "9".into(), | |
| 245 | - name: "app 1.tar.gz".into(), | |
| 246 | - size: 5, | |
| 247 | - content_type: "application/gzip".into(), | |
| 248 | - url: "https://api.github.com/assets/9".into(), | |
| 249 | - }], | |
| 250 | - ..ExtRelease::default() | |
| 251 | - }], | |
| 252 | - ..Fake::default() | |
| 253 | - }; | |
| 254 | - fake.comments.insert( | |
| 255 | - 1, | |
| 256 | - vec![ExtComment { | |
| 257 | - id: "100".into(), | |
| 258 | - author: "hubot".into(), | |
| 259 | - body: "same here".into(), | |
| 260 | - created_at: "2020-01-03T00:00:00Z".into(), | |
| 261 | - url: "https://github.com/tahinli/project/issues/1#c100".into(), | |
| 262 | - }], | |
| 263 | - ); | |
| 264 | - fake.files | |
| 265 | - .insert("https://api.github.com/assets/9".into(), b"hello".to_vec()); | |
| 266 | - fake | |
| 267 | -} | |
| 268 | - | |
| 269 | -#[tokio::test] | |
| 270 | -async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() { | |
| 271 | - let fx = fixture().await; | |
| 272 | - let job = new_job(&fx, Source::Git).await; | |
| 273 | - let git_spec = spec(Source::Git, ImportOptions::default()); | |
| 274 | - run_job::<Fake>( | |
| 275 | - &fx.state, | |
| 276 | - &job, | |
| 277 | - &git_spec, | |
| 278 | - None, | |
| 279 | - &Transport::Local(fx.upstream.clone()), | |
| 280 | - ) | |
| 281 | - .await; | |
| 282 | - | |
| 283 | - let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); | |
| 284 | - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); | |
| 285 | - let dir = forge_git::repo::repo_path(&fx.state.git.data_dir, &fx.repo.id).unwrap(); | |
| 286 | - let refs = forge_web_app::mirrors::ref_snapshot(&fx.state, &dir) | |
| 287 | - .await | |
| 288 | - .unwrap(); | |
| 289 | - assert!(refs.contains_key("refs/heads/master")); | |
| 290 | - assert!(refs.contains_key("refs/heads/dev")); | |
| 291 | - assert!(refs.contains_key("refs/tags/v1")); | |
| 292 | - let repo = fx | |
| 293 | - .state | |
| 294 | - .store | |
| 295 | - .repo_by_id(&fx.repo.id) | |
| 296 | - .await | |
| 297 | - .unwrap() | |
| 298 | - .unwrap(); | |
| 299 | - assert_eq!(repo.default_branch, "master"); | |
| 300 | - assert!( | |
| 301 | - fx.state | |
| 302 | - .store | |
| 303 | - .pull_mirror(&fx.repo.id) | |
| 304 | - .await | |
| 305 | - .unwrap() | |
| 306 | - .is_none() | |
| 307 | - ); | |
| 308 | - | |
| 309 | - let bad_job = new_job(&fx, Source::Git).await; | |
| 310 | - let bad_spec = spec(Source::Git, ImportOptions::default()); | |
| 311 | - run_job::<Fake>( | |
| 312 | - &fx.state, | |
| 313 | - &bad_job, | |
| 314 | - &bad_spec, | |
| 315 | - None, | |
| 316 | - &Transport::Local("/nonexistent/path.git".into()), | |
| 317 | - ) | |
| 318 | - .await; | |
| 319 | - let bad_job = fx | |
| 320 | - .state | |
| 321 | - .store | |
| 322 | - .import_job(&bad_job.id) | |
| 323 | - .await | |
| 324 | - .unwrap() | |
| 325 | - .unwrap(); | |
| 326 | - assert_eq!(bad_job.state, ImportState::Failed); | |
| 327 | - assert!(bad_job.error.is_some()); | |
| 328 | -} | |
| 329 | - | |
| 330 | -#[tokio::test] | |
| 331 | -async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() { | |
| 332 | - let fx = fixture().await; | |
| 333 | - let api = fake(); | |
| 334 | - let job = new_job(&fx, Source::GitHub).await; | |
| 335 | - let spec = spec(Source::GitHub, everything()); | |
| 336 | - run_job( | |
| 337 | - &fx.state, | |
| 338 | - &job, | |
| 339 | - &spec, | |
| 340 | - Some(&api), | |
| 341 | - &Transport::Local(fx.upstream.clone()), | |
| 342 | - ) | |
| 343 | - .await; | |
| 344 | - | |
| 345 | - let store = &fx.state.store; | |
| 346 | - let job = store.import_job(&job.id).await.unwrap().unwrap(); | |
| 347 | - assert_eq!(job.state, ImportState::Done, "{:?}", job.error); | |
| 348 | - | |
| 349 | - let (items, total) = store.list_issues(&fx.repo.id, &all_issues()).await.unwrap(); | |
| 350 | - assert_eq!(total, 2); | |
| 351 | - let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); | |
| 352 | - assert_eq!(issue.issue.state, IssueState::Closed); | |
| 353 | - assert_eq!( | |
| 354 | - issue.issue.author_id, fx.user.id, | |
| 355 | - "the importer owns the row" | |
| 356 | - ); | |
| 357 | - assert!( | |
| 358 | - issue | |
| 359 | - .issue | |
| 360 | - .body | |
| 361 | - .starts_with("> Originally by \\@octocat on GitHub, 2020-01-02"), | |
| 362 | - "{}", | |
| 363 | - issue.issue.body | |
| 364 | - ); | |
| 365 | - assert!(issue.labels.iter().any(|l| l.name == "bug")); | |
| 366 | - assert!(issue.issue.milestone_id.is_some()); | |
| 367 | - | |
| 368 | - let pull = items | |
| 369 | - .iter() | |
| 370 | - .find(|i| i.issue.title == "Add the thing") | |
| 371 | - .unwrap(); | |
| 372 | - assert!(pull.labels.iter().any(|l| l.name == "imported PR")); | |
| 373 | - assert!(pull.issue.body.contains("Imported pull request (merged)")); | |
| 374 | - assert!(pull.issue.body.contains("Originally by \\@hubot")); | |
| 375 | - | |
| 376 | - let comments = store.list_comments(&issue.issue.id).await.unwrap(); | |
| 377 | - assert_eq!(comments.len(), 1); | |
| 378 | - assert!( | |
| 379 | - comments[0] | |
| 380 | - .body | |
| 381 | - .contains("Originally by \\@hubot on GitHub") | |
| 382 | - ); | |
| 383 | - assert!(comments[0].body.ends_with("same here")); | |
| 384 | - | |
| 385 | - let release = store | |
| 386 | - .release_by_tag(&fx.repo.id, "v1") | |
| 387 | - .await | |
| 388 | - .unwrap() | |
| 389 | - .unwrap(); | |
| 390 | - assert!(release.body.contains("notes")); | |
| 391 | - let assets = store.list_release_assets(&release.id).await.unwrap(); | |
| 392 | - assert_eq!(assets.len(), 1); | |
| 393 | - assert_eq!(assets[0].name, "app_1.tar.gz"); | |
| 394 | - assert_eq!(assets[0].size, 5); | |
| 395 | - | |
| 396 | - let again = new_job(&fx, Source::GitHub).await; | |
| 397 | - run_job( | |
| 398 | - &fx.state, | |
| 399 | - &again, | |
| 400 | - &spec, | |
| 401 | - Some(&api), | |
| 402 | - &Transport::Local(fx.upstream.clone()), | |
| 403 | - ) | |
| 404 | - .await; | |
| 405 | - let again = store.import_job(&again.id).await.unwrap().unwrap(); | |
| 406 | - assert_eq!(again.state, ImportState::Done, "{:?}", again.error); | |
| 407 | - let (items, total) = store.list_issues(&fx.repo.id, &all_issues()).await.unwrap(); | |
| 408 | - assert_eq!(total, 2); | |
| 409 | - let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); | |
| 410 | - assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1); | |
| 411 | - assert_eq!(store.list_releases(&fx.repo.id).await.unwrap().len(), 1); | |
| 412 | - let release = store | |
| 413 | - .release_by_tag(&fx.repo.id, "v1") | |
| 414 | - .await | |
| 415 | - .unwrap() | |
| 416 | - .unwrap(); | |
| 417 | - assert_eq!( | |
| 418 | - store.list_release_assets(&release.id).await.unwrap().len(), | |
| 419 | - 1 | |
| 420 | - ); | |
| 421 | - let labels = store.list_labels(&fx.repo.id).await.unwrap(); | |
| 422 | - assert_eq!(labels.iter().filter(|l| l.name == "bug").count(), 1); | |
| 423 | -} | |
| 424 | - | |
| 425 | -#[tokio::test] | |
| 426 | -async fn a_rate_limit_fails_the_job_clearly_and_a_retry_finishes_it() { | |
| 427 | - let fx = fixture().await; | |
| 428 | - let api = fake(); | |
| 429 | - api.comment_failures | |
| 430 | - .lock() | |
| 431 | - .unwrap() | |
| 432 | - .push(ApiError::RateLimited { wait_secs: 3600 }); | |
| 433 | - let job = new_job(&fx, Source::GitHub).await; | |
| 434 | - let spec = spec(Source::GitHub, everything()); | |
| 435 | - let transport = Transport::Local(fx.upstream.clone()); | |
| 436 | - run_job(&fx.state, &job, &spec, Some(&api), &transport).await; | |
| 437 | - | |
| 438 | - let failed = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); | |
| 439 | - assert_eq!(failed.state, ImportState::Failed); | |
| 440 | - let message = failed.error.clone().unwrap(); | |
| 441 | - assert!(message.contains("rate limit"), "{message}"); | |
| 442 | - let events = fx | |
| 443 | - .state | |
| 444 | - .store | |
| 445 | - .list_import_events(&job.id, 50) | |
| 446 | - .await | |
| 447 | - .unwrap(); | |
| 448 | - assert!(events.iter().any(|e| e.level == "error")); | |
| 449 | - | |
| 450 | - run_job(&fx.state, &job, &spec, Some(&api), &transport).await; | |
| 451 | - let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); | |
| 452 | - assert_eq!(done.state, ImportState::Done, "{:?}", done.error); | |
| 453 | - assert!(done.error.is_none()); | |
| 454 | - let (_, total) = fx | |
| 455 | - .state | |
| 456 | - .store | |
| 457 | - .list_issues(&fx.repo.id, &all_issues()) | |
| 458 | - .await | |
| 459 | - .unwrap(); | |
| 460 | - assert_eq!(total, 2); | |
| 461 | -} | |
| 462 | - | |
| 463 | -#[tokio::test] | |
| 464 | -async fn the_token_is_never_written_to_the_database() { | |
| 465 | - let fx = fixture().await; | |
| 466 | - let api = fake(); | |
| 467 | - api.comment_failures | |
| 468 | - .lock() | |
| 469 | - .unwrap() | |
| 470 | - .push(ApiError::Http(format!("boom {}", "x"))); | |
| 471 | - let job = new_job(&fx, Source::GitHub).await; | |
| 472 | - let spec = spec(Source::GitHub, everything()); | |
| 473 | - run_job( | |
| 474 | - &fx.state, | |
| 475 | - &job, | |
| 476 | - &spec, | |
| 477 | - Some(&api), | |
| 478 | - &Transport::Local(fx.upstream.clone()), | |
| 479 | - ) | |
| 480 | - .await; | |
| 481 | - let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); | |
| 482 | - let events = fx | |
| 483 | - .state | |
| 484 | - .store | |
| 485 | - .list_import_events(&job.id, 500) | |
| 486 | - .await | |
| 487 | - .unwrap(); | |
| 488 | - let mut text = format!("{job:?}"); | |
| 489 | - for e in events { | |
| 490 | - text.push_str(&e.message); | |
| 491 | - } | |
| 492 | - assert!( | |
| 493 | - !text.contains(TOKEN), | |
| 494 | - "the token leaked into stored job data" | |
| 495 | - ); | |
| 496 | - assert!( | |
| 497 | - !format!("{spec:?}").contains(TOKEN), | |
| 498 | - "Debug prints the token" | |
| 499 | - ); | |
| 500 | -} | |
| 501 | - | |
| 502 | -#[tokio::test] | |
| 503 | -async fn retry_submit_leaves_another_users_failed_job_alone() { | |
| 504 | - let fx = fixture().await; | |
| 505 | - let other = fx | |
| 506 | - .state | |
| 507 | - .store | |
| 508 | - .create_user("mallory", None, "unused", false) | |
| 509 | - .await | |
| 510 | - .unwrap(); | |
| 511 | - let job = new_job(&fx, Source::GitHub).await; | |
| 512 | - fx.state | |
| 513 | - .store | |
| 514 | - .set_import_state(&job.id, ImportState::Failed, Some("rate limit")) | |
| 515 | - .await | |
| 516 | - .unwrap(); | |
| 517 | - create_session( | |
| 518 | - &fx.state.store, | |
| 519 | - &other.id, | |
| 520 | - "retry-other-session", | |
| 521 | - "retry-csrf", | |
| 522 | - ) | |
| 523 | - .await; | |
| 524 | - | |
| 525 | - let router = app_router(fx.state.clone()); | |
| 526 | - let cookie = format!("__Host-{SESSION_COOKIE}=retry-other-session"); | |
| 527 | - | |
| 528 | - let page = router | |
| 529 | - .handle( | |
| 530 | - Request::builder() | |
| 531 | - .method("GET") | |
| 532 | - .uri("/import/retry") | |
| 533 | - .header("cookie", cookie.as_str()) | |
| 534 | - .body(Body::empty()) | |
| 535 | - .unwrap(), | |
| 536 | - ) | |
| 537 | - .await; | |
| 538 | - assert_eq!(page.status().as_u16(), 200); | |
| 539 | - let bytes = to_bytes(page.into_body(), usize::MAX).await.unwrap(); | |
| 540 | - assert!(String::from_utf8_lossy(&bytes).contains("No failed imports")); | |
| 541 | - | |
| 542 | - let form = format!("csrf=retry-csrf&token=&sel_0={}", job.id); | |
| 543 | - let res = router | |
| 544 | - .handle( | |
| 545 | - Request::builder() | |
| 546 | - .method("POST") | |
| 547 | - .uri("/import/retry") | |
| 548 | - .header("cookie", cookie.as_str()) | |
| 549 | - .header("content-type", "application/x-www-form-urlencoded") | |
| 550 | - .body(Body::from(form)) | |
| 551 | - .unwrap(), | |
| 552 | - ) | |
| 553 | - .await; | |
| 554 | - assert_eq!(res.status().as_u16(), 303); | |
| 555 | - let _ = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | |
| 556 | - | |
| 557 | - let after = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); | |
| 558 | - assert_eq!(after.state, ImportState::Failed); | |
| 559 | - assert_eq!(after.error.as_deref(), Some("rate limit")); | |
| 560 | -} | |
| 561 | - | |
| 562 | -#[test] | |
| 563 | -fn the_origin_note_escapes_the_mention_and_cleans_the_name() { | |
| 564 | - let note = origin_note( | |
| 565 | - "GitHub", | |
| 566 | - "evil @tahinli\n", | |
| 567 | - "2021-03-04T00:00:00Z", | |
| 568 | - "https://github.com/o/r/issues/1", | |
| 569 | - ); | |
| 570 | - assert!(note.starts_with("> Originally by \\@eviltahinli on GitHub, 2021-03-04")); | |
| 571 | - assert!(note.contains("[original](https://github.com/o/r/issues/1)")); | |
| 572 | - assert!(note.ends_with("\n\n")); | |
| 573 | - let none = origin_note("GitHub", "", "", "javascript:alert(1)"); | |
| 574 | - assert!(none.contains("\\@unknown")); | |
| 575 | - assert!(!none.contains("javascript")); | |
| 576 | -} | |
| 577 | - | |
| 578 | -#[test] | |
| 579 | -fn bodies_are_cut_at_the_limit_on_a_char_boundary() { | |
| 580 | - let long = "\u{e9}".repeat(forge_core::issues::MAX_BODY); | |
| 581 | - let text = with_note("> note\n\n", &long); | |
| 582 | - assert!(text.len() <= forge_core::issues::MAX_BODY); | |
| 583 | - assert!(text.ends_with("(cut)")); | |
| 584 | -} | |
| 585 | - | |
| 586 | -#[test] | |
| 587 | -fn asset_names_are_made_safe() { | |
| 588 | - assert_eq!(asset_name("app 1.tar.gz"), "app_1.tar.gz"); | |
| 589 | - assert_eq!(asset_name("../../etc/passwd"), "_.._etc_passwd"); | |
| 590 | - assert_eq!(asset_name(".hidden"), "hidden"); | |
| 591 | - assert_eq!(asset_name("###"), "___"); | |
| 592 | - assert_eq!(asset_name(""), "asset"); | |
| 593 | - assert!(forge_core::releases::valid_asset_name(&asset_name( | |
| 594 | - "a b/c?d" | |
| 595 | - ))); | |
| 596 | -} | |
| 597 | - | |
| 598 | -#[path = "forgejo_tests.rs"] | |
| 599 | -mod forgejo; |
crates/forge-web/src/main.rsmodified+0 -2
| @@ -9,8 +9,6 @@ mod boot; | ||
| 9 | 9 | #[cfg(test)] |
| 10 | 10 | mod compression_route_tests; |
| 11 | 11 | #[cfg(test)] |
| 12 | -mod importer_route_tests; | |
| 13 | -#[cfg(test)] | |
| 14 | 12 | mod page_route_tests; |
| 15 | 13 | #[cfg(test)] |
| 16 | 14 | mod route_list_tests; |
crates/forge-web/src/routes.snapmodified+0 -16
| @@ -27,9 +27,6 @@ page /admin/users/{user_id}/unsuspend Only([POST]) | ||
| 27 | 27 | page /explore Only([GET]) |
| 28 | 28 | page /forgot Only([GET]) |
| 29 | 29 | page /forgot Only([POST]) |
| 30 | -page /import Only([GET]) | |
| 31 | -page /import/retry Only([GET]) | |
| 32 | -page /import/{job_id} Only([GET]) | |
| 33 | 30 | page /login Only([GET]) |
| 34 | 31 | page /login Only([POST]) |
| 35 | 32 | page /login/2fa Only([GET]) |
| @@ -37,10 +34,6 @@ page /login/2fa Only([POST]) | ||
| 37 | 34 | page /needs-you Only([GET]) |
| 38 | 35 | page /new Only([GET]) |
| 39 | 36 | page /new Only([POST]) |
| 40 | -page /new/import Only([GET]) | |
| 41 | -page /new/import Only([POST]) | |
| 42 | -page /new/import/bulk Only([GET]) | |
| 43 | -page /new/import/bulk Only([POST]) | |
| 44 | 37 | page /notifications Only([GET]) |
| 45 | 38 | page /org/new Only([GET]) |
| 46 | 39 | page /org/new Only([POST]) |
| @@ -54,7 +47,6 @@ page /reset/{token} Only([GET]) | ||
| 54 | 47 | page /reset/{token} Only([POST]) |
| 55 | 48 | page /review-requests Only([GET]) |
| 56 | 49 | page /settings/appearance Only([GET]) |
| 57 | -page /settings/export Only([GET]) | |
| 58 | 50 | page /settings/gpg Only([GET]) |
| 59 | 51 | page /settings/gpg Only([POST]) |
| 60 | 52 | page /settings/keys Only([GET]) |
| @@ -245,10 +237,6 @@ route /attachments/{id}/{name} Only([GET]) | ||
| 245 | 237 | route /avatars/{username} Only([GET]) |
| 246 | 238 | route /explore/events Only([GET]) |
| 247 | 239 | route /healthz Only([GET]) |
| 248 | -route /import/events Only([GET]) | |
| 249 | -route /import/retry Only([POST]) | |
| 250 | -route /import/{job_id}/events Only([GET]) | |
| 251 | -route /import/{job_id}/retry Only([POST]) | |
| 252 | 240 | route /login/passkey/begin Only([POST]) |
| 253 | 241 | route /login/passkey/finish Only([POST]) |
| 254 | 242 | route /logout Only([POST]) |
| @@ -284,10 +272,6 @@ route /org/{org}/teams/{team}/update Only([POST]) | ||
| 284 | 272 | route /review-requests/events Only([GET]) |
| 285 | 273 | route /settings/appearance Only([POST]) |
| 286 | 274 | route /settings/events Only([GET]) |
| 287 | -route /settings/export Only([POST]) | |
| 288 | -route /settings/export/events Only([GET]) | |
| 289 | -route /settings/export/{export_id}/delete Only([POST]) | |
| 290 | -route /settings/export/{export_id}/download Only([GET]) | |
| 291 | 275 | route /settings/gpg/delete Only([POST]) |
| 292 | 276 | route /settings/keys/delete Only([POST]) |
| 293 | 277 | route /settings/notifications Only([POST]) |
docs/architecture.mdmodified+1 -1
| @@ -277,7 +277,7 @@ Pages update without a reload. A write that changes what a page shows calls `Liv | ||
| 277 | 277 | | Admin replication `/admin/replication` | `/admin/replication/events` | each copy's status and the database snapshot | |
| 278 | 278 | | 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 | |
| 279 | 279 | | 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 | |
| 280 | -| 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 | | |
| 280 | +| 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 | | |
| 281 | 281 | | 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 | |
| 282 | 282 | | 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 | |
| 283 | 283 |
docs/ui-language.mdmodified+1 -1
| @@ -206,7 +206,7 @@ Turkish page shows no English, an English page no Turkish. | ||
| 206 | 206 | - Every control has one focus ring: 2px in `--focus`, inside its own edge (`outline-offset: -2px`), so |
| 207 | 207 | no sheet, row or scrolling list cuts it. |
| 208 | 208 | - A tab's own pages sit in its rail: the Security log is a Security rail item, not a page of its own. |
| 209 | -- No page is an orphan. A page that makes or shows something of yours (a new repository, an import, a | |
| 209 | +- No page is an orphan. A page that makes or shows something of yours (a new repository, a | |
| 210 | 210 | new organization) shows your profile tabs with the area it belongs to marked, and the inbox |
| 211 | 211 | pages (Notifications, Needs you, Review requests) share one rail, so a mouse reaches every neighbour. |
| 212 | 212 | - An action a server cannot carry out shows as unavailable: no "send again" when mail is not set up. |
style/_import.scssdeleted+0 -81
| @@ -1,81 +0,0 @@ | ||
| 1 | - | |
| 2 | - | |
| 3 | -.import-pick-list { | |
| 4 | - max-height: 60vh; | |
| 5 | - margin: 0; | |
| 6 | - padding: 0; | |
| 7 | - overflow-y: auto; | |
| 8 | - list-style: none; | |
| 9 | - | |
| 10 | -} | |
| 11 | - | |
| 12 | -.import-job { | |
| 13 | - display: flex; | |
| 14 | - flex-direction: column; | |
| 15 | - gap: 16px; | |
| 16 | - max-width: 960px; | |
| 17 | - min-width: 0; | |
| 18 | -} | |
| 19 | - | |
| 20 | -.import-progress { | |
| 21 | - width: 100%; | |
| 22 | - height: 8px; | |
| 23 | - border-radius: var(--radius-full); | |
| 24 | - overflow: hidden; | |
| 25 | -} | |
| 26 | - | |
| 27 | -.badge.import-running { | |
| 28 | - background: var(--accent-soft, var(--surface-2)); | |
| 29 | - color: var(--accent-ink); | |
| 30 | -} | |
| 31 | - | |
| 32 | -.badge.import-failed { | |
| 33 | - background: var(--danger-bg); | |
| 34 | - color: var(--alert-text); | |
| 35 | -} | |
| 36 | - | |
| 37 | -.import-log-title { | |
| 38 | - margin: 0; | |
| 39 | - font-size: 0.9375rem; | |
| 40 | -} | |
| 41 | - | |
| 42 | -.import-log { | |
| 43 | - display: flex; | |
| 44 | - flex-direction: column; | |
| 45 | - gap: 2px; | |
| 46 | - max-height: 46vh; | |
| 47 | - margin: 0; | |
| 48 | - padding: 0; | |
| 49 | - overflow-y: auto; | |
| 50 | - list-style: none; | |
| 51 | - font-family: var(--mono); | |
| 52 | - font-size: 0.8125rem; | |
| 53 | -} | |
| 54 | - | |
| 55 | -.import-log-line { | |
| 56 | - overflow-wrap: anywhere; | |
| 57 | - color: var(--text-2); | |
| 58 | - | |
| 59 | - &.import-log-warn { | |
| 60 | - color: var(--warn); | |
| 61 | - } | |
| 62 | - | |
| 63 | - &.import-log-error { | |
| 64 | - color: var(--danger); | |
| 65 | - } | |
| 66 | -} | |
| 67 | - | |
| 68 | -.export-page { | |
| 69 | - display: flex; | |
| 70 | - flex-direction: column; | |
| 71 | - gap: 16px; | |
| 72 | - max-width: 960px; | |
| 73 | -} | |
| 74 | - | |
| 75 | -.export-progress { | |
| 76 | - width: 120px; | |
| 77 | -} | |
| 78 | - | |
| 79 | -@media (max-width: 560px) { | |
| 80 | - | |
| 81 | -} |
style/_look.scssmodified+0 -1
| @@ -41,7 +41,6 @@ th, | ||
| 41 | 41 | .ci-side-title, |
| 42 | 42 | .ci-art-title, |
| 43 | 43 | .ci-warnings-title, |
| 44 | -.import-log-title, | |
| 45 | 44 | .row-title, |
| 46 | 45 | .mx-caption, |
| 47 | 46 | .card > .muted.small:first-child:has(+ .table-wrap, + .table, + ul, + ol) { |
style/_min_settings.scssmodified+1 -24
| @@ -53,30 +53,7 @@ | ||
| 53 | 53 | } |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | -// Data export: each archive is one flat line (when, state, Download, Delete); a building one adds its | |
| 57 | -// progress and an error under the line. | |
| 58 | -.export-row { | |
| 59 | - display: block; | |
| 60 | - margin: 0 -18px; | |
| 61 | - border-bottom: 1px solid var(--border); | |
| 62 | - | |
| 63 | - &:last-child { | |
| 64 | - border-bottom: 0; | |
| 65 | - } | |
| 66 | - | |
| 67 | - > .line { | |
| 68 | - padding-left: 18px; | |
| 69 | - padding-right: 18px; | |
| 70 | - border-bottom: 0; | |
| 71 | - } | |
| 72 | - | |
| 73 | - > progress, | |
| 74 | - > .alert { | |
| 75 | - margin: 0 18px 10px; | |
| 76 | - } | |
| 77 | -} | |
| 78 | - | |
| 79 | -// A request that cannot be sent right now (an export is building). | |
| 56 | +// A request that cannot be sent right now. | |
| 80 | 57 | button.act:disabled, |
| 81 | 58 | button.act:disabled:hover { |
| 82 | 59 | color: var(--muted); |
style/main.scssmodified+0 -1
| @@ -5451,7 +5451,6 @@ button.ci-job-last { | ||
| 5451 | 5451 | @import "pull"; |
| 5452 | 5452 | @import "dashboard"; |
| 5453 | 5453 | @import "browse"; |
| 5454 | -@import "import"; | |
| 5455 | 5454 | @import "authoring"; |
| 5456 | 5455 | |
| 5457 | 5456 | // Code inside cards, notices and settings panels must stay inside the card. Long tokens and |