forge
Explore
Log in

Don't you dare go Hollow

Route tests for import and export pages

Browse files at this commit

b6fa921136aea8d2a76691b3c57c86c9b5dfa2aaAhmet Kaan GümüşParent: eeec007
  • test
    • route tests for import and export pages
Show full message
✅ test: route tests for import and export pages

Includes: ✨ feat: import repos from git, GitHub and GitLab; per-user data export
Cargo.lockmodified+2 -0
@@ -1962,6 +1962,7 @@ dependencies = [
1962 "bytes",1962 "bytes",
1963 "comrak",1963 "comrak",
1964 "emojis",1964 "emojis",
1965+ "flate2",
1965 "forge-ci",1966 "forge-ci",
1966 "forge-core",1967 "forge-core",
1967 "forge-git",1968 "forge-git",
@@ -1991,6 +1992,7 @@ dependencies = [
1991 "similar",1992 "similar",
1992 "subtle",1993 "subtle",
1993 "syntect",1994 "syntect",
1995+ "tar",
1994 "tempfile",1996 "tempfile",
1995 "time",1997 "time",
1996 "tokio",1998 "tokio",
crates/forge-core/migrations/0061_imports.sqladded+38 -0
@@ -0,0 +1,38 @@
1+-- Repository imports from a git URL, GitHub or GitLab. A job is the visible, resumable unit of work.
2+-- The remote token is never stored: it lives in memory for the length of the job only.
3+
4+CREATE TABLE import_jobs (
5+ id TEXT PRIMARY KEY,
6+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
7+ repo_id TEXT REFERENCES repos(id) ON DELETE SET NULL,
8+ source TEXT NOT NULL, -- 'git' | 'github' | 'gitlab'
9+ source_ref TEXT NOT NULL, -- what the user typed, without credentials
10+ options TEXT NOT NULL DEFAULT '{}', -- JSON: which parts to import
11+ state TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed
12+ stage TEXT NOT NULL DEFAULT '',
13+ done INTEGER NOT NULL DEFAULT 0,
14+ total INTEGER NOT NULL DEFAULT 0,
15+ error TEXT,
16+ created_at TEXT NOT NULL,
17+ updated_at TEXT NOT NULL,
18+ finished_at TEXT);
19+CREATE INDEX import_jobs_user ON import_jobs(user_id, created_at);
20+
21+CREATE TABLE import_events (
22+ job_id TEXT NOT NULL REFERENCES import_jobs(id) ON DELETE CASCADE,
23+ seq INTEGER NOT NULL,
24+ level TEXT NOT NULL, -- 'info' | 'warn' | 'error'
25+ message TEXT NOT NULL,
26+ created_at TEXT NOT NULL,
27+ PRIMARY KEY (job_id, seq));
28+
29+-- Maps a remote object to the local one, so a retry skips what was imported already. Also keeps
30+-- who wrote the original and where it lives, for people with no local account.
31+CREATE TABLE import_map (
32+ repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
33+ kind TEXT NOT NULL, -- label | milestone | issue | comment | release | asset
34+ ext_id TEXT NOT NULL,
35+ local_id TEXT NOT NULL,
36+ orig_author TEXT NOT NULL DEFAULT '',
37+ orig_url TEXT NOT NULL DEFAULT '',
38+ PRIMARY KEY (repo_id, kind, ext_id));
crates/forge-core/migrations/0062_data_exports.sqladded+12 -0
@@ -0,0 +1,12 @@
1+-- Per-user data exports: a tar.gz built in the background, downloadable until it expires.
2+
3+CREATE TABLE data_exports (
4+ id TEXT PRIMARY KEY,
5+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
6+ state TEXT NOT NULL DEFAULT 'building', -- building | ready | failed
7+ size INTEGER NOT NULL DEFAULT 0,
8+ error TEXT,
9+ created_at TEXT NOT NULL,
10+ ready_at TEXT,
11+ expires_at TEXT NOT NULL);
12+CREATE INDEX data_exports_user ON data_exports(user_id, created_at);
crates/forge-core/src/store/exports.rsadded+168 -0
@@ -0,0 +1,168 @@
1+//! Storage for per-user data exports (migration 0062). The archive bytes live on disk; this layer
2+//! tracks the state and the expiry.
3+
4+use std::time::Duration;
5+
6+use turso::{Row, Value};
7+
8+use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
9+use crate::error::Result;
10+use crate::time::{now_stamp, stamp_after};
11+
12+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13+pub enum ExportState {
14+ Building,
15+ Ready,
16+ Failed,
17+}
18+
19+impl ExportState {
20+ pub fn as_str(self) -> &'static str {
21+ match self {
22+ ExportState::Building => "building",
23+ ExportState::Ready => "ready",
24+ ExportState::Failed => "failed",
25+ }
26+ }
27+
28+ fn parse(s: &str) -> Self {
29+ match s {
30+ "ready" => ExportState::Ready,
31+ "failed" => ExportState::Failed,
32+ _ => ExportState::Building,
33+ }
34+ }
35+}
36+
37+#[derive(Debug, Clone, PartialEq)]
38+pub struct DataExport {
39+ pub id: String,
40+ pub user_id: String,
41+ pub state: ExportState,
42+ pub size: i64,
43+ pub error: Option<String>,
44+ pub created_at: String,
45+ pub ready_at: Option<String>,
46+ pub expires_at: String,
47+}
48+
49+const COLS: &str = "id, user_id, state, size, error, created_at, ready_at, expires_at";
50+
51+fn map_export(row: &Row) -> Result<DataExport> {
52+ Ok(DataExport {
53+ id: col_text(row, 0)?,
54+ user_id: col_text(row, 1)?,
55+ state: ExportState::parse(&col_text(row, 2)?),
56+ size: col_int(row, 3)?,
57+ error: col_opt_text(row, 4)?,
58+ created_at: col_text(row, 5)?,
59+ ready_at: col_opt_text(row, 6)?,
60+ expires_at: col_text(row, 7)?,
61+ })
62+}
63+
64+impl Store {
65+ /// Starts an export. It expires `ttl` from now; becoming ready restarts the clock.
66+ pub async fn create_export(&self, user_id: &str, ttl: Duration) -> Result<DataExport> {
67+ let id = new_id();
68+ let now = now_stamp();
69+ let expires = stamp_after(ttl);
70+ {
71+ let conn = self.inner.conn.lock().await;
72+ conn.execute(
73+ "INSERT INTO data_exports (id, user_id, created_at, expires_at) \
74+ VALUES (?1, ?2, ?3, ?4)",
75+ (id.clone(), user_id.to_owned(), now, expires),
76+ )
77+ .await
78+ .map_err(db_err)?;
79+ }
80+ self.data_export(&id).await?.ok_or_else(super::missing_row)
81+ }
82+
83+ pub async fn data_export(&self, id: &str) -> Result<Option<DataExport>> {
84+ let conn = self.inner.conn.lock().await;
85+ fetch_opt(
86+ &conn,
87+ &format!("SELECT {COLS} FROM data_exports WHERE id = ?1"),
88+ (id.to_owned(),),
89+ map_export,
90+ )
91+ .await
92+ }
93+
94+ /// The user's exports, newest first.
95+ pub async fn list_exports(&self, user_id: &str) -> Result<Vec<DataExport>> {
96+ let conn = self.inner.conn.lock().await;
97+ fetch_all(
98+ &conn,
99+ &format!(
100+ "SELECT {COLS} FROM data_exports WHERE user_id = ?1 ORDER BY created_at DESC, id DESC"
101+ ),
102+ (user_id.to_owned(),),
103+ map_export,
104+ )
105+ .await
106+ }
107+
108+ /// Marks an export ready and restarts its expiry from now.
109+ pub async fn mark_export_ready(&self, id: &str, size: i64, ttl: Duration) -> Result<()> {
110+ let conn = self.inner.conn.lock().await;
111+ conn.execute(
112+ "UPDATE data_exports SET state = 'ready', size = ?2, ready_at = ?3, expires_at = ?4 \
113+ WHERE id = ?1",
114+ vec![
115+ Value::Text(id.to_owned()),
116+ Value::Integer(size),
117+ Value::Text(now_stamp()),
118+ Value::Text(stamp_after(ttl)),
119+ ],
120+ )
121+ .await
122+ .map_err(db_err)?;
123+ Ok(())
124+ }
125+
126+ pub async fn mark_export_failed(&self, id: &str, error: &str) -> Result<()> {
127+ let conn = self.inner.conn.lock().await;
128+ conn.execute(
129+ "UPDATE data_exports SET state = 'failed', error = ?2 WHERE id = ?1",
130+ (id.to_owned(), error.to_owned()),
131+ )
132+ .await
133+ .map_err(db_err)?;
134+ Ok(())
135+ }
136+
137+ /// Exports whose expiry has passed at `now`.
138+ pub async fn expired_exports(&self, now: &str) -> Result<Vec<DataExport>> {
139+ let conn = self.inner.conn.lock().await;
140+ fetch_all(
141+ &conn,
142+ &format!("SELECT {COLS} FROM data_exports WHERE expires_at <= ?1"),
143+ (now.to_owned(),),
144+ map_export,
145+ )
146+ .await
147+ }
148+
149+ pub async fn delete_export(&self, id: &str) -> Result<()> {
150+ let conn = self.inner.conn.lock().await;
151+ conn.execute("DELETE FROM data_exports WHERE id = ?1", (id.to_owned(),))
152+ .await
153+ .map_err(db_err)?;
154+ Ok(())
155+ }
156+
157+ /// Fails exports that were still building when the process stopped. Called at boot.
158+ pub async fn fail_interrupted_exports(&self) -> Result<u64> {
159+ let conn = self.inner.conn.lock().await;
160+ conn.execute(
161+ "UPDATE data_exports SET state = 'failed', error = 'interrupted by a server restart' \
162+ WHERE state = 'building'",
163+ (),
164+ )
165+ .await
166+ .map_err(db_err)
167+ }
168+}
crates/forge-core/src/store/imports.rsadded+351 -0
@@ -0,0 +1,351 @@
1+//! Storage for repository import jobs, their progress log and the remote-to-local id map
2+//! (migration 0061). No remote credential is ever stored here.
3+
4+use turso::{Row, Value};
5+
6+use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
7+use crate::error::{Error, Result};
8+use crate::time::now_stamp;
9+
10+/// Most progress lines kept per job. Older ones are dropped as new ones arrive.
11+pub const MAX_EVENTS: i64 = 500;
12+
13+/// Where a job is.
14+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15+pub enum ImportState {
16+ Queued,
17+ Running,
18+ Done,
19+ Failed,
20+}
21+
22+impl ImportState {
23+ pub fn as_str(self) -> &'static str {
24+ match self {
25+ ImportState::Queued => "queued",
26+ ImportState::Running => "running",
27+ ImportState::Done => "done",
28+ ImportState::Failed => "failed",
29+ }
30+ }
31+
32+ pub fn is_finished(self) -> bool {
33+ matches!(self, ImportState::Done | ImportState::Failed)
34+ }
35+
36+ fn parse(s: &str) -> Result<Self> {
37+ match s {
38+ "queued" => Ok(ImportState::Queued),
39+ "running" => Ok(ImportState::Running),
40+ "done" => Ok(ImportState::Done),
41+ "failed" => Ok(ImportState::Failed),
42+ other => Err(Error::Database(format!("unknown import state `{other}`"))),
43+ }
44+ }
45+}
46+
47+#[derive(Debug, Clone, PartialEq)]
48+pub struct ImportJob {
49+ pub id: String,
50+ pub user_id: String,
51+ pub repo_id: Option<String>,
52+ pub source: String,
53+ pub source_ref: String,
54+ pub options: String,
55+ pub state: ImportState,
56+ pub stage: String,
57+ pub done: i64,
58+ pub total: i64,
59+ pub error: Option<String>,
60+ pub created_at: String,
61+ pub updated_at: String,
62+ pub finished_at: Option<String>,
63+}
64+
65+#[derive(Debug, Clone, PartialEq)]
66+pub struct ImportEvent {
67+ pub seq: i64,
68+ pub level: String,
69+ pub message: String,
70+ pub created_at: String,
71+}
72+
73+/// The remote object a local row came from.
74+#[derive(Debug, Clone, PartialEq)]
75+pub struct ImportOrigin {
76+ pub local_id: String,
77+ pub author: String,
78+ pub url: String,
79+}
80+
81+const JOB_COLS: &str = "id, user_id, repo_id, source, source_ref, options, state, stage, done, \
82+ total, error, created_at, updated_at, finished_at";
83+
84+fn map_job(row: &Row) -> Result<ImportJob> {
85+ Ok(ImportJob {
86+ id: col_text(row, 0)?,
87+ user_id: col_text(row, 1)?,
88+ repo_id: col_opt_text(row, 2)?,
89+ source: col_text(row, 3)?,
90+ source_ref: col_text(row, 4)?,
91+ options: col_text(row, 5)?,
92+ state: ImportState::parse(&col_text(row, 6)?)?,
93+ stage: col_text(row, 7)?,
94+ done: col_int(row, 8)?,
95+ total: col_int(row, 9)?,
96+ error: col_opt_text(row, 10)?,
97+ created_at: col_text(row, 11)?,
98+ updated_at: col_text(row, 12)?,
99+ finished_at: col_opt_text(row, 13)?,
100+ })
101+}
102+
103+fn text(s: &str) -> Value {
104+ Value::Text(s.to_owned())
105+}
106+
107+impl Store {
108+ /// Creates a queued job. `source_ref` must not hold a credential.
109+ pub async fn create_import_job(
110+ &self,
111+ user_id: &str,
112+ repo_id: &str,
113+ source: &str,
114+ source_ref: &str,
115+ options: &str,
116+ ) -> Result<ImportJob> {
117+ let id = new_id();
118+ let now = now_stamp();
119+ {
120+ let conn = self.inner.conn.lock().await;
121+ conn.execute(
122+ "INSERT INTO import_jobs (id, user_id, repo_id, source, source_ref, options, \
123+ created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)",
124+ vec![
125+ text(&id),
126+ text(user_id),
127+ text(repo_id),
128+ text(source),
129+ text(source_ref),
130+ text(options),
131+ text(&now),
132+ ],
133+ )
134+ .await
135+ .map_err(db_err)?;
136+ }
137+ self.import_job(&id).await?.ok_or_else(super::missing_row)
138+ }
139+
140+ pub async fn import_job(&self, id: &str) -> Result<Option<ImportJob>> {
141+ let conn = self.inner.conn.lock().await;
142+ fetch_opt(
143+ &conn,
144+ &format!("SELECT {JOB_COLS} FROM import_jobs WHERE id = ?1"),
145+ (id.to_owned(),),
146+ map_job,
147+ )
148+ .await
149+ }
150+
151+ /// The user's jobs, newest first.
152+ pub async fn list_import_jobs(&self, user_id: &str, limit: u32) -> Result<Vec<ImportJob>> {
153+ let conn = self.inner.conn.lock().await;
154+ fetch_all(
155+ &conn,
156+ &format!(
157+ "SELECT {JOB_COLS} FROM import_jobs WHERE user_id = ?1 \
158+ ORDER BY created_at DESC, id DESC LIMIT ?2"
159+ ),
160+ (user_id.to_owned(), i64::from(limit.clamp(1, 200))),
161+ map_job,
162+ )
163+ .await
164+ }
165+
166+ /// The unfinished job of a repo, if any. A repo has at most one running import.
167+ pub async fn active_import_for_repo(&self, repo_id: &str) -> Result<Option<ImportJob>> {
168+ let conn = self.inner.conn.lock().await;
169+ fetch_opt(
170+ &conn,
171+ &format!(
172+ "SELECT {JOB_COLS} FROM import_jobs WHERE repo_id = ?1 \
173+ AND state IN ('queued', 'running') LIMIT 1"
174+ ),
175+ (repo_id.to_owned(),),
176+ map_job,
177+ )
178+ .await
179+ }
180+
181+ /// Moves a job to `state`. A finished state stamps `finished_at`. A retry clears the error.
182+ pub async fn set_import_state(
183+ &self,
184+ id: &str,
185+ state: ImportState,
186+ error: Option<&str>,
187+ ) -> Result<()> {
188+ let now = now_stamp();
189+ let finished = state.is_finished().then(|| now.clone());
190+ let conn = self.inner.conn.lock().await;
191+ conn.execute(
192+ "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \
193+ WHERE id = ?1",
194+ vec![
195+ text(id),
196+ text(state.as_str()),
197+ error.map_or(Value::Null, text),
198+ text(&now),
199+ finished.as_deref().map_or(Value::Null, text),
200+ ],
201+ )
202+ .await
203+ .map_err(db_err)?;
204+ Ok(())
205+ }
206+
207+ /// Records the current stage and how far it is.
208+ pub async fn set_import_progress(
209+ &self,
210+ id: &str,
211+ stage: &str,
212+ done: i64,
213+ total: i64,
214+ ) -> Result<()> {
215+ let conn = self.inner.conn.lock().await;
216+ conn.execute(
217+ "UPDATE import_jobs SET stage = ?2, done = ?3, total = ?4, updated_at = ?5 WHERE id = ?1",
218+ vec![
219+ text(id),
220+ text(stage),
221+ Value::Integer(done),
222+ Value::Integer(total),
223+ text(&now_stamp()),
224+ ],
225+ )
226+ .await
227+ .map_err(db_err)?;
228+ Ok(())
229+ }
230+
231+ /// Appends a progress line and drops the oldest beyond [`MAX_EVENTS`].
232+ pub async fn add_import_event(&self, job_id: &str, level: &str, message: &str) -> Result<()> {
233+ let conn = self.inner.conn.lock().await;
234+ let next = fetch_opt(
235+ &conn,
236+ "SELECT COALESCE(MAX(seq), 0) + 1 FROM import_events WHERE job_id = ?1",
237+ (job_id.to_owned(),),
238+ |row| col_int(row, 0),
239+ )
240+ .await?
241+ .unwrap_or(1);
242+ conn.execute(
243+ "INSERT INTO import_events (job_id, seq, level, message, created_at) \
244+ VALUES (?1, ?2, ?3, ?4, ?5)",
245+ vec![
246+ text(job_id),
247+ Value::Integer(next),
248+ text(level),
249+ text(message),
250+ text(&now_stamp()),
251+ ],
252+ )
253+ .await
254+ .map_err(db_err)?;
255+ conn.execute(
256+ "DELETE FROM import_events WHERE job_id = ?1 AND seq <= ?2",
257+ (job_id.to_owned(), next - MAX_EVENTS),
258+ )
259+ .await
260+ .map_err(db_err)?;
261+ Ok(())
262+ }
263+
264+ /// The newest `limit` lines of a job, oldest first.
265+ pub async fn list_import_events(&self, job_id: &str, limit: u32) -> Result<Vec<ImportEvent>> {
266+ let conn = self.inner.conn.lock().await;
267+ let mut rows = fetch_all(
268+ &conn,
269+ "SELECT seq, level, message, created_at FROM import_events WHERE job_id = ?1 \
270+ ORDER BY seq DESC LIMIT ?2",
271+ (job_id.to_owned(), i64::from(limit.clamp(1, 500))),
272+ |row| {
273+ Ok(ImportEvent {
274+ seq: col_int(row, 0)?,
275+ level: col_text(row, 1)?,
276+ message: col_text(row, 2)?,
277+ created_at: col_text(row, 3)?,
278+ })
279+ },
280+ )
281+ .await?;
282+ rows.reverse();
283+ Ok(rows)
284+ }
285+
286+ /// The local row a remote object was imported as, if it was.
287+ pub async fn import_origin(
288+ &self,
289+ repo_id: &str,
290+ kind: &str,
291+ ext_id: &str,
292+ ) -> Result<Option<ImportOrigin>> {
293+ let conn = self.inner.conn.lock().await;
294+ fetch_opt(
295+ &conn,
296+ "SELECT local_id, orig_author, orig_url FROM import_map \
297+ WHERE repo_id = ?1 AND kind = ?2 AND ext_id = ?3",
298+ (repo_id.to_owned(), kind.to_owned(), ext_id.to_owned()),
299+ |row| {
300+ Ok(ImportOrigin {
301+ local_id: col_text(row, 0)?,
302+ author: col_text(row, 1)?,
303+ url: col_text(row, 2)?,
304+ })
305+ },
306+ )
307+ .await
308+ }
309+
310+ /// Records that a remote object became `origin.local_id`. Idempotent.
311+ pub async fn record_import_origin(
312+ &self,
313+ repo_id: &str,
314+ kind: &str,
315+ ext_id: &str,
316+ origin: &ImportOrigin,
317+ ) -> Result<()> {
318+ let conn = self.inner.conn.lock().await;
319+ conn.execute(
320+ "INSERT INTO import_map (repo_id, kind, ext_id, local_id, orig_author, orig_url) \
321+ VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(repo_id, kind, ext_id) DO UPDATE SET \
322+ local_id = excluded.local_id, orig_author = excluded.orig_author, \
323+ orig_url = excluded.orig_url",
324+ vec![
325+ text(repo_id),
326+ text(kind),
327+ text(ext_id),
328+ text(&origin.local_id),
329+ text(&origin.author),
330+ text(&origin.url),
331+ ],
332+ )
333+ .await
334+ .map_err(db_err)?;
335+ Ok(())
336+ }
337+
338+ /// Fails every job that was queued or running when the process stopped. Called at boot.
339+ pub async fn fail_interrupted_imports(&self) -> Result<u64> {
340+ let now = now_stamp();
341+ let conn = self.inner.conn.lock().await;
342+ conn.execute(
343+ "UPDATE import_jobs SET state = 'failed', updated_at = ?1, finished_at = ?1, \
344+ error = 'interrupted by a server restart, retry to continue' \
345+ WHERE state IN ('queued', 'running')",
346+ (now,),
347+ )
348+ .await
349+ .map_err(db_err)
350+ }
351+}
crates/forge-core/src/store/migrate.rsmodified+2 -0
@@ -80,6 +80,8 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
80 53,80 53,
81 include_str!("../../migrations/0053_required_checks.sql"),81 include_str!("../../migrations/0053_required_checks.sql"),
82 ),82 ),
83+ (61, include_str!("../../migrations/0061_imports.sql")),
84+ (62, include_str!("../../migrations/0062_data_exports.sql")),
83 ];85 ];
84 86
85 /// The highest migration version this binary knows about.87 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+2 -0
@@ -9,6 +9,8 @@ pub mod commit_status;
9 pub mod contributions;9 pub mod contributions;
10 pub mod discussions;10 pub mod discussions;
11 pub mod edit_history_read;11 pub mod edit_history_read;
12+pub mod exports;
13+pub mod imports;
12 pub mod issues;14 pub mod issues;
13 pub mod labels;15 pub mod labels;
14 pub mod lfs;16 pub mod lfs;
crates/forge-git/src/mirror.rsmodified+13 -0
@@ -102,6 +102,19 @@ pub async fn mirror_fetch(
102 with_timeout(timeout, fetch(env, repo, url, auth, allow_http, pin, false)).await102 with_timeout(timeout, fetch(env, repo, url, auth, allow_http, pin, false)).await
103 }103 }
104 104
105+/// Fetches the mirror refs of a local path over the file transport. This exists so callers' tests
106+/// can import from a bare repo on disk; the web code never calls it, because every user-supplied
107+/// URL goes through [`mirror_fetch`], which refuses `file://`.
108+#[doc(hidden)]
109+pub async fn mirror_fetch_local(
110+ env: &GitEnv,
111+ repo: &Path,
112+ source: &str,
113+ timeout: Duration,
114+) -> Result<()> {
115+ with_timeout(timeout, fetch(env, repo, source, None, false, None, true)).await
116+}
117+
105 /// Pushes the mirror refs of the bare repo at `repo` to `url`, with prune. With `pin`, git connects118 /// Pushes the mirror refs of the bare repo at `repo` to `url`, with prune. With `pin`, git connects
106 /// to the pinned address. Times out after `timeout`, killing git.119 /// to the pinned address. Times out after `timeout`, killing git.
107 pub async fn mirror_push(120 pub async fn mirror_push(
crates/forge-web/Cargo.tomlmodified+2 -0
@@ -53,6 +53,8 @@ ulid.workspace = true
53 forge-runner = { workspace = true }53 forge-runner = { workspace = true }
54 lettre.workspace = true54 lettre.workspace = true
55 zip = { workspace = true }55 zip = { workspace = true }
56+tar.workspace = true
57+flate2.workspace = true
56 58
57 [build-dependencies]59 [build-dependencies]
58 grass.workspace = true60 grass.workspace = true
crates/forge-web/assets/nav.jsmodified+12 -0
@@ -525,6 +525,18 @@
525 searchTimer = setTimeout(function () { searchTimer = null; liveSearch(input); }, 250);525 searchTimer = setTimeout(function () { searchTimer = null; liveSearch(input); }, 250);
526 });526 });
527 527
528+ // A checkbox marked data-select-all="<selector>" ticks or clears every checkbox inside the first
529+ // element that matches the selector (the bulk import list).
530+ document.addEventListener('change', function (e) {
531+ var all = e.target && e.target.closest ? e.target.closest('[data-select-all]') : null;
532+ if (!all) { return; }
533+ var scope = document.querySelector(all.getAttribute('data-select-all'));
534+ if (!scope) { return; }
535+ Array.prototype.forEach.call(scope.querySelectorAll('input[type="checkbox"]'), function (box) {
536+ box.checked = all.checked;
537+ });
538+ });
539+
528 // Filter controls submit their form on change.540 // Filter controls submit their form on change.
529 document.addEventListener('change', function (e) {541 document.addEventListener('change', function (e) {
530 var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null;542 var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null;
crates/forge-web/src/boot.rsmodified+2 -0
@@ -141,6 +141,8 @@ pub async fn serve(
141 if let Err(e) = crate::signatures::rebuild_gpg_keyring(&state).await {141 if let Err(e) = crate::signatures::rebuild_gpg_keyring(&state).await {
142 tracing::error!(error = %e, "rebuilding the GPG keyring failed");142 tracing::error!(error = %e, "rebuilding the GPG keyring failed");
143 }143 }
144+ crate::importer::on_boot(&state).await;
145+ crate::exporter::on_boot(&state).await;
144 crate::webhooks::worker::spawn(state.clone());146 crate::webhooks::worker::spawn(state.clone());
145 crate::mirrors::worker::spawn(state.clone());147 crate::mirrors::worker::spawn(state.clone());
146 crate::advisories::worker::spawn(state.clone());148 crate::advisories::worker::spawn(state.clone());
crates/forge-web/src/exporter.rsadded+390 -0
@@ -0,0 +1,390 @@
1+//! Per-user data export: a tar.gz of the user's repos as bare git bundles, plus their issues with
2+//! comments, releases and profile as JSON. It is built in a background task, and the user is told
3+//! when it is ready (the export page updates through its event stream, and a mail goes out when the
4+//! account has an address). An export expires after [`EXPORT_TTL`]. Expired files are removed the
5+//! next time anyone starts or lists an export and at boot, so nothing waits on a timer.
6+//!
7+//! Archive layout:
8+//! - `profile.json`
9+//! - `repos/<name>/repo.bundle` (absent for an empty repo)
10+//! - `repos/<name>/repo.json` (description, visibility, default branch, labels, milestones)
11+//! - `repos/<name>/issues.json` (issues and pull requests, each with its comments)
12+//! - `repos/<name>/releases.json` (release metadata and asset names, not the asset bytes)
13+
14+use std::collections::HashMap;
15+use std::path::{Path, PathBuf};
16+use std::sync::{LazyLock, Mutex, PoisonError};
17+use std::time::Duration;
18+
19+use forge_core::issues::IssueFilter;
20+use forge_core::store::exports::{DataExport, ExportState};
21+use forge_core::time::now_stamp;
22+use forge_core::{IssueSort, Repo, User};
23+use forge_git::backup::bundle_create;
24+use serde_json::{Value, json};
25+use tokio::sync::watch;
26+
27+use crate::state::AppState;
28+
29+/// How long a finished export stays downloadable.
30+pub const EXPORT_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
31+/// How many days that is, for the page text.
32+pub const EXPORT_TTL_DAYS: u64 = 7;
33+const PAGE: u32 = 100;
34+
35+static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> =
36+ LazyLock::new(|| Mutex::new(HashMap::new()));
37+
38+/// Follows a user's exports. Subscribe before reading their state.
39+pub fn subscribe(user_id: &str) -> watch::Receiver<u64> {
40+ HUB.lock()
41+ .unwrap_or_else(PoisonError::into_inner)
42+ .entry(user_id.to_owned())
43+ .or_insert_with(|| watch::channel(0).0)
44+ .subscribe()
45+}
46+
47+fn bump(user_id: &str) {
48+ let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner);
49+ if let Some(tx) = hub.get(user_id) {
50+ tx.send_modify(|n| *n = n.wrapping_add(1));
51+ if tx.receiver_count() == 0 {
52+ hub.remove(user_id);
53+ }
54+ }
55+}
56+
57+pub fn export_dir(state: &AppState) -> PathBuf {
58+ state.config.data_dir.join("exports")
59+}
60+
61+pub fn archive_path(state: &AppState, id: &str) -> PathBuf {
62+ export_dir(state).join(format!("{id}.tar.gz"))
63+}
64+
65+/// Starts an export for `user` and returns its row. At most one runs per user: a second request
66+/// while one is building returns that one.
67+pub async fn start(state: &AppState, user: &User) -> forge_core::Result<DataExport> {
68+ sweep_expired(state).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 _ = tokio::fs::remove_file(archive_path(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+/// Builds the archive and returns its size in bytes.
137+async fn build(state: &AppState, user: &User, id: &str) -> Result<u64, String> {
138+ let dir = export_dir(state);
139+ tokio::fs::create_dir_all(&dir)
140+ .await
141+ .map_err(|e| e.to_string())?;
142+ let work = dir.join(format!("{id}.work"));
143+ let _ = tokio::fs::remove_dir_all(&work).await;
144+ tokio::fs::create_dir_all(work.join("repos"))
145+ .await
146+ .map_err(|e| e.to_string())?;
147+ let result = stage_and_pack(state, user, id, &work).await;
148+ let _ = tokio::fs::remove_dir_all(&work).await;
149+ result
150+}
151+
152+async fn stage_and_pack(
153+ state: &AppState,
154+ user: &User,
155+ id: &str,
156+ work: &Path,
157+) -> Result<u64, String> {
158+ write_json(&work.join("profile.json"), &profile_json(user)).await?;
159+ let repos = state
160+ .store
161+ .list_repos_by_owner(&user.id)
162+ .await
163+ .map_err(|e| e.to_string())?;
164+ for repo in &repos {
165+ let repo_dir = work.join("repos").join(&repo.name);
166+ tokio::fs::create_dir_all(&repo_dir)
167+ .await
168+ .map_err(|e| e.to_string())?;
169+ stage_repo(state, repo, &repo_dir).await?;
170+ }
171+ let target = archive_path(state, id);
172+ let partial = target.with_extension("part");
173+ let (work_buf, partial_buf, name) = (
174+ work.to_path_buf(),
175+ partial.clone(),
176+ format!("forge-export-{}", user.username),
177+ );
178+ tokio::task::spawn_blocking(move || pack(&work_buf, &partial_buf, &name))
179+ .await
180+ .map_err(|e| e.to_string())??;
181+ tokio::fs::rename(&partial, &target)
182+ .await
183+ .map_err(|e| e.to_string())?;
184+ let meta = tokio::fs::metadata(&target)
185+ .await
186+ .map_err(|e| e.to_string())?;
187+ Ok(meta.len())
188+}
189+
190+fn pack(work: &Path, out: &Path, top: &str) -> Result<(), String> {
191+ use std::os::unix::fs::OpenOptionsExt;
192+ let file = std::fs::OpenOptions::new()
193+ .write(true)
194+ .create(true)
195+ .truncate(true)
196+ .mode(0o600)
197+ .open(out)
198+ .map_err(|e| e.to_string())?;
199+ let gz = flate2::write::GzEncoder::new(file, flate2::Compression::default());
200+ let mut tar = tar::Builder::new(gz);
201+ tar.append_dir_all(top, work).map_err(|e| e.to_string())?;
202+ let gz = tar.into_inner().map_err(|e| e.to_string())?;
203+ gz.finish().map_err(|e| e.to_string())?;
204+ Ok(())
205+}
206+
207+async fn write_json(path: &Path, value: &Value) -> Result<(), String> {
208+ let text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
209+ tokio::fs::write(path, text)
210+ .await
211+ .map_err(|e| e.to_string())
212+}
213+
214+/// The account fields worth taking along. Never the password hash.
215+pub fn profile_json(user: &User) -> Value {
216+ json!({
217+ "username": user.username,
218+ "display_name": user.display_name,
219+ "email": user.email,
220+ "about": user.about,
221+ "created_at": user.created_at,
222+ "timezone": user.timezone,
223+ "language": user.language,
224+ "theme": user.theme,
225+ "exported_at": now_stamp(),
226+ })
227+}
228+
229+async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), String> {
230+ let git_dir =
231+ forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?;
232+ let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle"))
233+ .await
234+ .map_err(|e| format!("bundling {}: {e}", repo.name))?
235+ .is_some();
236+
237+ let labels = state
238+ .store
239+ .list_labels(&repo.id)
240+ .await
241+ .map_err(|e| e.to_string())?;
242+ let milestones = state
243+ .store
244+ .list_milestones(&repo.id, None)
245+ .await
246+ .map_err(|e| e.to_string())?;
247+ let meta = json!({
248+ "name": repo.name,
249+ "description": repo.description,
250+ "visibility": repo.visibility.as_str(),
251+ "default_branch": repo.default_branch,
252+ "created_at": repo.created_at,
253+ "archived": repo.archived,
254+ "has_bundle": bundled,
255+ "labels": labels.iter().map(|l| json!({"name": l.name, "color": l.color, "description": l.description})).collect::<Vec<_>>(),
256+ "milestones": milestones.iter().map(|m| json!({
257+ "title": m.title, "description": m.description, "due_on": m.due_on,
258+ "state": m.state.as_str(), "created_at": m.created_at, "closed_at": m.closed_at,
259+ })).collect::<Vec<_>>(),
260+ });
261+ write_json(&dir.join("repo.json"), &meta).await?;
262+
263+ let mut issues = Vec::new();
264+ let mut page = 1;
265+ loop {
266+ let filter = IssueFilter {
267+ state: None,
268+ sort: IssueSort::Oldest,
269+ page,
270+ per_page: PAGE,
271+ ..IssueFilter::default()
272+ };
273+ let (items, total) = state
274+ .store
275+ .list_issues(&repo.id, &filter)
276+ .await
277+ .map_err(|e| e.to_string())?;
278+ let got = items.len();
279+ for item in items {
280+ let comments = state
281+ .store
282+ .list_comments(&item.issue.id)
283+ .await
284+ .map_err(|e| e.to_string())?;
285+ let names = state
286+ .store
287+ .usernames_by_ids(
288+ &comments
289+ .iter()
290+ .map(|c| c.author_id.clone())
291+ .collect::<Vec<_>>(),
292+ )
293+ .await
294+ .map_err(|e| e.to_string())?;
295+ let names: HashMap<String, String> =
296+ names.into_iter().map(|(k, (name, _))| (k, name)).collect();
297+ issues.push(issue_json(&item, &comments, &names));
298+ }
299+ if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total {
300+ break;
301+ }
302+ page += 1;
303+ }
304+ write_json(&dir.join("issues.json"), &Value::Array(issues)).await?;
305+
306+ let releases = state
307+ .store
308+ .list_releases(&repo.id)
309+ .await
310+ .map_err(|e| e.to_string())?;
311+ let mut out = Vec::new();
312+ for r in releases {
313+ let assets = state
314+ .store
315+ .list_release_assets(&r.id)
316+ .await
317+ .map_err(|e| e.to_string())?;
318+ out.push(json!({
319+ "tag": r.tag, "title": r.title, "body": r.body, "draft": r.draft,
320+ "prerelease": r.prerelease, "author": r.author_name, "target_oid": r.target_oid,
321+ "created_at": r.created_at, "published_at": r.published_at,
322+ "assets": assets.iter().map(|a| json!({
323+ "name": a.name, "size": a.size, "sha256": a.sha256,
324+ "content_type": a.content_type, "downloads": a.download_count,
325+ })).collect::<Vec<_>>(),
326+ }));
327+ }
328+ write_json(&dir.join("releases.json"), &Value::Array(out)).await
329+}
330+
331+fn issue_json(
332+ item: &forge_core::IssueListItem,
333+ comments: &[forge_core::Comment],
334+ names: &HashMap<String, String>,
335+) -> Value {
336+ let i = &item.issue;
337+ json!({
338+ "number": i.number,
339+ "title": i.title,
340+ "body": i.body,
341+ "state": i.state.as_str(),
342+ "author": item.author,
343+ "labels": item.labels.iter().map(|l| l.name.clone()).collect::<Vec<_>>(),
344+ "assignees": item.assignees,
345+ "created_at": i.created_at,
346+ "closed_at": i.closed_at,
347+ "comments": comments.iter().map(|c| json!({
348+ "author": names.get(&c.author_id).cloned().unwrap_or_default(),
349+ "body": c.body,
350+ "created_at": c.created_at,
351+ })).collect::<Vec<_>>(),
352+ })
353+}
354+
355+/// Deletes every export past its expiry, rows and files. Failures are logged.
356+pub async fn sweep_expired(state: &AppState) {
357+ let expired = match state.store.expired_exports(&now_stamp()).await {
358+ Ok(rows) => rows,
359+ Err(e) => {
360+ tracing::warn!(error = %e, "export: could not list expired exports");
361+ return;
362+ }
363+ };
364+ for export in expired {
365+ let path = archive_path(state, &export.id);
366+ match tokio::fs::remove_file(&path).await {
367+ Ok(()) => {}
368+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
369+ Err(e) => {
370+ tracing::warn!(error = %e, "export: could not remove an expired archive");
371+ continue;
372+ }
373+ }
374+ if let Err(e) = state.store.delete_export(&export.id).await {
375+ tracing::warn!(error = %e, "export: could not delete an expired export row");
376+ }
377+ bump(&export.user_id);
378+ }
379+}
380+
381+/// Fails exports a restart cut short and removes expired ones.
382+pub async fn on_boot(state: &AppState) {
383+ if let Err(e) = state.store.fail_interrupted_exports().await {
384+ tracing::error!(error = %e, "export: could not clean up interrupted exports");
385+ }
386+ sweep_expired(state).await;
387+}
388+
389+#[cfg(test)]
390+mod tests;
crates/forge-web/src/exporter/tests.rsadded+175 -0
@@ -0,0 +1,175 @@
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+/// Reads a `.tar.gz` into `(path, bytes)` pairs.
10+fn entries(path: &Path) -> Vec<(String, Vec<u8>)> {
11+ let file = std::fs::File::open(path).expect("archive opens");
12+ let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(file));
13+ let mut out = Vec::new();
14+ for entry in archive.entries().expect("entries") {
15+ let mut entry = entry.expect("entry");
16+ let name = entry.path().expect("path").display().to_string();
17+ let mut bytes = Vec::new();
18+ entry.read_to_end(&mut bytes).expect("read");
19+ out.push((name, bytes));
20+ }
21+ out
22+}
23+
24+async fn setup() -> (AppState, User, Repo, tempfile::TempDir) {
25+ let dir = tempfile::tempdir().expect("tempdir");
26+ let state = test_state(dir.path()).await;
27+ let user = state
28+ .store
29+ .create_user("tahinli", Some("tahinli@example.com"), "unused", false)
30+ .await
31+ .expect("user");
32+ let repo = state
33+ .store
34+ .create_repo(&user.id, "project", "A project", Visibility::Public, "main")
35+ .await
36+ .expect("repo");
37+ let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path");
38+ forge_git::repo::init_bare(&state.git, &bare, "main")
39+ .await
40+ .expect("init");
41+ // One commit so the bundle is not empty.
42+ let run = |args: &[&str]| {
43+ let out = std::process::Command::new("git")
44+ .arg(format!("--git-dir={}", bare.display()))
45+ .args(args)
46+ .env("GIT_AUTHOR_NAME", "t")
47+ .env("GIT_AUTHOR_EMAIL", "t@example.com")
48+ .env("GIT_COMMITTER_NAME", "t")
49+ .env("GIT_COMMITTER_EMAIL", "t@example.com")
50+ .output()
51+ .expect("git");
52+ assert!(out.status.success(), "{out:?}");
53+ String::from_utf8_lossy(&out.stdout).trim().to_string()
54+ };
55+ let tree = run(&["hash-object", "-t", "tree", "-w", "--stdin"]);
56+ let commit = run(&["commit-tree", &tree, "-m", "first"]);
57+ run(&["update-ref", "refs/heads/main", &commit]);
58+ let issue = state
59+ .store
60+ .create_issue(&repo.id, &user.id, "It breaks", "steps")
61+ .await
62+ .expect("issue");
63+ state
64+ .store
65+ .add_comment(&issue.id, &user.id, "same here")
66+ .await
67+ .expect("comment");
68+ (state, user, repo, dir)
69+}
70+
71+#[tokio::test]
72+async fn the_archive_holds_the_profile_bundles_issues_and_releases() {
73+ let (state, user, _repo, _dir) = setup().await;
74+ let export = start(&state, &user).await.expect("start");
75+ // Wait for the background build by following its own signal, not by polling.
76+ let mut wake = subscribe(&user.id);
77+ loop {
78+ let row = state.store.data_export(&export.id).await.unwrap().unwrap();
79+ if row.state != ExportState::Building {
80+ assert_eq!(row.state, ExportState::Ready, "{:?}", row.error);
81+ assert!(row.size > 0);
82+ break;
83+ }
84+ tokio::time::timeout(Duration::from_secs(60), wake.changed())
85+ .await
86+ .expect("the export finishes")
87+ .expect("signal open");
88+ }
89+
90+ let files = entries(&archive_path(&state, &export.id));
91+ let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
92+ let has = |suffix: &str| names.iter().any(|n| n.ends_with(suffix));
93+ assert!(has("profile.json"), "{names:?}");
94+ assert!(has("repos/project/repo.bundle"), "{names:?}");
95+ assert!(has("repos/project/repo.json"));
96+ assert!(has("repos/project/issues.json"));
97+ assert!(has("repos/project/releases.json"));
98+
99+ let read = |suffix: &str| {
100+ let (_, bytes) = files.iter().find(|(n, _)| n.ends_with(suffix)).unwrap();
101+ String::from_utf8_lossy(bytes).into_owned()
102+ };
103+ let profile = read("profile.json");
104+ assert!(profile.contains("tahinli@example.com"));
105+ assert!(
106+ !profile.contains("password"),
107+ "no credential in the profile"
108+ );
109+ let issues: serde_json::Value = serde_json::from_str(&read("issues.json")).unwrap();
110+ assert_eq!(issues[0]["title"], "It breaks");
111+ assert_eq!(issues[0]["comments"][0]["body"], "same here");
112+ assert_eq!(issues[0]["comments"][0]["author"], "tahinli");
113+ // The bundle is a real bundle.
114+ let bundle = files
115+ .iter()
116+ .find(|(n, _)| n.ends_with("repo.bundle"))
117+ .unwrap();
118+ assert!(bundle.1.starts_with(b"# v2 git bundle") || bundle.1.starts_with(b"# v3 git bundle"));
119+}
120+
121+#[tokio::test]
122+async fn an_expired_export_is_removed_with_its_file() {
123+ let (state, user, _repo, _dir) = setup().await;
124+ let export = state
125+ .store
126+ .create_export(&user.id, Duration::from_secs(0))
127+ .await
128+ .expect("export");
129+ let path = archive_path(&state, &export.id);
130+ tokio::fs::create_dir_all(path.parent().unwrap())
131+ .await
132+ .unwrap();
133+ tokio::fs::write(&path, b"x").await.unwrap();
134+ sweep_expired(&state).await;
135+ assert!(state.store.data_export(&export.id).await.unwrap().is_none());
136+ assert!(!path.exists());
137+}
138+
139+#[tokio::test]
140+async fn a_fresh_export_survives_the_sweep() {
141+ let (state, user, _repo, _dir) = setup().await;
142+ let export = state
143+ .store
144+ .create_export(&user.id, EXPORT_TTL)
145+ .await
146+ .unwrap();
147+ sweep_expired(&state).await;
148+ assert!(state.store.data_export(&export.id).await.unwrap().is_some());
149+}
150+
151+#[tokio::test]
152+async fn a_second_request_while_building_returns_the_running_export() {
153+ let (state, user, _repo, _dir) = setup().await;
154+ let running = state
155+ .store
156+ .create_export(&user.id, EXPORT_TTL)
157+ .await
158+ .unwrap();
159+ let again = start(&state, &user).await.unwrap();
160+ assert_eq!(again.id, running.id);
161+}
162+
163+#[tokio::test]
164+async fn ready_mail_is_queued_for_an_account_with_an_address() {
165+ let (state, user, _repo, _dir) = setup().await;
166+ notify_ready(&state, &user, "abc").await;
167+ notify_ready(&state, &user, "abc").await;
168+ let queued = state
169+ .store
170+ .list_mail(None, "9999-12-31T00:00:00Z", 10)
171+ .await
172+ .expect("mail list")
173+ .len();
174+ assert_eq!(queued, 1, "one mail, however often the ready step runs");
175+}
crates/forge-web/src/i18n/migrate.rsadded+349 -0
@@ -0,0 +1,349 @@
1+//! Strings for importing repositories and exporting account data. Same pattern as the other
2+//! groups: one variant per phrase, an exhaustive `t`, so a missing translation fails to compile.
3+
4+use super::Lang;
5+
6+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7+pub enum K {
8+ // New repository tabs.
9+ TabCreate,
10+ TabImport,
11+ // Import form.
12+ ImportTitle,
13+ ImportIntro,
14+ SrcGit,
15+ SrcGitHub,
16+ SrcGitLab,
17+ GitUrl,
18+ GitUser,
19+ GitPassword,
20+ GitHubRepo,
21+ GitLabInstance,
22+ GitLabProject,
23+ TokenOptional,
24+ TokenHelp,
25+ TargetOwner,
26+ TargetName,
27+ TargetNameHelp,
28+ Description,
29+ WhatToImport,
30+ OptLabels,
31+ OptIssues,
32+ OptPulls,
33+ OptReleases,
34+ OptionsNote,
35+ StartImport,
36+ BulkLink,
37+ JobsLink,
38+ // Bulk import.
39+ BulkTitle,
40+ BulkIntro,
41+ BulkOwnerGitHub,
42+ BulkOwnerGitLab,
43+ BulkListButton,
44+ BulkSelectHeading,
45+ BulkSelectAll,
46+ BulkImportSelected,
47+ BulkNone,
48+ BulkPrivate,
49+ BulkFork,
50+ BulkArchived,
51+ // Jobs.
52+ JobsTitle,
53+ NoJobs,
54+ JobQueued,
55+ JobRunning,
56+ JobDone,
57+ JobFailed,
58+ JobRetry,
59+ JobRetryHelp,
60+ JobOpenRepo,
61+ JobProgress,
62+ JobNoLog,
63+ JobStarted,
64+ StageGit,
65+ StageLabels,
66+ StageMilestones,
67+ StageIssues,
68+ StageReleases,
69+ StageDone,
70+ // Errors.
71+ ErrBadRemote,
72+ ErrBadInstance,
73+ ErrBadOwner,
74+ ErrNothingSelected,
75+ ErrTooMany,
76+ // Data export.
77+ SettingsExport,
78+ ExportTitle,
79+ ExportIntro,
80+ ExportContents,
81+ ExportRequest,
82+ ExportBuilding,
83+ ExportReady,
84+ ExportFailed,
85+ ExportDownload,
86+ ExportNone,
87+ ExportRequested,
88+ ExportSize,
89+ ExportEmailNote,
90+}
91+
92+#[cfg(test)]
93+const ALL: &[K] = &[
94+ K::TabCreate,
95+ K::TabImport,
96+ K::ImportTitle,
97+ K::ImportIntro,
98+ K::SrcGit,
99+ K::SrcGitHub,
100+ K::SrcGitLab,
101+ K::GitUrl,
102+ K::GitUser,
103+ K::GitPassword,
104+ K::GitHubRepo,
105+ K::GitLabInstance,
106+ K::GitLabProject,
107+ K::TokenOptional,
108+ K::TokenHelp,
109+ K::TargetOwner,
110+ K::TargetName,
111+ K::TargetNameHelp,
112+ K::Description,
113+ K::WhatToImport,
114+ K::OptLabels,
115+ K::OptIssues,
116+ K::OptPulls,
117+ K::OptReleases,
118+ K::OptionsNote,
119+ K::StartImport,
120+ K::BulkLink,
121+ K::JobsLink,
122+ K::BulkTitle,
123+ K::BulkIntro,
124+ K::BulkOwnerGitHub,
125+ K::BulkOwnerGitLab,
126+ K::BulkListButton,
127+ K::BulkSelectHeading,
128+ K::BulkSelectAll,
129+ K::BulkImportSelected,
130+ K::BulkNone,
131+ K::BulkPrivate,
132+ K::BulkFork,
133+ K::BulkArchived,
134+ K::JobsTitle,
135+ K::NoJobs,
136+ K::JobQueued,
137+ K::JobRunning,
138+ K::JobDone,
139+ K::JobFailed,
140+ K::JobRetry,
141+ K::JobRetryHelp,
142+ K::JobOpenRepo,
143+ K::JobProgress,
144+ K::JobNoLog,
145+ K::JobStarted,
146+ K::StageGit,
147+ K::StageLabels,
148+ K::StageMilestones,
149+ K::StageIssues,
150+ K::StageReleases,
151+ K::StageDone,
152+ K::ErrBadRemote,
153+ K::ErrBadInstance,
154+ K::ErrBadOwner,
155+ K::ErrNothingSelected,
156+ K::ErrTooMany,
157+ K::SettingsExport,
158+ K::ExportTitle,
159+ K::ExportIntro,
160+ K::ExportContents,
161+ K::ExportRequest,
162+ K::ExportBuilding,
163+ K::ExportReady,
164+ K::ExportFailed,
165+ K::ExportDownload,
166+ K::ExportNone,
167+ K::ExportRequested,
168+ K::ExportSize,
169+ K::ExportEmailNote,
170+];
171+
172+/// `(English, Turkish)` for each phrase.
173+fn pair(key: K) -> (&'static str, &'static str) {
174+ match key {
175+ K::TabCreate => ("Create", "Oluştur"),
176+ K::TabImport => ("Import", "İçe aktar"),
177+ K::ImportTitle => ("Import a repository", "Depo içe aktar"),
178+ K::ImportIntro => (
179+ "Copy a repository with all its branches and tags. The result is a normal repository, not a mirror.",
180+ "Bir depoyu tüm dalları ve etiketleriyle kopyalayın. Sonuç yansı değil, normal bir depodur.",
181+ ),
182+ K::SrcGit => ("Git URL", "Git URL'si"),
183+ K::SrcGitHub => ("GitHub", "GitHub"),
184+ K::SrcGitLab => ("GitLab", "GitLab"),
185+ K::GitUrl => ("Repository URL", "Depo URL'si"),
186+ K::GitUser => ("Username (optional)", "Kullanıcı adı (isteğe bağlı)"),
187+ K::GitPassword => (
188+ "Password or token (optional)",
189+ "Parola veya belirteç (isteğe bağlı)",
190+ ),
191+ K::GitHubRepo => ("Repository (owner/name)", "Depo (sahip/ad)"),
192+ K::GitLabInstance => ("GitLab address", "GitLab adresi"),
193+ K::GitLabProject => ("Project path", "Proje yolu"),
194+ K::TokenOptional => ("Access token (optional)", "Erişim belirteci (isteğe bağlı)"),
195+ K::TokenHelp => (
196+ "Needed for private repositories and higher rate limits. It is used only while the import runs and is never stored.",
197+ "Özel depolar ve daha yüksek istek sınırı için gerekir. Yalnızca içe aktarma sürerken kullanılır ve asla saklanmaz.",
198+ ),
199+ K::TargetOwner => ("Owner", "Sahip"),
200+ K::TargetName => ("New repository name", "Yeni depo adı"),
201+ K::TargetNameHelp => (
202+ "Leave blank to keep the original name.",
203+ "Özgün adı korumak için boş bırakın.",
204+ ),
205+ K::Description => ("Description (optional)", "Açıklama (isteğe bağlı)"),
206+ K::WhatToImport => ("Also import", "Şunları da içe aktar"),
207+ K::OptLabels => ("Labels and milestones", "Etiketler ve kilometre taşları"),
208+ K::OptIssues => ("Issues and comments", "Konular ve yorumlar"),
209+ K::OptPulls => ("Pull requests (as issues)", "Çekme istekleri (konu olarak)"),
210+ K::OptReleases => ("Releases and their files", "Sürümler ve dosyaları"),
211+ K::OptionsNote => (
212+ "Authors with no account here are shown as \"originally by @name on GitHub\". Pull requests become issues marked \"imported PR\", because their branches may be gone.",
213+ "Burada hesabı olmayan yazarlar \"@ad tarafından, GitHub'da\" olarak gösterilir. Çekme istekleri, dalları silinmiş olabileceğinden \"imported PR\" işaretli konulara dönüşür.",
214+ ),
215+ K::StartImport => ("Start import", "İçe aktarmayı başlat"),
216+ K::BulkLink => ("Import several repositories", "Birden çok depoyu içe aktar"),
217+ K::JobsLink => ("Imports", "İçe aktarmalar"),
218+ K::BulkTitle => ("Import several repositories", "Birden çok depoyu içe aktar"),
219+ K::BulkIntro => (
220+ "List the repositories of a user or organization, tick the ones you want and import them together.",
221+ "Bir kullanıcının veya kuruluşun depolarını listeleyin, istediklerinizi işaretleyin ve birlikte içe aktarın.",
222+ ),
223+ K::BulkOwnerGitHub => (
224+ "GitHub user or organization",
225+ "GitHub kullanıcısı veya kuruluşu",
226+ ),
227+ K::BulkOwnerGitLab => ("GitLab user or group", "GitLab kullanıcısı veya grubu"),
228+ K::BulkListButton => ("List repositories", "Depoları listele"),
229+ K::BulkSelectHeading => (
230+ "Select the repositories to import",
231+ "İçe aktarılacak depoları seçin",
232+ ),
233+ K::BulkSelectAll => ("Select all", "Tümünü seç"),
234+ K::BulkImportSelected => ("Import selected", "Seçilenleri içe aktar"),
235+ K::BulkNone => ("No repositories found.", "Depo bulunamadı."),
236+ K::BulkPrivate => ("private", "özel"),
237+ K::BulkFork => ("fork", "çatal"),
238+ K::BulkArchived => ("archived", "arşivlenmiş"),
239+ K::JobsTitle => ("Imports", "İçe aktarmalar"),
240+ K::NoJobs => ("No imports yet.", "Henüz içe aktarma yok."),
241+ K::JobQueued => ("Queued", "Sırada"),
242+ K::JobRunning => ("Running", "Çalışıyor"),
243+ K::JobDone => ("Done", "Bitti"),
244+ K::JobFailed => ("Failed", "Başarısız"),
245+ K::JobRetry => ("Retry", "Yeniden dene"),
246+ K::JobRetryHelp => (
247+ "Enter the token again to continue. What was already imported is kept and skipped.",
248+ "Devam etmek için belirteci yeniden girin. İçe aktarılanlar korunur ve atlanır.",
249+ ),
250+ K::JobOpenRepo => ("Open repository", "Depoyu aç"),
251+ K::JobProgress => ("Progress", "İlerleme"),
252+ K::JobNoLog => ("Nothing yet.", "Henüz bir şey yok."),
253+ K::JobStarted => ("Started", "Başladı"),
254+ K::StageGit => ("Git data", "Git verisi"),
255+ K::StageLabels => ("Labels", "Etiketler"),
256+ K::StageMilestones => ("Milestones", "Kilometre taşları"),
257+ K::StageIssues => ("Issues and pull requests", "Konular ve çekme istekleri"),
258+ K::StageReleases => ("Releases", "Sürümler"),
259+ K::StageDone => ("Finished", "Tamamlandı"),
260+ K::ErrBadRemote => (
261+ "That repository address is not valid.",
262+ "Bu depo adresi geçerli değil.",
263+ ),
264+ K::ErrBadInstance => (
265+ "That GitLab address is not valid.",
266+ "Bu GitLab adresi geçerli değil.",
267+ ),
268+ K::ErrBadOwner => (
269+ "That user or organization name is not valid.",
270+ "Bu kullanıcı veya kuruluş adı geçerli değil.",
271+ ),
272+ K::ErrNothingSelected => ("Select at least one repository.", "En az bir depo seçin."),
273+ K::ErrTooMany => (
274+ "Too many repositories selected at once.",
275+ "Bir seferde çok fazla depo seçildi.",
276+ ),
277+ K::SettingsExport => ("Data export", "Veri dışa aktarımı"),
278+ K::ExportTitle => ("Export your data", "Verilerinizi dışa aktarın"),
279+ K::ExportIntro => (
280+ "Download an archive of your repositories as git bundles, with their issues, comments, releases and your profile as JSON.",
281+ "Depolarınızı git paketleri olarak, konuları, yorumları, sürümleri ve profilinizi JSON olarak içeren bir arşiv indirin.",
282+ ),
283+ K::ExportContents => (
284+ "The archive holds profile.json and, for each repository, repo.bundle, repo.json, issues.json and releases.json. Release files are listed but not included.",
285+ "Arşiv profile.json dosyasını ve her depo için repo.bundle, repo.json, issues.json ve releases.json dosyalarını içerir. Sürüm dosyaları listelenir ama dahil edilmez.",
286+ ),
287+ K::ExportRequest => ("Request an export", "Dışa aktarım iste"),
288+ K::ExportBuilding => ("Building", "Hazırlanıyor"),
289+ K::ExportReady => ("Ready", "Hazır"),
290+ K::ExportFailed => ("Failed", "Başarısız"),
291+ K::ExportDownload => ("Download", "İndir"),
292+ K::ExportNone => ("No exports yet.", "Henüz dışa aktarım yok."),
293+ K::ExportRequested => ("Requested", "İstendi"),
294+ K::ExportSize => ("Size", "Boyut"),
295+ K::ExportEmailNote => (
296+ "This page updates when the archive is ready, and we send an email if your account has an address.",
297+ "Arşiv hazır olunca bu sayfa güncellenir; hesabınızda adres varsa e-posta da gönderilir.",
298+ ),
299+ }
300+}
301+
302+pub fn t(lang: Lang, key: K) -> &'static str {
303+ let (en, tr) = pair(key);
304+ match lang {
305+ Lang::En => en,
306+ Lang::Tr => tr,
307+ }
308+}
309+
310+/// "Expires in N days" style line for the export list.
311+pub fn expires_on(lang: Lang, date: &str) -> String {
312+ match lang {
313+ Lang::En => format!("Expires {date}"),
314+ Lang::Tr => format!("Son geçerlilik {date}"),
315+ }
316+}
317+
318+/// The note about when a finished archive is removed.
319+pub fn export_ttl_note(lang: Lang, days: u64) -> String {
320+ match lang {
321+ Lang::En => format!("Archives are removed after {days} days."),
322+ Lang::Tr => format!("Arşivler {days} gün sonra silinir."),
323+ }
324+}
325+
326+pub fn progress_of(done: i64, total: i64) -> String {
327+ format!("{done} / {total}")
328+}
329+
330+#[cfg(test)]
331+mod tests {
332+ use super::*;
333+
334+ #[test]
335+ fn every_variant_has_both_languages() {
336+ for key in ALL {
337+ assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English");
338+ assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish");
339+ assert!(
340+ !t(Lang::En, *key).contains('\u{2014}'),
341+ "{key:?} has an em dash"
342+ );
343+ assert!(
344+ !t(Lang::Tr, *key).contains('\u{2014}'),
345+ "{key:?} has an em dash"
346+ );
347+ }
348+ }
349+}
crates/forge-web/src/i18n/mod.rsmodified+1 -0
@@ -24,6 +24,7 @@ pub mod code;
24 pub mod community;24 pub mod community;
25 pub mod integrations;25 pub mod integrations;
26 pub mod issues;26 pub mod issues;
27+pub mod migrate;
27 pub mod misc;28 pub mod misc;
28 pub mod orgs;29 pub mod orgs;
29 pub mod pulls;30 pub mod pulls;
crates/forge-web/src/importer/api.rsadded+1137 -0
@@ -0,0 +1,1137 @@
1+//! Remote forge APIs for imports. [`RemoteApi`] is the seam: the import job talks only to the
2+//! trait, so tests use a fake and CI never needs the network. [`GitHub`] and [`GitLab`] are the real
3+//! clients over REST. They paginate, wait out rate limits (and say so through the notice callback),
4+//! and send the token only to the API host, never to a redirect target.
5+
6+use std::fmt;
7+use std::future::Future;
8+use std::sync::Arc;
9+use std::time::Duration;
10+
11+use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER};
12+use serde::Deserialize;
13+use serde::de::DeserializeOwned;
14+
15+const PER_PAGE: usize = 100;
16+/// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever.
17+const MAX_PAGES: usize = 500;
18+/// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues.
19+const MAX_RATE_WAIT: u64 = 15 * 60;
20+/// Largest JSON page read.
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 {wait_secs} seconds; retry then, nothing imported is lost"
42+ ),
43+ ApiError::TooLarge => write!(f, "the file is larger than the allowed size"),
44+ ApiError::Http(msg) => write!(f, "request failed: {msg}"),
45+ ApiError::Parse(msg) => write!(f, "unexpected response: {msg}"),
46+ }
47+ }
48+}
49+
50+pub type ApiResult<T> = Result<T, ApiError>;
51+
52+#[derive(Debug, Clone, PartialEq, Eq, Default)]
53+pub struct ExtLabel {
54+ pub name: String,
55+ pub color: String,
56+ pub description: String,
57+}
58+
59+#[derive(Debug, Clone, PartialEq, Eq, Default)]
60+pub struct ExtMilestone {
61+ pub id: String,
62+ pub title: String,
63+ pub description: String,
64+ pub closed: bool,
65+ /// `YYYY-MM-DD`.
66+ pub due_on: Option<String>,
67+}
68+
69+#[derive(Debug, Clone, PartialEq, Eq, Default)]
70+pub struct ExtIssue {
71+ pub number: i64,
72+ pub title: String,
73+ pub body: String,
74+ pub closed: bool,
75+ pub not_planned: bool,
76+ pub merged: bool,
77+ pub author: String,
78+ pub labels: Vec<String>,
79+ pub milestone: Option<String>,
80+ pub created_at: String,
81+ pub url: String,
82+ pub is_pr: bool,
83+}
84+
85+#[derive(Debug, Clone, PartialEq, Eq, Default)]
86+pub struct ExtComment {
87+ pub id: String,
88+ pub author: String,
89+ pub body: String,
90+ pub created_at: String,
91+ pub url: String,
92+}
93+
94+#[derive(Debug, Clone, PartialEq, Eq, Default)]
95+pub struct ExtAsset {
96+ pub id: String,
97+ pub name: String,
98+ pub size: u64,
99+ pub content_type: String,
100+ pub url: String,
101+}
102+
103+#[derive(Debug, Clone, PartialEq, Eq, Default)]
104+pub struct ExtRelease {
105+ pub id: String,
106+ pub tag: String,
107+ pub title: String,
108+ pub body: String,
109+ pub draft: bool,
110+ pub prerelease: bool,
111+ pub author: String,
112+ pub created_at: String,
113+ pub url: String,
114+ pub assets: Vec<ExtAsset>,
115+}
116+
117+#[derive(Debug, Clone, PartialEq, Eq, Default)]
118+pub struct ExtRepo {
119+ pub name: String,
120+ /// `owner/name`, or the GitLab project path.
121+ pub full_name: String,
122+ pub description: String,
123+ pub private: bool,
124+ pub fork: bool,
125+ pub archived: bool,
126+ pub default_branch: String,
127+ pub web_url: String,
128+}
129+
130+/// What an import needs from a remote forge. `repo` is `owner/name` for GitHub and the full
131+/// project path for GitLab.
132+pub trait RemoteApi: Send + Sync {
133+ fn list_repos(&self, owner: &str) -> impl Future<Output = ApiResult<Vec<ExtRepo>>> + Send;
134+ fn labels(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtLabel>>> + Send;
135+ fn milestones(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtMilestone>>> + Send;
136+ /// Issues and pull (merge) requests, every state, with `is_pr` set on the latter.
137+ fn issues(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtIssue>>> + Send;
138+ fn comments(
139+ &self,
140+ repo: &str,
141+ issue: &ExtIssue,
142+ ) -> impl Future<Output = ApiResult<Vec<ExtComment>>> + Send;
143+ fn releases(&self, repo: &str) -> impl Future<Output = ApiResult<Vec<ExtRelease>>> + Send;
144+ /// The bytes of a release asset, at most `max_bytes`.
145+ fn download(
146+ &self,
147+ asset: &ExtAsset,
148+ max_bytes: u64,
149+ ) -> impl Future<Output = ApiResult<Vec<u8>>> + Send;
150+}
151+
152+/// True for one URL path segment of an owner, repo or group name.
153+pub fn valid_segment(s: &str) -> bool {
154+ !s.is_empty()
155+ && s.len() <= 100
156+ && s != "."
157+ && s != ".."
158+ && s.bytes()
159+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
160+}
161+
162+/// `owner/name` made of valid segments, `min..=max` of them.
163+pub fn valid_path(path: &str, min: usize, max: usize) -> bool {
164+ let parts: Vec<&str> = path.split('/').collect();
165+ (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p))
166+}
167+
168+/// How long to wait after a 403 or 429. `None` when the response is not a rate limit.
169+pub fn rate_wait(
170+ retry_after: Option<&str>,
171+ remaining: Option<&str>,
172+ reset_unix: Option<&str>,
173+ now_unix: i64,
174+) -> Option<u64> {
175+ if let Some(secs) = retry_after.and_then(|v| v.trim().parse::<u64>().ok()) {
176+ return Some(secs.max(1));
177+ }
178+ if remaining.map(str::trim) == Some("0") {
179+ let reset = reset_unix.and_then(|v| v.trim().parse::<i64>().ok())?;
180+ return Some(u64::try_from(reset - now_unix).unwrap_or(0).max(1));
181+ }
182+ None
183+}
184+
185+pub type Notice = Arc<dyn Fn(String) + Send + Sync>;
186+
187+/// A client under the outbound policy, with the token kept private to the API host.
188+pub struct Http {
189+ client: reqwest::Client,
190+ token: Option<String>,
191+ /// `Authorization: Bearer` (GitHub) or `PRIVATE-TOKEN` (GitLab).
192+ gitlab: bool,
193+ auth_host: String,
194+ notice: Notice,
195+}
196+
197+impl Http {
198+ pub fn new(
199+ client: reqwest::Client,
200+ token: Option<String>,
201+ gitlab: bool,
202+ auth_host: String,
203+ notice: Notice,
204+ ) -> Self {
205+ let token = token.filter(|t| !t.trim().is_empty());
206+ Http {
207+ client,
208+ token,
209+ gitlab,
210+ auth_host,
211+ notice,
212+ }
213+ }
214+
215+ fn host_of(url: &str) -> String {
216+ reqwest::Url::parse(url)
217+ .ok()
218+ .and_then(|u| u.host_str().map(str::to_ascii_lowercase))
219+ .unwrap_or_default()
220+ }
221+
222+ fn request(&self, url: &str, accept: &str, authed: bool) -> reqwest::RequestBuilder {
223+ let mut req = self.client.get(url).header(ACCEPT, accept);
224+ if authed
225+ && Self::host_of(url) == self.auth_host
226+ && let Some(token) = &self.token
227+ {
228+ req = if self.gitlab {
229+ req.header("PRIVATE-TOKEN", token)
230+ } else {
231+ req.header(AUTHORIZATION, format!("Bearer {token}"))
232+ .header("X-GitHub-Api-Version", "2022-11-28")
233+ };
234+ }
235+ req
236+ }
237+
238+ fn header(headers: &HeaderMap, name: &str) -> Option<String> {
239+ headers
240+ .get(name)
241+ .and_then(|v| v.to_str().ok())
242+ .map(str::to_owned)
243+ }
244+
245+ /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx.
246+ async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult<reqwest::Response> {
247+ let mut attempt = 0u32;
248+ loop {
249+ attempt += 1;
250+ let resp = self
251+ .request(url, accept, authed)
252+ .send()
253+ .await
254+ .map_err(|e| ApiError::Http(e.without_url().to_string()))?;
255+ let status = resp.status();
256+ if status.is_success() || status.is_redirection() {
257+ return Ok(resp);
258+ }
259+ let headers = resp.headers();
260+ match status.as_u16() {
261+ 401 => return Err(ApiError::Unauthorized("the token was refused".into())),
262+ 404 => return Err(ApiError::NotFound(Self::host_of(url))),
263+ 403 | 429 => {
264+ let wait = rate_wait(
265+ Self::header(headers, RETRY_AFTER.as_str()).as_deref(),
266+ Self::header(headers, "x-ratelimit-remaining").as_deref(),
267+ Self::header(headers, "x-ratelimit-reset").as_deref(),
268+ jiff::Timestamp::now().as_second(),
269+ )
270+ .or_else(|| (status.as_u16() == 429).then_some(60));
271+ let Some(wait) = wait else {
272+ return Err(ApiError::Unauthorized(
273+ "the server refused the request (is the token valid and allowed to read this?)"
274+ .into(),
275+ ));
276+ };
277+ if wait > MAX_RATE_WAIT || attempt > 4 {
278+ return Err(ApiError::RateLimited { wait_secs: wait });
279+ }
280+ (self.notice)(format!("Rate limited, waiting {wait} seconds"));
281+ tokio::time::sleep(Duration::from_secs(wait)).await;
282+ }
283+ 500..=599 if attempt <= 3 => {
284+ tokio::time::sleep(Duration::from_secs(u64::from(attempt) * 2)).await;
285+ }
286+ code => return Err(ApiError::Http(format!("status {code}"))),
287+ }
288+ }
289+ }
290+
291+ async fn body(resp: reqwest::Response, max: usize) -> ApiResult<Vec<u8>> {
292+ let mut resp = resp;
293+ let mut out = Vec::new();
294+ while let Some(chunk) = resp
295+ .chunk()
296+ .await
297+ .map_err(|e| ApiError::Http(e.without_url().to_string()))?
298+ {
299+ if out.len() + chunk.len() > max {
300+ return Err(ApiError::TooLarge);
301+ }
302+ out.extend_from_slice(&chunk);
303+ }
304+ Ok(out)
305+ }
306+
307+ pub async fn json<T: DeserializeOwned>(&self, url: &str) -> ApiResult<T> {
308+ let resp = self.send(url, "application/json", true).await?;
309+ let bytes = Self::body(resp, MAX_JSON_BYTES).await?;
310+ serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string()))
311+ }
312+
313+ /// Every page of a list endpoint, 100 per page, stopping at the first short page.
314+ pub async fn pages<T: DeserializeOwned>(&self, base: &str) -> ApiResult<Vec<T>> {
315+ let sep = if base.contains('?') { '&' } else { '?' };
316+ let mut out = Vec::new();
317+ for page in 1..=MAX_PAGES {
318+ let url = format!("{base}{sep}per_page={PER_PAGE}&page={page}");
319+ let items: Vec<T> = self.json(&url).await?;
320+ let short = items.len() < PER_PAGE;
321+ out.extend(items);
322+ if short {
323+ break;
324+ }
325+ }
326+ Ok(out)
327+ }
328+
329+ /// Downloads a file, following redirects by hand: the token goes to the API host only, and
330+ /// each hop is fetched under the same address policy as every other request.
331+ pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult<Vec<u8>> {
332+ let max = usize::try_from(max_bytes).unwrap_or(usize::MAX);
333+ let mut current = url.to_owned();
334+ for _ in 0..=MAX_REDIRECTS {
335+ let resp = self
336+ .send(&current, "application/octet-stream", true)
337+ .await?;
338+ if resp.status().is_redirection() {
339+ let next = resp
340+ .headers()
341+ .get(LOCATION)
342+ .and_then(|v| v.to_str().ok())
343+ .ok_or_else(|| ApiError::Http("redirect without a location".into()))?;
344+ let base =
345+ reqwest::Url::parse(&current).map_err(|e| ApiError::Http(e.to_string()))?;
346+ current = base
347+ .join(next)
348+ .map_err(|e| ApiError::Http(e.to_string()))?
349+ .to_string();
350+ if !current.starts_with("https://") {
351+ return Err(ApiError::Http("redirect to a non-https address".into()));
352+ }
353+ continue;
354+ }
355+ if let Some(len) = resp.content_length()
356+ && len > max_bytes
357+ {
358+ return Err(ApiError::TooLarge);
359+ }
360+ return Self::body(resp, max).await;
361+ }
362+ Err(ApiError::Http("too many redirects".into()))
363+ }
364+}
365+
366+fn day(stamp: &str) -> Option<String> {
367+ let d = stamp.get(..10)?;
368+ let ok = d.as_bytes().iter().enumerate().all(|(i, b)| match i {
369+ 4 | 7 => *b == b'-',
370+ _ => b.is_ascii_digit(),
371+ });
372+ ok.then(|| d.to_owned())
373+}
374+
375+fn s(v: Option<String>) -> String {
376+ v.unwrap_or_default()
377+}
378+
379+// ---- GitHub ----
380+
381+pub struct GitHub {
382+ http: Http,
383+ base: String,
384+}
385+
386+impl GitHub {
387+ pub fn new(http: Http) -> Self {
388+ GitHub {
389+ http,
390+ base: "https://api.github.com".into(),
391+ }
392+ }
393+}
394+
395+#[derive(Deserialize)]
396+struct GhUser {
397+ login: Option<String>,
398+}
399+
400+#[derive(Deserialize)]
401+struct GhLabel {
402+ name: String,
403+ color: Option<String>,
404+ description: Option<String>,
405+}
406+
407+#[derive(Deserialize)]
408+struct GhMilestone {
409+ number: i64,
410+ title: String,
411+ description: Option<String>,
412+ state: String,
413+ due_on: Option<String>,
414+}
415+
416+#[derive(Deserialize)]
417+struct GhPull {
418+ merged_at: Option<String>,
419+}
420+
421+#[derive(Deserialize)]
422+struct GhIssue {
423+ number: i64,
424+ title: String,
425+ body: Option<String>,
426+ state: String,
427+ state_reason: Option<String>,
428+ user: Option<GhUser>,
429+ #[serde(default)]
430+ labels: Vec<GhLabel>,
431+ milestone: Option<GhMilestoneRef>,
432+ created_at: Option<String>,
433+ html_url: Option<String>,
434+ pull_request: Option<GhPull>,
435+}
436+
437+#[derive(Deserialize)]
438+struct GhMilestoneRef {
439+ title: String,
440+}
441+
442+#[derive(Deserialize)]
443+struct GhComment {
444+ id: i64,
445+ body: Option<String>,
446+ user: Option<GhUser>,
447+ created_at: Option<String>,
448+ html_url: Option<String>,
449+}
450+
451+#[derive(Deserialize)]
452+struct GhAsset {
453+ id: i64,
454+ name: String,
455+ size: Option<u64>,
456+ content_type: Option<String>,
457+ url: String,
458+}
459+
460+#[derive(Deserialize)]
461+struct GhRelease {
462+ id: i64,
463+ tag_name: String,
464+ name: Option<String>,
465+ body: Option<String>,
466+ #[serde(default)]
467+ draft: bool,
468+ #[serde(default)]
469+ prerelease: bool,
470+ author: Option<GhUser>,
471+ created_at: Option<String>,
472+ html_url: Option<String>,
473+ #[serde(default)]
474+ assets: Vec<GhAsset>,
475+}
476+
477+#[derive(Deserialize)]
478+struct GhRepo {
479+ name: String,
480+ full_name: String,
481+ description: Option<String>,
482+ #[serde(default)]
483+ private: bool,
484+ #[serde(default)]
485+ fork: bool,
486+ #[serde(default)]
487+ archived: bool,
488+ default_branch: Option<String>,
489+ html_url: Option<String>,
490+}
491+
492+fn login(u: Option<GhUser>) -> String {
493+ u.and_then(|u| u.login).unwrap_or_default()
494+}
495+
496+#[cfg(test)]
497+pub fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> {
498+ let raw: Vec<GhLabel> = from_json(json)?;
499+ Ok(raw.into_iter().map(label_of).collect())
500+}
501+
502+fn label_of(l: GhLabel) -> ExtLabel {
503+ ExtLabel {
504+ name: l.name,
505+ color: format!("#{}", s(l.color).trim_start_matches('#')),
506+ description: s(l.description),
507+ }
508+}
509+
510+#[cfg(test)]
511+fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> {
512+ serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string()))
513+}
514+
515+#[cfg(test)]
516+pub fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> {
517+ let raw: Vec<GhIssue> = from_json(json)?;
518+ Ok(raw.into_iter().map(gh_issue).collect())
519+}
520+
521+fn gh_issue(i: GhIssue) -> ExtIssue {
522+ let merged = i
523+ .pull_request
524+ .as_ref()
525+ .is_some_and(|p| p.merged_at.is_some());
526+ ExtIssue {
527+ number: i.number,
528+ title: i.title,
529+ body: s(i.body),
530+ closed: i.state == "closed",
531+ not_planned: i.state_reason.as_deref() == Some("not_planned"),
532+ merged,
533+ author: login(i.user),
534+ labels: i.labels.into_iter().map(|l| l.name).collect(),
535+ milestone: i.milestone.map(|m| m.title),
536+ created_at: s(i.created_at),
537+ url: s(i.html_url),
538+ is_pr: i.pull_request.is_some(),
539+ }
540+}
541+
542+#[cfg(test)]
543+pub fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
544+ let raw: Vec<GhRelease> = from_json(json)?;
545+ Ok(raw
546+ .into_iter()
547+ .map(|r| ExtRelease {
548+ id: r.id.to_string(),
549+ title: r
550+ .name
551+ .filter(|n| !n.is_empty())
552+ .unwrap_or_else(|| r.tag_name.clone()),
553+ tag: r.tag_name,
554+ body: s(r.body),
555+ draft: r.draft,
556+ prerelease: r.prerelease,
557+ author: login(r.author),
558+ created_at: s(r.created_at),
559+ url: s(r.html_url),
560+ assets: r
561+ .assets
562+ .into_iter()
563+ .map(|a| ExtAsset {
564+ id: a.id.to_string(),
565+ name: a.name,
566+ size: a.size.unwrap_or(0),
567+ content_type: s(a.content_type),
568+ url: a.url,
569+ })
570+ .collect(),
571+ })
572+ .collect())
573+}
574+
575+impl RemoteApi for GitHub {
576+ async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
577+ if !valid_segment(owner) {
578+ return Err(ApiError::NotFound("owner".into()));
579+ }
580+ let org: ApiResult<Vec<GhRepo>> = self
581+ .http
582+ .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base))
583+ .await;
584+ let raw = match org {
585+ Ok(raw) => raw,
586+ Err(ApiError::NotFound(_)) => {
587+ self.http
588+ .pages(&format!("{}/users/{owner}/repos?type=owner", self.base))
589+ .await?
590+ }
591+ Err(e) => return Err(e),
592+ };
593+ Ok(raw
594+ .into_iter()
595+ .map(|r| ExtRepo {
596+ name: r.name,
597+ full_name: r.full_name,
598+ description: s(r.description),
599+ private: r.private,
600+ fork: r.fork,
601+ archived: r.archived,
602+ default_branch: s(r.default_branch),
603+ web_url: s(r.html_url),
604+ })
605+ .collect())
606+ }
607+
608+ async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> {
609+ check_repo(repo, 2, 2)?;
610+ let raw: Vec<GhLabel> = self
611+ .http
612+ .pages(&format!("{}/repos/{repo}/labels", self.base))
613+ .await?;
614+ Ok(raw.into_iter().map(label_of).collect())
615+ }
616+
617+ async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> {
618+ check_repo(repo, 2, 2)?;
619+ let raw: Vec<GhMilestone> = self
620+ .http
621+ .pages(&format!("{}/repos/{repo}/milestones?state=all", self.base))
622+ .await?;
623+ Ok(raw
624+ .into_iter()
625+ .map(|m| ExtMilestone {
626+ id: m.number.to_string(),
627+ title: m.title,
628+ description: s(m.description),
629+ closed: m.state == "closed",
630+ due_on: m.due_on.as_deref().and_then(day),
631+ })
632+ .collect())
633+ }
634+
635+ async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> {
636+ check_repo(repo, 2, 2)?;
637+ let raw: Vec<GhIssue> = self
638+ .http
639+ .pages(&format!(
640+ "{}/repos/{repo}/issues?state=all&sort=created&direction=asc",
641+ self.base
642+ ))
643+ .await?;
644+ Ok(raw.into_iter().map(gh_issue).collect())
645+ }
646+
647+ async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
648+ check_repo(repo, 2, 2)?;
649+ let raw: Vec<GhComment> = self
650+ .http
651+ .pages(&format!(
652+ "{}/repos/{repo}/issues/{}/comments",
653+ self.base, issue.number
654+ ))
655+ .await?;
656+ Ok(raw
657+ .into_iter()
658+ .map(|c| ExtComment {
659+ id: c.id.to_string(),
660+ author: login(c.user),
661+ body: s(c.body),
662+ created_at: s(c.created_at),
663+ url: s(c.html_url),
664+ })
665+ .collect())
666+ }
667+
668+ async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> {
669+ check_repo(repo, 2, 2)?;
670+ let raw: Vec<GhRelease> = self
671+ .http
672+ .pages(&format!("{}/repos/{repo}/releases", self.base))
673+ .await?;
674+ // Reuse the one conversion by round-tripping through the parser's mapping.
675+ Ok(raw.into_iter().map(gh_release).collect())
676+ }
677+
678+ async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<Vec<u8>> {
679+ if !asset.url.starts_with("https://api.github.com/") {
680+ return Err(ApiError::Http("unexpected asset address".into()));
681+ }
682+ self.http.download(&asset.url, max_bytes).await
683+ }
684+}
685+
686+fn gh_release(r: GhRelease) -> ExtRelease {
687+ ExtRelease {
688+ id: r.id.to_string(),
689+ title: r
690+ .name
691+ .filter(|n| !n.is_empty())
692+ .unwrap_or_else(|| r.tag_name.clone()),
693+ tag: r.tag_name,
694+ body: s(r.body),
695+ draft: r.draft,
696+ prerelease: r.prerelease,
697+ author: login(r.author),
698+ created_at: s(r.created_at),
699+ url: s(r.html_url),
700+ assets: r
701+ .assets
702+ .into_iter()
703+ .map(|a| ExtAsset {
704+ id: a.id.to_string(),
705+ name: a.name,
706+ size: a.size.unwrap_or(0),
707+ content_type: s(a.content_type),
708+ url: a.url,
709+ })
710+ .collect(),
711+ }
712+}
713+
714+fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> {
715+ if valid_path(repo, min, max) {
716+ Ok(())
717+ } else {
718+ Err(ApiError::NotFound("repository path".into()))
719+ }
720+}
721+
722+// ---- GitLab ----
723+
724+pub struct GitLab {
725+ http: Http,
726+ /// `https://host/api/v4`.
727+ base: String,
728+}
729+
730+impl GitLab {
731+ /// `instance` is the instance's web address, e.g. `https://gitlab.com`.
732+ pub fn new(http: Http, instance: &str) -> Self {
733+ GitLab {
734+ http,
735+ base: format!("{}/api/v4", instance.trim_end_matches('/')),
736+ }
737+ }
738+
739+ fn project(&self, repo: &str) -> ApiResult<String> {
740+ check_repo(repo, 2, 20)?;
741+ Ok(format!(
742+ "{}/projects/{}",
743+ self.base,
744+ repo.replace('/', "%2F")
745+ ))
746+ }
747+}
748+
749+#[derive(Deserialize)]
750+struct GlUser {
751+ username: Option<String>,
752+}
753+
754+#[derive(Deserialize)]
755+struct GlLabel {
756+ name: String,
757+ color: Option<String>,
758+ description: Option<String>,
759+}
760+
761+#[derive(Deserialize)]
762+struct GlMilestone {
763+ id: i64,
764+ title: String,
765+ description: Option<String>,
766+ state: String,
767+ due_date: Option<String>,
768+}
769+
770+#[derive(Deserialize)]
771+struct GlMilestoneRef {
772+ title: String,
773+}
774+
775+#[derive(Deserialize)]
776+struct GlIssue {
777+ iid: i64,
778+ title: String,
779+ description: Option<String>,
780+ state: String,
781+ author: Option<GlUser>,
782+ #[serde(default)]
783+ labels: Vec<String>,
784+ milestone: Option<GlMilestoneRef>,
785+ created_at: Option<String>,
786+ web_url: Option<String>,
787+}
788+
789+#[derive(Deserialize)]
790+struct GlNote {
791+ id: i64,
792+ body: Option<String>,
793+ author: Option<GlUser>,
794+ created_at: Option<String>,
795+ #[serde(default)]
796+ system: bool,
797+}
798+
799+#[derive(Deserialize)]
800+struct GlLink {
801+ id: i64,
802+ name: String,
803+ url: String,
804+ direct_asset_url: Option<String>,
805+}
806+
807+#[derive(Deserialize, Default)]
808+struct GlAssets {
809+ #[serde(default)]
810+ links: Vec<GlLink>,
811+}
812+
813+#[derive(Deserialize)]
814+struct GlRelease {
815+ tag_name: String,
816+ name: Option<String>,
817+ description: Option<String>,
818+ created_at: Option<String>,
819+ #[serde(default)]
820+ upcoming_release: bool,
821+ author: Option<GlUser>,
822+ #[serde(default)]
823+ assets: GlAssets,
824+ #[serde(rename = "_links")]
825+ links: Option<GlSelf>,
826+}
827+
828+#[derive(Deserialize)]
829+struct GlSelf {
830+ #[serde(rename = "self")]
831+ self_url: Option<String>,
832+}
833+
834+#[derive(Deserialize)]
835+struct GlProject {
836+ path: String,
837+ path_with_namespace: String,
838+ description: Option<String>,
839+ visibility: Option<String>,
840+ default_branch: Option<String>,
841+ web_url: Option<String>,
842+ #[serde(default)]
843+ archived: bool,
844+ forked_from_project: Option<serde_json::Value>,
845+}
846+
847+fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue {
848+ ExtIssue {
849+ number: i.iid,
850+ title: i.title,
851+ body: s(i.description),
852+ closed: i.state != "opened",
853+ not_planned: false,
854+ merged: i.state == "merged",
855+ author: i.author.and_then(|a| a.username).unwrap_or_default(),
856+ labels: i.labels,
857+ milestone: i.milestone.map(|m| m.title),
858+ created_at: s(i.created_at),
859+ url: s(i.web_url),
860+ is_pr,
861+ }
862+}
863+
864+#[cfg(test)]
865+pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> {
866+ let raw: Vec<GlIssue> = from_json(json)?;
867+ Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect())
868+}
869+
870+#[cfg(test)]
871+pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
872+ let raw: Vec<GlRelease> = from_json(json)?;
873+ Ok(raw.into_iter().map(gl_release).collect())
874+}
875+
876+fn gl_release(r: GlRelease) -> ExtRelease {
877+ ExtRelease {
878+ id: r.tag_name.clone(),
879+ title: r
880+ .name
881+ .filter(|n| !n.is_empty())
882+ .unwrap_or_else(|| r.tag_name.clone()),
883+ tag: r.tag_name,
884+ body: s(r.description),
885+ draft: r.upcoming_release,
886+ prerelease: false,
887+ author: r.author.and_then(|a| a.username).unwrap_or_default(),
888+ created_at: s(r.created_at),
889+ url: r.links.and_then(|l| l.self_url).unwrap_or_default(),
890+ assets: r
891+ .assets
892+ .links
893+ .into_iter()
894+ .map(|l| ExtAsset {
895+ id: l.id.to_string(),
896+ name: l.name,
897+ size: 0,
898+ content_type: String::new(),
899+ url: l
900+ .direct_asset_url
901+ .filter(|u| !u.is_empty())
902+ .unwrap_or(l.url),
903+ })
904+ .collect(),
905+ }
906+}
907+
908+impl RemoteApi for GitLab {
909+ async fn list_repos(&self, owner: &str) -> ApiResult<Vec<ExtRepo>> {
910+ check_repo(owner, 1, 20)?;
911+ let enc = owner.replace('/', "%2F");
912+ let group: ApiResult<Vec<GlProject>> = self
913+ .http
914+ .pages(&format!(
915+ "{}/groups/{enc}/projects?include_subgroups=false&simple=false",
916+ self.base
917+ ))
918+ .await;
919+ let raw = match group {
920+ Ok(raw) => raw,
921+ Err(ApiError::NotFound(_)) => {
922+ self.http
923+ .pages(&format!("{}/users/{enc}/projects", self.base))
924+ .await?
925+ }
926+ Err(e) => return Err(e),
927+ };
928+ Ok(raw
929+ .into_iter()
930+ .map(|p| ExtRepo {
931+ name: p.path,
932+ full_name: p.path_with_namespace,
933+ description: s(p.description),
934+ private: p.visibility.as_deref() != Some("public"),
935+ fork: p.forked_from_project.is_some(),
936+ archived: p.archived,
937+ default_branch: s(p.default_branch),
938+ web_url: s(p.web_url),
939+ })
940+ .collect())
941+ }
942+
943+ async fn labels(&self, repo: &str) -> ApiResult<Vec<ExtLabel>> {
944+ let raw: Vec<GlLabel> = self
945+ .http
946+ .pages(&format!("{}/labels", self.project(repo)?))
947+ .await?;
948+ Ok(raw
949+ .into_iter()
950+ .map(|l| ExtLabel {
951+ name: l.name,
952+ color: s(l.color),
953+ description: s(l.description),
954+ })
955+ .collect())
956+ }
957+
958+ async fn milestones(&self, repo: &str) -> ApiResult<Vec<ExtMilestone>> {
959+ let raw: Vec<GlMilestone> = self
960+ .http
961+ .pages(&format!("{}/milestones", self.project(repo)?))
962+ .await?;
963+ Ok(raw
964+ .into_iter()
965+ .map(|m| ExtMilestone {
966+ id: m.id.to_string(),
967+ title: m.title,
968+ description: s(m.description),
969+ closed: m.state == "closed",
970+ due_on: m.due_date.as_deref().and_then(day),
971+ })
972+ .collect())
973+ }
974+
975+ async fn issues(&self, repo: &str) -> ApiResult<Vec<ExtIssue>> {
976+ let project = self.project(repo)?;
977+ let issues: Vec<GlIssue> = self
978+ .http
979+ .pages(&format!(
980+ "{project}/issues?state=all&order_by=created_at&sort=asc"
981+ ))
982+ .await?;
983+ let pulls: Vec<GlIssue> = self
984+ .http
985+ .pages(&format!(
986+ "{project}/merge_requests?state=all&order_by=created_at&sort=asc"
987+ ))
988+ .await?;
989+ let mut out: Vec<ExtIssue> = issues.into_iter().map(|i| gl_issue(i, false)).collect();
990+ out.extend(pulls.into_iter().map(|i| gl_issue(i, true)));
991+ Ok(out)
992+ }
993+
994+ async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
995+ let kind = if issue.is_pr {
996+ "merge_requests"
997+ } else {
998+ "issues"
999+ };
1000+ let raw: Vec<GlNote> = self
1001+ .http
1002+ .pages(&format!(
1003+ "{}/{kind}/{}/notes?sort=asc&order_by=created_at",
1004+ self.project(repo)?,
1005+ issue.number
1006+ ))
1007+ .await?;
1008+ Ok(raw
1009+ .into_iter()
1010+ .filter(|n| !n.system)
1011+ .map(|n| ExtComment {
1012+ id: n.id.to_string(),
1013+ author: n.author.and_then(|a| a.username).unwrap_or_default(),
1014+ body: s(n.body),
1015+ created_at: s(n.created_at),
1016+ url: format!("{}#note_{}", issue.url, n.id),
1017+ })
1018+ .collect())
1019+ }
1020+
1021+ async fn releases(&self, repo: &str) -> ApiResult<Vec<ExtRelease>> {
1022+ let raw: Vec<GlRelease> = self
1023+ .http
1024+ .pages(&format!("{}/releases", self.project(repo)?))
1025+ .await?;
1026+ Ok(raw.into_iter().map(gl_release).collect())
1027+ }
1028+
1029+ async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult<Vec<u8>> {
1030+ if !asset.url.starts_with("https://") {
1031+ return Err(ApiError::Http("unexpected asset address".into()));
1032+ }
1033+ self.http.download(&asset.url, max_bytes).await
1034+ }
1035+}
1036+
1037+#[cfg(test)]
1038+mod tests {
1039+ use super::*;
1040+
1041+ #[test]
1042+ fn segments_reject_traversal_and_separators() {
1043+ assert!(valid_segment("tahinli"));
1044+ assert!(valid_segment("my-repo_1.rs"));
1045+ assert!(!valid_segment(".."));
1046+ assert!(!valid_segment("a/b"));
1047+ assert!(!valid_segment("a?b"));
1048+ assert!(!valid_segment(""));
1049+ assert!(valid_path("tahinli/forge", 2, 2));
1050+ assert!(!valid_path("tahinli", 2, 2));
1051+ assert!(!valid_path("a/b/c", 2, 2));
1052+ assert!(valid_path("grp/sub/proj", 2, 20));
1053+ }
1054+
1055+ #[test]
1056+ fn rate_limit_waits_follow_the_headers() {
1057+ assert_eq!(rate_wait(Some("30"), None, None, 100), Some(30));
1058+ assert_eq!(rate_wait(None, Some("0"), Some("160"), 100), Some(60));
1059+ assert_eq!(rate_wait(None, Some("0"), Some("90"), 100), Some(1));
1060+ assert_eq!(rate_wait(None, Some("12"), Some("160"), 100), None);
1061+ assert_eq!(rate_wait(None, None, None, 100), None);
1062+ assert_eq!(rate_wait(None, Some("0"), None, 100), None);
1063+ }
1064+
1065+ #[test]
1066+ fn github_issues_and_pulls_parse() {
1067+ let json = br##"[
1068+ {"number":1,"title":"Bug","body":"it breaks","state":"closed","state_reason":"not_planned",
1069+ "user":{"login":"octocat"},"labels":[{"name":"bug","color":"d73a4a"}],
1070+ "milestone":{"title":"v1"},"created_at":"2020-01-02T03:04:05Z",
1071+ "html_url":"https://github.com/o/r/issues/1"},
1072+ {"number":2,"title":"Add x","body":null,"state":"closed","user":{"login":"hubot"},
1073+ "labels":[],"milestone":null,"created_at":"2020-02-02T00:00:00Z",
1074+ "html_url":"https://github.com/o/r/pull/2","pull_request":{"merged_at":"2020-02-03T00:00:00Z"}}
1075+ ]"##;
1076+ let items = parse_github_issues(json).unwrap();
1077+ assert_eq!(items.len(), 2);
1078+ assert!(items[0].closed && items[0].not_planned && !items[0].is_pr);
1079+ assert_eq!(items[0].labels, vec!["bug"]);
1080+ assert_eq!(items[0].milestone.as_deref(), Some("v1"));
1081+ assert!(items[1].is_pr && items[1].merged);
1082+ assert_eq!(items[1].body, "");
1083+ assert_eq!(items[1].author, "hubot");
1084+ }
1085+
1086+ #[test]
1087+ fn github_labels_get_a_hash() {
1088+ let labels =
1089+ parse_github_labels(br#"[{"name":"bug","color":"d73a4a","description":null}]"#)
1090+ .unwrap();
1091+ assert_eq!(labels[0].color, "#d73a4a");
1092+ assert_eq!(labels[0].description, "");
1093+ }
1094+
1095+ #[test]
1096+ fn github_releases_carry_assets() {
1097+ let json = br#"[{"id":7,"tag_name":"v1.0","name":"","body":"notes","draft":false,
1098+ "prerelease":true,"author":{"login":"octocat"},"created_at":"2021-01-01T00:00:00Z",
1099+ "html_url":"https://github.com/o/r/releases/tag/v1.0",
1100+ "assets":[{"id":9,"name":"app.tar.gz","size":12,"content_type":"application/gzip",
1101+ "url":"https://api.github.com/repos/o/r/releases/assets/9"}]}]"#;
1102+ let rel = parse_github_releases(json).unwrap();
1103+ assert_eq!(rel[0].title, "v1.0", "a blank name falls back to the tag");
1104+ assert!(rel[0].prerelease);
1105+ assert_eq!(rel[0].assets[0].name, "app.tar.gz");
1106+ assert_eq!(rel[0].assets[0].size, 12);
1107+ }
1108+
1109+ #[test]
1110+ fn gitlab_states_map() {
1111+ let json = br#"[
1112+ {"iid":3,"title":"MR","description":"d","state":"merged","author":{"username":"tahinli"},
1113+ "labels":["x"],"milestone":null,"created_at":"2022-01-01T00:00:00Z","web_url":"https://gl/x/-/merge_requests/3"},
1114+ {"iid":4,"title":"open","description":null,"state":"opened","author":null,"labels":[],
1115+ "created_at":null,"web_url":null}]"#;
1116+ let items = parse_gitlab_issues(json, true).unwrap();
1117+ assert!(items[0].closed && items[0].merged && items[0].is_pr);
1118+ assert!(!items[1].closed);
1119+ assert_eq!(items[1].author, "");
1120+ }
1121+
1122+ #[test]
1123+ fn gitlab_release_links_become_assets() {
1124+ let json = br#"[{"tag_name":"v2","name":"Two","description":"n","created_at":"2022-01-01T00:00:00Z",
1125+ "assets":{"links":[{"id":1,"name":"bin","url":"https://x/a","direct_asset_url":"https://x/direct"}]}}]"#;
1126+ let rel = parse_gitlab_releases(json).unwrap();
1127+ assert_eq!(rel[0].assets[0].url, "https://x/direct");
1128+ assert_eq!(rel[0].tag, "v2");
1129+ }
1130+
1131+ #[test]
1132+ fn day_keeps_only_a_valid_date_prefix() {
1133+ assert_eq!(day("2020-05-06T00:00:00Z").as_deref(), Some("2020-05-06"));
1134+ assert_eq!(day("garbage!!!").as_deref(), None);
1135+ assert_eq!(day("x").as_deref(), None);
1136+ }
1137+}
crates/forge-web/src/importer/mod.rsadded+1074 -0
@@ -0,0 +1,1074 @@
1+//! Repository import: a one-shot copy of a repo from a git URL, GitHub or GitLab.
2+//!
3+//! The git data comes from the same fetch the pull mirrors use, once, into a normal repo (no mirror
4+//! row is created). For GitHub and GitLab the job can also copy labels, milestones, issues with
5+//! comments, pull requests (as issues marked "imported PR") and releases with their assets, through
6+//! a [`RemoteApi`]. Progress is written to the database and every step wakes the job page's event
7+//! stream, so the page updates with no polling.
8+//!
9+//! The token exists only in the [`JobSpec`] held by the running task. It is never written to the
10+//! database, a log line or an audit entry. A retry asks for it again. Every imported object is
11+//! recorded in `import_map`, so a retry (or a second run) skips what is already there.
12+
13+pub mod api;
14+pub mod remote;
15+
16+use std::collections::HashMap;
17+use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};
18+use std::time::Duration;
19+
20+use forge_core::issues::{IssueState, MAX_BODY, MAX_TITLE, StateReason};
21+use forge_core::releases::{MAX_ASSET_NAME_LEN, NewRelease};
22+use forge_core::store::imports::{ImportJob, ImportOrigin, ImportState};
23+use forge_core::{Repo, Store, User};
24+use forge_git::mirror::{RemoteAuth, mirror_fetch};
25+use serde::{Deserialize, Serialize};
26+use tokio::sync::{Semaphore, watch};
27+
28+use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi};
29+pub use self::remote::{default_name, make_github, make_gitlab, parse_remote, source_ref};
30+use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot};
31+use crate::state::AppState;
32+
33+/// Hard limit on the git part of one import.
34+const GIT_TIMEOUT: Duration = Duration::from_secs(60 * 60);
35+/// Imports that run at once. The rest wait their turn, which also spreads the API rate limit.
36+static SLOTS: Semaphore = Semaphore::const_new(2);
37+const IMPORTED_PR_LABEL: &str = "imported PR";
38+const IMPORTED_PR_COLOR: &str = "#8b7bd8";
39+const FALLBACK_LABEL_COLOR: &str = "#8b949e";
40+
41+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42+pub enum Source {
43+ Git,
44+ GitHub,
45+ GitLab,
46+}
47+
48+impl Source {
49+ pub fn as_str(self) -> &'static str {
50+ match self {
51+ Source::Git => "git",
52+ Source::GitHub => "github",
53+ Source::GitLab => "gitlab",
54+ }
55+ }
56+
57+ pub fn parse(s: &str) -> Option<Self> {
58+ match s {
59+ "git" => Some(Source::Git),
60+ "github" => Some(Source::GitHub),
61+ "gitlab" => Some(Source::GitLab),
62+ _ => None,
63+ }
64+ }
65+
66+ /// The name shown in "originally by x on ...".
67+ pub fn label(self) -> &'static str {
68+ match self {
69+ Source::Git => "git",
70+ Source::GitHub => "GitHub",
71+ Source::GitLab => "GitLab",
72+ }
73+ }
74+}
75+
76+/// Which parts beyond the git data to copy. Stored on the job (it holds no secret).
77+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
78+pub struct ImportOptions {
79+ #[serde(default)]
80+ pub labels: bool,
81+ #[serde(default)]
82+ pub issues: bool,
83+ #[serde(default)]
84+ pub pulls: bool,
85+ #[serde(default)]
86+ pub releases: bool,
87+}
88+
89+impl ImportOptions {
90+ pub fn any_api(&self) -> bool {
91+ self.labels || self.issues || self.pulls || self.releases
92+ }
93+}
94+
95+/// Everything a running job needs. Held in memory only: it carries the token.
96+#[derive(Clone)]
97+pub struct JobSpec {
98+ pub source: Source,
99+ /// The URL for `git`, `owner/repo` for GitHub, the project path for GitLab.
100+ pub remote: String,
101+ /// The GitLab instance, e.g. `https://gitlab.com`.
102+ pub instance: String,
103+ pub token: Option<String>,
104+ /// The user name sent with the token for a plain git URL.
105+ pub git_user: String,
106+ pub options: ImportOptions,
107+}
108+
109+impl std::fmt::Debug for JobSpec {
110+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111+ f.debug_struct("JobSpec")
112+ .field("source", &self.source)
113+ .field("remote", &self.remote)
114+ .field("token", &self.token.as_ref().map(|_| "[redacted]"))
115+ .finish()
116+ }
117+}
118+
119+impl JobSpec {
120+ pub fn clone_url(&self) -> String {
121+ match self.source {
122+ Source::Git => self.remote.clone(),
123+ Source::GitHub => format!("https://github.com/{}.git", self.remote),
124+ Source::GitLab => format!(
125+ "{}/{}.git",
126+ self.instance.trim_end_matches('/'),
127+ self.remote
128+ ),
129+ }
130+ }
131+
132+ fn auth(&self) -> Option<RemoteAuth> {
133+ let token = self.token.as_ref().filter(|t| !t.is_empty())?;
134+ let username = match self.source {
135+ Source::GitHub => "x-access-token".to_owned(),
136+ Source::GitLab => "oauth2".to_owned(),
137+ Source::Git if self.git_user.is_empty() => "git".to_owned(),
138+ Source::Git => self.git_user.clone(),
139+ };
140+ Some(RemoteAuth {
141+ username,
142+ secret: token.clone().into_bytes(),
143+ })
144+ }
145+}
146+
147+/// How the git data is fetched. Production uses the network under the outbound policy; tests use
148+/// a local path.
149+#[derive(Clone)]
150+pub enum Transport {
151+ Net,
152+ #[cfg(test)]
153+ Local(String),
154+}
155+
156+// ---- live signal ----
157+
158+static HUB: LazyLock<Mutex<HashMap<String, watch::Sender<u64>>>> =
159+ LazyLock::new(|| Mutex::new(HashMap::new()));
160+
161+fn hub() -> MutexGuard<'static, HashMap<String, watch::Sender<u64>>> {
162+ HUB.lock().unwrap_or_else(PoisonError::into_inner)
163+}
164+
165+/// Follows a job. Subscribe before reading its state, so a change in between is not lost.
166+pub fn subscribe(job_id: &str) -> watch::Receiver<u64> {
167+ hub()
168+ .entry(job_id.to_owned())
169+ .or_insert_with(|| watch::channel(0).0)
170+ .subscribe()
171+}
172+
173+fn bump(job_id: &str) {
174+ let mut hub = hub();
175+ if let Some(tx) = hub.get(job_id) {
176+ tx.send_modify(|n| *n = n.wrapping_add(1));
177+ if tx.receiver_count() == 0 {
178+ hub.remove(job_id);
179+ }
180+ }
181+}
182+
183+/// Wakes the followers one last time and drops the signal.
184+fn close(job_id: &str) {
185+ if let Some(tx) = hub().remove(job_id) {
186+ tx.send_modify(|n| *n = n.wrapping_add(1));
187+ }
188+}
189+
190+// ---- progress ----
191+
192+#[derive(Clone)]
193+struct Reporter {
194+ store: Store,
195+ job_id: String,
196+}
197+
198+impl Reporter {
199+ async fn log(&self, level: &str, message: impl AsRef<str>) {
200+ if let Err(e) = self
201+ .store
202+ .add_import_event(&self.job_id, level, message.as_ref())
203+ .await
204+ {
205+ tracing::warn!(error = %e, "import: could not record a progress line");
206+ }
207+ bump(&self.job_id);
208+ }
209+
210+ async fn stage(&self, stage: &str, done: usize, total: usize) {
211+ let (done, total) = (done as i64, total as i64);
212+ if let Err(e) = self
213+ .store
214+ .set_import_progress(&self.job_id, stage, done, total)
215+ .await
216+ {
217+ tracing::warn!(error = %e, "import: could not record progress");
218+ }
219+ bump(&self.job_id);
220+ }
221+}
222+
223+// ---- text helpers ----
224+
225+/// The first lines of an imported body or comment: who wrote the original, where and when. The
226+/// name is cleaned and its `@` escaped, so it can neither mention nor impersonate a local user.
227+pub fn origin_note(source: &str, author: &str, created: &str, url: &str) -> String {
228+ let clean: String = author
229+ .chars()
230+ .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
231+ .take(60)
232+ .collect();
233+ let who = if clean.is_empty() { "unknown" } else { &clean };
234+ let date: String = created.chars().take(10).collect();
235+ let mut line = format!("> Originally by \\@{who} on {source}");
236+ if !date.is_empty() && date.bytes().all(|b| b.is_ascii_digit() || b == b'-') {
237+ line.push_str(", ");
238+ line.push_str(&date);
239+ }
240+ let safe_url = url.starts_with("https://")
241+ && !url
242+ .chars()
243+ .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ')' | '(' | '<' | '>'));
244+ if safe_url {
245+ line.push_str(&format!(", [original]({url})"));
246+ }
247+ line.push_str("\n\n");
248+ line
249+}
250+
251+/// `note` then `body`, cut to the body limit at a character boundary.
252+pub fn with_note(note: &str, body: &str) -> String {
253+ let mut text = format!("{note}{body}");
254+ if text.len() > MAX_BODY {
255+ let mut end = MAX_BODY - 16;
256+ while !text.is_char_boundary(end) {
257+ end -= 1;
258+ }
259+ text.truncate(end);
260+ text.push_str("\n\n(cut)");
261+ }
262+ text
263+}
264+
265+fn clip_title(title: &str) -> String {
266+ let t: String = title
267+ .chars()
268+ .filter(|c| !c.is_control())
269+ .take(MAX_TITLE)
270+ .collect();
271+ let t = t.trim();
272+ if t.is_empty() {
273+ "(untitled)".to_owned()
274+ } else {
275+ t.to_owned()
276+ }
277+}
278+
279+/// An asset file name the release store accepts.
280+pub fn asset_name(name: &str) -> String {
281+ let mut out: String = name
282+ .chars()
283+ .map(|c| {
284+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') {
285+ c
286+ } else {
287+ '_'
288+ }
289+ })
290+ .collect();
291+ while out.starts_with('.') {
292+ out.remove(0);
293+ }
294+ out.truncate(MAX_ASSET_NAME_LEN);
295+ if out.is_empty() {
296+ "asset".to_owned()
297+ } else {
298+ out
299+ }
300+}
301+
302+// ---- running a job ----
303+
304+/// Starts the job in the background. It waits for a free slot, then runs.
305+pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) {
306+ tokio::spawn(async move {
307+ let Ok(_slot) = SLOTS.acquire().await else {
308+ return;
309+ };
310+ run_production(&state, &job, &spec).await;
311+ });
312+}
313+
314+async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) {
315+ let rep = Reporter {
316+ store: state.store.clone(),
317+ job_id: job.id.clone(),
318+ };
319+ let notice: Notice = {
320+ let rep = rep.clone();
321+ std::sync::Arc::new(move |msg: String| {
322+ let rep = rep.clone();
323+ tokio::spawn(async move { rep.log("warn", msg).await });
324+ })
325+ };
326+ let wants_api = spec.options.any_api() && spec.source != Source::Git;
327+ if !wants_api {
328+ run_job::<GitHub>(state, job, spec, None, &Transport::Net).await;
329+ return;
330+ }
331+ match spec.source {
332+ Source::GitHub => match make_github(state, spec.token.clone(), notice) {
333+ Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await,
334+ Err(e) => fail(state, &rep, &e).await,
335+ },
336+ Source::GitLab => match make_gitlab(state, &spec.instance, spec.token.clone(), notice) {
337+ Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await,
338+ Err(e) => fail(state, &rep, &e).await,
339+ },
340+ Source::Git => {}
341+ }
342+}
343+
344+async fn fail(state: &AppState, rep: &Reporter, message: &str) {
345+ rep.log("error", message).await;
346+ if let Err(e) = state
347+ .store
348+ .set_import_state(&rep.job_id, ImportState::Failed, Some(message))
349+ .await
350+ {
351+ tracing::error!(error = %e, "import: could not record a failure");
352+ }
353+ close(&rep.job_id);
354+}
355+
356+/// Runs one job to its end and records the outcome. `api` is `None` for a plain git import.
357+pub async fn run_job<A: RemoteApi>(
358+ state: &AppState,
359+ job: &ImportJob,
360+ spec: &JobSpec,
361+ api: Option<&A>,
362+ transport: &Transport,
363+) {
364+ let rep = Reporter {
365+ store: state.store.clone(),
366+ job_id: job.id.clone(),
367+ };
368+ if let Err(e) = state
369+ .store
370+ .set_import_state(&job.id, ImportState::Running, None)
371+ .await
372+ {
373+ tracing::error!(error = %e, "import: could not start the job");
374+ return;
375+ }
376+ bump(&job.id);
377+ match run_steps(state, job, spec, api, transport, &rep).await {
378+ Ok(summary) => {
379+ rep.log("info", summary).await;
380+ rep.stage("done", 0, 0).await;
381+ if let Err(e) = state
382+ .store
383+ .set_import_state(&job.id, ImportState::Done, None)
384+ .await
385+ {
386+ tracing::error!(error = %e, "import: could not finish the job");
387+ }
388+ close(&job.id);
389+ }
390+ Err(message) => fail(state, &rep, &message).await,
391+ }
392+}
393+
394+async fn run_steps<A: RemoteApi>(
395+ state: &AppState,
396+ job: &ImportJob,
397+ spec: &JobSpec,
398+ api: Option<&A>,
399+ transport: &Transport,
400+ rep: &Reporter,
401+) -> Result<String, String> {
402+ let repo_id = job.repo_id.clone().ok_or("the repository is gone")?;
403+ let repo = state
404+ .store
405+ .repo_by_id(&repo_id)
406+ .await
407+ .map_err(|e| e.to_string())?
408+ .ok_or("the repository is gone")?;
409+ let user = state
410+ .store
411+ .user_by_id(&job.user_id)
412+ .await
413+ .map_err(|e| e.to_string())?
414+ .ok_or("the importing user is gone")?;
415+
416+ rep.stage("git", 0, 0).await;
417+ rep.log("info", "Fetching branches and tags").await;
418+ fetch_git(state, &repo, spec, transport).await?;
419+ let repo = sync_default_branch(state, repo, rep).await;
420+ rep.log("info", "Git data imported").await;
421+
422+ let (Some(api), true) = (api, spec.options.any_api()) else {
423+ return Ok("Import finished".to_owned());
424+ };
425+ let run = Run {
426+ state,
427+ rep,
428+ repo: &repo,
429+ user: &user,
430+ api,
431+ spec,
432+ };
433+ let mut totals = Totals::default();
434+ if spec.options.labels {
435+ run.labels(&mut totals).await?;
436+ run.milestones(&mut totals).await?;
437+ }
438+ if spec.options.issues || spec.options.pulls {
439+ run.issues(&mut totals).await?;
440+ }
441+ if spec.options.releases {
442+ run.releases(&mut totals).await?;
443+ }
444+ Ok(format!(
445+ "Import finished: {} labels, {} milestones, {} issues, {} pull requests, {} comments, {} releases, {} assets{}",
446+ totals.labels,
447+ totals.milestones,
448+ totals.issues,
449+ totals.pulls,
450+ totals.comments,
451+ totals.releases,
452+ totals.assets,
453+ if totals.skipped > 0 {
454+ format!(", {} skipped", totals.skipped)
455+ } else {
456+ String::new()
457+ }
458+ ))
459+}
460+
461+async fn fetch_git(
462+ state: &AppState,
463+ repo: &Repo,
464+ spec: &JobSpec,
465+ transport: &Transport,
466+) -> Result<(), String> {
467+ let repo_dir =
468+ forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?;
469+ let url = spec.clone_url();
470+ let fetch = async {
471+ match transport {
472+ Transport::Net => {
473+ let policy = policy(state);
474+ let pin = check_remote(&url, &policy).await?;
475+ let auth = spec.auth();
476+ mirror_fetch(
477+ &state.git,
478+ &repo_dir,
479+ &url,
480+ auth.as_ref(),
481+ policy.allow_http,
482+ pin.as_ref(),
483+ GIT_TIMEOUT,
484+ )
485+ .await
486+ .map_err(|e| e.to_string())
487+ }
488+ #[cfg(test)]
489+ Transport::Local(path) => {
490+ forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT)
491+ .await
492+ .map_err(|e| e.to_string())
493+ }
494+ }
495+ };
496+ pull_refs(state, repo, fetch).await.map(|_| ())
497+}
498+
499+/// Points the stored default branch at the branch HEAD names, when the fetch moved HEAD to the
500+/// remote's default.
501+async fn sync_default_branch(state: &AppState, repo: Repo, rep: &Reporter) -> Repo {
502+ let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) else {
503+ return repo;
504+ };
505+ let head = forge_git::command::GitCommand::new(&state.git, "symbolic-ref")
506+ .git_dir(&dir)
507+ .arg("--short")
508+ .arg("HEAD")
509+ .output()
510+ .await
511+ .ok()
512+ .map(|out| String::from_utf8_lossy(&out).trim().to_owned())
513+ .filter(|b| !b.is_empty());
514+ let Some(head) = head else {
515+ return repo;
516+ };
517+ if head == repo.default_branch {
518+ return repo;
519+ }
520+ if let Err(e) = state
521+ .store
522+ .update_repo_general(&repo.id, &repo.description, &head)
523+ .await
524+ {
525+ rep.log("warn", format!("could not set the default branch: {e}"))
526+ .await;
527+ return repo;
528+ }
529+ state
530+ .store
531+ .repo_by_id(&repo.id)
532+ .await
533+ .ok()
534+ .flatten()
535+ .unwrap_or(repo)
536+}
537+
538+#[derive(Default)]
539+struct Totals {
540+ labels: usize,
541+ milestones: usize,
542+ issues: usize,
543+ pulls: usize,
544+ comments: usize,
545+ releases: usize,
546+ assets: usize,
547+ skipped: usize,
548+}
549+
550+fn api_err(e: ApiError) -> String {
551+ e.to_string()
552+}
553+
554+struct Run<'a, A> {
555+ state: &'a AppState,
556+ rep: &'a Reporter,
557+ repo: &'a Repo,
558+ user: &'a User,
559+ api: &'a A,
560+ spec: &'a JobSpec,
561+}
562+
563+impl<A: RemoteApi> Run<'_, A> {
564+ fn store(&self) -> &Store {
565+ &self.state.store
566+ }
567+
568+ async fn mapped(&self, kind: &str, ext: &str) -> Result<Option<ImportOrigin>, String> {
569+ self.store()
570+ .import_origin(&self.repo.id, kind, ext)
571+ .await
572+ .map_err(|e| e.to_string())
573+ }
574+
575+ async fn record(&self, kind: &str, ext: &str, local: &str, author: &str, url: &str) {
576+ let origin = ImportOrigin {
577+ local_id: local.to_owned(),
578+ author: author.to_owned(),
579+ url: url.to_owned(),
580+ };
581+ if let Err(e) = self
582+ .store()
583+ .record_import_origin(&self.repo.id, kind, ext, &origin)
584+ .await
585+ {
586+ tracing::warn!(error = %e, "import: could not record an id mapping");
587+ }
588+ }
589+
590+ async fn labels(&self, totals: &mut Totals) -> Result<(), String> {
591+ self.rep.stage("labels", 0, 0).await;
592+ let labels = self.api.labels(&self.spec.remote).await.map_err(api_err)?;
593+ let total = labels.len();
594+ for (i, label) in labels.into_iter().enumerate() {
595+ self.rep.stage("labels", i, total).await;
596+ let key = label.name.to_lowercase();
597+ if self.mapped("label", &key).await?.is_some() {
598+ continue;
599+ }
600+ match self
601+ .store()
602+ .create_label(&self.repo.id, &label.name, &label.color, &label.description)
603+ .await
604+ {
605+ Ok(created) => {
606+ self.record("label", &key, &created.id, "", "").await;
607+ totals.labels += 1;
608+ }
609+ Err(forge_core::Error::Conflict(_)) => {}
610+ Err(e) => {
611+ totals.skipped += 1;
612+ self.rep
613+ .log("warn", format!("label `{}` skipped: {e}", label.name))
614+ .await;
615+ }
616+ }
617+ }
618+ self.rep.log("info", format!("{total} labels read")).await;
619+ Ok(())
620+ }
621+
622+ async fn milestones(&self, totals: &mut Totals) -> Result<(), String> {
623+ self.rep.stage("milestones", 0, 0).await;
624+ let items = self
625+ .api
626+ .milestones(&self.spec.remote)
627+ .await
628+ .map_err(api_err)?;
629+ let total = items.len();
630+ for (i, m) in items.into_iter().enumerate() {
631+ self.rep.stage("milestones", i, total).await;
632+ if self.mapped("milestone", &m.id).await?.is_some() {
633+ continue;
634+ }
635+ let created = match self
636+ .store()
637+ .create_milestone(&self.repo.id, &m.title, &m.description, m.due_on.as_deref())
638+ .await
639+ {
640+ Ok(created) => created,
641+ Err(e) => {
642+ totals.skipped += 1;
643+ self.rep
644+ .log("warn", format!("milestone `{}` skipped: {e}", m.title))
645+ .await;
646+ continue;
647+ }
648+ };
649+ if m.closed
650+ && let Err(e) = self
651+ .store()
652+ .update_milestone(
653+ &self.repo.id,
654+ &created.id,
655+ &created.title,
656+ &created.description,
657+ created.due_on.as_deref(),
658+ IssueState::Closed,
659+ )
660+ .await
661+ {
662+ self.rep
663+ .log("warn", format!("milestone `{}` stays open: {e}", m.title))
664+ .await;
665+ }
666+ self.record("milestone", &m.id, &created.id, "", "").await;
667+ totals.milestones += 1;
668+ }
669+ Ok(())
670+ }
671+
672+ /// The id of the repo label `name` (case-insensitive), created when it is missing.
673+ async fn label_id(
674+ &self,
675+ cache: &mut HashMap<String, String>,
676+ name: &str,
677+ color: &str,
678+ ) -> Option<String> {
679+ let key = name.trim().to_lowercase();
680+ if let Some(id) = cache.get(&key) {
681+ return Some(id.clone());
682+ }
683+ match self
684+ .store()
685+ .create_label(&self.repo.id, name, color, "")
686+ .await
687+ {
688+ Ok(label) => {
689+ cache.insert(key, label.id.clone());
690+ Some(label.id)
691+ }
692+ Err(_) => None,
693+ }
694+ }
695+
696+ async fn issues(&self, totals: &mut Totals) -> Result<(), String> {
697+ self.rep.stage("issues", 0, 0).await;
698+ let mut items: Vec<ExtIssue> = self
699+ .api
700+ .issues(&self.spec.remote)
701+ .await
702+ .map_err(api_err)?
703+ .into_iter()
704+ .filter(|i| {
705+ if i.is_pr {
706+ self.spec.options.pulls
707+ } else {
708+ self.spec.options.issues
709+ }
710+ })
711+ .collect();
712+ items.sort_by_key(|i| (i.is_pr, i.number));
713+ // GitHub numbers issues and pull requests together; GitLab keeps two sequences. Sorting
714+ // by number alone keeps GitHub numbers aligned, so do that for it.
715+ if self.spec.source == Source::GitHub {
716+ items.sort_by_key(|i| i.number);
717+ }
718+ let total = items.len();
719+ let mut labels: HashMap<String, String> = self
720+ .store()
721+ .list_labels(&self.repo.id)
722+ .await
723+ .map_err(|e| e.to_string())?
724+ .into_iter()
725+ .map(|l| (l.name.to_lowercase(), l.id))
726+ .collect();
727+ let milestones: HashMap<String, String> = self
728+ .store()
729+ .list_milestones(&self.repo.id, None)
730+ .await
731+ .map_err(|e| e.to_string())?
732+ .into_iter()
733+ .map(|m| (m.title.to_lowercase(), m.id))
734+ .collect();
735+ self.rep
736+ .log(
737+ "info",
738+ format!("Importing {total} issues and pull requests"),
739+ )
740+ .await;
741+ for (i, item) in items.iter().enumerate() {
742+ self.rep.stage("issues", i, total).await;
743+ let kind = if item.is_pr { "pull" } else { "issue" };
744+ let ext = item.number.to_string();
745+ let local = match self.mapped(kind, &ext).await? {
746+ Some(o) => o.local_id,
747+ None => match self.create_item(item, &mut labels, &milestones).await {
748+ Ok(id) => {
749+ self.record(kind, &ext, &id, &item.author, &item.url).await;
750+ if item.is_pr {
751+ totals.pulls += 1;
752+ } else {
753+ totals.issues += 1;
754+ }
755+ id
756+ }
757+ Err(e) => {
758+ totals.skipped += 1;
759+ self.rep
760+ .log("warn", format!("#{} skipped: {e}", item.number))
761+ .await;
762+ continue;
763+ }
764+ },
765+ };
766+ let comments = self
767+ .api
768+ .comments(&self.spec.remote, item)
769+ .await
770+ .map_err(api_err)?;
771+ for c in comments {
772+ if self
773+ .mapped("comment", &format!("{kind}:{}", c.id))
774+ .await?
775+ .is_some()
776+ {
777+ continue;
778+ }
779+ let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url);
780+ let body = with_note(&note, &c.body);
781+ match self.store().add_comment(&local, &self.user.id, &body).await {
782+ Ok(created) => {
783+ self.record(
784+ "comment",
785+ &format!("{kind}:{}", c.id),
786+ &created.id,
787+ &c.author,
788+ &c.url,
789+ )
790+ .await;
791+ totals.comments += 1;
792+ }
793+ Err(e) => {
794+ totals.skipped += 1;
795+ self.rep
796+ .log(
797+ "warn",
798+ format!("a comment on #{} skipped: {e}", item.number),
799+ )
800+ .await;
801+ }
802+ }
803+ }
804+ }
805+ self.rep.stage("issues", total, total).await;
806+ Ok(())
807+ }
808+
809+ /// Creates the local issue with its labels, milestone and state. Returns its id.
810+ async fn create_item(
811+ &self,
812+ item: &ExtIssue,
813+ labels: &mut HashMap<String, String>,
814+ milestones: &HashMap<String, String>,
815+ ) -> Result<String, forge_core::Error> {
816+ let source = self.spec.source.label();
817+ let mut note = origin_note(source, &item.author, &item.created_at, &item.url);
818+ if item.is_pr {
819+ let how = if item.merged {
820+ "merged"
821+ } else if item.closed {
822+ "closed"
823+ } else {
824+ "open"
825+ };
826+ note.push_str(&format!(
827+ "> Imported pull request ({how}). Its branches may no longer exist, so there is nothing to merge here.\n\n"
828+ ));
829+ }
830+ let body = with_note(&note, &item.body);
831+ let issue = self
832+ .store()
833+ .create_issue(
834+ &self.repo.id,
835+ &self.user.id,
836+ &clip_title(&item.title),
837+ &body,
838+ )
839+ .await?;
840+ let mut ids = Vec::new();
841+ for name in &item.labels {
842+ if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await {
843+ ids.push(id);
844+ }
845+ }
846+ if item.is_pr
847+ && let Some(id) = self
848+ .label_id(labels, IMPORTED_PR_LABEL, IMPORTED_PR_COLOR)
849+ .await
850+ {
851+ ids.push(id);
852+ }
853+ ids.dedup();
854+ if !ids.is_empty() {
855+ self.store()
856+ .set_issue_labels(&issue.id, &self.user.id, &ids)
857+ .await?;
858+ }
859+ if let Some(id) = item
860+ .milestone
861+ .as_ref()
862+ .and_then(|t| milestones.get(&t.to_lowercase()))
863+ {
864+ self.store()
865+ .set_issue_milestone(&issue.id, &self.user.id, Some(id))
866+ .await?;
867+ }
868+ if item.closed {
869+ let reason = if item.not_planned {
870+ StateReason::NotPlanned
871+ } else {
872+ StateReason::Completed
873+ };
874+ self.store()
875+ .set_issue_state(
876+ &issue.id,
877+ Some(&self.user.id),
878+ IssueState::Closed,
879+ Some(reason),
880+ serde_json::Value::Null,
881+ )
882+ .await?;
883+ }
884+ Ok(issue.id)
885+ }
886+
887+ async fn releases(&self, totals: &mut Totals) -> Result<(), String> {
888+ self.rep.stage("releases", 0, 0).await;
889+ let releases = self
890+ .api
891+ .releases(&self.spec.remote)
892+ .await
893+ .map_err(api_err)?;
894+ let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id)
895+ .map_err(|e| e.to_string())?;
896+ let refs = ref_snapshot(self.state, &repo_dir).await?;
897+ let max_bytes = self.state.live().releases.max_asset_mb * 1024 * 1024;
898+ let total = releases.len();
899+ for (i, rel) in releases.iter().enumerate() {
900+ self.rep.stage("releases", i, total).await;
901+ let Some(release) = self.release_of(rel, &refs, totals).await? else {
902+ continue;
903+ };
904+ for asset in &rel.assets {
905+ self.asset(&release, rel, asset, max_bytes, totals).await?;
906+ }
907+ }
908+ self.rep.stage("releases", total, total).await;
909+ Ok(())
910+ }
911+
912+ /// The local release for `rel`: the one a past run made, a new one, or `None` when it cannot
913+ /// be made (no tag in the imported git data).
914+ async fn release_of(
915+ &self,
916+ rel: &ExtRelease,
917+ refs: &std::collections::BTreeMap<String, String>,
918+ totals: &mut Totals,
919+ ) -> Result<Option<forge_core::releases::Release>, String> {
920+ if let Some(o) = self.mapped("release", &rel.id).await? {
921+ return self
922+ .store()
923+ .release(&o.local_id)
924+ .await
925+ .map_err(|e| e.to_string());
926+ }
927+ let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else {
928+ totals.skipped += 1;
929+ self.rep
930+ .log(
931+ "warn",
932+ format!(
933+ "release `{}` skipped: its tag is not in the git data",
934+ rel.tag
935+ ),
936+ )
937+ .await;
938+ return Ok(None);
939+ };
940+ if let Some(existing) = self
941+ .store()
942+ .release_by_tag(&self.repo.id, &rel.tag)
943+ .await
944+ .map_err(|e| e.to_string())?
945+ {
946+ self.record("release", &rel.id, &existing.id, &rel.author, &rel.url)
947+ .await;
948+ return Ok(Some(existing));
949+ }
950+ let note = origin_note(
951+ self.spec.source.label(),
952+ &rel.author,
953+ &rel.created_at,
954+ &rel.url,
955+ );
956+ let body = with_note(&note, &rel.body);
957+ let title = clip_title(&rel.title);
958+ let created = self
959+ .store()
960+ .create_release(&NewRelease {
961+ repo_id: &self.repo.id,
962+ tag: &rel.tag,
963+ target_oid: oid,
964+ title: &title,
965+ body: &body,
966+ draft: rel.draft,
967+ prerelease: rel.prerelease,
968+ author_id: &self.user.id,
969+ })
970+ .await;
971+ match created {
972+ Ok(release) => {
973+ self.record("release", &rel.id, &release.id, &rel.author, &rel.url)
974+ .await;
975+ totals.releases += 1;
976+ Ok(Some(release))
977+ }
978+ Err(e) => {
979+ totals.skipped += 1;
980+ self.rep
981+ .log("warn", format!("release `{}` skipped: {e}", rel.tag))
982+ .await;
983+ Ok(None)
984+ }
985+ }
986+ }
987+
988+ async fn asset(
989+ &self,
990+ release: &forge_core::releases::Release,
991+ rel: &ExtRelease,
992+ asset: &ExtAsset,
993+ max_bytes: u64,
994+ totals: &mut Totals,
995+ ) -> Result<(), String> {
996+ let ext = format!("{}:{}", rel.id, asset.id);
997+ if self.mapped("asset", &ext).await?.is_some() {
998+ return Ok(());
999+ }
1000+ if asset.size > max_bytes {
1001+ totals.skipped += 1;
1002+ self.rep
1003+ .log(
1004+ "warn",
1005+ format!(
1006+ "asset `{}` skipped: larger than the upload limit",
1007+ asset.name
1008+ ),
1009+ )
1010+ .await;
1011+ return Ok(());
1012+ }
1013+ self.rep
1014+ .log("info", format!("Downloading asset {}", asset.name))
1015+ .await;
1016+ let bytes = match self.api.download(asset, max_bytes).await {
1017+ Ok(bytes) => bytes,
1018+ Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => {
1019+ return Err(e.to_string());
1020+ }
1021+ Err(e) => {
1022+ totals.skipped += 1;
1023+ self.rep
1024+ .log("warn", format!("asset `{}` skipped: {e}", asset.name))
1025+ .await;
1026+ return Ok(());
1027+ }
1028+ };
1029+ let name = asset_name(&asset.name);
1030+ let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str());
1031+ let stream =
1032+ futures_util::stream::iter([Ok::<_, std::io::Error>(bytes::Bytes::from(bytes))]);
1033+ match crate::release_ops::put_asset(
1034+ self.state,
1035+ self.repo,
1036+ release,
1037+ self.user,
1038+ &name,
1039+ content_type,
1040+ stream,
1041+ max_bytes,
1042+ )
1043+ .await
1044+ {
1045+ Ok((stored, _)) => {
1046+ self.record("asset", &ext, &stored.id, &rel.author, &asset.url)
1047+ .await;
1048+ totals.assets += 1;
1049+ }
1050+ Err(e) => {
1051+ totals.skipped += 1;
1052+ self.rep
1053+ .log(
1054+ "warn",
1055+ format!("asset `{}` skipped: {}", asset.name, e.message()),
1056+ )
1057+ .await;
1058+ }
1059+ }
1060+ Ok(())
1061+ }
1062+}
1063+
1064+/// Marks jobs a restart cut short as failed, so their pages offer a retry.
1065+pub async fn on_boot(state: &AppState) {
1066+ match state.store.fail_interrupted_imports().await {
1067+ Ok(0) => {}
1068+ Ok(n) => tracing::warn!(count = n, "import: marked interrupted jobs as failed"),
1069+ Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"),
1070+ }
1071+}
1072+
1073+#[cfg(test)]
1074+mod tests;
crates/forge-web/src/importer/remote.rsadded+157 -0
@@ -0,0 +1,157 @@
1+//! Turning what the user typed into a remote reference, and building the API clients.
2+
3+use std::time::Duration;
4+
5+use super::Source;
6+use super::api::{self, GitHub, GitLab, Http, Notice};
7+use crate::mirrors::policy;
8+use crate::state::AppState;
9+use crate::webhooks::client::{policy_client, validate_url};
10+
11+/// A GitHub client under the outbound policy.
12+pub fn make_github(
13+ state: &AppState,
14+ token: Option<String>,
15+ notice: Notice,
16+) -> Result<GitHub, String> {
17+ let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
18+ .map_err(|e| format!("could not build the HTTP client: {e}"))?;
19+ Ok(GitHub::new(Http::new(
20+ client,
21+ token,
22+ false,
23+ "api.github.com".into(),
24+ notice,
25+ )))
26+}
27+
28+/// A GitLab client for `instance`, which must pass the outbound policy.
29+pub fn make_gitlab(
30+ state: &AppState,
31+ instance: &str,
32+ token: Option<String>,
33+ notice: Notice,
34+) -> Result<GitLab, String> {
35+ let instance = instance.trim_end_matches('/');
36+ let host = validate_url(instance, &policy(state))
37+ .map_err(|e| format!("instance address refused: {e}"))?
38+ .host_str()
39+ .unwrap_or_default()
40+ .to_ascii_lowercase();
41+ let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1")
42+ .map_err(|e| format!("could not build the HTTP client: {e}"))?;
43+ Ok(GitLab::new(
44+ Http::new(client, token, true, host, notice),
45+ instance,
46+ ))
47+}
48+
49+/// Splits what the user typed into `(remote, instance)` for a source. `None` when it is not a
50+/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab takes a project URL
51+/// (`https://host/group/project`) or, with `instance` given, a bare path.
52+pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> {
53+ let text = text.trim();
54+ match source {
55+ Source::Git => (text.starts_with("https://") || text.starts_with("http://"))
56+ .then(|| (text.to_owned(), String::new())),
57+ Source::GitHub => {
58+ let path = text
59+ .strip_prefix("https://github.com/")
60+ .unwrap_or(text)
61+ .trim_end_matches('/');
62+ let path = path.strip_suffix(".git").unwrap_or(path);
63+ api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new()))
64+ }
65+ Source::GitLab => {
66+ if let Some((scheme, rest)) = text
67+ .strip_prefix("https://")
68+ .map(|r| ("https", r))
69+ .or_else(|| text.strip_prefix("http://").map(|r| ("http", r)))
70+ {
71+ let (host, path) = rest.split_once('/')?;
72+ let path = path.trim_end_matches('/');
73+ let path = path.strip_suffix(".git").unwrap_or(path);
74+ if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, 20) {
75+ return None;
76+ }
77+ return Some((path.to_owned(), format!("{scheme}://{host}")));
78+ }
79+ let instance = instance.trim().trim_end_matches('/');
80+ let path = text.trim_matches('/');
81+ let path = path.strip_suffix(".git").unwrap_or(path);
82+ let host = instance
83+ .strip_prefix("https://")
84+ .or_else(|| instance.strip_prefix("http://"))?;
85+ let ok = !host.is_empty()
86+ && !host.contains('@')
87+ && !host.contains('/')
88+ && api::valid_path(path, 2, 20);
89+ ok.then(|| (path.to_owned(), instance.to_owned()))
90+ }
91+ }
92+}
93+
94+/// The reference stored on a job and shown to the user: no credential in it.
95+pub fn source_ref(source: Source, remote: &str, instance: &str) -> String {
96+ match source {
97+ Source::GitLab => format!("{}/{}", instance.trim_end_matches('/'), remote),
98+ _ => remote.to_owned(),
99+ }
100+}
101+
102+/// The repository name a remote would get by default: its last path segment without `.git`.
103+pub fn default_name(remote: &str) -> String {
104+ remote
105+ .trim_end_matches('/')
106+ .rsplit('/')
107+ .next()
108+ .unwrap_or_default()
109+ .trim_end_matches(".git")
110+ .to_owned()
111+}
112+
113+#[cfg(test)]
114+mod tests {
115+ use super::*;
116+
117+ #[test]
118+ fn github_accepts_owner_name_or_url() {
119+ let ok = |t: &str| parse_remote(Source::GitHub, t, "").map(|r| r.0);
120+ assert_eq!(ok("tahinli/forge").as_deref(), Some("tahinli/forge"));
121+ assert_eq!(
122+ ok("https://github.com/tahinli/forge.git").as_deref(),
123+ Some("tahinli/forge")
124+ );
125+ assert_eq!(ok("tahinli").as_deref(), None);
126+ assert_eq!(ok("a/b/c").as_deref(), None);
127+ assert_eq!(ok("../etc").as_deref(), None);
128+ }
129+
130+ #[test]
131+ fn gitlab_takes_a_url_or_a_path_with_an_instance() {
132+ let url = parse_remote(Source::GitLab, "https://gl.example.org/grp/sub/proj", "");
133+ assert_eq!(
134+ url,
135+ Some(("grp/sub/proj".into(), "https://gl.example.org".into()))
136+ );
137+ let bare = parse_remote(Source::GitLab, "grp/proj", "https://gitlab.com/");
138+ assert_eq!(bare, Some(("grp/proj".into(), "https://gitlab.com".into())));
139+ assert_eq!(parse_remote(Source::GitLab, "grp/proj", ""), None);
140+ assert_eq!(
141+ parse_remote(Source::GitLab, "https://u:p@host/a/b", ""),
142+ None
143+ );
144+ }
145+
146+ #[test]
147+ fn git_needs_http_scheme_and_names_default_from_the_path() {
148+ assert!(parse_remote(Source::Git, "file:///etc", "").is_none());
149+ assert!(parse_remote(Source::Git, "https://example.org/x/y.git", "").is_some());
150+ assert_eq!(default_name("https://example.org/x/y.git"), "y");
151+ assert_eq!(default_name("grp/proj"), "proj");
152+ assert_eq!(
153+ source_ref(Source::GitLab, "g/p", "https://gitlab.com"),
154+ "https://gitlab.com/g/p"
155+ );
156+ }
157+}
crates/forge-web/src/importer/tests.rsadded+544 -0
@@ -0,0 +1,544 @@
1+//! Import tests. The remote API is a fake behind [`RemoteApi`], and the git side is a bare repo on
2+//! disk fetched over the local transport, so nothing here touches the network.
3+
4+use std::collections::HashMap;
5+use std::path::Path;
6+use std::sync::Mutex;
7+
8+use forge_core::issues::IssueFilter;
9+use forge_core::store::imports::{ImportJob, ImportState};
10+use forge_core::{IssueState, Visibility};
11+
12+use super::api::{
13+ ApiError, ApiResult, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, ExtRelease,
14+ ExtRepo, RemoteApi,
15+};
16+use super::{
17+ ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note,
18+};
19+use crate::state::AppState;
20+use crate::test_support::test_state;
21+
22+const TOKEN: &str = "ghp_supersecret_token_value";
23+
24+#[derive(Default)]
25+struct Fake {
26+ labels: Vec<ExtLabel>,
27+ milestones: Vec<ExtMilestone>,
28+ issues: Vec<ExtIssue>,
29+ comments: HashMap<i64, Vec<ExtComment>>,
30+ releases: Vec<ExtRelease>,
31+ files: HashMap<String, Vec<u8>>,
32+ /// Errors handed out by `comments`, one per call, before it starts answering.
33+ comment_failures: Mutex<Vec<ApiError>>,
34+ comment_calls: Mutex<usize>,
35+}
36+
37+impl RemoteApi for Fake {
38+ async fn list_repos(&self, _owner: &str) -> ApiResult<Vec<ExtRepo>> {
39+ Ok(vec![ExtRepo {
40+ name: "project".into(),
41+ full_name: "tahinli/project".into(),
42+ ..ExtRepo::default()
43+ }])
44+ }
45+
46+ async fn labels(&self, _repo: &str) -> ApiResult<Vec<ExtLabel>> {
47+ Ok(self.labels.clone())
48+ }
49+
50+ async fn milestones(&self, _repo: &str) -> ApiResult<Vec<ExtMilestone>> {
51+ Ok(self.milestones.clone())
52+ }
53+
54+ async fn issues(&self, _repo: &str) -> ApiResult<Vec<ExtIssue>> {
55+ Ok(self.issues.clone())
56+ }
57+
58+ async fn comments(&self, _repo: &str, issue: &ExtIssue) -> ApiResult<Vec<ExtComment>> {
59+ *self.comment_calls.lock().unwrap() += 1;
60+ if let Some(e) = self.comment_failures.lock().unwrap().pop() {
61+ return Err(e);
62+ }
63+ Ok(self
64+ .comments
65+ .get(&issue.number)
66+ .cloned()
67+ .unwrap_or_default())
68+ }
69+
70+ async fn releases(&self, _repo: &str) -> ApiResult<Vec<ExtRelease>> {
71+ Ok(self.releases.clone())
72+ }
73+
74+ async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult<Vec<u8>> {
75+ self.files
76+ .get(&asset.url)
77+ .cloned()
78+ .ok_or_else(|| ApiError::NotFound("asset".into()))
79+ }
80+}
81+
82+fn plumbing(git_dir: &Path, args: &[&str]) -> String {
83+ let out = std::process::Command::new("git")
84+ .arg(format!("--git-dir={}", git_dir.display()))
85+ .args(args)
86+ .env("GIT_AUTHOR_NAME", "t")
87+ .env("GIT_AUTHOR_EMAIL", "t@example.com")
88+ .env("GIT_COMMITTER_NAME", "t")
89+ .env("GIT_COMMITTER_EMAIL", "t@example.com")
90+ .output()
91+ .expect("git runs");
92+ assert!(out.status.success(), "git {args:?}: {out:?}");
93+ String::from_utf8_lossy(&out.stdout).trim().to_string()
94+}
95+
96+fn commit_to(git_dir: &Path, refname: &str, message: &str) {
97+ let tree = plumbing(git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]);
98+ let commit = plumbing(git_dir, &["commit-tree", &tree, "-m", message]);
99+ plumbing(git_dir, &["update-ref", refname, &commit]);
100+}
101+
102+/// A bare "remote" with `master`, a `dev` branch and a `v1` tag, HEAD on `master`.
103+fn upstream(dir: &Path) -> String {
104+ let path = dir.join("upstream.git");
105+ let out = std::process::Command::new("git")
106+ .args(["init", "--bare", "-q"])
107+ .arg(&path)
108+ .output()
109+ .expect("git init");
110+ assert!(out.status.success());
111+ plumbing(&path, &["symbolic-ref", "HEAD", "refs/heads/master"]);
112+ commit_to(&path, "refs/heads/master", "one");
113+ commit_to(&path, "refs/heads/dev", "dev work");
114+ commit_to(&path, "refs/tags/v1", "tagged");
115+ path.display().to_string()
116+}
117+
118+struct Fixture {
119+ state: AppState,
120+ repo: forge_core::Repo,
121+ user: forge_core::User,
122+ _dir: tempfile::TempDir,
123+ upstream: String,
124+}
125+
126+async fn fixture() -> Fixture {
127+ let dir = tempfile::tempdir().expect("tempdir");
128+ let state = test_state(dir.path()).await;
129+ let user = state
130+ .store
131+ .create_user("tahinli", None, "unused", false)
132+ .await
133+ .expect("user");
134+ let repo = state
135+ .store
136+ .create_repo(&user.id, "project", "", Visibility::Public, "main")
137+ .await
138+ .expect("repo");
139+ let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path");
140+ forge_git::repo::init_bare(&state.git, &bare, "main")
141+ .await
142+ .expect("init bare");
143+ let upstream = upstream(dir.path());
144+ Fixture {
145+ state,
146+ repo,
147+ user,
148+ _dir: dir,
149+ upstream,
150+ }
151+}
152+
153+fn spec(source: Source, options: ImportOptions) -> JobSpec {
154+ JobSpec {
155+ source,
156+ remote: "tahinli/project".into(),
157+ instance: String::new(),
158+ token: Some(TOKEN.into()),
159+ git_user: String::new(),
160+ options,
161+ }
162+}
163+
164+async fn new_job(fx: &Fixture, source: Source) -> ImportJob {
165+ fx.state
166+ .store
167+ .create_import_job(
168+ &fx.user.id,
169+ &fx.repo.id,
170+ source.as_str(),
171+ "tahinli/project",
172+ "{}",
173+ )
174+ .await
175+ .expect("job")
176+}
177+
178+fn everything() -> ImportOptions {
179+ ImportOptions {
180+ labels: true,
181+ issues: true,
182+ pulls: true,
183+ releases: true,
184+ }
185+}
186+
187+fn fake() -> Fake {
188+ let mut fake = Fake {
189+ labels: vec![ExtLabel {
190+ name: "bug".into(),
191+ color: "#d73a4a".into(),
192+ description: "Broken".into(),
193+ }],
194+ milestones: vec![ExtMilestone {
195+ id: "1".into(),
196+ title: "v1".into(),
197+ closed: true,
198+ due_on: Some("2020-05-06".into()),
199+ ..ExtMilestone::default()
200+ }],
201+ issues: vec![
202+ ExtIssue {
203+ number: 1,
204+ title: "It breaks".into(),
205+ body: "steps".into(),
206+ closed: true,
207+ author: "octocat".into(),
208+ labels: vec!["bug".into()],
209+ milestone: Some("v1".into()),
210+ created_at: "2020-01-02T03:04:05Z".into(),
211+ url: "https://github.com/tahinli/project/issues/1".into(),
212+ ..ExtIssue::default()
213+ },
214+ ExtIssue {
215+ number: 2,
216+ title: "Add the thing".into(),
217+ body: "patch".into(),
218+ closed: true,
219+ merged: true,
220+ is_pr: true,
221+ author: "hubot".into(),
222+ created_at: "2020-02-02T00:00:00Z".into(),
223+ url: "https://github.com/tahinli/project/pull/2".into(),
224+ ..ExtIssue::default()
225+ },
226+ ],
227+ releases: vec![ExtRelease {
228+ id: "7".into(),
229+ tag: "v1".into(),
230+ title: "First".into(),
231+ body: "notes".into(),
232+ author: "octocat".into(),
233+ assets: vec![ExtAsset {
234+ id: "9".into(),
235+ name: "app 1.tar.gz".into(),
236+ size: 5,
237+ content_type: "application/gzip".into(),
238+ url: "https://api.github.com/assets/9".into(),
239+ }],
240+ ..ExtRelease::default()
241+ }],
242+ ..Fake::default()
243+ };
244+ fake.comments.insert(
245+ 1,
246+ vec![ExtComment {
247+ id: "100".into(),
248+ author: "hubot".into(),
249+ body: "same here".into(),
250+ created_at: "2020-01-03T00:00:00Z".into(),
251+ url: "https://github.com/tahinli/project/issues/1#c100".into(),
252+ }],
253+ );
254+ fake.files
255+ .insert("https://api.github.com/assets/9".into(), b"hello".to_vec());
256+ fake
257+}
258+
259+#[tokio::test]
260+async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() {
261+ let fx = fixture().await;
262+ let job = new_job(&fx, Source::Git).await;
263+ let spec = spec(Source::Git, ImportOptions::default());
264+ run_job::<Fake>(
265+ &fx.state,
266+ &job,
267+ &spec,
268+ None,
269+ &Transport::Local(fx.upstream.clone()),
270+ )
271+ .await;
272+
273+ let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
274+ assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
275+ let dir = forge_git::repo::repo_path(&fx.state.git.data_dir, &fx.repo.id).unwrap();
276+ let refs = crate::mirrors::ref_snapshot(&fx.state, &dir).await.unwrap();
277+ assert!(refs.contains_key("refs/heads/master"));
278+ assert!(refs.contains_key("refs/heads/dev"));
279+ assert!(refs.contains_key("refs/tags/v1"));
280+ // The remote's default branch becomes the repo's, and no mirror row exists: it is a normal repo.
281+ let repo = fx
282+ .state
283+ .store
284+ .repo_by_id(&fx.repo.id)
285+ .await
286+ .unwrap()
287+ .unwrap();
288+ assert_eq!(repo.default_branch, "master");
289+ assert!(
290+ fx.state
291+ .store
292+ .pull_mirror(&fx.repo.id)
293+ .await
294+ .unwrap()
295+ .is_none()
296+ );
297+}
298+
299+#[tokio::test]
300+async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() {
301+ let fx = fixture().await;
302+ let api = fake();
303+ let job = new_job(&fx, Source::GitHub).await;
304+ let spec = spec(Source::GitHub, everything());
305+ run_job(
306+ &fx.state,
307+ &job,
308+ &spec,
309+ Some(&api),
310+ &Transport::Local(fx.upstream.clone()),
311+ )
312+ .await;
313+
314+ let store = &fx.state.store;
315+ let job = store.import_job(&job.id).await.unwrap().unwrap();
316+ assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
317+
318+ let all = IssueFilter {
319+ state: None,
320+ per_page: 100,
321+ ..IssueFilter::default()
322+ };
323+ let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();
324+ assert_eq!(total, 2);
325+ let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap();
326+ assert_eq!(issue.issue.state, IssueState::Closed);
327+ assert_eq!(
328+ issue.issue.author_id, fx.user.id,
329+ "the importer owns the row"
330+ );
331+ assert!(
332+ issue
333+ .issue
334+ .body
335+ .starts_with("> Originally by \\@octocat on GitHub, 2020-01-02"),
336+ "{}",
337+ issue.issue.body
338+ );
339+ assert!(issue.labels.iter().any(|l| l.name == "bug"));
340+ assert!(issue.issue.milestone_id.is_some());
341+
342+ let pull = items
343+ .iter()
344+ .find(|i| i.issue.title == "Add the thing")
345+ .unwrap();
346+ assert!(pull.labels.iter().any(|l| l.name == "imported PR"));
347+ assert!(pull.issue.body.contains("Imported pull request (merged)"));
348+ assert!(pull.issue.body.contains("Originally by \\@hubot"));
349+
350+ let comments = store.list_comments(&issue.issue.id).await.unwrap();
351+ assert_eq!(comments.len(), 1);
352+ assert!(
353+ comments[0]
354+ .body
355+ .contains("Originally by \\@hubot on GitHub")
356+ );
357+ assert!(comments[0].body.ends_with("same here"));
358+
359+ let release = store
360+ .release_by_tag(&fx.repo.id, "v1")
361+ .await
362+ .unwrap()
363+ .unwrap();
364+ assert!(release.body.contains("notes"));
365+ let assets = store.list_release_assets(&release.id).await.unwrap();
366+ assert_eq!(assets.len(), 1);
367+ assert_eq!(assets[0].name, "app_1.tar.gz");
368+ assert_eq!(assets[0].size, 5);
369+}
370+
371+#[tokio::test]
372+async fn running_an_import_twice_creates_nothing_twice() {
373+ let fx = fixture().await;
374+ let api = fake();
375+ let spec = spec(Source::GitHub, everything());
376+ for _ in 0..2 {
377+ let job = new_job(&fx, Source::GitHub).await;
378+ run_job(
379+ &fx.state,
380+ &job,
381+ &spec,
382+ Some(&api),
383+ &Transport::Local(fx.upstream.clone()),
384+ )
385+ .await;
386+ let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
387+ assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
388+ }
389+ let store = &fx.state.store;
390+ let all = IssueFilter {
391+ state: None,
392+ per_page: 100,
393+ ..IssueFilter::default()
394+ };
395+ let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();
396+ assert_eq!(total, 2);
397+ let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap();
398+ assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1);
399+ assert_eq!(store.list_releases(&fx.repo.id).await.unwrap().len(), 1);
400+ let release = store
401+ .release_by_tag(&fx.repo.id, "v1")
402+ .await
403+ .unwrap()
404+ .unwrap();
405+ assert_eq!(
406+ store.list_release_assets(&release.id).await.unwrap().len(),
407+ 1
408+ );
409+ // The labels: the imported one, plus "imported PR", each once.
410+ let labels = store.list_labels(&fx.repo.id).await.unwrap();
411+ assert_eq!(labels.iter().filter(|l| l.name == "bug").count(), 1);
412+}
413+
414+#[tokio::test]
415+async fn a_rate_limit_fails_the_job_clearly_and_a_retry_finishes_it() {
416+ let fx = fixture().await;
417+ let api = fake();
418+ api.comment_failures
419+ .lock()
420+ .unwrap()
421+ .push(ApiError::RateLimited { wait_secs: 3600 });
422+ let job = new_job(&fx, Source::GitHub).await;
423+ let spec = spec(Source::GitHub, everything());
424+ let transport = Transport::Local(fx.upstream.clone());
425+ run_job(&fx.state, &job, &spec, Some(&api), &transport).await;
426+
427+ let failed = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
428+ assert_eq!(failed.state, ImportState::Failed);
429+ let message = failed.error.clone().unwrap();
430+ assert!(message.contains("rate limit"), "{message}");
431+ let events = fx
432+ .state
433+ .store
434+ .list_import_events(&job.id, 50)
435+ .await
436+ .unwrap();
437+ assert!(events.iter().any(|e| e.level == "error"));
438+
439+ // Retry on the same job: the first issue exists already and is not created again.
440+ run_job(&fx.state, &job, &spec, Some(&api), &transport).await;
441+ let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
442+ assert_eq!(done.state, ImportState::Done, "{:?}", done.error);
443+ assert!(done.error.is_none());
444+ let all = IssueFilter {
445+ state: None,
446+ per_page: 100,
447+ ..IssueFilter::default()
448+ };
449+ let (_, total) = fx.state.store.list_issues(&fx.repo.id, &all).await.unwrap();
450+ assert_eq!(total, 2);
451+}
452+
453+#[tokio::test]
454+async fn the_token_is_never_written_to_the_database() {
455+ let fx = fixture().await;
456+ let api = fake();
457+ api.comment_failures
458+ .lock()
459+ .unwrap()
460+ .push(ApiError::Http(format!("boom {}", "x")));
461+ let job = new_job(&fx, Source::GitHub).await;
462+ let spec = spec(Source::GitHub, everything());
463+ run_job(
464+ &fx.state,
465+ &job,
466+ &spec,
467+ Some(&api),
468+ &Transport::Local(fx.upstream.clone()),
469+ )
470+ .await;
471+ let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
472+ let events = fx
473+ .state
474+ .store
475+ .list_import_events(&job.id, 500)
476+ .await
477+ .unwrap();
478+ let mut text = format!("{job:?}");
479+ for e in events {
480+ text.push_str(&e.message);
481+ }
482+ assert!(
483+ !text.contains(TOKEN),
484+ "the token leaked into stored job data"
485+ );
486+ assert!(
487+ !format!("{spec:?}").contains(TOKEN),
488+ "Debug prints the token"
489+ );
490+}
491+
492+#[tokio::test]
493+async fn a_failed_git_fetch_marks_the_job_failed() {
494+ let fx = fixture().await;
495+ let job = new_job(&fx, Source::Git).await;
496+ let spec = spec(Source::Git, ImportOptions::default());
497+ run_job::<Fake>(
498+ &fx.state,
499+ &job,
500+ &spec,
501+ None,
502+ &Transport::Local("/nonexistent/path.git".into()),
503+ )
504+ .await;
505+ let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
506+ assert_eq!(job.state, ImportState::Failed);
507+ assert!(job.error.is_some());
508+}
509+
510+#[test]
511+fn the_origin_note_escapes_the_mention_and_cleans_the_name() {
512+ let note = origin_note(
513+ "GitHub",
514+ "evil @tahinli\n",
515+ "2021-03-04T00:00:00Z",
516+ "https://github.com/o/r/issues/1",
517+ );
518+ assert!(note.starts_with("> Originally by \\@eviltahinli on GitHub, 2021-03-04"));
519+ assert!(note.contains("[original](https://github.com/o/r/issues/1)"));
520+ assert!(note.ends_with("\n\n"));
521+ let none = origin_note("GitHub", "", "", "javascript:alert(1)");
522+ assert!(none.contains("\\@unknown"));
523+ assert!(!none.contains("javascript"));
524+}
525+
526+#[test]
527+fn bodies_are_cut_at_the_limit_on_a_char_boundary() {
528+ let long = "\u{e9}".repeat(forge_core::issues::MAX_BODY);
529+ let text = with_note("> note\n\n", &long);
530+ assert!(text.len() <= forge_core::issues::MAX_BODY);
531+ assert!(text.ends_with("(cut)"));
532+}
533+
534+#[test]
535+fn asset_names_are_made_safe() {
536+ assert_eq!(asset_name("app 1.tar.gz"), "app_1.tar.gz");
537+ assert_eq!(asset_name("../../etc/passwd"), "_.._etc_passwd");
538+ assert_eq!(asset_name(".hidden"), "hidden");
539+ assert_eq!(asset_name("###"), "___");
540+ assert_eq!(asset_name(""), "asset");
541+ assert!(forge_core::releases::valid_asset_name(&asset_name(
542+ "a b/c?d"
543+ )));
544+}
crates/forge-web/src/main.rsmodified+2 -0
@@ -23,10 +23,12 @@ mod boot;
23 mod ci;23 mod ci;
24 mod client_ip;24 mod client_ip;
25 mod compression;25 mod compression;
26+mod exporter;
26 mod git_auth;27 mod git_auth;
27 mod git_http;28 mod git_http;
28 mod hook_cmd;29 mod hook_cmd;
29 mod i18n;30 mod i18n;
31+mod importer;
30 mod internal;32 mod internal;
31 mod lfs;33 mod lfs;
32 mod lfs_pointer;34 mod lfs_pointer;
crates/forge-web/src/pages/import.rsadded+1172 -0
@@ -0,0 +1,1172 @@
1+//! Pages: import a repository (`/new/import`), import several (`/new/import/bulk`), and watch an
2+//! import (`/import`, `/import/{id}`). The job page follows its event stream (`data-live`), so it
3+//! updates as the import runs with no polling and no reload.
4+
5+use std::collections::HashMap;
6+
7+use forge_core::store::imports::{ImportJob, ImportState};
8+use forge_core::time::stamp_to_unix;
9+use forge_core::{AuditAction, Repo, User, Visibility};
10+use forge_git::repo::{init_bare, repo_path};
11+use futures_util::stream;
12+use serde::Deserialize;
13+use topcoat::Result;
14+use topcoat::context::{Cx, app_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::{page, path_param, query_params, route};
19+use topcoat::view::{View, component, view};
20+
21+use crate::audit::{self, Actor, Target};
22+use crate::auth::{require_csrf, require_user};
23+use crate::i18n::migrate::{self as g, K};
24+use crate::i18n::{self, Key, Lang};
25+use crate::importer::api::{ApiError, RemoteApi};
26+use crate::importer::{
27+ self, ImportOptions, JobSpec, Source, default_name, make_github, make_gitlab, parse_remote,
28+ source_ref,
29+};
30+use crate::pages::ci_runs::{changed_event, events_response};
31+use crate::pages::new_repo::{owner_choices, repo_owner};
32+use crate::state::AppState;
33+use crate::views::{alert, csrf_field, now_unix, relative_time, shell, user_facing_message};
34+
35+path_param!(job_id);
36+
37+/// Most repositories one bulk submit starts.
38+const MAX_BULK: usize = 50;
39+const DEFAULT_BRANCH: &str = "main";
40+
41+#[derive(Deserialize, Default)]
42+struct ImportForm {
43+ #[serde(default)]
44+ csrf: String,
45+ #[serde(default)]
46+ source: String,
47+ #[serde(default)]
48+ remote: String,
49+ #[serde(default)]
50+ instance: String,
51+ #[serde(default)]
52+ token: String,
53+ #[serde(default)]
54+ git_user: String,
55+ #[serde(default)]
56+ owner: String,
57+ #[serde(default)]
58+ name: String,
59+ #[serde(default)]
60+ description: String,
61+ #[serde(default)]
62+ visibility: String,
63+ #[serde(default)]
64+ opt_labels: String,
65+ #[serde(default)]
66+ opt_issues: String,
67+ #[serde(default)]
68+ opt_pulls: String,
69+ #[serde(default)]
70+ opt_releases: String,
71+}
72+
73+#[derive(Deserialize, Default)]
74+struct BulkForm {
75+ #[serde(default)]
76+ csrf: String,
77+ #[serde(default)]
78+ stage: String,
79+ #[serde(default)]
80+ source: String,
81+ #[serde(default)]
82+ instance: String,
83+ #[serde(default)]
84+ token: String,
85+ #[serde(default)]
86+ from: String,
87+ #[serde(default)]
88+ owner: String,
89+ #[serde(default)]
90+ visibility: String,
91+ #[serde(default)]
92+ opt_labels: String,
93+ #[serde(default)]
94+ opt_issues: String,
95+ #[serde(default)]
96+ opt_pulls: String,
97+ #[serde(default)]
98+ opt_releases: String,
99+ /// The ticked repositories arrive as `sel_0`, `sel_1`, ... with the repository as the value.
100+ #[serde(flatten)]
101+ extra: HashMap<String, String>,
102+}
103+
104+#[query_params(error = bad_request)]
105+struct SourceQuery {
106+ source: Option<String>,
107+ error: Option<String>,
108+}
109+
110+#[query_params(error = bad_request)]
111+struct SeenQuery {
112+ v: Option<String>,
113+}
114+
115+fn options_of(labels: &str, issues: &str, pulls: &str, releases: &str) -> ImportOptions {
116+ ImportOptions {
117+ labels: !labels.is_empty(),
118+ issues: !issues.is_empty(),
119+ pulls: !pulls.is_empty(),
120+ releases: !releases.is_empty(),
121+ }
122+}
123+
124+fn source_of(raw: Option<&str>) -> Source {
125+ raw.and_then(Source::parse).unwrap_or(Source::GitHub)
126+}
127+
128+fn token_of(raw: &str) -> Option<String> {
129+ let t = raw.trim();
130+ (!t.is_empty()).then(|| t.to_owned())
131+}
132+
133+// ---- shared pieces ----
134+
135+#[component]
136+pub(crate) async fn newrepo_tabs(lang: Lang, active: &str) -> Result<impl View> {
137+ let create = active == "create";
138+ let import = active == "import";
139+ Ok(view! {
140+ <nav class="import-tabs" aria-label=(g::t(lang, K::ImportTitle))>
141+ <a href="/new" class="import-tab" aria-current=(create.then_some("page"))>(g::t(lang, K::TabCreate))</a>
142+ <a href="/new/import" class="import-tab" aria-current=(import.then_some("page"))>(g::t(lang, K::TabImport))</a>
143+ <a href="/import" class="import-tab import-tab-end">(g::t(lang, K::JobsLink))</a>
144+ </nav>
145+ })
146+}
147+
148+#[component]
149+async fn source_tabs(lang: Lang, base: &str, active: Source) -> Result<impl View> {
150+ let git = format!("{base}?source=git");
151+ let github = format!("{base}?source=github");
152+ let gitlab = format!("{base}?source=gitlab");
153+ Ok(view! {
154+ <nav class="import-sources" aria-label=(g::t(lang, K::TabImport))>
155+ <a href=(git.as_str()) class="import-source" aria-current=((active == Source::Git).then_some("page"))>(g::t(lang, K::SrcGit))</a>
156+ <a href=(github.as_str()) class="import-source" aria-current=((active == Source::GitHub).then_some("page"))>(g::t(lang, K::SrcGitHub))</a>
157+ <a href=(gitlab.as_str()) class="import-source" aria-current=((active == Source::GitLab).then_some("page"))>(g::t(lang, K::SrcGitLab))</a>
158+ </nav>
159+ })
160+}
161+
162+#[component]
163+async fn visibility_pick(lang: Lang, private: bool) -> Result<impl View> {
164+ Ok(view! {
165+ <fieldset class="newrepo-visibility">
166+ <legend class="sr-only">(i18n::t(lang, Key::NewRepository))</legend>
167+ <div class="segmented snippet-segmented">
168+ <label class="segment">
169+ <input type="radio" name="visibility" value="private" checked=(private)>
170+ <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
171+ <span>(crate::i18n::community::t(lang, crate::i18n::community::K::VisibilityPrivate))</span>
172+ </label>
173+ <label class="segment">
174+ <input type="radio" name="visibility" value="public" checked=(!private)>
175+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>
176+ <span>(crate::i18n::community::t(lang, crate::i18n::community::K::VisibilityPublic))</span>
177+ </label>
178+ </div>
179+ </fieldset>
180+ })
181+}
182+
183+#[component]
184+async fn option_boxes(lang: Lang, opts: ImportOptions) -> Result<impl View> {
185+ Ok(view! {
186+ <fieldset class="import-opts">
187+ <legend>(g::t(lang, K::WhatToImport))</legend>
188+ <label class="inline"><input type="checkbox" name="opt_labels" value="on" checked=(opts.labels)><span>(g::t(lang, K::OptLabels))</span></label>
189+ <label class="inline"><input type="checkbox" name="opt_issues" value="on" checked=(opts.issues)><span>(g::t(lang, K::OptIssues))</span></label>
190+ <label class="inline"><input type="checkbox" name="opt_pulls" value="on" checked=(opts.pulls)><span>(g::t(lang, K::OptPulls))</span></label>
191+ <label class="inline"><input type="checkbox" name="opt_releases" value="on" checked=(opts.releases)><span>(g::t(lang, K::OptReleases))</span></label>
192+ <p class="muted small">(g::t(lang, K::OptionsNote))</p>
193+ </fieldset>
194+ })
195+}
196+
197+// ---- single import ----
198+
199+struct Draft {
200+ source: Source,
201+ remote: String,
202+ instance: String,
203+ git_user: String,
204+ owner: String,
205+ name: String,
206+ description: String,
207+ private: bool,
208+ opts: ImportOptions,
209+}
210+
211+impl Draft {
212+ fn fresh(source: Source) -> Self {
213+ Draft {
214+ source,
215+ remote: String::new(),
216+ instance: "https://gitlab.com".into(),
217+ git_user: String::new(),
218+ owner: String::new(),
219+ name: String::new(),
220+ description: String::new(),
221+ private: true,
222+ opts: ImportOptions {
223+ labels: true,
224+ issues: true,
225+ pulls: true,
226+ releases: true,
227+ },
228+ }
229+ }
230+
231+ /// The submitted values, never the token.
232+ fn from_form(form: &ImportForm, source: Source) -> Self {
233+ Draft {
234+ source,
235+ remote: form.remote.trim().to_owned(),
236+ instance: form.instance.trim().to_owned(),
237+ git_user: form.git_user.trim().to_owned(),
238+ owner: form.owner.trim().to_owned(),
239+ name: form.name.trim().to_owned(),
240+ description: form.description.clone(),
241+ private: form.visibility != "public",
242+ opts: options_of(
243+ &form.opt_labels,
244+ &form.opt_issues,
245+ &form.opt_pulls,
246+ &form.opt_releases,
247+ ),
248+ }
249+ }
250+}
251+
252+#[component]
253+async fn import_form(
254+ lang: Lang,
255+ csrf: &str,
256+ draft: Draft,
257+ error: Option<String>,
258+ owners: Vec<String>,
259+) -> Result<impl View> {
260+ let source = draft.source;
261+ let selected_owner = if draft.owner.is_empty() {
262+ owners.first().cloned().unwrap_or_default()
263+ } else {
264+ draft.owner.clone()
265+ };
266+ let source_value = source.as_str();
267+ let is_git = source == Source::Git;
268+ let is_gitlab = source == Source::GitLab;
269+ let bulk_href = if is_git {
270+ String::new()
271+ } else {
272+ format!("/new/import/bulk?source={source_value}")
273+ };
274+ let remote_label = match source {
275+ Source::Git => g::t(lang, K::GitUrl),
276+ Source::GitHub => g::t(lang, K::GitHubRepo),
277+ Source::GitLab => g::t(lang, K::GitLabProject),
278+ };
279+ let remote_placeholder = match source {
280+ Source::Git => "https://example.org/tahinli/project.git",
281+ Source::GitHub => "tahinli/project",
282+ Source::GitLab => "tahinli/project",
283+ };
284+ let token_label = if is_git {
285+ g::t(lang, K::GitPassword)
286+ } else {
287+ g::t(lang, K::TokenOptional)
288+ };
289+ let private = draft.private;
290+ let opts = draft.opts;
291+ Ok(view! {
292+ newrepo_tabs(lang: lang, active: "import")
293+ if let Some(message) = error {
294+ alert(message: message.as_str())
295+ }
296+ <form method="post" action="/new/import" class="newrepo-form">
297+ csrf_field(token: csrf)
298+ <input type="hidden" name="source" value=(source_value)>
299+ <header class="newrepo-head">
300+ <h1>(g::t(lang, K::ImportTitle))</h1>
301+ <div class="newrepo-head-actions">
302+ visibility_pick(lang: lang, private: private)
303+ <button type="submit" class="primary">(g::t(lang, K::StartImport))</button>
304+ </div>
305+ </header>
306+ source_tabs(lang: lang, base: "/new/import", active: source)
307+ <p class="muted small">(g::t(lang, K::ImportIntro))</p>
308+ <div class="newrepo-card">
309+ if is_gitlab {
310+ <label>
311+ <span>(g::t(lang, K::GitLabInstance))</span>
312+ <input type="url" name="instance" value=(draft.instance.as_str()) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono">
313+ </label>
314+ }
315+ <label>
316+ <span>(remote_label)</span>
317+ <input type="text" name="remote" value=(draft.remote.as_str()) placeholder=(remote_placeholder) required=(true) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono">
318+ </label>
319+ <div class="newrepo-row">
320+ if is_git {
321+ <label class="newrepo-half">
322+ <span>(g::t(lang, K::GitUser))</span>
323+ <input type="text" name="git_user" value=(draft.git_user.as_str()) autocomplete="off" maxlength="255">
324+ </label>
325+ }
326+ <label class="newrepo-half">
327+ <span>(token_label)</span>
328+ <input type="password" name="token" autocomplete="new-password" maxlength="1024">
329+ </label>
330+ </div>
331+ <p class="muted small">(g::t(lang, K::TokenHelp))</p>
332+ if !is_git {
333+ option_boxes(lang: lang, opts: opts)
334+ }
335+ </div>
336+ <div class="newrepo-card">
337+ <div class="newrepo-row newrepo-slug">
338+ <label class="newrepo-owner">
339+ <span>(g::t(lang, K::TargetOwner))</span>
340+ <select name="owner">
341+ for name in owners.iter() {
342+ <option value=(name.as_str()) selected=(*name == selected_owner)>(name.as_str())</option>
343+ }
344+ </select>
345+ </label>
346+ <span class="newrepo-slash" aria-hidden="true">("/")</span>
347+ <label class="newrepo-name">
348+ <span>(g::t(lang, K::TargetName))</span>
349+ <input type="text" name="name" value=(draft.name.as_str()) maxlength="64" autocomplete="off" class="newrepo-mono">
350+ </label>
351+ </div>
352+ <p class="muted small">(g::t(lang, K::TargetNameHelp))</p>
353+ <label>
354+ <span>(g::t(lang, K::Description))</span>
355+ <textarea name="description" rows="2" maxlength="350">(draft.description.as_str())</textarea>
356+ </label>
357+ </div>
358+ if !is_git {
359+ <p class="small"><a href=(bulk_href.as_str())>(g::t(lang, K::BulkLink))</a></p>
360+ }
361+ </form>
362+ })
363+}
364+
365+#[page("/new/import")]
366+async fn import_page(cx: &Cx) -> Result<impl View> {
367+ let viewer = require_user(cx).await?;
368+ let lang = i18n::lang(cx, Some(&viewer.0));
369+ let query = query_params::<SourceQuery>(cx)?;
370+ let source = source_of(query.source.as_deref());
371+ let owners = owner_choices(app_context::<AppState>(cx), &viewer.0).await?;
372+ let csrf = viewer.1.csrf_token.clone();
373+ Ok(view! { cx =>
374+ shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer),
375+ import_form(lang: lang, csrf: csrf.as_str(), draft: Draft::fresh(source), error: None, owners: owners))
376+ })
377+}
378+
379+#[page(POST "/new/import")]
380+async fn import_submit(cx: &Cx, Form(form): Form<ImportForm>) -> Result<impl View> {
381+ let viewer = require_csrf(cx, &form.csrf).await?;
382+ let lang = i18n::lang(cx, Some(&viewer.0));
383+ let source = source_of(Some(&form.source));
384+ match start_single(cx, &viewer.0, lang, source, &form).await? {
385+ Ok(job_id) => Err(see_other(format!("/import/{job_id}")).into()),
386+ Err(message) => {
387+ let owners = owner_choices(app_context::<AppState>(cx), &viewer.0).await?;
388+ let csrf = viewer.1.csrf_token.clone();
389+ let draft = Draft::from_form(&form, source);
390+ Ok(view! { cx =>
391+ shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer),
392+ import_form(lang: lang, csrf: csrf.as_str(), draft: draft, error: Some(message), owners: owners))
393+ })
394+ }
395+ }
396+}
397+
398+/// Validates the form, creates the repo and the job, and starts it. `Ok(Err(message))` is a
399+/// rejection to show; the token is never part of what is returned.
400+async fn start_single(
401+ cx: &Cx,
402+ viewer: &User,
403+ lang: Lang,
404+ source: Source,
405+ form: &ImportForm,
406+) -> Result<std::result::Result<String, String>> {
407+ let state = app_context::<AppState>(cx);
408+ let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else {
409+ let message = if source == Source::GitLab && form.remote.trim().starts_with("http") {
410+ g::t(lang, K::ErrBadInstance)
411+ } else {
412+ g::t(lang, K::ErrBadRemote)
413+ };
414+ return Ok(Err(message.to_owned()));
415+ };
416+ if source == Source::Git
417+ && crate::webhooks::client::validate_url(&remote, &crate::mirrors::policy(state)).is_err()
418+ {
419+ return Ok(Err(g::t(lang, K::ErrBadRemote).to_owned()));
420+ }
421+ let target = match repo_owner(state, viewer, lang, &form.owner).await? {
422+ Ok(target) => target,
423+ Err(message) => return Ok(Err(message)),
424+ };
425+ let name = match form.name.trim() {
426+ "" => default_name(&remote),
427+ given => given.to_owned(),
428+ };
429+ let spec = JobSpec {
430+ source,
431+ remote: remote.clone(),
432+ instance: instance.clone(),
433+ token: token_of(&form.token),
434+ git_user: form.git_user.trim().to_owned(),
435+ options: if source == Source::Git {
436+ ImportOptions::default()
437+ } else {
438+ options_of(
439+ &form.opt_labels,
440+ &form.opt_issues,
441+ &form.opt_pulls,
442+ &form.opt_releases,
443+ )
444+ },
445+ };
446+ let visibility = if form.visibility == "public" {
447+ Visibility::Public
448+ } else {
449+ Visibility::Private
450+ };
451+ begin(
452+ cx,
453+ viewer,
454+ &target,
455+ &name,
456+ form.description.trim(),
457+ visibility,
458+ spec,
459+ )
460+ .await
461+}
462+
463+/// Creates the repo and the import job for `spec` and starts it. `Ok(Err(message))` is a rejection.
464+async fn begin(
465+ cx: &Cx,
466+ actor: &User,
467+ target: &User,
468+ name: &str,
469+ description: &str,
470+ visibility: Visibility,
471+ spec: JobSpec,
472+) -> Result<std::result::Result<String, String>> {
473+ let state = app_context::<AppState>(cx);
474+ let lang = i18n::lang(cx, Some(actor));
475+ let name = match forge_core::names::validate_name(name) {
476+ Ok(name) => name,
477+ Err(e) => {
478+ return Ok(Err(user_facing_message(&e).unwrap_or_else(|| {
479+ crate::i18n::misc::t(lang, crate::i18n::misc::K::InvalidRepoName).to_owned()
480+ })));
481+ }
482+ };
483+ if description.chars().count() > 350 {
484+ return Ok(Err(crate::i18n::misc::description_too_long(lang, 350)));
485+ }
486+ let repo = match state
487+ .store
488+ .create_repo(&target.id, &name, description, visibility, DEFAULT_BRANCH)
489+ .await
490+ {
491+ Ok(repo) => repo,
492+ Err(e) => match user_facing_message(&e) {
493+ Some(message) => return Ok(Err(message)),
494+ None => return Err(e.into()),
495+ },
496+ };
497+ let path = repo_path(&state.config.data_dir, &repo.id)?;
498+ if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await {
499+ return Ok(Err(crate::i18n::misc::git_init_failed(lang, e)));
500+ }
501+ let job = state
502+ .store
503+ .create_import_job(
504+ &actor.id,
505+ &repo.id,
506+ spec.source.as_str(),
507+ &source_ref(spec.source, &spec.remote, &spec.instance),
508+ &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()),
509+ )
510+ .await?;
511+ let full_name = format!("{}/{}", repo.owner_name, repo.name);
512+ audit::record(
513+ &state.store,
514+ Some(cx),
515+ Actor::User(actor),
516+ AuditAction::RepoCreated,
517+ Target {
518+ kind: "repo",
519+ id: &repo.id,
520+ name: &full_name,
521+ },
522+ serde_json::json!({ "import": spec.source.as_str() }),
523+ )
524+ .await;
525+ importer::spawn_job(state.clone(), job.clone(), spec);
526+ Ok(Ok(job.id))
527+}
528+
529+// ---- bulk import ----
530+
531+#[component]
532+async fn bulk_form(
533+ lang: Lang,
534+ csrf: &str,
535+ source: Source,
536+ instance: &str,
537+ owners: Vec<String>,
538+ error: Option<String>,
539+) -> Result<impl View> {
540+ let is_gitlab = source == Source::GitLab;
541+ let source_value = source.as_str();
542+ let owner_label = if is_gitlab {
543+ g::t(lang, K::BulkOwnerGitLab)
544+ } else {
545+ g::t(lang, K::BulkOwnerGitHub)
546+ };
547+ Ok(view! {
548+ newrepo_tabs(lang: lang, active: "import")
549+ if let Some(message) = error {
550+ alert(message: message.as_str())
551+ }
552+ <form method="post" action="/new/import/bulk" class="newrepo-form">
553+ csrf_field(token: csrf)
554+ <input type="hidden" name="source" value=(source_value)>
555+ <input type="hidden" name="stage" value="list">
556+ <header class="newrepo-head">
557+ <h1>(g::t(lang, K::BulkTitle))</h1>
558+ <div class="newrepo-head-actions">
559+ <button type="submit" class="primary">(g::t(lang, K::BulkListButton))</button>
560+ </div>
561+ </header>
562+ source_tabs(lang: lang, base: "/new/import/bulk", active: source)
563+ <p class="muted small">(g::t(lang, K::BulkIntro))</p>
564+ <div class="newrepo-card">
565+ if is_gitlab {
566+ <label>
567+ <span>(g::t(lang, K::GitLabInstance))</span>
568+ <input type="url" name="instance" value=(instance) autocomplete="off" spellcheck="false" maxlength="2048" class="newrepo-mono">
569+ </label>
570+ }
571+ <label>
572+ <span>(owner_label)</span>
573+ <input type="text" name="from" required=(true) autocomplete="off" spellcheck="false" maxlength="100" class="newrepo-mono">
574+ </label>
575+ <label>
576+ <span>(g::t(lang, K::TokenOptional))</span>
577+ <input type="password" name="token" autocomplete="new-password" maxlength="1024">
578+ </label>
579+ <p class="muted small">(g::t(lang, K::TokenHelp))</p>
580+ </div>
581+ <input type="hidden" name="owner" value=(owners.first().map(String::as_str).unwrap_or(""))>
582+ </form>
583+ })
584+}
585+
586+struct Listed {
587+ name: String,
588+ full_name: String,
589+ description: String,
590+ private: bool,
591+ fork: bool,
592+ archived: bool,
593+}
594+
595+#[component]
596+async fn bulk_select(
597+ lang: Lang,
598+ csrf: &str,
599+ form: BulkFormEcho,
600+ repos: Vec<Listed>,
601+ owners: Vec<String>,
602+) -> Result<impl View> {
603+ let count = repos.len();
604+ let empty = repos.is_empty();
605+ let private = form.private;
606+ let opts = form.opts;
607+ let selected_owner = if form.owner.is_empty() {
608+ owners.first().cloned().unwrap_or_default()
609+ } else {
610+ form.owner.clone()
611+ };
612+ Ok(view! {
613+ newrepo_tabs(lang: lang, active: "import")
614+ <form method="post" action="/new/import/bulk" class="newrepo-form">
615+ csrf_field(token: csrf)
616+ <input type="hidden" name="stage" value="run">
617+ <input type="hidden" name="source" value=(form.source.as_str())>
618+ <input type="hidden" name="instance" value=(form.instance.as_str())>
619+ <input type="hidden" name="token" value=(form.token.as_str())>
620+ <input type="hidden" name="from" value=(form.from.as_str())>
621+ <header class="newrepo-head">
622+ <h1>(g::t(lang, K::BulkSelectHeading))</h1>
623+ <div class="newrepo-head-actions">
624+ visibility_pick(lang: lang, private: private)
625+ if !empty {
626+ <button type="submit" class="primary">(g::t(lang, K::BulkImportSelected))</button>
627+ }
628+ </div>
629+ </header>
630+ if empty {
631+ <p class="muted">(g::t(lang, K::BulkNone))</p>
632+ } else {
633+ <div class="newrepo-card import-pick">
634+ <label class="inline import-pick-all">
635+ <input type="checkbox" data-select-all=".import-pick-list">
636+ <span>(g::t(lang, K::BulkSelectAll))</span>
637+ <span class="muted small">(count)</span>
638+ </label>
639+ <ul class="import-pick-list item-list">
640+ for (i, repo) in repos.iter().enumerate() {
641+ <li class="import-pick-row">
642+ <label class="inline">
643+ <input type="checkbox" name=(format!("sel_{i}")) value=(repo.full_name.as_str())>
644+ <span class="import-pick-name">(repo.name.as_str())</span>
645+ if repo.private {
646+ <span class="badge private">(g::t(lang, K::BulkPrivate))</span>
647+ }
648+ if repo.fork {
649+ <span class="badge">(g::t(lang, K::BulkFork))</span>
650+ }
651+ if repo.archived {
652+ <span class="badge">(g::t(lang, K::BulkArchived))</span>
653+ }
654+ </label>
655+ if !repo.description.is_empty() {
656+ <span class="muted small import-pick-desc">(repo.description.as_str())</span>
657+ }
658+ </li>
659+ }
660+ </ul>
661+ </div>
662+ <div class="newrepo-card">
663+ <label class="newrepo-owner">
664+ <span>(g::t(lang, K::TargetOwner))</span>
665+ <select name="owner">
666+ for name in owners.iter() {
667+ <option value=(name.as_str()) selected=(*name == selected_owner)>(name.as_str())</option>
668+ }
669+ </select>
670+ </label>
671+ if form.source != "git" {
672+ option_boxes(lang: lang, opts: opts)
673+ }
674+ </div>
675+ }
676+ </form>
677+ })
678+}
679+
680+/// The bulk form's values carried to the selection step (the token is in a hidden field, sent back
681+/// once; the server never stores it).
682+struct BulkFormEcho {
683+ source: String,
684+ instance: String,
685+ token: String,
686+ from: String,
687+ owner: String,
688+ private: bool,
689+ opts: ImportOptions,
690+}
691+
692+#[page("/new/import/bulk")]
693+async fn bulk_page(cx: &Cx) -> Result<impl View> {
694+ let viewer = require_user(cx).await?;
695+ let lang = i18n::lang(cx, Some(&viewer.0));
696+ let query = query_params::<SourceQuery>(cx)?;
697+ let source = match source_of(query.source.as_deref()) {
698+ Source::Git => Source::GitHub,
699+ other => other,
700+ };
701+ let owners = owner_choices(app_context::<AppState>(cx), &viewer.0).await?;
702+ let csrf = viewer.1.csrf_token.clone();
703+ Ok(view! { cx =>
704+ shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer),
705+ bulk_form(lang: lang, csrf: csrf.as_str(), source: source, instance: "https://gitlab.com", owners: owners, error: query.error.clone().filter(|e| e.len() < 300)))
706+ })
707+}
708+
709+fn notice_for(state: &AppState) -> importer::api::Notice {
710+ let _ = state;
711+ std::sync::Arc::new(|_msg: String| {})
712+}
713+
714+/// Lists the repos of `from` through the API. The error text is safe to show.
715+async fn list_remote(
716+ state: &AppState,
717+ source: Source,
718+ instance: &str,
719+ from: &str,
720+ token: Option<String>,
721+) -> std::result::Result<Vec<importer::api::ExtRepo>, String> {
722+ let notice = notice_for(state);
723+ let listed = match source {
724+ Source::GitLab => {
725+ make_gitlab(state, instance, token, notice)?
726+ .list_repos(from)
727+ .await
728+ }
729+ _ => make_github(state, token, notice)?.list_repos(from).await,
730+ };
731+ listed.map_err(|e: ApiError| e.to_string())
732+}
733+
734+#[page(POST "/new/import/bulk")]
735+async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
736+ let viewer = require_csrf(cx, &form.csrf).await?;
737+ let lang = i18n::lang(cx, Some(&viewer.0));
738+ let state = app_context::<AppState>(cx);
739+ let source = match source_of(Some(&form.source)) {
740+ Source::Git => Source::GitHub,
741+ other => other,
742+ };
743+ let owners = owner_choices(state, &viewer.0).await?;
744+ let csrf = viewer.1.csrf_token.clone();
745+ let instance = if source == Source::GitLab && !form.instance.trim().is_empty() {
746+ form.instance.trim().to_owned()
747+ } else {
748+ "https://gitlab.com".to_owned()
749+ };
750+
751+ if form.stage == "run" {
752+ let Err(redirect) = run_bulk(cx, &viewer.0, lang, source, &instance, &form).await;
753+ return Err(redirect);
754+ }
755+
756+ let from = form.from.trim();
757+ let bad_owner =
758+ !crate::importer::api::valid_path(from, 1, if source == Source::GitLab { 20 } else { 1 });
759+ let result = if bad_owner {
760+ Err(g::t(lang, K::ErrBadOwner).to_owned())
761+ } else {
762+ list_remote(state, source, &instance, from, token_of(&form.token)).await
763+ };
764+ let (error, picker) = match result {
765+ Err(message) => (Some(message), None),
766+ Ok(found) => {
767+ let repos: Vec<Listed> = found
768+ .into_iter()
769+ .map(|r| Listed {
770+ name: r.name,
771+ full_name: r.full_name,
772+ description: r.description,
773+ private: r.private,
774+ fork: r.fork,
775+ archived: r.archived,
776+ })
777+ .collect();
778+ let echo = BulkFormEcho {
779+ source: source.as_str().to_owned(),
780+ instance: instance.clone(),
781+ token: form.token.trim().to_owned(),
782+ from: from.to_owned(),
783+ owner: form.owner.trim().to_owned(),
784+ private: true,
785+ opts: ImportOptions {
786+ labels: true,
787+ issues: true,
788+ pulls: true,
789+ releases: true,
790+ },
791+ };
792+ (None, Some((echo, repos)))
793+ }
794+ };
795+ Ok(view! { cx =>
796+ shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer),
797+ bulk_stage(lang: lang, csrf: csrf.as_str(), source: source, instance: instance.as_str(), owners: owners, error: error, picker: picker))
798+ })
799+}
800+
801+/// The bulk page body: the picker once a listing exists, the lookup form otherwise.
802+#[component]
803+async fn bulk_stage(
804+ lang: Lang,
805+ csrf: &str,
806+ source: Source,
807+ instance: &str,
808+ owners: Vec<String>,
809+ error: Option<String>,
810+ picker: Option<(BulkFormEcho, Vec<Listed>)>,
811+) -> Result<impl View> {
812+ Ok(view! {
813+ if let Some((echo, repos)) = picker {
814+ bulk_select(lang: lang, csrf: csrf, form: echo, repos: repos, owners: owners)
815+ } else {
816+ bulk_form(lang: lang, csrf: csrf, source: source, instance: instance, owners: owners, error: error)
817+ }
818+ })
819+}
820+
821+/// Starts one job per ticked repository, then shows the imports list.
822+async fn run_bulk(
823+ cx: &Cx,
824+ viewer: &User,
825+ lang: Lang,
826+ source: Source,
827+ instance: &str,
828+ form: &BulkForm,
829+) -> Result<std::convert::Infallible> {
830+ let state = app_context::<AppState>(cx);
831+ let mut picked: Vec<(usize, &String)> = form
832+ .extra
833+ .iter()
834+ .filter_map(|(k, v)| Some((k.strip_prefix("sel_")?.parse::<usize>().ok()?, v)))
835+ .collect();
836+ picked.sort_by_key(|(i, _)| *i);
837+ let fail = |message: &str| -> Result<std::convert::Infallible> {
838+ Err(see_other(format!(
839+ "/new/import/bulk?source={}&error={}",
840+ source.as_str(),
841+ crate::views::enc(message)
842+ ))
843+ .into())
844+ };
845+ if picked.is_empty() {
846+ return fail(g::t(lang, K::ErrNothingSelected));
847+ }
848+ if picked.len() > MAX_BULK {
849+ return fail(g::t(lang, K::ErrTooMany));
850+ }
851+ let target = match repo_owner(state, viewer, lang, &form.owner).await? {
852+ Ok(target) => target,
853+ Err(message) => return fail(&message),
854+ };
855+ let options = options_of(
856+ &form.opt_labels,
857+ &form.opt_issues,
858+ &form.opt_pulls,
859+ &form.opt_releases,
860+ );
861+ let visibility = if form.visibility == "public" {
862+ Visibility::Public
863+ } else {
864+ Visibility::Private
865+ };
866+ for (_, full_name) in picked {
867+ let Some((remote, inst)) = parse_remote(source, full_name, instance) else {
868+ continue;
869+ };
870+ let spec = JobSpec {
871+ source,
872+ remote: remote.clone(),
873+ instance: inst,
874+ token: token_of(&form.token),
875+ git_user: String::new(),
876+ options,
877+ };
878+ let name = default_name(&remote);
879+ // A name already taken, or any refusal, is skipped here; the list page shows the rest.
880+ if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? {
881+ tracing::info!(repo = %remote, %message, "bulk import: skipped a repository");
882+ }
883+ }
884+ Err(see_other("/import").into())
885+}
886+
887+// ---- jobs ----
888+
889+fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) {
890+ match state {
891+ ImportState::Queued => ("badge", g::t(lang, K::JobQueued)),
892+ ImportState::Running => ("badge import-running", g::t(lang, K::JobRunning)),
893+ ImportState::Done => ("badge public", g::t(lang, K::JobDone)),
894+ ImportState::Failed => ("badge import-failed", g::t(lang, K::JobFailed)),
895+ }
896+}
897+
898+fn stage_name(lang: Lang, stage: &str) -> &'static str {
899+ match stage {
900+ "git" => g::t(lang, K::StageGit),
901+ "labels" => g::t(lang, K::StageLabels),
902+ "milestones" => g::t(lang, K::StageMilestones),
903+ "issues" => g::t(lang, K::StageIssues),
904+ "releases" => g::t(lang, K::StageReleases),
905+ "done" => g::t(lang, K::StageDone),
906+ _ => "",
907+ }
908+}
909+
910+fn ago(lang: Lang, stamp: &str) -> String {
911+ stamp_to_unix(stamp).map_or_else(String::new, |t| relative_time(lang, t, now_unix()))
912+}
913+
914+#[component]
915+async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<impl View> {
916+ let empty = jobs.is_empty();
917+ Ok(view! {
918+ newrepo_tabs(lang: lang, active: "jobs")
919+ <section class="page-head">
920+ <h1>(g::t(lang, K::JobsTitle))</h1>
921+ </section>
922+ if empty {
923+ <p class="muted">(g::t(lang, K::NoJobs))</p>
924+ } else {
925+ <section class="card">
926+ <ul class="item-list import-jobs">
927+ for (job, repo) in jobs.iter() {
928+ <li class="item import-job-row">
929+ <div class="item-main">
930+ <a href=(format!("/import/{}", job.id)) class="import-job-name">(job.source_ref.as_str())</a>
931+ <span class="muted small">(g::t(lang, K::JobStarted)) " " (ago(lang, &job.created_at))</span>
932+ </div>
933+ if let Some(repo) = repo {
934+ <a href=(format!("/{}/{}", repo.owner_name, repo.name)) class="muted small mono">(format!("{}/{}", repo.owner_name, repo.name))</a>
935+ }
936+ <span class=(state_badge(lang, job.state).0)>(state_badge(lang, job.state).1)</span>
937+ </li>
938+ }
939+ </ul>
940+ </section>
941+ }
942+ })
943+}
944+
945+#[page("/import")]
946+async fn jobs_page(cx: &Cx) -> Result<impl View> {
947+ let viewer = require_user(cx).await?;
948+ let lang = i18n::lang(cx, Some(&viewer.0));
949+ let state = app_context::<AppState>(cx);
950+ let jobs = state.store.list_import_jobs(&viewer.0.id, 50).await?;
951+ let mut rows = Vec::with_capacity(jobs.len());
952+ for job in jobs {
953+ let repo = match &job.repo_id {
954+ Some(id) => state.store.repo_by_id(id).await?,
955+ None => None,
956+ };
957+ rows.push((job, repo));
958+ }
959+ Ok(view! { cx =>
960+ shell(title: g::t(lang, K::JobsTitle), viewer: Some(&viewer), jobs_list(lang: lang, jobs: rows))
961+ })
962+}
963+
964+#[component]
965+async fn job_view(
966+ lang: Lang,
967+ csrf: &str,
968+ job: ImportJob,
969+ repo: Option<Repo>,
970+ log: Vec<forge_core::store::imports::ImportEvent>,
971+) -> Result<impl View> {
972+ let (badge_class, badge_text) = state_badge(lang, job.state);
973+ let live = (!job.state.is_finished()).then(|| {
974+ format!(
975+ "/import/{}/events?v={}",
976+ job.id,
977+ crate::views::enc(&job.updated_at)
978+ )
979+ });
980+ let stage = stage_name(lang, &job.stage);
981+ let has_progress = job.total > 0 && !job.state.is_finished();
982+ let progress_text = g::progress_of(job.done, job.total);
983+ let failed = job.state == ImportState::Failed;
984+ let done = job.state == ImportState::Done;
985+ let repo_href = repo
986+ .as_ref()
987+ .map(|r| format!("/{}/{}", r.owner_name, r.name));
988+ let retry_action = format!("/import/{}/retry", job.id);
989+ let error = job.error.clone();
990+ let state_word = job.state.as_str();
991+ let empty_log = log.is_empty();
992+ Ok(view! {
993+ newrepo_tabs(lang: lang, active: "jobs")
994+ <section class="import-job" data-live=(live.as_deref()) data-live-state=(state_word)>
995+ <header class="newrepo-head">
996+ <h1 class="import-job-title">(job.source_ref.as_str())</h1>
997+ <span class=(badge_class)>(badge_text)</span>
998+ <div class="newrepo-head-actions">
999+ if let Some(href) = repo_href.as_ref() {
1000+ if done {
1001+ <a href=(href.as_str()) class="button primary">(g::t(lang, K::JobOpenRepo))</a>
1002+ }
1003+ }
1004+ </div>
1005+ </header>
1006+ <div class="newrepo-card">
1007+ if !stage.is_empty() {
1008+ <div class="import-stage">
1009+ <strong>(stage)</strong>
1010+ if has_progress {
1011+ <span class="muted small">(progress_text.as_str())</span>
1012+ }
1013+ </div>
1014+ }
1015+ if has_progress {
1016+ <progress class="import-progress" value=(job.done) max=(job.total)></progress>
1017+ } else if !job.state.is_finished() {
1018+ <progress class="import-progress"></progress>
1019+ }
1020+ if let Some(message) = error {
1021+ alert(message: message.as_str())
1022+ }
1023+ if failed {
1024+ <form method="post" action=(retry_action.as_str()) class="import-retry">
1025+ csrf_field(token: csrf)
1026+ <label>
1027+ <span>(g::t(lang, K::TokenOptional))</span>
1028+ <input type="password" name="token" autocomplete="new-password" maxlength="1024">
1029+ </label>
1030+ <p class="muted small">(g::t(lang, K::JobRetryHelp))</p>
1031+ <button type="submit" class="primary">(g::t(lang, K::JobRetry))</button>
1032+ </form>
1033+ }
1034+ </div>
1035+ <div class="newrepo-card">
1036+ <h2 class="import-log-title">(g::t(lang, K::JobProgress))</h2>
1037+ if empty_log {
1038+ <p class="muted small">(g::t(lang, K::JobNoLog))</p>
1039+ } else {
1040+ <ol class="import-log">
1041+ for line in log.iter() {
1042+ <li class=(format!("import-log-line import-log-{}", line.level))>(line.message.as_str())</li>
1043+ }
1044+ </ol>
1045+ }
1046+ </div>
1047+ </section>
1048+ })
1049+}
1050+
1051+/// The job when the viewer owns it. Anyone else gets 404.
1052+async fn owned_job(cx: &Cx, viewer: &User) -> Result<ImportJob> {
1053+ let id = path_param::<JobId>(cx).to_owned();
1054+ let state = app_context::<AppState>(cx);
1055+ match state.store.import_job(&id).await? {
1056+ Some(job) if job.user_id == viewer.id => Ok(job),
1057+ _ => Err(not_found().into()),
1058+ }
1059+}
1060+
1061+#[page("/import/{job_id}")]
1062+async fn job_page(cx: &Cx) -> Result<impl View> {
1063+ let viewer = require_user(cx).await?;
1064+ let lang = i18n::lang(cx, Some(&viewer.0));
1065+ let state = app_context::<AppState>(cx);
1066+ let job = owned_job(cx, &viewer.0).await?;
1067+ let repo = match &job.repo_id {
1068+ Some(id) => state.store.repo_by_id(id).await?,
1069+ None => None,
1070+ };
1071+ let log = state.store.list_import_events(&job.id, 200).await?;
1072+ let csrf = viewer.1.csrf_token.clone();
1073+ let title = job.source_ref.clone();
1074+ Ok(view! { cx =>
1075+ shell(title: title.as_str(), viewer: Some(&viewer),
1076+ job_view(lang: lang, csrf: csrf.as_str(), job: job, repo: repo, log: log))
1077+ })
1078+}
1079+
1080+/// The job's `changed` stream. It sends when the job differs from the version the page was
1081+/// rendered with, then on every change, and ends once the job is finished.
1082+#[route(GET "/import/{job_id}/events")]
1083+async fn job_events(cx: &Cx) -> Result<Response> {
1084+ let viewer = require_user(cx).await?;
1085+ let job = owned_job(cx, &viewer.0).await?;
1086+ let query = query_params::<SeenQuery>(cx)?;
1087+ let state = app_context::<AppState>(cx);
1088+ let seen = query.v.clone().unwrap_or_default();
1089+ // Subscribed before the job is read again below, so a change in between is not lost.
1090+ let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id));
1091+ let store = state.store.clone();
1092+ let id = job.id.clone();
1093+ let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| {
1094+ let store = store.clone();
1095+ let id = id.clone();
1096+ async move {
1097+ if ended {
1098+ return None;
1099+ }
1100+ loop {
1101+ let job = store.import_job(&id).await.ok().flatten()?;
1102+ if job.updated_at != seen {
1103+ seen = job.updated_at.clone();
1104+ let finished = job.state.is_finished();
1105+ return Some((
1106+ changed_event(job.state.as_str().to_owned()),
1107+ (wake, seen, finished),
1108+ ));
1109+ }
1110+ if job.state.is_finished() {
1111+ return None;
1112+ }
1113+ let rx = wake.as_mut()?;
1114+ rx.changed().await.ok()?;
1115+ }
1116+ }
1117+ });
1118+ events_response(cx, events)
1119+}
1120+
1121+#[derive(Deserialize)]
1122+struct RetryForm {
1123+ #[serde(default)]
1124+ csrf: String,
1125+ #[serde(default)]
1126+ token: String,
1127+}
1128+
1129+#[route(POST "/import/{job_id}/retry")]
1130+async fn job_retry(cx: &Cx, Form(form): Form<RetryForm>) -> Result<SeeOther> {
1131+ let viewer = require_csrf(cx, &form.csrf).await?;
1132+ let state = app_context::<AppState>(cx);
1133+ let job = owned_job(cx, &viewer.0).await?;
1134+ let href = format!("/import/{}", job.id);
1135+ if job.state != ImportState::Failed {
1136+ return Err(see_other(href).into());
1137+ }
1138+ let Some(source) = Source::parse(&job.source) else {
1139+ return Err(see_other(href).into());
1140+ };
1141+ let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else {
1142+ return Err(see_other(href).into());
1143+ };
1144+ if let Some(repo_id) = &job.repo_id
1145+ && state.store.active_import_for_repo(repo_id).await?.is_some()
1146+ {
1147+ return Err(see_other(href).into());
1148+ }
1149+ let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default();
1150+ state
1151+ .store
1152+ .set_import_state(&job.id, ImportState::Queued, None)
1153+ .await?;
1154+ state
1155+ .store
1156+ .add_import_event(
1157+ &job.id,
1158+ "info",
1159+ "Retrying; what was imported before is skipped",
1160+ )
1161+ .await?;
1162+ let spec = JobSpec {
1163+ source,
1164+ remote,
1165+ instance,
1166+ token: token_of(&form.token),
1167+ git_user: String::new(),
1168+ options,
1169+ };
1170+ importer::spawn_job(state.clone(), job, spec);
1171+ Err(see_other(href).into())
1172+}
crates/forge-web/src/pages/import_tests.rsadded+171 -0
@@ -0,0 +1,171 @@
1+//! Route-level tests for the import pages and the data export page: they render, they need a
2+//! session, and one user cannot see another user's job or archive.
3+
4+use forge_core::Store;
5+use topcoat::router::request::Request;
6+use topcoat::router::{Body, Router, to_bytes};
7+
8+use crate::auth::SESSION_COOKIE;
9+use crate::test_support::{app_router, create_session, test_state};
10+
11+const TOKEN: &str = "import-session";
12+const CSRF: &str = "import-csrf";
13+const OTHER: &str = "other-session";
14+
15+struct Fixture {
16+ _dir: tempfile::TempDir,
17+ router: Router,
18+ store: Store,
19+ user_id: String,
20+}
21+
22+async fn fixture() -> Fixture {
23+ let dir = tempfile::tempdir().expect("tempdir");
24+ let data_dir = dir.path().join("data");
25+ std::fs::create_dir_all(&data_dir).expect("data dir");
26+ let state = test_state(&data_dir).await;
27+ let owner = state
28+ .store
29+ .create_user("tahinli", None, "h", false)
30+ .await
31+ .expect("user");
32+ let other = state
33+ .store
34+ .create_user("nina", None, "h", false)
35+ .await
36+ .expect("user");
37+ create_session(&state.store, &owner.id, TOKEN, CSRF).await;
38+ create_session(&state.store, &other.id, OTHER, "other-csrf").await;
39+ Fixture {
40+ _dir: dir,
41+ router: app_router(state.clone()),
42+ store: state.store.clone(),
43+ user_id: owner.id,
44+ }
45+}
46+
47+async fn send(
48+ router: &Router,
49+ method: &str,
50+ uri: &str,
51+ token: Option<&str>,
52+ form: Option<String>,
53+) -> (u16, String) {
54+ let mut builder = Request::builder().method(method).uri(uri);
55+ if let Some(token) = token {
56+ builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
57+ }
58+ let body = match form {
59+ Some(form) => {
60+ builder = builder.header("content-type", "application/x-www-form-urlencoded");
61+ Body::from(form)
62+ }
63+ None => Body::empty(),
64+ };
65+ let res = router.handle(builder.body(body).expect("request")).await;
66+ let status = res.status().as_u16();
67+ let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
68+ (status, String::from_utf8_lossy(&bytes).into_owned())
69+}
70+
71+#[tokio::test]
72+async fn the_import_pages_render_for_a_signed_in_user() {
73+ let fx = fixture().await;
74+ for (uri, needle) in [
75+ ("/new/import?source=git", "Import a repository"),
76+ ("/new/import?source=github", "Import a repository"),
77+ ("/new/import?source=gitlab", "Import a repository"),
78+ (
79+ "/new/import/bulk?source=github",
80+ "Import several repositories",
81+ ),
82+ ("/import", "Imports"),
83+ ("/settings/export", "Export your data"),
84+ ] {
85+ let (status, body) = send(&fx.router, "GET", uri, Some(TOKEN), None).await;
86+ assert_eq!(status, 200, "{uri}: {body}");
87+ assert!(body.contains(needle), "{uri} lacks {needle}");
88+ }
89+}
90+
91+#[tokio::test]
92+async fn the_import_and_export_pages_need_a_session() {
93+ let fx = fixture().await;
94+ for uri in [
95+ "/new/import",
96+ "/new/import/bulk",
97+ "/import",
98+ "/settings/export",
99+ ] {
100+ let (status, body) = send(&fx.router, "GET", uri, None, None).await;
101+ assert_ne!(status, 200, "{uri}: {body}");
102+ }
103+}
104+
105+#[tokio::test]
106+async fn a_post_without_the_csrf_token_starts_nothing() {
107+ let fx = fixture().await;
108+ let form = "source=git&remote=https%3A%2F%2Fexample.org%2Fa.git&csrf=wrong".to_owned();
109+ let (status, _) = send(&fx.router, "POST", "/new/import", Some(TOKEN), Some(form)).await;
110+ assert_ne!(status, 303, "a bad token must not redirect to a job");
111+ assert!(
112+ fx.store
113+ .list_import_jobs(&fx.user_id, 10)
114+ .await
115+ .expect("jobs")
116+ .is_empty()
117+ );
118+ let (status, _) = send(
119+ &fx.router,
120+ "POST",
121+ "/settings/export",
122+ Some(TOKEN),
123+ Some("csrf=wrong".into()),
124+ )
125+ .await;
126+ assert_ne!(status, 303);
127+ assert!(
128+ fx.store
129+ .list_exports(&fx.user_id)
130+ .await
131+ .expect("exports")
132+ .is_empty()
133+ );
134+}
135+
136+#[tokio::test]
137+async fn a_private_address_is_refused_before_any_job_exists() {
138+ let fx = fixture().await;
139+ let form = format!(
140+ "csrf={CSRF}&source=git&remote=https%3A%2F%2F127.0.0.1%2Fa.git&owner=tahinli&visibility=private"
141+ );
142+ let (status, body) = send(&fx.router, "POST", "/new/import", Some(TOKEN), Some(form)).await;
143+ assert_ne!(status, 500, "{body}");
144+ assert!(
145+ fx.store
146+ .list_import_jobs(&fx.user_id, 10)
147+ .await
148+ .expect("jobs")
149+ .is_empty(),
150+ "no job for a refused address"
151+ );
152+}
153+
154+#[tokio::test]
155+async fn another_users_archive_cannot_be_downloaded() {
156+ let fx = fixture().await;
157+ let export = fx
158+ .store
159+ .create_export(&fx.user_id, std::time::Duration::from_secs(3600))
160+ .await
161+ .expect("export");
162+ fx.store
163+ .mark_export_ready(&export.id, 10, std::time::Duration::from_secs(3600))
164+ .await
165+ .expect("ready");
166+ let uri = format!("/settings/export/{}/download", export.id);
167+ let (status, _) = send(&fx.router, "GET", &uri, Some(OTHER), None).await;
168+ assert_eq!(status, 404, "a stranger gets not found");
169+ let (status, _) = send(&fx.router, "GET", &uri, None, None).await;
170+ assert_ne!(status, 200);
171+}
crates/forge-web/src/pages/mod.rsmodified+4 -0
@@ -34,6 +34,9 @@ pub mod explore;
34 pub mod finder;34 pub mod finder;
35 pub mod forgot;35 pub mod forgot;
36 pub mod fork;36 pub mod fork;
37+pub mod import;
38+#[cfg(test)]
39+mod import_tests;
37 pub mod invites;40 pub mod invites;
38 pub mod issue_meta;41 pub mod issue_meta;
39 #[cfg(test)]42 #[cfg(test)]
@@ -87,6 +90,7 @@ pub mod repo_webhooks;
87 #[cfg(test)]90 #[cfg(test)]
88 mod security_tab_tests;91 mod security_tab_tests;
89 pub mod settings_appearance;92 pub mod settings_appearance;
93+pub mod settings_export;
90 pub mod settings_gpg;94 pub mod settings_gpg;
91 #[cfg(test)]95 #[cfg(test)]
92 mod settings_gpg_tests;96 mod settings_gpg_tests;
crates/forge-web/src/pages/new_repo.rsmodified+3 -2
@@ -126,6 +126,7 @@ async fn new_repo_form(
126 let draft_mirror_username = draft.mirror_username;126 let draft_mirror_username = draft.mirror_username;
127 let draft_mirror_interval = draft.mirror_interval;127 let draft_mirror_interval = draft.mirror_interval;
128 Ok(view! {128 Ok(view! {
129+ crate::pages::import::newrepo_tabs(lang: lang, active: "create")
129 if let Some(message) = error {130 if let Some(message) = error {
130 alert(message: message.as_str())131 alert(message: message.as_str())
131 }132 }
@@ -216,7 +217,7 @@ async fn new_repo_form(
216 217
217 /// The accounts the viewer may create a repo under: themselves, then the orgs where218 /// The accounts the viewer may create a repo under: themselves, then the orgs where
218 /// `may_create_repo_in` allows it.219 /// `may_create_repo_in` allows it.
219-async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> {220+pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> {
220 let mut names = vec![viewer.username.clone()];221 let mut names = vec![viewer.username.clone()];
221 for (org, _) in state.store.orgs_for_user(&viewer.id).await? {222 for (org, _) in state.store.orgs_for_user(&viewer.id).await? {
222 if may_create_repo_in(state, &org.id, &viewer.id).await? {223 if may_create_repo_in(state, &org.id, &viewer.id).await? {
@@ -257,7 +258,7 @@ async fn new_repo_submit(cx: &Cx, Form(form): Form<NewRepoForm>) -> Result<impl
257 258
258 /// The account the new repo belongs to. Blank or the viewer's own name means the viewer. An org259 /// The account the new repo belongs to. Blank or the viewer's own name means the viewer. An org
259 /// name is accepted only when the viewer may create repos under it.260 /// name is accepted only when the viewer may create repos under it.
260-async fn repo_owner(261+pub(crate) async fn repo_owner(
261 state: &AppState,262 state: &AppState,
262 viewer: &User,263 viewer: &User,
263 lang: Lang,264 lang: Lang,
crates/forge-web/src/pages/settings_export.rsadded+215 -0
@@ -0,0 +1,215 @@
1+//! Page: data export (`/settings/export`). Request an archive of your repos, issues, releases and
2+//! profile, watch it build, and download it until it expires. The page follows an event stream
3+//! while an export is building, so it turns ready with no reload and no polling.
4+
5+use forge_core::store::exports::{DataExport, ExportState};
6+use forge_core::time::stamp_to_unix;
7+use futures_util::{TryStreamExt, stream};
8+use http::header::{
9+ CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue,
10+ X_CONTENT_TYPE_OPTIONS,
11+};
12+use http_body::Frame;
13+use http_body_util::StreamBody;
14+use serde::Deserialize;
15+use tokio_util::io::ReaderStream;
16+use topcoat::Result;
17+use topcoat::context::{Cx, app_context};
18+use topcoat::router::content::Form;
19+use topcoat::router::error::{SeeOther, not_found, see_other};
20+use topcoat::router::response::Response;
21+use topcoat::router::{Body, page, path_param, query_params, route};
22+use topcoat::view::{View, component, view};
23+
24+use crate::auth::{require_csrf, require_user};
25+use crate::exporter;
26+use crate::i18n::migrate::{self as g, K};
27+use crate::i18n::{self, Lang};
28+use crate::pages::ci_runs::{changed_event, events_response};
29+use crate::state::AppState;
30+use crate::views::{alert, csrf_field, human_size, now_unix, relative_time, shell};
31+
32+path_param!(export_id);
33+
34+#[derive(Deserialize)]
35+struct CsrfForm {
36+ #[serde(default)]
37+ csrf: String,
38+}
39+
40+#[query_params(error = bad_request)]
41+struct SeenQuery {
42+ v: Option<String>,
43+}
44+
45+/// One word per export and its state, so the stream can tell the page is out of date.
46+fn signature(exports: &[DataExport]) -> String {
47+ exports
48+ .iter()
49+ .map(|e| format!("{}:{}", e.id, e.state.as_str()))
50+ .collect::<Vec<_>>()
51+ .join(",")
52+}
53+
54+fn ago(lang: Lang, stamp: &str) -> String {
55+ stamp_to_unix(stamp).map_or_else(String::new, |t| relative_time(lang, t, now_unix()))
56+}
57+
58+fn day(stamp: &str) -> String {
59+ stamp.chars().take(10).collect()
60+}
61+
62+#[component]
63+async fn export_view(lang: Lang, csrf: &str, exports: Vec<DataExport>) -> Result<impl View> {
64+ let building = exports.iter().any(|e| e.state == ExportState::Building);
65+ let live = building.then(|| {
66+ format!(
67+ "/settings/export/events?v={}",
68+ crate::views::enc(&signature(&exports))
69+ )
70+ });
71+ let empty = exports.is_empty();
72+ let ttl_note = g::export_ttl_note(lang, exporter::EXPORT_TTL_DAYS);
73+ Ok(view! {
74+ <section class="page-head">
75+ <h1>(g::t(lang, K::ExportTitle))</h1>
76+ </section>
77+ <div class="export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>
78+ <section class="card export-intro">
79+ <p>(g::t(lang, K::ExportIntro))</p>
80+ <p class="muted small">(g::t(lang, K::ExportContents))</p>
81+ <p class="muted small">(g::t(lang, K::ExportEmailNote)) " " (ttl_note.as_str())</p>
82+ <form method="post" action="/settings/export" class="inline-form">
83+ csrf_field(token: csrf)
84+ <button type="submit" class="primary" disabled=(building)>(g::t(lang, K::ExportRequest))</button>
85+ </form>
86+ </section>
87+ <section class="card">
88+ if empty {
89+ <p class="muted">(g::t(lang, K::ExportNone))</p>
90+ } else {
91+ <ul class="item-list export-list">
92+ for export in exports.iter() {
93+ <li class="item export-row">
94+ <div class="item-main">
95+ <strong>(g::t(lang, K::ExportRequested)) " " (ago(lang, &export.created_at))</strong>
96+ if export.state == ExportState::Ready {
97+ <span class="muted small">
98+ (g::t(lang, K::ExportSize)) ": " (human_size(lang, u64::try_from(export.size).unwrap_or(0)))
99+ " · " (g::expires_on(lang, &day(&export.expires_at)))
100+ </span>
101+ }
102+ </div>
103+ if export.state == ExportState::Ready {
104+ <span class="badge public">(g::t(lang, K::ExportReady))</span>
105+ <a class="button primary" href=(format!("/settings/export/{}/download", export.id))>(g::t(lang, K::ExportDownload))</a>
106+ }
107+ if export.state == ExportState::Building {
108+ <span class="badge import-running">(g::t(lang, K::ExportBuilding))</span>
109+ <progress class="import-progress export-progress"></progress>
110+ }
111+ if export.state == ExportState::Failed {
112+ <span class="badge import-failed">(g::t(lang, K::ExportFailed))</span>
113+ }
114+ </li>
115+ if let Some(message) = export.error.as_ref() {
116+ <li class="export-error">alert(message: message.as_str())</li>
117+ }
118+ }
119+ </ul>
120+ }
121+ </section>
122+ </div>
123+ })
124+}
125+
126+#[page("/settings/export")]
127+async fn export_page(cx: &Cx) -> Result<impl View> {
128+ let viewer = require_user(cx).await?;
129+ let lang = i18n::lang(cx, Some(&viewer.0));
130+ let state = app_context::<AppState>(cx);
131+ exporter::sweep_expired(state).await;
132+ let exports = state.store.list_exports(&viewer.0.id).await?;
133+ let csrf = viewer.1.csrf_token.clone();
134+ Ok(view! { cx =>
135+ shell(title: g::t(lang, K::SettingsExport), viewer: Some(&viewer),
136+ export_view(lang: lang, csrf: csrf.as_str(), exports: exports))
137+ })
138+}
139+
140+#[route(POST "/settings/export")]
141+async fn export_request(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
142+ let viewer = require_csrf(cx, &form.csrf).await?;
143+ let state = app_context::<AppState>(cx);
144+ exporter::start(state, &viewer.0).await?;
145+ Err(see_other("/settings/export").into())
146+}
147+
148+/// The `changed` stream of the export page. It sends when the exports differ from what the page
149+/// shows, then on each change, and ends once nothing is building.
150+#[route(GET "/settings/export/events")]
151+async fn export_events(cx: &Cx) -> Result<Response> {
152+ let viewer = require_user(cx).await?;
153+ let query = query_params::<SeenQuery>(cx)?;
154+ let state = app_context::<AppState>(cx);
155+ let user_id = viewer.0.id.clone();
156+ let wake = exporter::subscribe(&user_id);
157+ let store = state.store.clone();
158+ let seen = query.v.clone().unwrap_or_default();
159+ let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| {
160+ let store = store.clone();
161+ let user_id = user_id.clone();
162+ async move {
163+ if ended {
164+ return None;
165+ }
166+ loop {
167+ let exports = store.list_exports(&user_id).await.ok()?;
168+ let sig = signature(&exports);
169+ let building = exports.iter().any(|e| e.state == ExportState::Building);
170+ if sig != seen {
171+ seen = sig;
172+ return Some((changed_event("export".to_owned()), (wake, seen, !building)));
173+ }
174+ if !building {
175+ return None;
176+ }
177+ wake.changed().await.ok()?;
178+ }
179+ }
180+ });
181+ events_response(cx, events)
182+}
183+
184+/// Sends the archive. Only its owner, only while it is ready and unexpired.
185+#[route(GET "/settings/export/{export_id}/download")]
186+async fn export_download(cx: &Cx) -> Result<Response> {
187+ let viewer = require_user(cx).await?;
188+ let id = path_param::<ExportId>(cx).to_owned();
189+ let state = app_context::<AppState>(cx);
190+ exporter::sweep_expired(state).await;
191+ let export = match state.store.data_export(&id).await? {
192+ Some(e) if e.user_id == viewer.0.id && e.state == ExportState::Ready => e,
193+ _ => return Err(not_found().into()),
194+ };
195+ let file = match tokio::fs::File::open(exporter::archive_path(state, &export.id)).await {
196+ Ok(file) => file,
197+ Err(_) => return Err(not_found().into()),
198+ };
199+ let len = file.metadata().await?.len();
200+ let chunks = ReaderStream::new(file).map_ok(Frame::data);
201+ let mut res = Response::new(Body::new(StreamBody::new(chunks)));
202+ let headers = res.headers_mut();
203+ headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/gzip"));
204+ headers.insert(
205+ CONTENT_DISPOSITION,
206+ HeaderValue::from_str(&format!(
207+ "attachment; filename=\"forge-export-{}.tar.gz\"",
208+ viewer.0.username
209+ ))?,
210+ );
211+ headers.insert(CONTENT_LENGTH, HeaderValue::from(len));
212+ headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
213+ headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-store"));
214+ Ok(res)
215+}
crates/forge-web/src/views/mod.rsmodified+10 -0
@@ -26,6 +26,7 @@ use topcoat::view::{Child, View, component, view};
26 use crate::i18n::admin::{self as ad, K as AK};26 use crate::i18n::admin::{self as ad, K as AK};
27 use crate::i18n::code::{self as g, K};27 use crate::i18n::code::{self as g, K};
28 use crate::i18n::community::{self as cm, K as CK};28 use crate::i18n::community::{self as cm, K as CK};
29+use crate::i18n::migrate::{self as mg, K as MGK};
29 use crate::i18n::misc::{self as mi, K as MK};30 use crate::i18n::misc::{self as mi, K as MK};
30 use crate::i18n::orgs::{self as o, K as OK};31 use crate::i18n::orgs::{self as o, K as OK};
31 use crate::i18n::{self, Key, Lang, t};32 use crate::i18n::{self, Key, Lang, t};
@@ -563,6 +564,12 @@ fn settings_items(lang: Lang) -> Vec<NavItem> {
563 o::t(lang, OK::CustomizePins),564 o::t(lang, OK::CustomizePins),
564 "pins",565 "pins",
565 ),566 ),
567+ item(
568+ "export",
569+ "/settings/export",
570+ mg::t(lang, MGK::SettingsExport),
571+ "export",
572+ ),
566 ]573 ]
567 }574 }
568 575
@@ -701,6 +708,9 @@ async fn nav_icon(name: &str) -> Result<impl View> {
701 if name == "appearance" {708 if name == "appearance" {
702 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>709 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>
703 }710 }
711+ if name == "export" {
712+ <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12"/><path d="m7 10 5 5 5-5"/><path d="M5 21h14"/></svg>
713+ }
704 if name == "pins" {714 if name == "pins" {
705 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 17v5"/><path d="M9 3h6l-1 6 3 3v2H7v-2l3-3z"/></svg>715 <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 17v5"/><path d="M9 3h6l-1 6 3 3v2H7v-2l3-3z"/></svg>
706 }716 }
crates/forge-web/src/webhooks/client.rsmodified+19 -0
@@ -252,6 +252,25 @@ async fn resolve_allowed(policy: Arc<WebhookPolicy>, host: String) -> Result<Add
252 Ok(addrs)252 Ok(addrs)
253 }253 }
254 254
255+/// A reqwest client under the same outbound policy as webhooks: internal addresses are dropped at
256+/// resolve time, redirects are never followed and no proxy is used. For API imports.
257+pub fn policy_client(
258+ policy: WebhookPolicy,
259+ timeout: Duration,
260+ user_agent: &'static str,
261+) -> reqwest::Result<reqwest::Client> {
262+ reqwest::Client::builder()
263+ .redirect(reqwest::redirect::Policy::none())
264+ .connect_timeout(Duration::from_secs(10))
265+ .timeout(timeout)
266+ .dns_resolver(Arc::new(PolicyResolver {
267+ policy: Arc::new(policy),
268+ }))
269+ .user_agent(user_agent)
270+ .no_proxy()
271+ .build()
272+}
273+
255 /// What happened when a delivery was sent. A failure leaves `status` as `None` and sets `error`.274 /// What happened when a delivery was sent. A failure leaves `status` as `None` and sets `error`.
256 #[derive(Debug, Clone, PartialEq, Eq)]275 #[derive(Debug, Clone, PartialEq, Eq)]
257 pub struct SendOutcome {276 pub struct SendOutcome {
style/_import.scssadded+286 -0
@@ -0,0 +1,286 @@
1+// Import and export (pages/import.rs, pages/settings_export.rs). Tokens only, so both themes follow
2+// main.scss. The forms reuse the .newrepo-* cards.
3+
4+.import-tabs {
5+ display: flex;
6+ flex-wrap: wrap;
7+ align-items: center;
8+ gap: 4px;
9+ max-width: 960px;
10+ margin: 0 0 16px;
11+ border-bottom: 1px solid var(--border);
12+}
13+
14+.import-tab {
15+ margin-bottom: -1px;
16+ padding: 8px 14px;
17+ border-bottom: 2px solid transparent;
18+ font-size: 0.875rem;
19+ font-weight: 500;
20+ color: var(--muted);
21+ text-decoration: none;
22+
23+ &:hover {
24+ color: var(--text);
25+ }
26+
27+ &[aria-current="page"] {
28+ color: var(--accent-ink);
29+ border-bottom-color: var(--accent);
30+ }
31+
32+ &.import-tab-end {
33+ margin-left: auto;
34+ }
35+}
36+
37+.import-sources {
38+ display: inline-flex;
39+ align-items: center;
40+ align-self: flex-start;
41+ gap: 2px;
42+ max-width: 100%;
43+ padding: 2px;
44+ border: 1px solid var(--border);
45+ border-radius: var(--radius-full);
46+ background: var(--surface-2);
47+}
48+
49+.import-source {
50+ display: inline-flex;
51+ align-items: center;
52+ height: 26px;
53+ padding: 0 14px;
54+ border-radius: var(--radius-full);
55+ font-size: 0.8125rem;
56+ font-weight: 500;
57+ color: var(--muted);
58+ text-decoration: none;
59+ white-space: nowrap;
60+
61+ &:hover {
62+ color: var(--text);
63+ }
64+
65+ &[aria-current="page"] {
66+ background: var(--surface);
67+ color: var(--accent-ink);
68+ box-shadow: 0 1px 2px rgba(30, 36, 32, .12);
69+ }
70+}
71+
72+.import-opts {
73+ display: flex;
74+ flex-direction: column;
75+ gap: 8px;
76+ min-width: 0;
77+ margin: 0;
78+ padding: 0;
79+ border: 0;
80+
81+ legend {
82+ padding: 0;
83+ margin-bottom: 6px;
84+ font-size: 0.875rem;
85+ font-weight: 500;
86+ color: var(--text-2);
87+ }
88+
89+ p {
90+ margin: 4px 0 0;
91+ }
92+}
93+
94+.import-pick {
95+ gap: 0;
96+ padding: 0;
97+}
98+
99+.import-pick-all {
100+ margin: 0;
101+ padding: 12px 22px;
102+ border-bottom: 1px solid var(--border);
103+}
104+
105+.import-pick-list {
106+ max-height: 52vh;
107+ overflow-y: auto;
108+}
109+
110+.import-pick-row {
111+ display: flex;
112+ flex-wrap: wrap;
113+ align-items: baseline;
114+ gap: 2px 12px;
115+ padding: 9px 22px;
116+ border-bottom: 1px solid var(--border);
117+
118+ &:last-child {
119+ border-bottom: 0;
120+ }
121+
122+ .inline {
123+ margin: 0;
124+ }
125+}
126+
127+.import-pick-name {
128+ font-family: var(--mono);
129+ font-size: 0.875rem;
130+}
131+
132+.import-pick-desc {
133+ min-width: 0;
134+ overflow: hidden;
135+ text-overflow: ellipsis;
136+ white-space: nowrap;
137+ max-width: 100%;
138+}
139+
140+.import-job {
141+ display: flex;
142+ flex-direction: column;
143+ gap: 16px;
144+ max-width: 960px;
145+ min-width: 0;
146+}
147+
148+.import-job-title {
149+ margin: 0;
150+ min-width: 0;
151+ font-size: 1.25rem;
152+ font-family: var(--mono);
153+ overflow-wrap: anywhere;
154+}
155+
156+.import-job-name {
157+ font-family: var(--mono);
158+ font-size: 0.875rem;
159+ overflow-wrap: anywhere;
160+}
161+
162+.import-job-row {
163+ display: flex;
164+ flex-wrap: wrap;
165+ align-items: center;
166+ gap: 8px 14px;
167+
168+ .item-main {
169+ flex: 1 1 260px;
170+ min-width: 0;
171+ }
172+}
173+
174+.import-stage {
175+ display: flex;
176+ align-items: baseline;
177+ gap: 10px;
178+}
179+
180+.import-progress {
181+ width: 100%;
182+ height: 8px;
183+ border-radius: var(--radius-full);
184+ overflow: hidden;
185+}
186+
187+.badge.import-running {
188+ background: var(--accent-soft, var(--surface-2));
189+ color: var(--accent-ink);
190+}
191+
192+.badge.import-failed {
193+ background: var(--danger-bg);
194+ color: var(--alert-text);
195+}
196+
197+.import-retry {
198+ display: flex;
199+ flex-direction: column;
200+ gap: 10px;
201+ max-width: 420px;
202+
203+ p {
204+ margin: 0;
205+ }
206+}
207+
208+.import-log-title {
209+ margin: 0;
210+ font-size: 0.9375rem;
211+}
212+
213+.import-log {
214+ display: flex;
215+ flex-direction: column;
216+ gap: 2px;
217+ max-height: 46vh;
218+ margin: 0;
219+ padding: 0;
220+ overflow-y: auto;
221+ list-style: none;
222+ font-family: var(--mono);
223+ font-size: 0.8125rem;
224+}
225+
226+.import-log-line {
227+ overflow-wrap: anywhere;
228+ color: var(--text-2);
229+
230+ &.import-log-warn {
231+ color: var(--warn);
232+ }
233+
234+ &.import-log-error {
235+ color: var(--danger);
236+ }
237+}
238+
239+.export-page {
240+ display: flex;
241+ flex-direction: column;
242+ gap: 16px;
243+ max-width: 960px;
244+}
245+
246+.export-intro {
247+ display: flex;
248+ flex-direction: column;
249+ gap: 8px;
250+
251+ p {
252+ margin: 0;
253+ }
254+}
255+
256+.export-row {
257+ display: flex;
258+ flex-wrap: wrap;
259+ align-items: center;
260+ gap: 8px 14px;
261+
262+ .item-main {
263+ flex: 1 1 240px;
264+ min-width: 0;
265+ }
266+}
267+
268+.export-progress {
269+ width: 120px;
270+}
271+
272+.export-error {
273+ list-style: none;
274+
275+ .alert {
276+ margin: 0;
277+ }
278+}
279+
280+@media (max-width: 560px) {
281+ .import-pick-row,
282+ .import-pick-all {
283+ padding-left: 14px;
284+ padding-right: 14px;
285+ }
286+}
style/main.scssmodified+1 -0
@@ -5573,6 +5573,7 @@ button.ci-job-last {
5573 @import "dashboard";5573 @import "dashboard";
5574 @import "wiki";5574 @import "wiki";
5575 @import "browse";5575 @import "browse";
5576+@import "import";
5576 5577
5577 // Code inside cards, notices and settings panels must stay inside the card. Long tokens and5578 // Code inside cards, notices and settings panels must stay inside the card. Long tokens and
5578 // commands wrap instead of running past the right edge. The rendered README card (.readme) and5579 // commands wrap instead of running past the right edge. The rendered README card (.readme) and