forge
Explore
Log in

Don't you dare go Hollow

Page crates (forge-web-pages, forge-web-account, forge-web-repo, forge-web) drop duplicated helpers, string states and stale comments

Browse files at this commit

76d78e3e084fd68b2d5d5d3d0fea2758f74e0ec0Ahmet Kaan GümüşParent: 2e748ef
  • refactor
    • page crates (forge-web-pages, forge-web-account, forge-web-repo, forge-web) drop duplicated helpers, string states and stale comments
    • fixes: out-of-range explore and profile pages clamp before slicing, admin restart redirects to the right category, SSH key titles are length-checked on the server, password rules match on every page, and other verified page fixes
Show full message
♻️ refactor: page crates (forge-web-pages, forge-web-account, forge-web-repo, forge-web) drop duplicated helpers, string states and stale comments; fixes: out-of-range explore and profile pages clamp before slicing, admin restart redirects to the right category, SSH key titles are length-checked on the server, password rules match on every page, and other verified page fixes

100 changed files +2486 -4255

crates/forge-core/src/store/admin_alerts.rsmodified+11 -0
@@ -253,6 +253,17 @@ impl Store {
253 fetch_all(&conn, &sql, params, map_notice).await253 fetch_all(&conn, &sql, params, map_notice).await
254 }254 }
255 255
256+ pub async fn admin_notice(&self, user_id: &str, id: &str) -> Result<Option<AdminNotice>> {
257+ let conn = self.read_conn().await;
258+ fetch_opt(
259+ &conn,
260+ &format!("SELECT {NOTICE_COLS} FROM admin_notifications WHERE id = ?1 AND user_id = ?2"),
261+ (id.to_owned(), user_id.to_owned()),
262+ map_notice,
263+ )
264+ .await
265+ }
266+
256 /// Marks one of the user's alert rows read. Another user's row changes nothing.267 /// Marks one of the user's alert rows read. Another user's row changes nothing.
257 pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> {268 pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> {
258 let conn = self.inner.conn.lock().await;269 let conn = self.inner.conn.lock().await;
crates/forge-core/src/store/imports.rsmodified+16 -0
@@ -204,6 +204,22 @@ impl Store {
204 Ok(())204 Ok(())
205 }205 }
206 206
207+ pub async fn requeue_failed_import(&self, id: &str) -> Result<bool> {
208+ let conn = self.inner.conn.lock().await;
209+ let changed = conn
210+ .execute(
211+ "UPDATE import_jobs SET state = 'queued', error = NULL, finished_at = NULL, \
212+ updated_at = ?2 WHERE id = ?1 AND state = 'failed' AND NOT EXISTS (\
213+ SELECT 1 FROM import_jobs other WHERE other.repo_id = \
214+ (SELECT repo_id FROM import_jobs WHERE id = ?1) \
215+ AND other.state IN ('queued', 'running'))",
216+ vec![text(id), text(&now_stamp())],
217+ )
218+ .await
219+ .map_err(db_err)?;
220+ Ok(changed > 0)
221+ }
222+
207 /// Records the current stage and how far it is.223 /// Records the current stage and how far it is.
208 pub async fn set_import_progress(224 pub async fn set_import_progress(
209 &self,225 &self,
crates/forge-core/src/store/mod.rsmodified+57 -0
@@ -837,6 +837,39 @@ impl Store {
837 affected(n)837 affected(n)
838 }838 }
839 839
840+ pub async fn save_profile(
841+ &self,
842+ user_id: &str,
843+ display_name: &str,
844+ about: &str,
845+ timezone: &str,
846+ ) -> Result<()> {
847+ let display_name = match validate_display_name(display_name)? {
848+ Some(name) => Value::Text(name),
849+ None => Value::Null,
850+ };
851+ if about.chars().count() > MAX_ABOUT_CHARS {
852+ return Err(Error::Invalid(format!(
853+ "about is longer than {MAX_ABOUT_CHARS} characters"
854+ )));
855+ }
856+ crate::tz::validate_timezone(timezone)?;
857+ let conn = self.inner.conn.lock().await;
858+ let n = conn
859+ .execute(
860+ "UPDATE users SET display_name = ?2, about = ?3, timezone = ?4 WHERE id = ?1",
861+ vec![
862+ Value::Text(user_id.to_owned()),
863+ display_name,
864+ Value::Text(about.to_owned()),
865+ Value::Text(timezone.to_owned()),
866+ ],
867+ )
868+ .await
869+ .map_err(db_err)?;
870+ affected(n)
871+ }
872+
840 /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest.873 /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest.
841 pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> {874 pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> {
842 let conn = self.inner.conn.lock().await;875 let conn = self.inner.conn.lock().await;
@@ -1583,6 +1616,30 @@ impl Store {
1583 affected(n)1616 affected(n)
1584 }1617 }
1585 1618
1619+ pub async fn reset_password(&self, user_id: &str, password_hash: &str) -> Result<()> {
1620+ let conn = self.inner.conn.lock().await;
1621+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
1622+ let outcome: Result<()> = async {
1623+ let n = tx
1624+ .execute(
1625+ "UPDATE users SET password_hash = ?2, password_changed_at = ?3 WHERE id = ?1",
1626+ (user_id.to_string(), password_hash.to_string(), now_stamp()),
1627+ )
1628+ .await
1629+ .map_err(db_err)?;
1630+ affected(n)?;
1631+ tx.execute(
1632+ "DELETE FROM sessions WHERE user_id = ?1",
1633+ (user_id.to_string(),),
1634+ )
1635+ .await
1636+ .map_err(db_err)?;
1637+ Ok(())
1638+ }
1639+ .await;
1640+ finish(tx, outcome).await
1641+ }
1642+
1586 /// Deletes every session of the user except `keep_session_id`. Returns how many were removed.1643 /// Deletes every session of the user except `keep_session_id`. Returns how many were removed.
1587 pub async fn delete_sessions_except(1644 pub async fn delete_sessions_except(
1588 &self,1645 &self,
crates/forge-core/src/store/webhooks.rsmodified+11 -5
@@ -308,25 +308,28 @@ impl Store {
308 .await308 .await
309 }309 }
310 310
311- /// The repo's hooks, oldest first, each with the state of its most recent delivery311+ /// The repo's hooks, oldest first, each with the state and stamp of its most recent delivery
312 /// (`None` when it has none yet).312 /// (`None` when it has none yet).
313 pub async fn list_webhooks(313 pub async fn list_webhooks(
314 &self,314 &self,
315 repo_id: &str,315 repo_id: &str,
316- ) -> Result<Vec<(Webhook, Option<DeliveryState>)>> {316+ ) -> Result<Vec<(Webhook, Option<(DeliveryState, String)>)>> {
317 let sql = format!(317 let sql = format!(
318 "SELECT {WEBHOOK_COLS}, \318 "SELECT {WEBHOOK_COLS}, \
319 (SELECT d.state FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \319 (SELECT d.state FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \
320+ ORDER BY d.created_at DESC, d.id DESC LIMIT 1), \
321+ (SELECT d.created_at FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \
320 ORDER BY d.created_at DESC, d.id DESC LIMIT 1) \322 ORDER BY d.created_at DESC, d.id DESC LIMIT 1) \
321 FROM webhooks WHERE repo_id = ?1 ORDER BY created_at, id"323 FROM webhooks WHERE repo_id = ?1 ORDER BY created_at, id"
322 );324 );
323 let conn = self.read_conn().await;325 let conn = self.read_conn().await;
324 fetch_all(&conn, &sql, (repo_id.to_string(),), |row| {326 fetch_all(&conn, &sql, (repo_id.to_string(),), |row| {
325 let last = match col_opt_text(row, 7)? {327 let last = match col_opt_text(row, 7)? {
326- Some(s) => Some(328+ Some(s) => Some((
327 DeliveryState::parse(&s)329 DeliveryState::parse(&s)
328 .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?,330 .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?,
329- ),331+ col_text(row, 8)?,
332+ )),
330 None => None,333 None => None,
331 };334 };
332 Ok((map_webhook(row)?, last))335 Ok((map_webhook(row)?, last))
@@ -922,7 +925,10 @@ mod tests {
922 assert_eq!(failed.duration_ms, Some(12));925 assert_eq!(failed.duration_ms, Some(12));
923 assert!(failed.delivered_at.is_none());926 assert!(failed.delivered_at.is_none());
924 assert_eq!(927 assert_eq!(
925- store.list_webhooks(&repo.id).await.unwrap()[0].1,928+ store.list_webhooks(&repo.id).await.unwrap()[0]
929+ .1
930+ .as_ref()
931+ .map(|(state, _)| *state),
926 Some(DeliveryState::Failed)932 Some(DeliveryState::Failed)
927 );933 );
928 934
crates/forge-web-account/Cargo.tomlmodified+0 -3
@@ -12,7 +12,6 @@ forge-web-pages.workspace = true
12 forge-core.workspace = true12 forge-core.workspace = true
13 forge-git.workspace = true13 forge-git.workspace = true
14 forge-ci.workspace = true14 forge-ci.workspace = true
15-forge-web-base.workspace = true
16 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }15 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
17 tokio.workspace = true16 tokio.workspace = true
18 futures-util.workspace = true17 futures-util.workspace = true
@@ -31,8 +30,6 @@ hex.workspace = true
31 sha2.workspace = true30 sha2.workspace = true
32 time.workspace = true31 time.workspace = true
33 ulid.workspace = true32 ulid.workspace = true
34-zip = { workspace = true }
35-tar.workspace = true
36 33
37 34
38 webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] }35 webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] }
crates/forge-web-account/src/pages/activity.rsmodified+2 -2
@@ -41,7 +41,7 @@ fn run_json(run: &ActorRun) -> Value {
41 }41 }
42 42
43 /// How a finished run ended, as the activity JSON names it. None for any other state.43 /// How a finished run ended, as the activity JSON names it. None for any other state.
44-pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> {44+fn outcome_word(state: RunState) -> Option<&'static str> {
45 match state {45 match state {
46 RunState::Success => Some("passed"),46 RunState::Success => Some("passed"),
47 RunState::Failure | RunState::Error => Some("failed"),47 RunState::Failure | RunState::Error => Some("failed"),
@@ -53,7 +53,7 @@ pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> {
53 /// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts53 /// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts
54 /// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting`54 /// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting`
55 /// lists the newest review requests and mentions. Reads only; the caller decides how to send it.55 /// lists the newest review requests and mentions. Reads only; the caller decides how to send it.
56-pub(crate) async fn activity_json(state: &AppState, user: &User) -> Result<Value> {56+async fn activity_json(state: &AppState, user: &User) -> Result<Value> {
57 let kinds = state.store.inbox_kind_counts(&user.id).await?;57 let kinds = state.store.inbox_kind_counts(&user.id).await?;
58 let runs = state.store.actor_runs(&user.id, RECENT_SECS).await?;58 let runs = state.store.actor_runs(&user.id, RECENT_SECS).await?;
59 let waiting = state.store.waiting_on(&user.id, WAITING_LIMIT).await?;59 let waiting = state.store.waiting_on(&user.id, WAITING_LIMIT).await?;
crates/forge-web-account/src/pages/admin_backups.rsmodified+2 -25
@@ -29,10 +29,9 @@ use crate::pages::admin_server::{
29 BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice,29 BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice,
30 };30 };
31 use crate::pages::admin_users::admin_only;31 use crate::pages::admin_users::admin_only;
32-use crate::pages::issues_list::stamp_unix;
33 use crate::state::AppState;32 use crate::state::AppState;
34 use crate::views::parts::{RailItem, head, post_act, rail};33 use crate::views::parts::{RailItem, head, post_act, rail};
35-use crate::views::{alert, enc, rel_time, shell};34+use crate::views::{alert, enc, human_size, rel_time, shell, stamp_unix};
36 35
37 /// Runs shown on the page.36 /// Runs shown on the page.
38 const RUN_LIMIT: u32 = 20;37 const RUN_LIMIT: u32 = 20;
@@ -59,21 +58,6 @@ struct RunRow {
59 detail: String,58 detail: String,
60 }59 }
61 60
62-/// `"512 B"`, `"12.3 KiB"`, `"4.0 MiB"` and so on.
63-fn human_bytes(bytes: u64) -> String {
64- const UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"];
65- if bytes < 1024 {
66- return format!("{bytes} B");
67- }
68- let mut value = bytes as f64 / 1024.0;
69- let mut unit = 0;
70- while value >= 1024.0 && unit + 1 < UNITS.len() {
71- value /= 1024.0;
72- unit += 1;
73- }
74- format!("{value:.1} {}", UNITS[unit])
75-}
76-
77 fn duration_text(run: &BackupRun) -> String {61 fn duration_text(run: &BackupRun) -> String {
78 let start = stamp_unix(&run.started_at);62 let start = stamp_unix(&run.started_at);
79 let Some(end) = run.finished_at.as_deref().map(stamp_unix) else {63 let Some(end) = run.finished_at.as_deref().map(stamp_unix) else {
@@ -101,7 +85,7 @@ fn run_row(run: &BackupRun, lang: Lang) -> RunRow {
101 trigger: g::trigger_name(lang, run.trigger).to_owned(),85 trigger: g::trigger_name(lang, run.trigger).to_owned(),
102 started: run.started_at.clone(),86 started: run.started_at.clone(),
103 duration: duration_text(run),87 duration: duration_text(run),
104- size: run.bytes.map(human_bytes).unwrap_or_default(),88+ size: run.bytes.map(|b| human_size(lang, b)).unwrap_or_default(),
105 status,89 status,
106 detail,90 detail,
107 }91 }
@@ -583,11 +567,4 @@ mod tests {
583 );567 );
584 assert_eq!(fx.state.jobs.running(), None);568 assert_eq!(fx.state.jobs.running(), None);
585 }569 }
586-
587- #[test]
588- fn human_bytes_scales() {
589- assert_eq!(human_bytes(512), "512 B");
590- assert_eq!(human_bytes(2048), "2.0 KiB");
591- assert_eq!(human_bytes(3 * 1024 * 1024), "3.0 MiB");
592- }
593 }570 }
crates/forge-web-account/src/pages/admin_health.rsmodified+53 -52
@@ -1,6 +1,6 @@
1 //! Page: instance health for admins (`/admin/health`). A summary line, then one sheet with the alerts,1 //! Page: instance health for admins (`/admin/health`). A summary line, then one sheet with the alerts,
2 //! a storage topic with the data disk's usage bar, and a services topic. Every number is a cheap query2 //! a storage topic with the data disk's usage bar, and a services topic. Every number is a cheap query
3-//! or a short external probe (`df`), so there is no polling; reloading the page, or opening it again,3+//! or a `statvfs` call, so there is no polling; reloading the page, or opening it again,
4 //! reads fresh values. The tree size of the repos (`du`) walks every repo, so a background task caches4 //! reads fresh values. The tree size of the repos (`du`) walks every repo, so a background task caches
5 //! it (see [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404.5 //! it (see [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404.
6 6
@@ -80,10 +80,12 @@ struct Usage {
80 path: String,80 path: String,
81 /// Percent used, the bar's fill.81 /// Percent used, the bar's fill.
82 pct: u8,82 pct: u8,
83- /// At least 90% used.83+ /// At least [`DISK_BAD_PCT`] used.
84 bad: bool,84 bad: bool,
85 }85 }
86 86
87+const DISK_BAD_PCT: u8 = 90;
88+
87 /// One fact in the storage topic: one row.89 /// One fact in the storage topic: one row.
88 struct Fact {90 struct Fact {
89 label: &'static str,91 label: &'static str,
@@ -102,6 +104,18 @@ struct Service {
102 stamp: Option<String>,104 stamp: Option<String>,
103 }105 }
104 106
107+impl Service {
108+ fn new(label: &'static str, dot: Dot, value: String) -> Self {
109+ Self {
110+ label,
111+ dot,
112+ value,
113+ detail: String::new(),
114+ stamp: None,
115+ }
116+ }
117+}
118+
105 /// Everything the page shows, and how many items need attention.119 /// Everything the page shows, and how many items need attention.
106 struct Health {120 struct Health {
107 usage: Option<Usage>,121 usage: Option<Usage>,
@@ -127,15 +141,6 @@ fn space(lang: Lang, total: u64, avail: u64) -> (u8, String) {
127 (pct, text)141 (pct, text)
128 }142 }
129 143
130-/// `(total, available)` bytes from `df -Pk <path>` output.
131-fn parse_df(output: &str) -> Option<(u64, u64)> {
132- let line = output.lines().nth(1)?;
133- let fields: Vec<&str> = line.split_whitespace().collect();
134- let total: u64 = fields.get(1)?.parse().ok()?;
135- let avail: u64 = fields.get(3)?.parse().ok()?;
136- Some((total.saturating_mul(1024), avail.saturating_mul(1024)))
137-}
138-
139 /// Kilobytes from `du -sk <path>` output, as bytes.144 /// Kilobytes from `du -sk <path>` output, as bytes.
140 fn parse_du(output: &str) -> Option<u64> {145 fn parse_du(output: &str) -> Option<u64> {
141 let kb: u64 = output.split_whitespace().next()?.parse().ok()?;146 let kb: u64 = output.split_whitespace().next()?.parse().ok()?;
@@ -155,7 +160,11 @@ async fn probe(program: &str, args: &[&str], path: &Path, limit: Duration) -> Op
155 }160 }
156 161
157 async fn disk(path: &Path) -> Option<(u64, u64)> {162 async fn disk(path: &Path) -> Option<(u64, u64)> {
158- parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?)163+ let path = path.to_path_buf();
164+ tokio::task::spawn_blocking(move || crate::alerts::disk_space(&path))
165+ .await
166+ .ok()
167+ .flatten()
159 }168 }
160 169
161 async fn tree_size(path: &Path, limit: Duration) -> Option<u64> {170 async fn tree_size(path: &Path, limit: Duration) -> Option<u64> {
@@ -255,7 +264,7 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
255 free_of_total,264 free_of_total,
256 path: data_dir.to_string_lossy().into_owned(),265 path: data_dir.to_string_lossy().into_owned(),
257 pct,266 pct,
258- bad: pct >= 90,267+ bad: pct >= DISK_BAD_PCT,
259 }268 }
260 });269 });
261 270
@@ -286,7 +295,11 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
286 label: at(lang, A::BackupDirectory),295 label: at(lang, A::BackupDirectory),
287 value: text,296 value: text,
288 detail: backup,297 detail: backup,
289- dot: if pct >= 90 { Dot::Bad } else { Dot::Neutral },298+ dot: if pct >= DISK_BAD_PCT {
299+ Dot::Bad
300+ } else {
301+ Dot::Neutral
302+ },
290 }303 }
291 }304 }
292 None => Fact {305 None => Fact {
@@ -347,20 +360,16 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
347 stamp: Some(run.started_at.clone()),360 stamp: Some(run.started_at.clone()),
348 }361 }
349 }362 }
350- None if backup_on => Service {363+ None if backup_on => Service::new(
351- label: at(lang, A::LastBackup),364+ at(lang, A::LastBackup),
352- dot: Dot::Neutral,365+ Dot::Neutral,
353- value: at(lang, A::Never).to_owned(),366+ at(lang, A::Never).to_owned(),
354- detail: String::new(),367+ ),
355- stamp: None,368+ None => Service::new(
356- },369+ at(lang, A::LastBackup),
357- None => Service {370+ Dot::Off,
358- label: at(lang, A::LastBackup),371+ at(lang, A::NotConfigured).to_owned(),
359- dot: Dot::Off,372+ ),
360- value: at(lang, A::NotConfigured).to_owned(),
361- detail: String::new(),
362- stamp: None,
363- },
364 });373 });
365 374
366 let replicating = !live.replication.target.trim().is_empty();375 let replicating = !live.replication.target.trim().is_empty();
@@ -390,22 +399,18 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
390 stamp: status.last_ok_at.clone(),399 stamp: status.last_ok_at.clone(),
391 }400 }
392 }401 }
393- None => Service {402+ None => Service::new(
394- label: at(lang, A::Replication),403+ at(lang, A::Replication),
395- dot: Dot::Neutral,404+ Dot::Neutral,
396- value: at(lang, A::Never).to_owned(),405+ at(lang, A::Never).to_owned(),
397- detail: String::new(),406+ ),
398- stamp: None,
399- },
400 }407 }
401 } else {408 } else {
402- Service {409+ Service::new(
403- label: at(lang, A::Replication),410+ at(lang, A::Replication),
404- dot: Dot::Off,411+ Dot::Off,
405- value: at(lang, A::NotConfigured).to_owned(),412+ at(lang, A::NotConfigured).to_owned(),
406- detail: String::new(),413+ )
407- stamp: None,
408- }
409 });414 });
410 415
411 let uptime = uptime_secs().map_or_else(416 let uptime = uptime_secs().map_or_else(
@@ -488,7 +493,6 @@ async fn health_view(
488 nav: (Vec<PageLink>, Option<String>, Option<String>),493 nav: (Vec<PageLink>, Option<String>, Option<String>),
489 ) -> Result<impl View> {494 ) -> Result<impl View> {
490 // The heading counts every active alert; the sheet lists the current page of them.495 // The heading counts every active alert; the sheet lists the current page of them.
491- let count = total;
492 let (links, prev, next) = nav;496 let (links, prev, next) = nav;
493 let Health {497 let Health {
494 usage,498 usage,
@@ -498,7 +502,7 @@ async fn health_view(
498 attention,502 attention,
499 } = health;503 } = health;
500 // An active alert needs attention as much as a failing service does.504 // An active alert needs attention as much as a failing service does.
501- let attention = attention + count;505+ let attention = attention + total;
502 // The verdict leads the head's line, with its dot, so the page says how things are first.506 // The verdict leads the head's line, with its dot, so the page says how things are first.
503 let summary = if attention > 0 {507 let summary = if attention > 0 {
504 SubPart {508 SubPart {
@@ -517,9 +521,9 @@ async fn health_view(
517 Ok(view! {521 Ok(view! {
518 head(title: at(lang, A::Health), sub: sub, live: Some("/admin/health/events"))522 head(title: at(lang, A::Health), sub: sub, live: Some("/admin/health/events"))
519 <div class="sheet health-sheet">523 <div class="sheet health-sheet">
520- if count > 0 {524+ if total > 0 {
521 <section class="sec" role="alert">525 <section class="sec" role="alert">
522- <h2>(alert_text::banner_heading(lang, count))</h2>526+ <h2>(alert_text::banner_heading(lang, total))</h2>
523 for a in alerts.into_iter() {527 for a in alerts.into_iter() {
524 <div class="line" data-kb-row="">528 <div class="line" data-kb-row="">
525 <span class="name">(a.title.as_str())</span>529 <span class="name">(a.title.as_str())</span>
@@ -612,8 +616,8 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
612 616
613 /// What the health page shows that can change between renders, as one string: the alerts, the617 /// What the health page shows that can change between renders, as one string: the alerts, the
614 /// counts, the mail queue, the disk figures and the uptime, each as the page would display it. The618 /// counts, the mail queue, the disk figures and the uptime, each as the page would display it. The
615-/// disk figures come from `statvfs` (the same numbers `df` prints), not a process. The tree size619+/// disk figures come from `statvfs`. The tree size of the repos is the cached value of the
616-/// of the repos is the cached value of the background walk, as the page displays it.620+/// background walk, as the page displays it.
617 async fn health_fingerprint(state: &AppState) -> Result<String> {621 async fn health_fingerprint(state: &AppState) -> Result<String> {
618 let counts = state.store.health_counts().await?;622 let counts = state.store.health_counts().await?;
619 let mail = state623 let mail = state
@@ -660,10 +664,7 @@ mod tests {
660 use super::*;664 use super::*;
661 665
662 #[test]666 #[test]
663- fn df_and_du_output_parse_to_bytes() {667+ fn du_output_parses_to_bytes() {
664- let df = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/sda1 1000 400 600 40% /\n";
665- assert_eq!(parse_df(df), Some((1000 * 1024, 600 * 1024)), "df");
666- assert_eq!(parse_df("garbage"), None, "df garbage");
667 assert_eq!(parse_du("12\t/data/repos\n"), Some(12 * 1024), "du");668 assert_eq!(parse_du("12\t/data/repos\n"), Some(12 * 1024), "du");
668 assert_eq!(parse_du(""), None, "du empty");669 assert_eq!(parse_du(""), None, "du empty");
669 }670 }
crates/forge-web-account/src/pages/admin_mail.rsmodified+2 -60
@@ -1,12 +1,3 @@
1-//! Page: outgoing mail (`/admin/mail`). Instance admins only; anyone else gets 404.
2-//!
3-//! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank
4-//! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every
5-//! message in the outbox with its state, kind, tries and last error, filtered by state. A failed
6-//! message can be retried or discarded there. Both tabs carry `data-live`, so each queue change or
7-//! saved setting re-renders the tab through `/admin/mail/events` with no reload and no polling.
8-//! Saving the settings and queuing a test are audited.
9-
10 use std::collections::HashMap;1 use std::collections::HashMap;
11 2
12 use forge_core::mail::{3 use forge_core::mail::{
@@ -15,13 +6,10 @@ use forge_core::mail::{
15 use forge_core::server_settings::Group;6 use forge_core::server_settings::Group;
16 use forge_core::time::now_stamp;7 use forge_core::time::now_stamp;
17 use forge_core::{AuditAction, Error};8 use forge_core::{AuditAction, Error};
18-use futures_util::{Stream, stream};
19 use serde::Deserialize;9 use serde::Deserialize;
20-use tokio::sync::watch;
21 use topcoat::Result;10 use topcoat::Result;
22 use topcoat::context::{Cx, context};11 use topcoat::context::{Cx, context};
23 use topcoat::router::content::Form;12 use topcoat::router::content::Form;
24-use topcoat::router::content::sse::Event;
25 use topcoat::router::error::{forbidden, see_other};13 use topcoat::router::error::{forbidden, see_other};
26 use topcoat::router::response::Response;14 use topcoat::router::response::Response;
27 use topcoat::router::{page, query_params, route};15 use topcoat::router::{page, query_params, route};
@@ -31,7 +19,7 @@ use crate::audit::{self, Actor, Target};
31 use crate::auth::check_csrf;19 use crate::auth::check_csrf;
32 use crate::i18n::admin::{self as g, K};20 use crate::i18n::admin::{self as g, K};
33 use crate::i18n::{self, Key, Lang};21 use crate::i18n::{self, Key, Lang};
34-use crate::live::{changed_event, events_response};22+use crate::live::{events_response, wake_stream};
35 use crate::mail::{enqueue, live, templates};23 use crate::mail::{enqueue, live, templates};
36 use crate::pages::admin_server::{24 use crate::pages::admin_server::{
37 MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows,25 MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows,
@@ -41,7 +29,6 @@ use crate::state::AppState;
41 use crate::views::parts::{confirm_act, head, post_act};29 use crate::views::parts::{confirm_act, head, post_act};
42 use crate::views::{enc, rel_time, shell};30 use crate::views::{enc, rel_time, shell};
43 31
44-/// Rows shown in the queue at most.
45 const LIST_LIMIT: u32 = 100;32 const LIST_LIMIT: u32 = 100;
46 33
47 #[query_params(error = bad_request)]34 #[query_params(error = bad_request)]
@@ -51,14 +38,12 @@ pub(crate) struct NoticeQuery {
51 state: Option<String>,38 state: Option<String>,
52 }39 }
53 40
54-/// The two tabs of the page.
55 #[derive(Debug, Clone, Copy, PartialEq, Eq)]41 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
56 enum Tab {42 enum Tab {
57 Settings,43 Settings,
58 Queue,44 Queue,
59 }45 }
60 46
61-/// One queue row, already formatted. There is no body field on purpose.
62 struct QueueRow {47 struct QueueRow {
63 id: String,48 id: String,
64 to: String,49 to: String,
@@ -73,7 +58,6 @@ struct QueueRow {
73 failed: bool,58 failed: bool,
74 }59 }
75 60
76-/// One state filter: the link, its label and how many rows it covers.
77 struct FilterChip {61 struct FilterChip {
78 href: String,62 href: String,
79 label: &'static str,63 label: &'static str,
@@ -81,14 +65,12 @@ struct FilterChip {
81 current: bool,65 current: bool,
82 }66 }
83 67
84-/// The queue tab: the filter chips, the rows and the state the filter is on, for the forms.
85 struct QueueData {68 struct QueueData {
86 chips: Vec<FilterChip>,69 chips: Vec<FilterChip>,
87 rows: Vec<QueueRow>,70 rows: Vec<QueueRow>,
88 filter_param: String,71 filter_param: String,
89 }72 }
90 73
91-/// Everything the page shows. The password is never in here.
92 struct PageData {74 struct PageData {
93 host: String,75 host: String,
94 port: String,76 port: String,
@@ -98,13 +80,11 @@ struct PageData {
98 from_name: String,80 from_name: String,
99 enabled: bool,81 enabled: bool,
100 has_password: bool,82 has_password: bool,
101- /// The delivery setting (`mail.transport`), a settings row saved with the settings form.
102 transport: Vec<Row>,83 transport: Vec<Row>,
103 tab: Tab,84 tab: Tab,
104 queue: Option<QueueData>,85 queue: Option<QueueData>,
105 }86 }
106 87
107-/// The CSS class of a state pill. The pills reuse the CI state colours.
108 fn state_class(state: MailState) -> &'static str {88 fn state_class(state: MailState) -> &'static str {
109 match state {89 match state {
110 MailState::Sent => "ci-state ci-success",90 MailState::Sent => "ci-state ci-success",
@@ -133,7 +113,6 @@ fn row_view(entry: &OutboxEntry, now: &str, lang: Lang) -> QueueRow {
133 }113 }
134 }114 }
135 115
136-/// The queue tab's data. `filter` of `None` lists every state.
137 async fn queue_data(116 async fn queue_data(
138 state: &AppState,117 state: &AppState,
139 lang: Lang,118 lang: Lang,
@@ -224,8 +203,6 @@ async fn mail_view(
224 <a href="/admin/mail?tab=queue" aria-current=((!settings_on).then_some("page"))>(g::t(lang, K::MailTabQueue))</a>203 <a href="/admin/mail?tab=queue" aria-current=((!settings_on).then_some("page"))>(g::t(lang, K::MailTabQueue))</a>
225 </nav>204 </nav>
226 if settings_on {205 if settings_on {
227- // Saved by any admin session: the stream re-renders the settings with the same signal
228- // as the queue (the save bumps it too), and the form keeps what was typed.
229 <div class="sheet" data-live="/admin/mail/events">206 <div class="sheet" data-live="/admin/mail/events">
230 <form method="post" action="/admin/mail" class="srv-form">207 <form method="post" action="/admin/mail" class="srv-form">
231 <input type="hidden" name="csrf" value=(csrf.as_str())>208 <input type="hidden" name="csrf" value=(csrf.as_str())>
@@ -349,29 +326,17 @@ async fn mail_page(cx: &Cx) -> Result<impl View> {
349 })326 })
350 }327 }
351 328
352-/// The live `changed` stream of the queue. One event per queue change. Nothing is sent on connect:
353-/// the page was just rendered.
354-fn queue_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static {
355- stream::unfold(wake, |mut wake| async move {
356- wake.changed().await.ok()?;
357- Some((changed_event("queue".to_owned()), wake))
358- })
359-}
360-
361-/// The queue's change stream. Admins only.
362 #[route(GET "/admin/mail/events")]329 #[route(GET "/admin/mail/events")]
363 async fn mail_events(cx: &Cx) -> Result<Response> {330 async fn mail_events(cx: &Cx) -> Result<Response> {
364 admin_only(cx).await?;331 admin_only(cx).await?;
365- // Subscribed before the response is sent, so a change after this point is sent.
366 let wake = live::subscribe();332 let wake = live::subscribe();
367- events_response(cx, queue_changes(wake))333+ events_response(cx, wake_stream(wake, "queue"))
368 }334 }
369 335
370 #[derive(Deserialize, Default)]336 #[derive(Deserialize, Default)]
371 struct SettingsForm {337 struct SettingsForm {
372 #[serde(default)]338 #[serde(default)]
373 csrf: String,339 csrf: String,
374- /// The delivery setting, saved as an override like the server settings.
375 #[serde(default, rename = "mail.transport")]340 #[serde(default, rename = "mail.transport")]
376 transport: String,341 transport: String,
377 #[serde(default)]342 #[serde(default)]
@@ -424,8 +389,6 @@ async fn mail_save(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<Response>
424 Err(see_other(&location).into())389 Err(see_other(&location).into())
425 }390 }
426 391
427-/// Validates and stores the settings, wakes the worker, and audits the change. The password is
428-/// not part of the audit entry.
429 async fn save_settings(392 async fn save_settings(
430 cx: &Cx,393 cx: &Cx,
431 state: &AppState,394 state: &AppState,
@@ -499,8 +462,6 @@ async fn mail_test(cx: &Cx, Form(form): Form<TestForm>) -> Result<Response> {
499 Err(see_other(&location).into())462 Err(see_other(&location).into())
500 }463 }
501 464
502-/// Queues a test message to the admin's own address. Refused while mail is off or when the admin
503-/// has no address on the account.
504 async fn queue_test(465 async fn queue_test(
505 cx: &Cx,466 cx: &Cx,
506 state: &AppState,467 state: &AppState,
@@ -555,7 +516,6 @@ struct QueueForm {
555 csrf: String,516 csrf: String,
556 #[serde(default)]517 #[serde(default)]
557 id: String,518 id: String,
558- /// The filter the admin was on, so the redirect lands back on it.
559 #[serde(default)]519 #[serde(default)]
560 state: String,520 state: String,
561 }521 }
@@ -570,8 +530,6 @@ async fn queue_discard(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response>
570 queue_action(cx, form, QueueAction::Discard).await530 queue_action(cx, form, QueueAction::Discard).await
571 }531 }
572 532
573-/// Retries or discards one failed message. Anything else is refused with a notice and changes
574-/// nothing. Either way the worker is woken and the queue's watchers are told.
575 async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<Response> {533 async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<Response> {
576 let viewer = admin_only(cx).await?;534 let viewer = admin_only(cx).await?;
577 if !check_csrf(&viewer.1, &form.csrf) {535 if !check_csrf(&viewer.1, &form.csrf) {
@@ -626,7 +584,6 @@ mod tests {
626 state: AppState,584 state: AppState,
627 }585 }
628 586
629- /// An instance with an admin (who has an address) and a plain user.
630 async fn fixture() -> Fixture {587 async fn fixture() -> Fixture {
631 let dir = tempfile::tempdir().expect("tempdir");588 let dir = tempfile::tempdir().expect("tempdir");
632 let data_dir = dir.path().join("data");589 let data_dir = dir.path().join("data");
@@ -692,14 +649,10 @@ mod tests {
692 .any(|e| e.action == action)649 .any(|e| e.action == action)
693 }650 }
694 651
695- // Scenario: the settings page. Gates and refusals come first while the store is still
696- // pristine, then a save, the page with no password shown, the test mail while mail is on,
697- // and the Turkish page. Each step is a precondition of the next one.
698 #[tokio::test]652 #[tokio::test]
699 async fn settings_gates_saves_test_mail_and_turkish_page() {653 async fn settings_gates_saves_test_mail_and_turkish_page() {
700 let fx = fixture().await;654 let fx = fixture().await;
701 655
702- // Anonymous and non-admin users get 404 on the page and its posts.
703 let (anon, _) = send(&fx.router, "GET", "/admin/mail", None, None).await;656 let (anon, _) = send(&fx.router, "GET", "/admin/mail", None, None).await;
704 assert_eq!(anon, 404);657 assert_eq!(anon, 404);
705 let (user, _) = send(&fx.router, "GET", "/admin/mail", Some(USER_TOKEN), None).await;658 let (user, _) = send(&fx.router, "GET", "/admin/mail", Some(USER_TOKEN), None).await;
@@ -731,7 +684,6 @@ mod tests {
731 .has_password684 .has_password
732 );685 );
733 686
734- // A missing CSRF token is refused.
735 let (status, _) = send(687 let (status, _) = send(
736 &fx.router,688 &fx.router,
737 "POST",689 "POST",
@@ -742,7 +694,6 @@ mod tests {
742 .await;694 .await;
743 assert_eq!(status, 403, "a missing CSRF token is refused");695 assert_eq!(status, 403, "a missing CSRF token is refused");
744 696
745- // Test mail while mail is off queues nothing.
746 let (status, _) = send(697 let (status, _) = send(
747 &fx.router,698 &fx.router,
748 "POST",699 "POST",
@@ -762,7 +713,6 @@ mod tests {
762 "nothing is queued while mail is off"713 "nothing is queued while mail is off"
763 );714 );
764 715
765- // A bad port is answered with a notice and changes nothing.
766 let (status, _) = send(716 let (status, _) = send(
767 &fx.router,717 &fx.router,
768 "POST",718 "POST",
@@ -777,7 +727,6 @@ mod tests {
777 assert!(!saved.has_password);727 assert!(!saved.has_password);
778 assert!(!audit_has(&fx.state.store, AuditAction::MailSettingsUpdated).await);728 assert!(!audit_has(&fx.state.store, AuditAction::MailSettingsUpdated).await);
779 729
780- // A good save stores the settings, audits them, and the page never shows the password.
781 let (status, _) = send(730 let (status, _) = send(
782 &fx.router,731 &fx.router,
783 "POST",732 "POST",
@@ -802,7 +751,6 @@ mod tests {
802 "the stored password is never rendered"751 "the stored password is never rendered"
803 );752 );
804 753
805- // With mail on, a test mail is queued to the admin's address and audited.
806 let (status, _) = send(754 let (status, _) = send(
807 &fx.router,755 &fx.router,
808 "POST",756 "POST",
@@ -818,7 +766,6 @@ mod tests {
818 assert!(rows[0].idem_key.starts_with("test:"));766 assert!(rows[0].idem_key.starts_with("test:"));
819 assert!(audit_has(&fx.state.store, AuditAction::MailTestQueued).await);767 assert!(audit_has(&fx.state.store, AuditAction::MailTestQueued).await);
820 768
821- // The page follows the viewer's language.
822 let req = Request::builder()769 let req = Request::builder()
823 .method("GET")770 .method("GET")
824 .uri("/admin/mail")771 .uri("/admin/mail")
@@ -851,13 +798,10 @@ mod tests {
851 }798 }
852 }799 }
853 800
854- // Scenario: the queue tab is admin only and live, filters by state, and never renders a
855- // body. The queue actions and event stream are gated the same way.
856 #[tokio::test]801 #[tokio::test]
857 async fn queue_tab_is_admin_only_live_filters_and_never_renders_a_body() {802 async fn queue_tab_is_admin_only_live_filters_and_never_renders_a_body() {
858 let fx = fixture().await;803 let fx = fixture().await;
859 804
860- // Anonymous and plain users get 404 on the stream and on both queue actions.
861 for (method, uri) in [805 for (method, uri) in [
862 ("GET", "/admin/mail/events"),806 ("GET", "/admin/mail/events"),
863 ("POST", "/admin/mail/queue/retry"),807 ("POST", "/admin/mail/queue/retry"),
@@ -963,7 +907,6 @@ mod tests {
963 "the queue is on its own tab"907 "the queue is on its own tab"
964 );908 );
965 909
966- // An admin gets the queue event stream.
967 let request = Request::builder()910 let request = Request::builder()
968 .method("GET")911 .method("GET")
969 .uri("/admin/mail/events")912 .uri("/admin/mail/events")
@@ -1046,7 +989,6 @@ mod tests {
1046 assert_eq!(discarded.len(), 1);989 assert_eq!(discarded.len(), 1);
1047 assert_eq!(discarded[0].id, ids[1]);990 assert_eq!(discarded[0].id, ids[1]);
1048 991
1049- // A queued message cannot be retried, and a bad token changes nothing.
1050 let (status, _) = send(992 let (status, _) = send(
1051 &fx.router,993 &fx.router,
1052 "POST",994 "POST",
crates/forge-web-account/src/pages/admin_replication.rsmodified+30 -57
@@ -57,7 +57,7 @@ pub(crate) struct NoticeQuery {
57 const REPO_ROWS: usize = 10;57 const REPO_ROWS: usize = 10;
58 58
59 /// The health filter's values, in the order the menu lists them.59 /// The health filter's values, in the order the menu lists them.
60-const HEALTH_KEYS: [&str; 4] = ["error", "lagging", "never", "ok"];60+const HEALTH_MENU: [Health; 4] = [Health::Error, Health::Lagging, Health::Never, Health::Ok];
61 61
62 /// How a subject reads on the page.62 /// How a subject reads on the page.
63 #[derive(Debug, Clone, Copy, PartialEq, Eq)]63 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -98,9 +98,7 @@ impl Health {
98 }98 }
99 99
100 fn from_key(key: &str) -> Option<Health> {100 fn from_key(key: &str) -> Option<Health> {
101- [Health::Ok, Health::Lagging, Health::Error, Health::Never]101+ HEALTH_MENU.into_iter().find(|h| h.key() == key)
102- .into_iter()
103- .find(|h| h.key() == key)
104 }102 }
105 103
106 fn label(self, lang: Lang) -> &'static str {104 fn label(self, lang: Lang) -> &'static str {
@@ -127,29 +125,23 @@ fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health {
127 }125 }
128 }126 }
129 127
130-/// One line of the repos table, already formatted.128+/// One line of the repos table.
131 struct RepoRow {129 struct RepoRow {
132 name: String,130 name: String,
133 kind: Health,131 kind: Health,
134- dot: &'static str,
135- tone: &'static str,
136- health: &'static str,
137 /// The last good copy's stamp, shown as a live relative time.132 /// The last good copy's stamp, shown as a live relative time.
138 last_ok: Option<String>,133 last_ok: Option<String>,
139 error: String,134 error: String,
140 }135 }
141 136
142-impl RepoRow {137+fn repo_row(name: String, status: Option<&ReplicationStatus>, cutoff: &str) -> RepoRow {
143- fn copy(&self) -> RepoRow {138+ RepoRow {
144- RepoRow {139+ name,
145- name: self.name.clone(),140+ kind: health(status, cutoff),
146- kind: self.kind,141+ last_ok: status.and_then(|s| s.last_ok_at.clone()),
147- dot: self.dot,142+ error: status
148- tone: self.tone,143+ .and_then(|s| s.last_error.clone())
149- health: self.health,144+ .unwrap_or_default(),
150- last_ok: self.last_ok.clone(),
151- error: self.error.clone(),
152- }
153 }145 }
154 }146 }
155 147
@@ -187,39 +179,21 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData>
187 Some(repo) => format!("{}/{}", repo.owner_name, repo.name),179 Some(repo) => format!("{}/{}", repo.owner_name, repo.name),
188 None => id.clone(),180 None => id.clone(),
189 };181 };
190- let h = health(status, &repo_cutoff);182+ repos.push(repo_row(name, status, &repo_cutoff));
191- repos.push(RepoRow {
192- name,
193- kind: h,
194- dot: h.dot(),
195- tone: h.tone(),
196- health: h.label(lang),
197- last_ok: status.and_then(|s| s.last_ok_at.clone()),
198- error: status
199- .and_then(|s| s.last_error.clone())
200- .unwrap_or_default(),
201- });
202 }183 }
203 // Repos deleted since their last push: their standby copy is removed at the next reconcile.184 // Repos deleted since their last push: their standby copy is removed at the next reconcile.
204 for status in statuses.values() {185 for status in statuses.values() {
205 if status.subject != DB_SUBJECT && !ids.contains(&status.subject) {186 if status.subject != DB_SUBJECT && !ids.contains(&status.subject) {
206- let h = health(Some(status), &repo_cutoff);187+ let name = g::deleted_repo_name(lang, &status.subject);
207- repos.push(RepoRow {188+ repos.push(repo_row(name, Some(status), &repo_cutoff));
208- name: g::deleted_repo_name(lang, &status.subject),
209- kind: h,
210- dot: h.dot(),
211- tone: h.tone(),
212- health: h.label(lang),
213- last_ok: status.last_ok_at.clone(),
214- error: status.last_error.clone().unwrap_or_default(),
215- });
216 }189 }
217 }190 }
218 191
192+ let db_health = health(db, &db_cutoff);
219 Ok(PageData {193 Ok(PageData {
220 enabled: config.enabled(),194 enabled: config.enabled(),
221- db_dot: health(db, &db_cutoff).dot(),195+ db_dot: db_health.dot(),
222- db_health: health(db, &db_cutoff).label(lang),196+ db_health: db_health.label(lang),
223 db_last_ok: db.and_then(|s| s.last_ok_at.clone()),197 db_last_ok: db.and_then(|s| s.last_ok_at.clone()),
224 db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()),198 db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()),
225 db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(),199 db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(),
@@ -238,6 +212,7 @@ async fn replication_view(
238 list: RepoList,212 list: RepoList,
239 ) -> Result<impl View> {213 ) -> Result<impl View> {
240 let RepoList {214 let RepoList {
215+ has_repos,
241 finder,216 finder,
242 health,217 health,
243 rows,218 rows,
@@ -245,7 +220,6 @@ async fn replication_view(
245 pages,220 pages,
246 nav: (links, prev, next),221 nav: (links, prev, next),
247 } = list;222 } = list;
248- let has_repos = !data.repos.is_empty();
249 let all_label = s(lang, "All", "Tümü");223 let all_label = s(lang, "All", "Tümü");
250 let health_label = s(lang, "Health", "Durum");224 let health_label = s(lang, "Health", "Durum");
251 let placeholder = s(lang, "Search repositories", "Depolarda ara");225 let placeholder = s(lang, "Search repositories", "Depolarda ara");
@@ -306,10 +280,8 @@ async fn replication_view(
306 (health_label) " "280 (health_label) " "
307 <select name="health" data-autosubmit="true">281 <select name="health" data-autosubmit="true">
308 <option value="" selected=(health.is_none())>(all_label)</option>282 <option value="" selected=(health.is_none())>(all_label)</option>
309- for key in HEALTH_KEYS {283+ for h in HEALTH_MENU {
310- if let Some(h) = Health::from_key(key) {284+ <option value=(h.key()) selected=(health == Some(h))>(h.label(lang))</option>
311- <option value=(key) selected=(health == Some(h))>(h.label(lang))</option>
312- }
313 }285 }
314 </select>286 </select>
315 </label>287 </label>
@@ -320,7 +292,7 @@ async fn replication_view(
320 for row in rows.into_iter() {292 for row in rows.into_iter() {
321 <div class="line" data-kb-row="">293 <div class="line" data-kb-row="">
322 <span class="name">(row.name.as_str())</span>294 <span class="name">(row.name.as_str())</span>
323- <span class="val"><span class=(row.dot) aria-hidden="true"></span> <span class=(row.tone)>(row.health)</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span>295+ <span class="val"><span class=(row.kind.dot()) aria-hidden="true"></span> <span class=(row.kind.tone())>(row.kind.label(lang))</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span>
324 </div>296 </div>
325 if !row.error.is_empty() {297 if !row.error.is_empty() {
326 alert(message: row.error.as_str())298 alert(message: row.error.as_str())
@@ -341,7 +313,7 @@ async fn page_fingerprint(state: &AppState) -> Result<String> {
341 let rows: Vec<_> = data313 let rows: Vec<_> = data
342 .repos314 .repos
343 .iter()315 .iter()
344- .map(|row| (&row.name, row.health, &row.last_ok, &row.error))316+ .map(|row| (&row.name, row.kind.label(Lang::En), &row.last_ok, &row.error))
345 .collect();317 .collect();
346 Ok(format!(318 Ok(format!(
347 "{}|{}|{:?}|{:?}|{}|{:?}",319 "{}|{}|{:?}|{:?}|{}|{:?}",
@@ -368,6 +340,7 @@ async fn replication_events(cx: &Cx) -> Result<Response> {
368 340
369 /// One page of the repo list, after the search and the health filter.341 /// One page of the repo list, after the search and the health filter.
370 struct RepoList {342 struct RepoList {
343+ has_repos: bool,
371 finder: Finder,344 finder: Finder,
372 health: Option<Health>,345 health: Option<Health>,
373 rows: Vec<RepoRow>,346 rows: Vec<RepoRow>,
@@ -376,20 +349,19 @@ struct RepoList {
376 nav: (Vec<PageLink>, Option<String>, Option<String>),349 nav: (Vec<PageLink>, Option<String>, Option<String>),
377 }350 }
378 351
379-/// Takes the repos that match the query out of `data`, a page of them.352+/// Filters the repos by the query and cuts out the page asked for.
380-fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList {353+fn repo_list(repos: Vec<RepoRow>, query: &NoticeQuery) -> RepoList {
381 let finder = Finder::new(354 let finder = Finder::new(
382 query.q.as_deref(),355 query.q.as_deref(),
383 query.exact.as_deref(),356 query.exact.as_deref(),
384 query.case.as_deref(),357 query.case.as_deref(),
385 );358 );
386 let health = query.health.as_deref().and_then(Health::from_key);359 let health = query.health.as_deref().and_then(Health::from_key);
387- let matching: Vec<RepoRow> = data360+ let has_repos = !repos.is_empty();
388- .repos361+ let matching: Vec<RepoRow> = repos
389- .iter()362+ .into_iter()
390 .filter(|row| health.is_none_or(|h| row.kind == h))363 .filter(|row| health.is_none_or(|h| row.kind == h))
391 .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()]))364 .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()]))
392- .map(RepoRow::copy)
393 .collect();365 .collect();
394 let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1);366 let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1);
395 let page = query367 let page = query
@@ -412,6 +384,7 @@ fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList {
412 list_href("/admin/replication", &params)384 list_href("/admin/replication", &params)
413 });385 });
414 RepoList {386 RepoList {
387+ has_repos,
415 finder,388 finder,
416 health,389 health,
417 rows,390 rows,
@@ -428,7 +401,7 @@ async fn replication_page(cx: &Cx) -> Result<impl View> {
428 let lang = i18n::lang(cx, Some(&viewer.0));401 let lang = i18n::lang(cx, Some(&viewer.0));
429 let state = context::<AppState>(cx);402 let state = context::<AppState>(cx);
430 let mut data = page_data(state, lang).await?;403 let mut data = page_data(state, lang).await?;
431- let list = repo_list(&mut data, query);404+ let list = repo_list(std::mem::take(&mut data.repos), query);
432 let settings = setting_rows(state, lang, REPLICATION_KEYS).await?;405 let settings = setting_rows(state, lang, REPLICATION_KEYS).await?;
433 let csrf = viewer.1.csrf_token.clone();406 let csrf = viewer.1.csrf_token.clone();
434 let title = g::t(lang, K::Replication);407 let title = g::t(lang, K::Replication);
crates/forge-web-account/src/pages/admin_server.rsmodified+4 -110
@@ -1,19 +1,3 @@
1-//! Page: the forge's own settings (`/admin/server`). Instance admins only; anyone else gets 404.
2-//!
3-//! One category of settings at a time (`?cat=`). Each field shows its effective value, where that value comes
4-//! from (default, config file, or a UI override) and how a change reaches the process: live
5-//! (applied at once), restart (saved, applied at the next start) or read-only. Saving a tab stores
6-//! the changed fields as database overrides on top of the config file, which is never rewritten.
7-//! A field with an override has "Reset to file value". Secret fields are write-only: the page
8-//! shows only whether they are set. See `forge_core::server_settings` for the rules.
9-//! Saving and resetting are audited, with the keys but never the values.
10-//!
11-//! "Restart server" asks for a graceful stop through the self-update path: the process exits with
12-//! `RESTART_EXIT_CODE` and systemd (`Restart=on-failure`) starts the binary again, which picks up a
13-//! newly installed one. The page that follows shows "Restarting" and follows an event stream. The
14-//! stream sends the server's boot id when it connects, so the browser's own reconnect after the
15-//! restart brings a new id, and the page then re-renders itself with no reload and no polling.
16-
17 use std::collections::{BTreeMap, HashMap};1 use std::collections::{BTreeMap, HashMap};
18 2
19 use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty};3 use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty};
@@ -45,32 +29,20 @@ use crate::views::{enc, shell};
45 #[query_params(error = bad_request)]29 #[query_params(error = bad_request)]
46 pub(crate) struct ServerQuery {30 pub(crate) struct ServerQuery {
47 notice: Option<String>,31 notice: Option<String>,
48- /// The category shown: `general`, `limits`, `storage`, `backups`, `integrations` or `alerts`.
49 cat: Option<String>,32 cat: Option<String>,
50- /// The search text: when set, the page lists the matching settings from every category instead.
51 q: Option<String>,33 q: Option<String>,
52- /// Set when the search asks for the text as typed, as one piece.
53 exact: Option<String>,34 exact: Option<String>,
54- /// Set when the search keeps upper and lower case apart.
55 case: Option<String>,35 case: Option<String>,
56- /// The older name for `cat`, still read so an old link opens the same category.
57 tab: Option<String>,36 tab: Option<String>,
58- /// The boot id of the server that was asked to restart.
59 restarting: Option<String>,37 restarting: Option<String>,
60 }38 }
61 39
62-/// How long the restart waits after the request is answered, so the redirect that follows is
63-/// served by the old process.
64 const RESTART_GRACE: std::time::Duration = std::time::Duration::from_millis(750);40 const RESTART_GRACE: std::time::Duration = std::time::Duration::from_millis(750);
65 41
66-/// Where the page stands in a restart.
67 #[derive(Clone, Copy, PartialEq, Eq)]42 #[derive(Clone, Copy, PartialEq, Eq)]
68 enum Restart {43 enum Restart {
69- /// No restart was asked from this page.
70 None,44 None,
71- /// Asked, and this process is still the old one or on its way down.
72 Pending,45 Pending,
73- /// Asked, and a new process answered.
74 Done,46 Done,
75 }47 }
76 48
@@ -88,12 +60,10 @@ struct OptionRow {
88 selected: bool,60 selected: bool,
89 }61 }
90 62
91-/// One field, already formatted for the template. A secret's value is never in here.
92 pub(crate) struct Row {63 pub(crate) struct Row {
93 key: &'static str,64 key: &'static str,
94 label: &'static str,65 label: &'static str,
95 kind_label: &'static str,66 kind_label: &'static str,
96- /// What a line shows for the value: the text, the chosen option, On or Off, or the secret state.
97 value_text: String,67 value_text: String,
98 value: String,68 value: String,
99 file_value: String,69 file_value: String,
@@ -112,9 +82,6 @@ pub(crate) struct Row {
112 fixed: bool,82 fixed: bool,
113 }83 }
114 84
115-/// One page of settings: a part of a category small enough to read without scrolling. Saving posts
116-/// the page's slug; the save covers the page's category, and only the page's switches are read as
117-/// off when absent.
118 pub(crate) struct SrvPage {85 pub(crate) struct SrvPage {
119 pub(crate) slug: &'static str,86 pub(crate) slug: &'static str,
120 group: Group,87 group: Group,
@@ -129,9 +96,6 @@ impl SrvPage {
129 }96 }
130 }97 }
131 98
132-/// The pages in rail order. Every setting is on exactly one page: the backup and replication
133-/// settings are on their own pages (`BACKUP_KEYS`, `REPLICATION_KEYS`) and `mail.transport` is on
134-/// the Mail page (`MAIL_KEYS`).
135 pub(crate) const PAGES: &[SrvPage] = &[99 pub(crate) const PAGES: &[SrvPage] = &[
136 SrvPage {100 SrvPage {
137 slug: "general",101 slug: "general",
@@ -238,7 +202,6 @@ pub(crate) const PAGES: &[SrvPage] = &[
238 group: Group::Alerts,202 group: Group::Alerts,
239 en: "Alerts",203 en: "Alerts",
240 tr: "Uyarılar",204 tr: "Uyarılar",
241- // Each threshold sits under the alert it tunes.
242 keys: &[205 keys: &[
243 "alerts.enabled",206 "alerts.enabled",
244 "alerts.email",207 "alerts.email",
@@ -255,7 +218,6 @@ pub(crate) const PAGES: &[SrvPage] = &[
255 },218 },
256 ];219 ];
257 220
258-/// The settings of the Backups page. Their group is `Group::Backups`.
259 pub(crate) const BACKUP_KEYS: &[&str] = &[221 pub(crate) const BACKUP_KEYS: &[&str] = &[
260 "backup.dir",222 "backup.dir",
261 "backup.interval_hours",223 "backup.interval_hours",
@@ -264,7 +226,6 @@ pub(crate) const BACKUP_KEYS: &[&str] = &[
264 "backup.healthcheck_url",226 "backup.healthcheck_url",
265 ];227 ];
266 228
267-/// The settings of the Replication page. Their group is `Group::Backups`.
268 pub(crate) const REPLICATION_KEYS: &[&str] = &[229 pub(crate) const REPLICATION_KEYS: &[&str] = &[
269 "replication.target",230 "replication.target",
270 "replication.ssh_port",231 "replication.ssh_port",
@@ -275,16 +236,12 @@ pub(crate) const REPLICATION_KEYS: &[&str] = &[
275 "replication.healthcheck_url",236 "replication.healthcheck_url",
276 ];237 ];
277 238
278-/// The settings of the Mail page. Their group is `Group::Integrations`.
279 pub(crate) const MAIL_KEYS: &[&str] = &["mail.transport"];239 pub(crate) const MAIL_KEYS: &[&str] = &["mail.transport"];
280 240
281-/// The page named by `slug`.
282 pub(crate) fn page_by_slug(slug: &str) -> Option<&'static SrvPage> {241 pub(crate) fn page_by_slug(slug: &str) -> Option<&'static SrvPage> {
283 PAGES.iter().find(|page| page.slug == slug)242 PAGES.iter().find(|page| page.slug == slug)
284 }243 }
285 244
286-/// Where the old slugs of moved pages went: `retention`, `s3`, `backups` and `replication`. `None`
287-/// for every slug that still names a page.
288 fn moved_slug(slug: &str) -> Option<&'static str> {245 fn moved_slug(slug: &str) -> Option<&'static str> {
289 match slug {246 match slug {
290 "retention" => Some("/admin/server?cat=limits"),247 "retention" => Some("/admin/server?cat=limits"),
@@ -295,16 +252,12 @@ fn moved_slug(slug: &str) -> Option<&'static str> {
295 }252 }
296 }253 }
297 254
298-/// Where a setting's row lives: the page's name and the link to the row.
299 pub(crate) struct Home {255 pub(crate) struct Home {
300- /// The page's name, with the area it belongs to when that is not obvious ("Backups").
301 pub(crate) label: String,256 pub(crate) label: String,
302- /// True for a setting on the server settings page, so the area name is written before it.
303 pub(crate) server: bool,257 pub(crate) server: bool,
304 pub(crate) href: String,258 pub(crate) href: String,
305 }259 }
306 260
307-/// The page that holds the setting `key`, and the link to its row.
308 pub(crate) fn page_of(lang: Lang, key: &str) -> Home {261 pub(crate) fn page_of(lang: Lang, key: &str) -> Home {
309 if BACKUP_KEYS.contains(&key) {262 if BACKUP_KEYS.contains(&key) {
310 return Home {263 return Home {
@@ -338,8 +291,6 @@ pub(crate) fn page_of(lang: Lang, key: &str) -> Home {
338 }291 }
339 }292 }
340 293
341-/// The keys a topic shows, out of its `keys`, given the values now in effect. Storage shows the
342-/// fields of the chosen backend only: `fs` shows none, `s3` and `r2` their own.
343 fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> {294 fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> {
344 let backend = views295 let backend = views
345 .iter()296 .iter()
@@ -360,7 +311,6 @@ fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> {
360 .collect()311 .collect()
361 }312 }
362 313
363-/// The words for a choice's stored value. Values that are names (smtp, s3, eu) read as they are.
364 fn option_label(lang: Lang, option: &str) -> String {314 fn option_label(lang: Lang, option: &str) -> String {
365 let (en, tr) = match option {315 let (en, tr) = match option {
366 "" => return g::t(lang, K::SrvEmpty).to_owned(),316 "" => return g::t(lang, K::SrvEmpty).to_owned(),
@@ -379,7 +329,6 @@ fn option_label(lang: Lang, option: &str) -> String {
379 fn row(lang: Lang, view: &FieldView) -> Row {329 fn row(lang: Lang, view: &FieldView) -> Row {
380 let field: &Field = view.field;330 let field: &Field = view.field;
381 let kind_label = match field.kind {331 let kind_label = match field.kind {
382- // A live field needs no word: applying at once is what a field is expected to do.
383 Kind::Live => "",332 Kind::Live => "",
384 Kind::Restart => g::t(lang, K::SrvKindRestart),333 Kind::Restart => g::t(lang, K::SrvKindRestart),
385 Kind::ReadOnly => g::t(lang, K::SrvKindReadOnly),334 Kind::ReadOnly => g::t(lang, K::SrvKindReadOnly),
@@ -456,7 +405,6 @@ fn row(lang: Lang, view: &FieldView) -> Row {
456 }405 }
457 }406 }
458 407
459-/// The rows of the settings `keys`, in `keys` order.
460 fn rows_of(lang: Lang, views: &[FieldView], keys: &[&str]) -> Vec<Row> {408 fn rows_of(lang: Lang, views: &[FieldView], keys: &[&str]) -> Vec<Row> {
461 keys.iter()409 keys.iter()
462 .filter_map(|key| views.iter().find(|view| view.field.key == *key))410 .filter_map(|key| views.iter().find(|view| view.field.key == *key))
@@ -464,14 +412,6 @@ fn rows_of(lang: Lang, views: &[FieldView], keys: &[&str]) -> Vec<Row> {
464 .collect()412 .collect()
465 }413 }
466 414
467-/// The rows of one server settings page, in the page's order.
468-async fn rows_for(state: &AppState, lang: Lang, page: &SrvPage) -> forge_core::Result<Vec<Row>> {
469- let overrides = state.store.server_overrides().await?;
470- let views = state.settings.views(&overrides);
471- Ok(rows_of(lang, &views, page.keys))
472-}
473-
474-/// The rows of a settings topic outside the server page (Backups, Replication, Mail), in `keys` order.
475 pub(crate) async fn setting_rows(415 pub(crate) async fn setting_rows(
476 state: &AppState,416 state: &AppState,
477 lang: Lang,417 lang: Lang,
@@ -482,9 +422,6 @@ pub(crate) async fn setting_rows(
482 Ok(rows_of(lang, &views, keys))422 Ok(rows_of(lang, &views, keys))
483 }423 }
484 424
485-/// Saves the posted values of one settings topic. `topic` is every key the topic can show; only
486-/// the ones it shows now (see `shown_keys`) are read, and an unchecked switch of those counts as
487-/// off. `Ok(None)` means nothing differed from what is in effect.
488 pub(crate) async fn save_topic(425 pub(crate) async fn save_topic(
489 cx: &Cx,426 cx: &Cx,
490 state: &AppState,427 state: &AppState,
@@ -510,7 +447,6 @@ pub(crate) async fn save_topic(
510 save(cx, state, user, group, &submitted, lang).await447 save(cx, state, user, group, &submitted, lang).await
511 }448 }
512 449
513-/// The notice a settings save shows: saved, nothing changed, or why it was refused.
514 pub(crate) fn notice_of(lang: Lang, result: forge_core::Result<Option<()>>) -> String {450 pub(crate) fn notice_of(lang: Lang, result: forge_core::Result<Option<()>>) -> String {
515 match result {451 match result {
516 Ok(Some(())) => g::t(lang, K::SrvSaved).to_owned(),452 Ok(Some(())) => g::t(lang, K::SrvSaved).to_owned(),
@@ -519,7 +455,6 @@ pub(crate) fn notice_of(lang: Lang, result: forge_core::Result<Option<()>>) -> S
519 }455 }
520 }456 }
521 457
522-/// The words for an error a page shows: the message itself for a refusal the user can fix.
523 pub(crate) fn refusal(error: Error) -> String {458 pub(crate) fn refusal(error: Error) -> String {
524 match error {459 match error {
525 Error::Invalid(message) | Error::Config(message) => message,460 Error::Invalid(message) | Error::Config(message) => message,
@@ -527,8 +462,6 @@ pub(crate) fn refusal(error: Error) -> String {
527 }462 }
528 }463 }
529 464
530-/// The page a settings form goes back to. Only a page of the admin area is taken; anything else
531-/// goes to the server settings.
532 pub(crate) fn back_to(raw: &str) -> &str {465 pub(crate) fn back_to(raw: &str) -> &str {
533 if raw.starts_with("/admin/") && !raw.contains("//") && !raw.contains('\\') {466 if raw.starts_with("/admin/") && !raw.contains("//") && !raw.contains('\\') {
534 raw467 raw
@@ -537,14 +470,11 @@ pub(crate) fn back_to(raw: &str) -> &str {
537 }470 }
538 }471 }
539 472
540-/// `back` with a notice on its query string.
541 pub(crate) fn with_notice(back: &str, notice: &str) -> String {473 pub(crate) fn with_notice(back: &str, notice: &str) -> String {
542 let sep = if back.contains('?') { '&' } else { '?' };474 let sep = if back.contains('?') { '&' } else { '?' };
543 format!("{back}{sep}notice={}", enc(notice))475 format!("{back}{sep}notice={}", enc(notice))
544 }476 }
545 477
546-/// The hidden form that resets one setting: the rows' "Reset to file value" buttons post to it by
547-/// id. It goes outside the forms that save, since a form cannot hold another.
548 #[component]478 #[component]
549 pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<impl View> {479 pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<impl View> {
550 Ok(view! {480 Ok(view! {
@@ -555,7 +485,6 @@ pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<im
555 })485 })
556 }486 }
557 487
558-/// The rows of a settings topic, one line each. The caller's form holds them.
559 #[component]488 #[component]
560 pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result<impl View> {489 pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result<impl View> {
561 Ok(view! {490 Ok(view! {
@@ -565,7 +494,6 @@ pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result
565 })494 })
566 }495 }
567 496
568-/// The settings from every category whose key or label matches the search.
569 async fn search_hits(497 async fn search_hits(
570 state: &AppState,498 state: &AppState,
571 lang: Lang,499 lang: Lang,
@@ -581,8 +509,6 @@ async fn search_hits(
581 .collect())509 .collect())
582 }510 }
583 511
584-/// One setting on one line: its name, then its control (or its value when it cannot be changed
585-/// here), then what to know about it. Every control is the same width, so the notes line up.
586 #[component]512 #[component]
587 async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {513 async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {
588 let id = format!("srv-{}", row.key);514 let id = format!("srv-{}", row.key);
@@ -617,7 +543,6 @@ async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {
617 })543 })
618 }544 }
619 545
620-/// The facts after a setting's control: its kind, whether a restart is needed, and its override.
621 #[component]546 #[component]
622 async fn srv_hints(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {547 async fn srv_hints(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {
623 Ok(view! {548 Ok(view! {
@@ -657,8 +582,6 @@ async fn server_view(
657 let tab = page.slug;582 let tab = page.slug;
658 let any_editable = rows.iter().any(|r| !r.fixed);583 let any_editable = rows.iter().any(|r| !r.fixed);
659 let search_label = s(lang, "Search server settings", "Sunucu ayarlarında ara");584 let search_label = s(lang, "Search server settings", "Sunucu ayarlarında ara");
660- // A pending restart names the boot id it waits for: the stream then sends at once when a new
661- // process answers, and the page re-renders.
662 let live = match restart {585 let live = match restart {
663 Restart::Pending => format!(586 Restart::Pending => format!(
664 "/admin/server/events?restarting={}",587 "/admin/server/events?restarting={}",
@@ -752,7 +675,7 @@ async fn server_page(cx: &Cx) -> Result<impl View> {
752 query.case.as_deref(),675 query.case.as_deref(),
753 );676 );
754 let (rows, search) = if finder.is_empty() {677 let (rows, search) = if finder.is_empty() {
755- (rows_for(state, lang, page).await?, None)678+ (setting_rows(state, lang, page.keys).await?, None)
756 } else {679 } else {
757 (Vec::new(), Some(search_hits(state, lang, &finder).await?))680 (Vec::new(), Some(search_hits(state, lang, &finder).await?))
758 };681 };
@@ -787,8 +710,6 @@ async fn server_save(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> Resu
787 .into())710 .into())
788 }711 }
789 712
790-/// Validates the whole tab as one unit, stores it, publishes the live fields and audits the keys.
791-/// `Ok(None)` means nothing differed from what is already in effect.
792 async fn save(713 async fn save(
793 cx: &Cx,714 cx: &Cx,
794 state: &AppState,715 state: &AppState,
@@ -834,8 +755,6 @@ struct RestartForm {
834 tab: String,755 tab: String,
835 }756 }
836 757
837-/// Audits the request, answers with the page that shows "Restarting", and a moment later asks the
838-/// server to stop gracefully. The process then exits with `RESTART_EXIT_CODE` and systemd starts it.
839 #[route(POST "/admin/server/restart")]758 #[route(POST "/admin/server/restart")]
840 async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Response> {759 async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Response> {
841 let viewer = admin_only(cx).await?;760 let viewer = admin_only(cx).await?;
@@ -843,7 +762,7 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon
843 return Err(forbidden().into());762 return Err(forbidden().into());
844 }763 }
845 let state = context::<AppState>(cx);764 let state = context::<AppState>(cx);
846- let group = Group::parse(&form.tab).unwrap_or(Group::General);765+ let page = page_by_slug(&form.tab).unwrap_or(&PAGES[0]);
847 audit::record(766 audit::record(
848 &state.store,767 &state.store,
849 Some(cx),768 Some(cx),
@@ -864,16 +783,12 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon
864 });783 });
865 Err(see_other(format!(784 Err(see_other(format!(
866 "/admin/server?cat={}&restarting={}",785 "/admin/server?cat={}&restarting={}",
867- group.slug(),786+ page.slug,
868 enc(self_update::boot_id())787 enc(self_update::boot_id())
869 ))788 ))
870 .into())789 .into())
871 }790 }
872 791
873-/// The server settings' change stream. Admins only. It sends `changed` when a setting is saved or
874-/// reset, by any session. When the page waits for a restart (`restarting` names the boot id it
875-/// waits past) and this process is not that one, it sends one `changed` on connect: the browser
876-/// reconnects to the new process after the old one goes down, and that re-renders the page.
877 #[route(GET "/admin/server/events")]792 #[route(GET "/admin/server/events")]
878 async fn server_events(cx: &Cx) -> Result<Response> {793 async fn server_events(cx: &Cx) -> Result<Response> {
879 admin_only(cx).await?;794 admin_only(cx).await?;
@@ -898,7 +813,6 @@ struct ResetForm {
898 csrf: String,813 csrf: String,
899 #[serde(default)]814 #[serde(default)]
900 key: String,815 key: String,
901- /// The page the reset came from: where the viewer goes back to.
902 #[serde(default)]816 #[serde(default)]
903 back: String,817 back: String,
904 }818 }
@@ -913,9 +827,7 @@ async fn server_reset(cx: &Cx, Form(form): Form<ResetForm>) -> Result<Response>
913 let state = context::<AppState>(cx);827 let state = context::<AppState>(cx);
914 let notice = match reset(cx, state, &viewer.0, &form.key).await {828 let notice = match reset(cx, state, &viewer.0, &form.key).await {
915 Ok(()) => g::t(lang, K::SrvResetDone).to_owned(),829 Ok(()) => g::t(lang, K::SrvResetDone).to_owned(),
916- Err(Error::Invalid(message)) => message,830+ Err(other) => refusal(other),
917- Err(Error::Config(message)) => message,
918- Err(other) => other.to_string(),
919 };831 };
920 Err(see_other(with_notice(back_to(&form.back), &notice)).into())832 Err(see_other(with_notice(back_to(&form.back), &notice)).into())
921 }833 }
@@ -1032,7 +944,6 @@ mod tests {
1032 body944 body
1033 }945 }
1034 946
1035- /// Posts a tab and follows the redirect to read the notice it shows.
1036 async fn save(fx: &Fixture, tab: &str, fields: &str) -> String {947 async fn save(fx: &Fixture, tab: &str, fields: &str) -> String {
1037 let form = format!("csrf={CSRF}&tab={tab}&{fields}");948 let form = format!("csrf={CSRF}&tab={tab}&{fields}");
1038 let (status, _, location) = send(949 let (status, _, location) = send(
@@ -1047,7 +958,6 @@ mod tests {
1047 admin_get(fx, &location).await958 admin_get(fx, &location).await
1048 }959 }
1049 960
1050- /// Posts a settings topic of its own page (Backups, Replication) and reads the page it goes to.
1051 async fn save_topic_at(fx: &Fixture, path: &str, fields: &str) -> String {961 async fn save_topic_at(fx: &Fixture, path: &str, fields: &str) -> String {
1052 let form = format!("csrf={CSRF}&{fields}");962 let form = format!("csrf={CSRF}&{fields}");
1053 let (status, _, location) =963 let (status, _, location) =
@@ -1056,8 +966,6 @@ mod tests {
1056 admin_get(fx, &location).await966 admin_get(fx, &location).await
1057 }967 }
1058 968
1059- // Scenario: non-admins get 404 on every route, bad CSRF is refused and refused values are
1060- // never stored. Nothing here saves, so the store stays pristine for the next scenarios.
1061 #[tokio::test]969 #[tokio::test]
1062 async fn gates_csrf_read_only_and_bad_values_change_nothing() {970 async fn gates_csrf_read_only_and_bad_values_change_nothing() {
1063 let fx = fixture().await;971 let fx = fixture().await;
@@ -1086,7 +994,6 @@ mod tests {
1086 }994 }
1087 assert!(fx.state.store.server_overrides().await.unwrap().is_empty());995 assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
1088 996
1089- // A bad CSRF token is refused for a settings save and for a restart.
1090 let form = "csrf=wrong&tab=limits&ci.max_log_mb=99".to_owned();997 let form = "csrf=wrong&tab=limits&ci.max_log_mb=99".to_owned();
1091 let (status, _, _) = send(998 let (status, _, _) = send(
1092 &fx.router,999 &fx.router,
@@ -1108,14 +1015,12 @@ mod tests {
1108 assert_eq!(status, 403, "bad csrf restart");1015 assert_eq!(status, 403, "bad csrf restart");
1109 assert_eq!(fx.state.live().ci.max_log_mb, 16);1016 assert_eq!(fx.state.live().ci.max_log_mb, 16);
1110 1017
1111- // A read-only field is shown but cannot be posted.
1112 let page = admin_get(&fx, "/admin/server?tab=addresses").await;1018 let page = admin_get(&fx, "/admin/server?tab=addresses").await;
1113 assert!(page.contains("127.0.0.1:7660"));1019 assert!(page.contains("127.0.0.1:7660"));
1114 assert!(!page.contains("name=\"listen\""));1020 assert!(!page.contains("name=\"listen\""));
1115 save(&fx, "addresses", "listen=0.0.0.0%3A1").await;1021 save(&fx, "addresses", "listen=0.0.0.0%3A1").await;
1116 assert!(fx.state.store.server_overrides().await.unwrap().is_empty());1022 assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
1117 1023
1118- // Out-of-range, wrong-kind and unknown-storage values are rejected, and nothing is stored.
1119 for (tab, fields) in [1024 for (tab, fields) in [
1120 ("general", "registration=everyone"),1025 ("general", "registration=everyone"),
1121 ("general", "trusted_proxies=not-an-ip"),1026 ("general", "trusted_proxies=not-an-ip"),
@@ -1133,8 +1038,6 @@ mod tests {
1133 assert_eq!(fx.state.live().ci.max_log_mb, 16);1038 assert_eq!(fx.state.live().ci.max_log_mb, 16);
1134 }1039 }
1135 1040
1136- // Scenario: a live override applies at once and reset goes back; registration follows the
1137- // saved general setting.
1138 #[tokio::test]1041 #[tokio::test]
1139 async fn live_overrides_apply_reset_and_registration_follows() {1042 async fn live_overrides_apply_reset_and_registration_follows() {
1140 let fx = fixture().await;1043 let fx = fixture().await;
@@ -1172,13 +1075,10 @@ mod tests {
1172 assert_eq!(open, 200, "registration opens at once");1075 assert_eq!(open, 200, "registration opens at once");
1173 }1076 }
1174 1077
1175- // Scenario: a restart field is stored but waits for a restart, secrets are never rendered
1176- // and are stored sealed, and saves are audited without their values.
1177 #[tokio::test]1078 #[tokio::test]
1178 async fn restart_fields_secrets_and_audit_hold_their_rules() {1079 async fn restart_fields_secrets_and_audit_hold_their_rules() {
1179 let fx = fixture().await;1080 let fx = fixture().await;
1180 1081
1181- // A restart field is stored, the live value stays, and the page says so.
1182 save(&fx, "addresses", "base_url=https%3A%2F%2Fnew.example").await;1082 save(&fx, "addresses", "base_url=https%3A%2F%2Fnew.example").await;
1183 assert_eq!(1083 assert_eq!(
1184 fx.state1084 fx.state
@@ -1195,7 +1095,6 @@ mod tests {
1195 assert!(page.contains("restart needed"));1095 assert!(page.contains("restart needed"));
1196 assert!(page.contains("https://new.example"));1096 assert!(page.contains("https://new.example"));
1197 1097
1198- // A secret is saved, never shown on any tab, and a blank post keeps it.
1199 let secret = "https://hc.example/ping/TOPSECRET-TOKEN";1098 let secret = "https://hc.example/ping/TOPSECRET-TOKEN";
1200 let body = save_topic_at(1099 let body = save_topic_at(
1201 &fx,1100 &fx,
@@ -1230,7 +1129,6 @@ mod tests {
1230 .unwrap()1129 .unwrap()
1231 .contains_key("backup.healthcheck_url")1130 .contains_key("backup.healthcheck_url")
1232 );1131 );
1233- // Reset removes the secret and leaves the restart field alone.
1234 let form = format!("csrf={CSRF}&tab=backups&key=backup.healthcheck_url");1132 let form = format!("csrf={CSRF}&tab=backups&key=backup.healthcheck_url");
1235 send(1133 send(
1236 &fx.router,1134 &fx.router,
@@ -1244,7 +1142,6 @@ mod tests {
1244 assert!(!stored.contains_key("backup.healthcheck_url"));1142 assert!(!stored.contains_key("backup.healthcheck_url"));
1245 assert!(stored.contains_key("base_url"));1143 assert!(stored.contains_key("base_url"));
1246 1144
1247- // Saves are audited by key only: no value, secret or otherwise, reaches the log.
1248 save(&fx, "limits", "ci.max_log_mb=77").await;1145 save(&fx, "limits", "ci.max_log_mb=77").await;
1249 let entries = fx1146 let entries = fx
1250 .state1147 .state
@@ -1268,12 +1165,10 @@ mod tests {
1268 }1165 }
1269 }1166 }
1270 1167
1271- // Scenario: restart is audited, and the page shows the restarting state until a new process runs.
1272 #[tokio::test]1168 #[tokio::test]
1273 async fn restart_is_audited_and_the_page_shows_the_restarting_state() {1169 async fn restart_is_audited_and_the_page_shows_the_restarting_state() {
1274 let fx = fixture().await;1170 let fx = fixture().await;
1275 1171
1276- // The page offers the button with a confirm step.
1277 let page = admin_get(&fx, "/admin/server").await;1172 let page = admin_get(&fx, "/admin/server").await;
1278 assert!(page.contains("Restart server"));1173 assert!(page.contains("Restart server"));
1279 assert!(page.contains("/admin/server/restart"));1174 assert!(page.contains("/admin/server/restart"));
@@ -1302,7 +1197,6 @@ mod tests {
1302 .any(|e| e.action == AuditAction::ServerRestarted)1197 .any(|e| e.action == AuditAction::ServerRestarted)
1303 );1198 );
1304 1199
1305- // Same process: "Restarting" with the event stream. A new process: back to normal.
1306 let page = admin_get(&fx, &location).await;1200 let page = admin_get(&fx, &location).await;
1307 assert!(page.contains("Restarting..."));1201 assert!(page.contains("Restarting..."));
1308 assert!(page.contains(r#"data-live="/admin/server/events?restarting="#));1202 assert!(page.contains(r#"data-live="/admin/server/events?restarting="#));
crates/forge-web-account/src/pages/admin_user_detail.rsmodified+19 -17
@@ -7,7 +7,7 @@ use forge_core::names::normalize_name;
7 use forge_core::store::orgs::OrgMemberRole;7 use forge_core::store::orgs::OrgMemberRole;
8 use forge_core::store::suspension::{AccountFacts, Suspension};8 use forge_core::store::suspension::{AccountFacts, Suspension};
9 use forge_core::store::user_delete::GHOST_USERNAME;9 use forge_core::store::user_delete::GHOST_USERNAME;
10-use forge_core::{AuditAction, Store, User};10+use forge_core::{AuditAction, Session, Store, User};
11 use serde::Deserialize;11 use serde::Deserialize;
12 use topcoat::Result;12 use topcoat::Result;
13 use topcoat::context::{Cx, context};13 use topcoat::context::{Cx, context};
@@ -87,15 +87,20 @@ fn is_ghost(user: &User) -> bool {
87 normalize_name(&user.username) == GHOST_USERNAME87 normalize_name(&user.username) == GHOST_USERNAME
88 }88 }
89 89
90-async fn load(cx: &Cx) -> Result<Detail> {90+async fn visible_account(store: &Store, id: &str) -> Result<User> {
91- let store = &context::<AppState>(cx).store;91+ let Some(user) = store.user_by_id(id).await? else {
92- let id = path_param_segment(cx, "user_id").to_owned();
93- let Some(target) = store.user_by_id(&id).await? else {
94 return Err(not_found().into());92 return Err(not_found().into());
95 };93 };
96- if target.is_org() || is_ghost(&target) {94+ if user.is_org() || is_ghost(&user) {
97 return Err(not_found().into());95 return Err(not_found().into());
98 }96 }
97+ Ok(user)
98+}
99+
100+async fn load(cx: &Cx) -> Result<Detail> {
101+ let store = &context::<AppState>(cx).store;
102+ let id = path_param_segment(cx, "user_id").to_owned();
103+ let target = visible_account(store, &id).await?;
99 let login_filter = forge_core::AuditFilter {104 let login_filter = forge_core::AuditFilter {
100 actor_id: Some(target.id.clone()),105 actor_id: Some(target.id.clone()),
101 action: Some(AuditAction::LoginSuccess),106 action: Some(AuditAction::LoginSuccess),
@@ -537,12 +542,7 @@ async fn org_body(
537 542
538 /// What the page shows of one account, as one string. A missing or hidden account is a 404.543 /// What the page shows of one account, as one string. A missing or hidden account is a 404.
539 async fn account_fingerprint(store: &Store, user_id: &str) -> Result<String> {544 async fn account_fingerprint(store: &Store, user_id: &str) -> Result<String> {
540- let Some(target) = store.user_by_id(user_id).await? else {545+ let target = visible_account(store, user_id).await?;
541- return Err(not_found().into());
542- };
543- if target.is_org() || is_ghost(&target) {
544- return Err(not_found().into());
545- }
546 let facts = store.account_facts(user_id).await?;546 let facts = store.account_facts(user_id).await?;
547 let suspension = store.suspension(user_id).await?;547 let suspension = store.suspension(user_id).await?;
548 let passkeys = store.passkey_count(user_id).await?;548 let passkeys = store.passkey_count(user_id).await?;
@@ -621,8 +621,12 @@ enum Outcome {
621 Refused(String),621 Refused(String),
622 }622 }
623 623
624-async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, Detail)> {624+async fn perform(
625- let viewer = admin_only(cx).await?;625+ cx: &Cx,
626+ viewer: &(User, Session),
627+ form: &ActionForm,
628+ action: Action,
629+) -> Result<(Outcome, Detail)> {
626 if !check_csrf(&viewer.1, &form.csrf) {630 if !check_csrf(&viewer.1, &form.csrf) {
627 return Err(forbidden().into());631 return Err(forbidden().into());
628 }632 }
@@ -747,10 +751,8 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome,
747 751
748 /// Redirects to the detail page after a success, or renders it with a message.752 /// Redirects to the detail page after a success, or renders it with a message.
749 async fn respond(cx: &Cx, form: ActionForm, action: Action) -> Result<impl View> {753 async fn respond(cx: &Cx, form: ActionForm, action: Action) -> Result<impl View> {
750- // `view!` expects the `cx` binding that `#[page]` provides.
751- let cx = cx;
752- let (outcome, detail) = perform(cx, &form, action).await?;
753 let viewer = admin_only(cx).await?;754 let viewer = admin_only(cx).await?;
755+ let (outcome, detail) = perform(cx, &viewer, &form, action).await?;
754 let lang = i18n::lang(cx, Some(&viewer.0));756 let lang = i18n::lang(cx, Some(&viewer.0));
755 let notice = match outcome {757 let notice = match outcome {
756 Outcome::Done(key) => {758 Outcome::Done(key) => {
crates/forge-web-account/src/pages/assets.rsmodified+51 -123
@@ -6,7 +6,7 @@ use topcoat::Result;
6 use topcoat::context::Cx;6 use topcoat::context::Cx;
7 use topcoat::router::request::uri;7 use topcoat::router::request::uri;
8 use topcoat::router::response::Response;8 use topcoat::router::response::Response;
9-use topcoat::router::{HeaderMap, StatusCode, header, route};9+use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, route};
10 10
11 use crate::accent;11 use crate::accent;
12 use crate::custom_colour;12 use crate::custom_colour;
@@ -15,15 +15,25 @@ use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href};
15 /// Immutable only when the request names the current version (`href` is the URL the pages link).15 /// Immutable only when the request names the current version (`href` is the URL the pages link).
16 /// Any other `?v=` (a page from an older or newer build, or none) revalidates, so a mismatched16 /// Any other `?v=` (a page from an older or newer build, or none) revalidates, so a mismatched
17 /// version is never cached for a year under a URL that later means this build's file.17 /// version is never cached for a year under a URL that later means this build's file.
18-fn cache_for(cx: &Cx, href: &str) -> topcoat::router::HeaderValue {18+fn cache_for(cx: &Cx, href: &str) -> &'static str {
19 let request = uri(cx);19 let request = uri(cx);
20 let current = href.split_once('?').map(|(_, query)| query);20 let current = href.split_once('?').map(|(_, query)| query);
21- let value = if request.query() == current {21+ if request.query() == current {
22 "public, max-age=31536000, immutable"22 "public, max-age=31536000, immutable"
23 } else {23 } else {
24 "no-cache"24 "no-cache"
25- };25+ }
26- topcoat::router::HeaderValue::from_static(value)26+}
27+
28+fn respond<B>(
29+ content_type: &'static str,
30+ cache: &'static str,
31+ body: B,
32+) -> (StatusCode, HeaderMap, B) {
33+ let mut headers = HeaderMap::new();
34+ headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
35+ headers.insert(header::CACHE_CONTROL, HeaderValue::from_static(cache));
36+ (StatusCode::OK, headers, body)
27 }37 }
28 38
29 const CSS: &str = forge_web_app::build_info::MAIN_CSS;39 const CSS: &str = forge_web_app::build_info::MAIN_CSS;
@@ -31,15 +41,7 @@ const CSS: &str = forge_web_app::build_info::MAIN_CSS;
31 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.41 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.
32 #[route(GET "/assets/main.css")]42 #[route(GET "/assets/main.css")]
33 async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {43 async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
34- let mut headers = HeaderMap::new();44+ Ok(respond("text/css; charset=utf-8", cache_for(cx, STYLESHEET_HREF), CSS))
35- headers.insert(
36- header::CONTENT_TYPE,
37- "text/css; charset=utf-8"
38- .parse()
39- .expect("static header value"),
40- );
41- headers.insert(header::CACHE_CONTROL, cache_for(cx, STYLESHEET_HREF));
42- Ok((StatusCode::OK, headers, CSS))
43 }45 }
44 46
45 /// The soft-navigation script (`assets/nav.js`). Served from the same origin, so the CSP's47 /// The soft-navigation script (`assets/nav.js`). Served from the same origin, so the CSP's
@@ -49,29 +51,17 @@ const NAV_JS: &str = include_str!("../../../forge-web/assets/nav.js");
49 /// Immutable like `main.css`: the URL carries a content hash.51 /// Immutable like `main.css`: the URL carries a content hash.
50 #[route(GET "/assets/nav.js")]52 #[route(GET "/assets/nav.js")]
51 async fn nav_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {53 async fn nav_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
52- let mut headers = HeaderMap::new();54+ Ok(respond("text/javascript; charset=utf-8", cache_for(cx, NAV_SCRIPT_HREF), NAV_JS))
53- headers.insert(
54- header::CONTENT_TYPE,
55- "text/javascript; charset=utf-8"
56- .parse()
57- .expect("static header value"),
58- );
59- headers.insert(header::CACHE_CONTROL, cache_for(cx, NAV_SCRIPT_HREF));
60- Ok((StatusCode::OK, headers, NAV_JS))
61 }55 }
62 56
63 /// Immutable like `main.css`: the URL carries a content hash.57 /// Immutable like `main.css`: the URL carries a content hash.
64 #[route(GET "/assets/highlight.css")]58 #[route(GET "/assets/highlight.css")]
65 async fn highlight_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {59 async fn highlight_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
66- let mut headers = HeaderMap::new();60+ Ok(respond(
67- headers.insert(61+ "text/css; charset=utf-8",
68- header::CONTENT_TYPE,62+ cache_for(cx, highlight_href()),
69- "text/css; charset=utf-8"63+ crate::views::highlight_css_text(),
70- .parse()64+ ))
71- .expect("static header value"),
72- );
73- headers.insert(header::CACHE_CONTROL, cache_for(cx, highlight_href()));
74- Ok((StatusCode::OK, headers, crate::views::highlight_css_text()))
75 }65 }
76 66
77 /// The colours of the hue choices on one page. The query names the four choices: `al` and `ad` for67 /// The colours of the hue choices on one page. The query names the four choices: `al` and `ad` for
@@ -101,20 +91,11 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> {
101 .map(|(id, hue, vivid)| (id.as_str(), *hue, *vivid))91 .map(|(id, hue, vivid)| (id.as_str(), *hue, *vivid))
102 });92 });
103 let css = custom_colour::stylesheet(accent_light, accent_dark, base_light, base_dark);93 let css = custom_colour::stylesheet(accent_light, accent_dark, base_light, base_dark);
104- let mut headers = HeaderMap::new();94+ Ok(respond(
105- headers.insert(95+ "text/css; charset=utf-8",
106- header::CONTENT_TYPE,96+ "public, max-age=31536000, immutable",
107- "text/css; charset=utf-8"97+ css,
108- .parse()98+ ))
109- .expect("static header value"),
110- );
111- headers.insert(
112- header::CACHE_CONTROL,
113- "public, max-age=31536000, immutable"
114- .parse()
115- .expect("static header value"),
116- );
117- Ok((StatusCode::OK, headers, css))
118 }99 }
119 100
120 // The offline page (shown by the service worker when a page load finds the server down) and its101 // The offline page (shown by the service worker when a page load finds the server down) and its
@@ -124,34 +105,12 @@ const OFFLINE_JS: &str = include_str!("../../../forge-web/assets/offline.js");
124 105
125 #[route(GET "/assets/offline.html")]106 #[route(GET "/assets/offline.html")]
126 async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {107 async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
127- let mut headers = HeaderMap::new();108+ Ok(respond("text/html; charset=utf-8", "no-cache", OFFLINE_HTML))
128- headers.insert(
129- header::CONTENT_TYPE,
130- "text/html; charset=utf-8"
131- .parse()
132- .expect("static header value"),
133- );
134- headers.insert(
135- header::CACHE_CONTROL,
136- "no-cache".parse().expect("static header value"),
137- );
138- Ok((StatusCode::OK, headers, OFFLINE_HTML))
139 }109 }
140 110
141 #[route(GET "/assets/offline.js")]111 #[route(GET "/assets/offline.js")]
142 async fn offline_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {112 async fn offline_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
143- let mut headers = HeaderMap::new();113+ Ok(respond("text/javascript; charset=utf-8", "no-cache", OFFLINE_JS))
144- headers.insert(
145- header::CONTENT_TYPE,
146- "text/javascript; charset=utf-8"
147- .parse()
148- .expect("static header value"),
149- );
150- headers.insert(
151- header::CACHE_CONTROL,
152- "no-cache".parse().expect("static header value"),
153- );
154- Ok((StatusCode::OK, headers, OFFLINE_JS))
155 }114 }
156 115
157 /// The stream every page and the offline page watch to learn that the server is back. It carries116 /// The stream every page and the offline page watch to learn that the server is back. It carries
@@ -186,93 +145,62 @@ const FIGTREE_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/Figtree-O
186 const PLEX_MONO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/IBMPlexMono-OFL.txt");145 const PLEX_MONO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/IBMPlexMono-OFL.txt");
187 const ARCHIVO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/Archivo-OFL.txt");146 const ARCHIVO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/Archivo-OFL.txt");
188 147
189-type Bytes = (StatusCode, HeaderMap, &'static [u8]);
190-
191-fn bytes_response(body: &'static [u8], content_type: &'static str, cache: &'static str) -> Bytes {
192- let mut headers = HeaderMap::new();
193- headers.insert(
194- header::CONTENT_TYPE,
195- content_type.parse().expect("static header value"),
196- );
197- headers.insert(
198- header::CACHE_CONTROL,
199- cache.parse().expect("static header value"),
200- );
201- (StatusCode::OK, headers, body)
202-}
203-
204 const FONT_CACHE: &str = "public, max-age=31536000, immutable";148 const FONT_CACHE: &str = "public, max-age=31536000, immutable";
205 const LICENSE_CACHE: &str = "public, max-age=86400";149 const LICENSE_CACHE: &str = "public, max-age=86400";
206 150
207 #[route(GET "/assets/fonts/figtree-5.3.0-latin-wght.woff2")]151 #[route(GET "/assets/fonts/figtree-5.3.0-latin-wght.woff2")]
208-async fn figtree_latin(cx: &Cx) -> Result<Bytes> {152+async fn figtree_latin(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
209- Ok(bytes_response(FIGTREE_LATIN, "font/woff2", FONT_CACHE))153+ Ok(respond("font/woff2", FONT_CACHE, FIGTREE_LATIN))
210 }154 }
211 155
212 #[route(GET "/assets/fonts/figtree-5.3.0-latin-ext-wght.woff2")]156 #[route(GET "/assets/fonts/figtree-5.3.0-latin-ext-wght.woff2")]
213-async fn figtree_latin_ext(cx: &Cx) -> Result<Bytes> {157+async fn figtree_latin_ext(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
214- Ok(bytes_response(FIGTREE_LATIN_EXT, "font/woff2", FONT_CACHE))158+ Ok(respond("font/woff2", FONT_CACHE, FIGTREE_LATIN_EXT))
215 }159 }
216 160
217 #[route(GET "/assets/fonts/archivo-5.3.0-latin-wdth.woff2")]161 #[route(GET "/assets/fonts/archivo-5.3.0-latin-wdth.woff2")]
218-async fn archivo_latin(cx: &Cx) -> Result<Bytes> {162+async fn archivo_latin(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
219- Ok(bytes_response(ARCHIVO_LATIN, "font/woff2", FONT_CACHE))163+ Ok(respond("font/woff2", FONT_CACHE, ARCHIVO_LATIN))
220 }164 }
221 165
222 #[route(GET "/assets/fonts/archivo-5.3.0-latin-ext-wdth.woff2")]166 #[route(GET "/assets/fonts/archivo-5.3.0-latin-ext-wdth.woff2")]
223-async fn archivo_latin_ext(cx: &Cx) -> Result<Bytes> {167+async fn archivo_latin_ext(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
224- Ok(bytes_response(ARCHIVO_LATIN_EXT, "font/woff2", FONT_CACHE))168+ Ok(respond("font/woff2", FONT_CACHE, ARCHIVO_LATIN_EXT))
225 }169 }
226 170
227 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400.woff2")]171 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400.woff2")]
228-async fn plex_mono_400(cx: &Cx) -> Result<Bytes> {172+async fn plex_mono_400(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
229- Ok(bytes_response(PLEX_MONO_400, "font/woff2", FONT_CACHE))173+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_400))
230 }174 }
231 175
232 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-500.woff2")]176 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-500.woff2")]
233-async fn plex_mono_500(cx: &Cx) -> Result<Bytes> {177+async fn plex_mono_500(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
234- Ok(bytes_response(PLEX_MONO_500, "font/woff2", FONT_CACHE))178+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_500))
235 }179 }
236 180
237 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-600.woff2")]181 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-600.woff2")]
238-async fn plex_mono_600(cx: &Cx) -> Result<Bytes> {182+async fn plex_mono_600(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
239- Ok(bytes_response(PLEX_MONO_600, "font/woff2", FONT_CACHE))183+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_600))
240 }184 }
241 185
242 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400-italic.woff2")]186 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400-italic.woff2")]
243-async fn plex_mono_400_italic(cx: &Cx) -> Result<Bytes> {187+async fn plex_mono_400_italic(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
244- Ok(bytes_response(188+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_400_ITALIC))
245- PLEX_MONO_400_ITALIC,
246- "font/woff2",
247- FONT_CACHE,
248- ))
249 }189 }
250 190
251 #[route(GET "/assets/fonts/Figtree-OFL.txt")]191 #[route(GET "/assets/fonts/Figtree-OFL.txt")]
252-async fn figtree_license(cx: &Cx) -> Result<Bytes> {192+async fn figtree_license(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
253- Ok(bytes_response(193+ Ok(respond("text/plain; charset=utf-8", LICENSE_CACHE, FIGTREE_LICENSE))
254- FIGTREE_LICENSE,
255- "text/plain; charset=utf-8",
256- LICENSE_CACHE,
257- ))
258 }194 }
259 195
260 #[route(GET "/assets/fonts/Archivo-OFL.txt")]196 #[route(GET "/assets/fonts/Archivo-OFL.txt")]
261-async fn archivo_license(cx: &Cx) -> Result<Bytes> {197+async fn archivo_license(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
262- Ok(bytes_response(198+ Ok(respond("text/plain; charset=utf-8", LICENSE_CACHE, ARCHIVO_LICENSE))
263- ARCHIVO_LICENSE,
264- "text/plain; charset=utf-8",
265- LICENSE_CACHE,
266- ))
267 }199 }
268 200
269 #[route(GET "/assets/fonts/IBMPlexMono-OFL.txt")]201 #[route(GET "/assets/fonts/IBMPlexMono-OFL.txt")]
270-async fn plex_mono_license(cx: &Cx) -> Result<Bytes> {202+async fn plex_mono_license(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
271- Ok(bytes_response(203+ Ok(respond("text/plain; charset=utf-8", LICENSE_CACHE, PLEX_MONO_LICENSE))
272- PLEX_MONO_LICENSE,
273- "text/plain; charset=utf-8",
274- LICENSE_CACHE,
275- ))
276 }204 }
277 205
278 #[cfg(test)]206 #[cfg(test)]
crates/forge-web-account/src/pages/audit_log.rsmodified+15 -37
@@ -50,9 +50,6 @@ pub(crate) struct AuditQuery {
50 to: Option<String>,50 to: Option<String>,
51 exact: Option<String>,51 exact: Option<String>,
52 case: Option<String>,52 case: Option<String>,
53- /// Old cursor links. Still accepted so old bookmarks load, and ignored.
54- #[allow(dead_code)]
55- before: Option<String>,
56 /// The 1-based page number. Anything unreadable is page 1.53 /// The 1-based page number. Anything unreadable is page 1.
57 page: Option<String>,54 page: Option<String>,
58 }55 }
@@ -196,27 +193,12 @@ impl Group {
196 &self.rows[0]193 &self.rows[0]
197 }194 }
198 195
199- /// The target when every entry has the same one.196+ /// The value of `field` when every entry has the same one.
200- fn shared_target(&self) -> Option<&str> {197+ fn shared<'a>(&'a self, field: fn(&RowView) -> &str) -> Option<&'a str> {
201- let first = self.first().target.as_str();198+ let first = field(self.first());
202 self.rows199 self.rows
203 .iter()200 .iter()
204- .all(|row| row.target == first)201+ .all(|row| field(row) == first)
205- .then_some(first)
206- }
207-
208- /// The IP when every entry came from the same one.
209- fn shared_ip(&self) -> Option<&str> {
210- let first = self.first().ip.as_str();
211- self.rows.iter().all(|row| row.ip == first).then_some(first)
212- }
213-
214- /// The details when every entry has the same.
215- fn shared_details(&self) -> Option<&str> {
216- let first = self.first().details.as_str();
217- self.rows
218- .iter()
219- .all(|row| row.details == first)
220 .then_some(first)202 .then_some(first)
221 }203 }
222 }204 }
@@ -298,9 +280,10 @@ fn details_words(lang: Lang, data: &str) -> String {
298 }280 }
299 281
300 fn row_view(entry: &AuditEntry, lang: Lang) -> RowView {282 fn row_view(entry: &AuditEntry, lang: Lang) -> RowView {
301- let actor = match (entry.actor_name.as_str(), entry.actor_id.is_some()) {283+ let actor = if entry.actor_name.is_empty() {
302- ("", _) => g::t(lang, K::Anonymous).to_owned(),284+ g::t(lang, K::Anonymous).to_owned()
303- (name, _) => name.to_owned(),285+ } else {
286+ entry.actor_name.clone()
304 };287 };
305 let name = if entry.target_name.is_empty() {288 let name = if entry.target_name.is_empty() {
306 entry.target_id.as_str()289 entry.target_id.as_str()
@@ -369,19 +352,14 @@ fn requested_page(query: &AuditQuery) -> u64 {
369 }352 }
370 353
371 /// The groups of one page, the page clamped to the pages there are, and the page count.354 /// The groups of one page, the page clamped to the pages there are, and the page count.
372-fn page_of(mut groups: Vec<Group>, page: u64) -> (Vec<Group>, u64, u64) {355+fn page_of(groups: Vec<Group>, page: u64) -> (Vec<Group>, u64, u64) {
373 let pages = (groups.len() as u64).div_ceil(PAGE_ROWS as u64).max(1);356 let pages = (groups.len() as u64).div_ceil(PAGE_ROWS as u64).max(1);
374 let page = page.clamp(1, pages);357 let page = page.clamp(1, pages);
375 let start = (page - 1) as usize * PAGE_ROWS;358 let start = (page - 1) as usize * PAGE_ROWS;
376- let shown: Vec<Group> = groups.drain(..).skip(start).take(PAGE_ROWS).collect();359+ let shown: Vec<Group> = groups.into_iter().skip(start).take(PAGE_ROWS).collect();
377 (shown, page, pages)360 (shown, page, pages)
378 }361 }
379 362
380-/// The newest entries the filter selects, as many as a search reads.
381-async fn fetch_entries(store: &Store, filter: &AuditFilter) -> forge_core::Result<Vec<AuditEntry>> {
382- store.list_audit_page(filter, 0, SEARCH_CAP).await
383-}
384-
385 /// The numbered pager's entries and links for `page` of `pages`, under `base` with `params`.363 /// The numbered pager's entries and links for `page` of `pages`, under `base` with `params`.
386 fn nav_for(364 fn nav_for(
387 page: u64,365 page: u64,
@@ -523,13 +501,13 @@ async fn single_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) ->
523 #[component]501 #[component]
524 async fn group_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) -> Result<impl View> {502 async fn group_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) -> Result<impl View> {
525 let count = group.rows.len().to_string();503 let count = group.rows.len().to_string();
526- let target = group.shared_target().map(str::to_owned);504+ let target = group.shared(|row| &row.target).map(str::to_owned);
527 let ip = group505 let ip = group
528- .shared_ip()506+ .shared(|row| &row.ip)
529 .map(str::to_owned)507 .map(str::to_owned)
530 .filter(|ip| !ip.is_empty());508 .filter(|ip| !ip.is_empty());
531 let details = group509 let details = group
532- .shared_details()510+ .shared(|row| &row.details)
533 .map(str::to_owned)511 .map(str::to_owned)
534 .filter(|d| !d.is_empty());512 .filter(|d| !d.is_empty());
535 let mut seen: Vec<String> = group.rows.iter().map(|row| row.target.clone()).collect();513 let mut seen: Vec<String> = group.rows.iter().map(|row| row.target.clone()).collect();
@@ -702,7 +680,7 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> {
702 let entries = if notice.is_some() {680 let entries = if notice.is_some() {
703 Vec::new()681 Vec::new()
704 } else {682 } else {
705- fetch_entries(store, &filter).await?683+ store.list_audit_page(&filter, 0, SEARCH_CAP).await?
706 };684 };
707 let groups = fold_groups(&entries, lang, &finder);685 let groups = fold_groups(&entries, lang, &finder);
708 let total = groups.iter().map(|group| group.rows.len()).sum();686 let total = groups.iter().map(|group| group.rows.len()).sum();
@@ -778,7 +756,7 @@ async fn own_log_page(cx: &Cx) -> Result<impl View> {
778 if let Some(known) = AuditAction::parse(&action) {756 if let Some(known) = AuditAction::parse(&action) {
779 filter.action = Some(known);757 filter.action = Some(known);
780 }758 }
781- let entries = fetch_entries(store, &filter).await?;759+ let entries = store.list_audit_page(&filter, 0, SEARCH_CAP).await?;
782 let groups = fold_groups(&entries, lang, &finder);760 let groups = fold_groups(&entries, lang, &finder);
783 let total = groups.iter().map(|group| group.rows.len()).sum();761 let total = groups.iter().map(|group| group.rows.len()).sum();
784 let (groups, page, pages) = page_of(groups, requested_page(query));762 let (groups, page, pages) = page_of(groups, requested_page(query));
crates/forge-web-account/src/pages/explore.rsmodified+22 -14
@@ -65,7 +65,11 @@ fn orgs_href(finder: &Finder, page: u64) -> String {
65 }65 }
66 66
67 /// The organizations the search matches, by name, and how many there are: one page.67 /// The organizations the search matches, by name, and how many there are: one page.
68-async fn org_listing(state: &AppState, finder: &Finder, page: u64) -> Result<(Vec<User>, u64)> {68+async fn org_listing(
69+ state: &AppState,
70+ finder: &Finder,
71+ page: u64,
72+) -> Result<(Vec<User>, u64, u64)> {
69 let mut all: Vec<User> = state73 let mut all: Vec<User> = state
70 .store74 .store
71 .list_orgs()75 .list_orgs()
@@ -80,12 +84,13 @@ async fn org_listing(state: &AppState, finder: &Finder, page: u64) -> Result<(Ve
80 .collect();84 .collect();
81 all.sort_by_key(|org| org.username.to_lowercase());85 all.sort_by_key(|org| org.username.to_lowercase());
82 let total = all.len() as u64;86 let total = all.len() as u64;
87+ let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1));
83 let shown = all88 let shown = all
84 .into_iter()89 .into_iter()
85- .skip(((page.max(1) - 1) * PER_PAGE) as usize)90+ .skip(((page - 1) * PER_PAGE) as usize)
86 .take(PER_PAGE as usize)91 .take(PER_PAGE as usize)
87 .collect();92 .collect();
88- Ok((shown, total))93+ Ok((shown, total, page))
89 }94 }
90 95
91 /// `/explore` with the given search, sort key and page. An empty search is left out.96 /// `/explore` with the given search, sort key and page. An empty search is left out.
@@ -129,7 +134,7 @@ async fn listing(
129 finder: &Finder,134 finder: &Finder,
130 sort: &'static str,135 sort: &'static str,
131 page: u64,136 page: u64,
132-) -> Result<(Vec<(Repo, u64, String)>, u64)> {137+) -> Result<(Vec<(Repo, u64, String)>, u64, u64)> {
133 let sort_kind = match sort {138 let sort_kind = match sort {
134 "stars" => RepoSort::MostStars,139 "stars" => RepoSort::MostStars,
135 "name" => RepoSort::Name,140 "name" => RepoSort::Name,
@@ -147,26 +152,30 @@ async fn listing(
147 })152 })
148 .collect();153 .collect();
149 let total = matching.len() as u64;154 let total = matching.len() as u64;
155+ let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1));
150 let shown = matching156 let shown = matching
151 .into_iter()157 .into_iter()
152- .skip(((page.max(1) - 1) * PER_PAGE) as usize)158+ .skip(((page - 1) * PER_PAGE) as usize)
153 .take(PER_PAGE as usize)159 .take(PER_PAGE as usize)
154 .collect();160 .collect();
155- Ok((shown, total))161+ Ok((shown, total, page))
156 }162 }
157 163
158 #[page("/explore")]164 #[page("/explore")]
159 async fn explore_page(cx: &Cx) -> Result<impl View> {165 async fn explore_page(cx: &Cx) -> Result<impl View> {
160 let query = query_params::<ExploreQuery>(cx)?;166 let query = query_params::<ExploreQuery>(cx)?;
161 let (finder, sort, page) = listing_args(query);167 let (finder, sort, page) = listing_args(query);
162- let live = explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1);
163 let viewer = current_user(cx).await?;168 let viewer = current_user(cx).await?;
164 let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u));169 let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u));
165 let state = context::<AppState>(cx);170 let state = context::<AppState>(cx);
166 let on_orgs = orgs_tab(query);171 let on_orgs = orgs_tab(query);
167- let (listed, repo_total) = listing(state, &finder, sort, page).await?;172+ let (listed, org_page, total, page) = if on_orgs {
168- let (org_page, org_total) = org_listing(state, &finder, page).await?;173+ let (orgs, total, page) = org_listing(state, &finder, page).await?;
169- let total = if on_orgs { org_total } else { repo_total };174+ (Vec::new(), orgs, total, page)
175+ } else {
176+ let (repos, total, page) = listing(state, &finder, sort, page).await?;
177+ (repos, Vec::new(), total, page)
178+ };
170 let (_, repos_all) = state179 let (_, repos_all) = state
171 .store180 .store
172 .list_public_repos(None, RepoSort::RecentlyUpdated, 1, 1)181 .list_public_repos(None, RepoSort::RecentlyUpdated, 1, 1)
@@ -175,7 +184,7 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
175 let live = if on_orgs {184 let live = if on_orgs {
176 orgs_href(&finder, page).replacen("/explore?", "/explore/events?", 1)185 orgs_href(&finder, page).replacen("/explore?", "/explore/events?", 1)
177 } else {186 } else {
178- live187+ explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1)
179 };188 };
180 189
181 let now = now_unix();190 let now = now_unix();
@@ -191,7 +200,6 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
191 orgs.push((org.username, avatar));200 orgs.push((org.username, avatar));
192 }201 }
193 let pages = total.div_ceil(PER_PAGE).max(1);202 let pages = total.div_ceil(PER_PAGE).max(1);
194- let page = page.min(pages);
195 let sort_links: Vec<SortLink> = SORTS203 let sort_links: Vec<SortLink> = SORTS
196 .iter()204 .iter()
197 .map(|(key, label)| SortLink {205 .map(|(key, label)| SortLink {
@@ -255,12 +263,12 @@ async fn explore_fingerprint(
255 on_orgs: bool,263 on_orgs: bool,
256 ) -> Result<String> {264 ) -> Result<String> {
257 if on_orgs {265 if on_orgs {
258- let (orgs, total) = org_listing(state, finder, page).await?;266+ let (orgs, total, _) = org_listing(state, finder, page).await?;
259 let mut lines = vec![total.to_string()];267 let mut lines = vec![total.to_string()];
260 lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username)));268 lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username)));
261 return Ok(lines.join("\n"));269 return Ok(lines.join("\n"));
262 }270 }
263- let (listed, total) = listing(state, finder, sort, page).await?;271+ let (listed, total, _) = listing(state, finder, sort, page).await?;
264 let mut lines = vec![total.to_string()];272 let mut lines = vec![total.to_string()];
265 for (repo, stars, activity) in listed {273 for (repo, stars, activity) in listed {
266 lines.push(format!(274 lines.push(format!(
crates/forge-web-account/src/pages/forgot.rsmodified+4 -6
@@ -221,9 +221,7 @@ async fn reset_submit(cx: &Cx, Form(form): Form<ResetForm>) -> Result<impl View>
221 Some(user_id) => {221 Some(user_id) => {
222 // The link is spent before the slow hash, so two redemptions cannot both pass.222 // The link is spent before the slow hash, so two redemptions cannot both pass.
223 let hash = hash_password_async(form.password.clone()).await?;223 let hash = hash_password_async(form.password.clone()).await?;
224- state.store.set_password_hash(&user_id, &hash).await?;224+ state.store.reset_password(&user_id, &hash).await?;
225- // Every session of the account ends, including the one that asked for the reset.
226- state.store.delete_user_sessions(&user_id).await?;
227 if let Some(user) = state.store.user_by_id(&user_id).await? {225 if let Some(user) = state.store.user_by_id(&user_id).await? {
228 audit::record(226 audit::record(
229 &state.store,227 &state.store,
@@ -300,9 +298,9 @@ mod tests {
300 assert_eq!(status, 200, "{address}");298 assert_eq!(status, 200, "{address}");
301 assert!(html.contains("a reset link is on its way"), "{address}");299 assert!(html.contains("a reset link is on its way"), "{address}");
302 }300 }
303- // Give the spawned lookups time to finish, then check that nothing was queued: Frank has301+ for address in ["nobody@example.com", "frank@example.com"] {
304- // no verified address, so his account gets no mail.302+ send_reset_if_verified(state, address).await.unwrap();
305- tokio::time::sleep(Duration::from_millis(200)).await;303+ }
306 let mail = state.store.recent_mail(20).await.unwrap();304 let mail = state.store.recent_mail(20).await.unwrap();
307 assert!(mail.iter().all(|m| !m.body.contains("/reset/")));305 assert!(mail.iter().all(|m| !m.body.contains("/reset/")));
308 }306 }
crates/forge-web-account/src/pages/import.rsmodified+26 -120
@@ -1,7 +1,3 @@
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;1 use std::collections::HashMap;
6 2
7 use forge_core::store::imports::{ImportJob, ImportState};3 use forge_core::store::imports::{ImportJob, ImportState};
@@ -21,7 +17,7 @@ use crate::audit::{self, Actor, Target};
21 use crate::auth::{require_csrf, require_user};17 use crate::auth::{require_csrf, require_user};
22 use crate::i18n::migrate::{self as g, K};18 use crate::i18n::migrate::{self as g, K};
23 use crate::i18n::{self, Lang};19 use crate::i18n::{self, Lang};
24-use crate::importer::api::{ApiError, RemoteApi};20+use crate::importer::api::{ApiError, ExtRepo, RemoteApi};
25 use crate::importer::{21 use crate::importer::{
26 self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab,22 self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab,
27 parse_remote, source_ref,23 parse_remote, source_ref,
@@ -37,7 +33,6 @@ use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message};
37 33
38 path_param!(job_id);34 path_param!(job_id);
39 35
40-/// Most repositories one bulk submit starts.
41 const MAX_BULK: usize = 50;36 const MAX_BULK: usize = 50;
42 const DEFAULT_BRANCH: &str = "main";37 const DEFAULT_BRANCH: &str = "main";
43 38
@@ -99,7 +94,6 @@ struct BulkForm {
99 opt_pulls: String,94 opt_pulls: String,
100 #[serde(default)]95 #[serde(default)]
101 opt_releases: String,96 opt_releases: String,
102- /// The ticked repositories arrive as `sel_0`, `sel_1`, ... with the repository as the value.
103 #[serde(flatten)]97 #[serde(flatten)]
104 extra: HashMap<String, String>,98 extra: HashMap<String, String>,
105 }99 }
@@ -112,9 +106,7 @@ struct SourceQuery {
112 106
113 #[query_params(error = bad_request)]107 #[query_params(error = bad_request)]
114 struct JobsQuery {108 struct JobsQuery {
115- /// The repositories a bulk import left out, with why, as one line.
116 skipped: Option<String>,109 skipped: Option<String>,
117- /// The 1-based page of the history.
118 page: Option<String>,110 page: Option<String>,
119 }111 }
120 112
@@ -136,7 +128,6 @@ fn source_of(raw: Option<&str>) -> Source {
136 raw.and_then(Source::parse).unwrap_or(Source::GitHub)128 raw.and_then(Source::parse).unwrap_or(Source::GitHub)
137 }129 }
138 130
139-/// The instance a source form starts with.
140 fn default_instance(source: Source) -> &'static str {131 fn default_instance(source: Source) -> &'static str {
141 match source {132 match source {
142 Source::Forgejo => "https://codeberg.org",133 Source::Forgejo => "https://codeberg.org",
@@ -144,7 +135,6 @@ fn default_instance(source: Source) -> &'static str {
144 }135 }
145 }136 }
146 137
147-/// Sources that are self-hostable and so take an instance address.
148 fn has_instance(source: Source) -> bool {138 fn has_instance(source: Source) -> bool {
149 matches!(source, Source::GitLab | Source::Forgejo)139 matches!(source, Source::GitLab | Source::Forgejo)
150 }140 }
@@ -162,8 +152,6 @@ fn token_of(raw: &str) -> Option<String> {
162 (!t.is_empty()).then(|| t.to_owned())152 (!t.is_empty()).then(|| t.to_owned())
163 }153 }
164 154
165-// ---- shared pieces ----
166-
167 #[component]155 #[component]
168 pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<impl View> {156 pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<impl View> {
169 let create = active == "create";157 let create = active == "create";
@@ -197,7 +185,6 @@ async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result<
197 })185 })
198 }186 }
199 187
200-/// Public or private, as two switches with what each means under it. Shared with the create page.
201 #[component]188 #[component]
202 pub(crate) async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result<impl View> {189 pub(crate) async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result<impl View> {
203 Ok(view! {190 Ok(view! {
@@ -226,8 +213,6 @@ async fn option_boxes(cx: &Cx, lang: Lang, opts: ImportOptions) -> Result<impl V
226 })213 })
227 }214 }
228 215
229-// ---- single import ----
230-
231 struct Draft {216 struct Draft {
232 source: Source,217 source: Source,
233 remote: String,218 remote: String,
@@ -260,7 +245,6 @@ impl Draft {
260 }245 }
261 }246 }
262 247
263- /// The submitted values, never the token.
264 fn from_form(form: &ImportForm, source: Source) -> Self {248 fn from_form(form: &ImportForm, source: Source) -> Self {
265 Draft {249 Draft {
266 source,250 source,
@@ -325,7 +309,7 @@ async fn import_form(
325 let opts = draft.opts;309 let opts = draft.opts;
326 Ok(view! {310 Ok(view! {
327 head(title: g::t(lang, K::ImportTitle))311 head(title: g::t(lang, K::ImportTitle))
328- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())312+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
329 newrepo_tabs(lang: lang, active: "import")313 newrepo_tabs(lang: lang, active: "import")
330 <div class="sheet fit">314 <div class="sheet fit">
331 <form method="post" action="/new/import" class="fields">315 <form method="post" action="/new/import" class="fields">
@@ -389,7 +373,6 @@ async fn import_form(
389 })373 })
390 }374 }
391 375
392-/// The GET import page: the form. Past imports are on the Import history tab.
393 #[component]376 #[component]
394 async fn import_home(377 async fn import_home(
395 cx: &Cx,378 cx: &Cx,
@@ -404,7 +387,6 @@ async fn import_home(
404 })387 })
405 }388 }
406 389
407-/// The import form again after a rejected submit.
408 #[component]390 #[component]
409 async fn import_error_body(391 async fn import_error_body(
410 cx: &Cx,392 cx: &Cx,
@@ -454,8 +436,6 @@ async fn import_submit(cx: &Cx, Form(form): Form<ImportForm>) -> Result<impl Vie
454 }436 }
455 }437 }
456 438
457-/// Validates the form, creates the repo and the job, and starts it. `Ok(Err(message))` is a
458-/// rejection to show; the token is never part of what is returned.
459 async fn start_single(439 async fn start_single(
460 cx: &Cx,440 cx: &Cx,
461 viewer: &User,441 viewer: &User,
@@ -519,7 +499,6 @@ async fn start_single(
519 .await499 .await
520 }500 }
521 501
522-/// Creates the repo and the import job for `spec` and starts it. `Ok(Err(message))` is a rejection.
523 async fn begin(502 async fn begin(
524 cx: &Cx,503 cx: &Cx,
525 actor: &User,504 actor: &User,
@@ -558,9 +537,10 @@ async fn begin(
558 };537 };
559 let path = repo_path(&state.config.data_dir, &repo.id)?;538 let path = repo_path(&state.config.data_dir, &repo.id)?;
560 if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await {539 if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await {
540+ state.store.delete_repo(&repo.id).await?;
561 return Ok(Err(crate::i18n::misc::git_init_failed(lang, e)));541 return Ok(Err(crate::i18n::misc::git_init_failed(lang, e)));
562 }542 }
563- let job = state543+ let job = match state
564 .store544 .store
565 .create_import_job(545 .create_import_job(
566 &actor.id,546 &actor.id,
@@ -569,7 +549,14 @@ async fn begin(
569 &source_ref(spec.source, &spec.remote, &spec.instance),549 &source_ref(spec.source, &spec.remote, &spec.instance),
570 &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()),550 &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()),
571 )551 )
572- .await?;552+ .await
553+ {
554+ Ok(job) => job,
555+ Err(e) => {
556+ state.store.delete_repo(&repo.id).await?;
557+ return Err(e.into());
558+ }
559+ };
573 let full_name = format!("{}/{}", repo.owner_name, repo.name);560 let full_name = format!("{}/{}", repo.owner_name, repo.name);
574 audit::record(561 audit::record(
575 &state.store,562 &state.store,
@@ -588,8 +575,6 @@ async fn begin(
588 Ok(Ok(job.id))575 Ok(Ok(job.id))
589 }576 }
590 577
591-// ---- bulk import ----
592-
593 #[component]578 #[component]
594 async fn bulk_form(579 async fn bulk_form(
595 cx: &Cx,580 cx: &Cx,
@@ -609,11 +594,10 @@ async fn bulk_form(
609 Source::Forgejo => g::t(lang, K::BulkOwnerForgejo),594 Source::Forgejo => g::t(lang, K::BulkOwnerForgejo),
610 _ => g::t(lang, K::BulkOwnerGitHub),595 _ => g::t(lang, K::BulkOwnerGitHub),
611 };596 };
612- // A Forgejo token can list its own repositories, so the owner may stay empty.
613 let owner_required = source != Source::Forgejo;597 let owner_required = source != Source::Forgejo;
614 Ok(view! {598 Ok(view! {
615 head(title: g::t(lang, K::BulkTitle))599 head(title: g::t(lang, K::BulkTitle))
616- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())600+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
617 newrepo_tabs(lang: lang, active: "import")601 newrepo_tabs(lang: lang, active: "import")
618 <div class="sheet fit">602 <div class="sheet fit">
619 <form method="post" action="/new/import/bulk" class="fields">603 <form method="post" action="/new/import/bulk" class="fields">
@@ -645,15 +629,6 @@ async fn bulk_form(
645 })629 })
646 }630 }
647 631
648-struct Listed {
649- name: String,
650- full_name: String,
651- description: String,
652- private: bool,
653- fork: bool,
654- archived: bool,
655-}
656-
657 #[component]632 #[component]
658 async fn bulk_select(633 async fn bulk_select(
659 cx: &Cx,634 cx: &Cx,
@@ -661,13 +636,11 @@ async fn bulk_select(
661 username: String,636 username: String,
662 csrf: &str,637 csrf: &str,
663 form: BulkFormEcho,638 form: BulkFormEcho,
664- repos: Vec<Listed>,639+ repos: Vec<ExtRepo>,
665 owners: Vec<String>,640 owners: Vec<String>,
666 ) -> Result<impl View> {641 ) -> Result<impl View> {
667 let count = repos.len();642 let count = repos.len();
668 let empty = repos.is_empty();643 let empty = repos.is_empty();
669- let private = form.private;
670- let opts = form.opts;
671 let selected_owner = if form.owner.is_empty() {644 let selected_owner = if form.owner.is_empty() {
672 owners.first().cloned().unwrap_or_default()645 owners.first().cloned().unwrap_or_default()
673 } else {646 } else {
@@ -675,7 +648,7 @@ async fn bulk_select(
675 };648 };
676 Ok(view! {649 Ok(view! {
677 head(title: g::t(lang, K::BulkSelectHeading))650 head(title: g::t(lang, K::BulkSelectHeading))
678- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())651+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
679 newrepo_tabs(lang: lang, active: "import")652 newrepo_tabs(lang: lang, active: "import")
680 <div class="sheet">653 <div class="sheet">
681 <form method="post" action="/new/import/bulk" class="fields">654 <form method="post" action="/new/import/bulk" class="fields">
@@ -696,10 +669,8 @@ async fn bulk_select(
696 }669 }
697 </select>670 </select>
698 </div>671 </div>
699- visibility_pick(lang: lang, private: private)672+ visibility_pick(lang: lang, private: false)
700- if form.source != "git" {673+ option_boxes(lang: lang, opts: ImportOptions { labels: true, issues: true, pulls: true, releases: true })
701- option_boxes(lang: lang, opts: opts)
702- }
703 <label class="line" data-kb-row="">674 <label class="line" data-kb-row="">
704 <input type="checkbox" data-select-all=".import-pick-list">675 <input type="checkbox" data-select-all=".import-pick-list">
705 <span class="name">(g::t(lang, K::BulkSelectAll))</span>676 <span class="name">(g::t(lang, K::BulkSelectAll))</span>
@@ -732,16 +703,12 @@ async fn bulk_select(
732 })703 })
733 }704 }
734 705
735-/// The bulk form's values carried to the selection step (the token is in a hidden field, sent back
736-/// once; the server never stores it).
737 struct BulkFormEcho {706 struct BulkFormEcho {
738 source: String,707 source: String,
739 instance: String,708 instance: String,
740 token: String,709 token: String,
741 from: String,710 from: String,
742 owner: String,711 owner: String,
743- private: bool,
744- opts: ImportOptions,
745 }712 }
746 713
747 #[page("/new/import/bulk")]714 #[page("/new/import/bulk")]
@@ -761,20 +728,14 @@ async fn bulk_page(cx: &Cx) -> Result<impl View> {
761 })728 })
762 }729 }
763 730
764-fn notice_for(state: &AppState) -> importer::api::Notice {
765- let _ = state;
766- std::sync::Arc::new(|_msg: String| {})
767-}
768-
769-/// Lists the repos of `from` through the API. The error text is safe to show.
770 async fn list_remote(731 async fn list_remote(
771 state: &AppState,732 state: &AppState,
772 source: Source,733 source: Source,
773 instance: &str,734 instance: &str,
774 from: &str,735 from: &str,
775 token: Option<String>,736 token: Option<String>,
776-) -> std::result::Result<Vec<importer::api::ExtRepo>, String> {737+) -> std::result::Result<Vec<ExtRepo>, String> {
777- let notice = notice_for(state);738+ let notice: importer::api::Notice = std::sync::Arc::new(|_msg: String| {});
778 let listed = match source {739 let listed = match source {
779 Source::GitLab => {740 Source::GitLab => {
780 make_gitlab(state, instance, token, notice)?741 make_gitlab(state, instance, token, notice)?
@@ -815,7 +776,6 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
815 776
816 let from = form.from.trim();777 let from = form.from.trim();
817 let owner_max = if source == Source::GitLab { 20 } else { 1 };778 let owner_max = if source == Source::GitLab { 20 } else { 1 };
818- // Forgejo lists the token's own repositories for an empty owner.
819 let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some();779 let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some();
820 let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max);780 let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max);
821 let result = if bad_owner {781 let result = if bad_owner {
@@ -826,32 +786,14 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
826 let (error, picker) = match result {786 let (error, picker) = match result {
827 Err(message) => (Some(message), None),787 Err(message) => (Some(message), None),
828 Ok(found) => {788 Ok(found) => {
829- let repos: Vec<Listed> = found
830- .into_iter()
831- .map(|r| Listed {
832- name: r.name,
833- full_name: r.full_name,
834- description: r.description,
835- private: r.private,
836- fork: r.fork,
837- archived: r.archived,
838- })
839- .collect();
840 let echo = BulkFormEcho {789 let echo = BulkFormEcho {
841 source: source.as_str().to_owned(),790 source: source.as_str().to_owned(),
842 instance: instance.clone(),791 instance: instance.clone(),
843 token: form.token.trim().to_owned(),792 token: form.token.trim().to_owned(),
844 from: from.to_owned(),793 from: from.to_owned(),
845 owner: form.owner.trim().to_owned(),794 owner: form.owner.trim().to_owned(),
846- private: false,
847- opts: ImportOptions {
848- labels: true,
849- issues: true,
850- pulls: true,
851- releases: true,
852- },
853 };795 };
854- (None, Some((echo, repos)))796+ (None, Some((echo, found)))
855 }797 }
856 };798 };
857 Ok(view! {799 Ok(view! {
@@ -860,7 +802,6 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
860 })802 })
861 }803 }
862 804
863-/// The bulk page body: the picker once a listing exists, the lookup form otherwise.
864 #[component]805 #[component]
865 async fn bulk_stage(806 async fn bulk_stage(
866 cx: &Cx,807 cx: &Cx,
@@ -871,7 +812,7 @@ async fn bulk_stage(
871 instance: &str,812 instance: &str,
872 owners: Vec<String>,813 owners: Vec<String>,
873 error: Option<String>,814 error: Option<String>,
874- picker: Option<(BulkFormEcho, Vec<Listed>)>,815+ picker: Option<(BulkFormEcho, Vec<ExtRepo>)>,
875 ) -> Result<impl View> {816 ) -> Result<impl View> {
876 Ok(view! {817 Ok(view! {
877 if let Some((echo, repos)) = picker {818 if let Some((echo, repos)) = picker {
@@ -882,7 +823,6 @@ async fn bulk_stage(
882 })823 })
883 }824 }
884 825
885-/// Starts one job per ticked repository, then shows the imports list.
886 async fn run_bulk(826 async fn run_bulk(
887 cx: &Cx,827 cx: &Cx,
888 viewer: &User,828 viewer: &User,
@@ -948,8 +888,6 @@ async fn run_bulk(
948 options,888 options,
949 };889 };
950 let name = default_name(&remote);890 let name = default_name(&remote);
951- // The repository from a failed import of this source is there already: retry that import
952- // instead of refusing the name as taken.
953 if let Some(repo) = state891 if let Some(repo) = state
954 .store892 .store
955 .repo_by_owner_and_name(&target.username, &name)893 .repo_by_owner_and_name(&target.username, &name)
@@ -961,7 +899,6 @@ async fn run_bulk(
961 retry_job(state, job.clone(), &form.token).await?;899 retry_job(state, job.clone(), &form.token).await?;
962 continue;900 continue;
963 }901 }
964- // A name already taken, or any refusal, skips that one; the list page says which and why.
965 if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? {902 if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? {
966 tracing::info!(repo = %remote, %message, "bulk import: skipped a repository");903 tracing::info!(repo = %remote, %message, "bulk import: skipped a repository");
967 skipped.push(format!("{name} ({message})"));904 skipped.push(format!("{name} ({message})"));
@@ -978,8 +915,6 @@ async fn run_bulk(
978 Err(see_other(format!("/import?skipped={}", crate::views::enc(&list))).into())915 Err(see_other(format!("/import?skipped={}", crate::views::enc(&list))).into())
979 }916 }
980 917
981-// ---- jobs ----
982-
983 fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) {918 fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) {
984 match state {919 match state {
985 ImportState::Queued => ("badge", g::t(lang, K::JobQueued)),920 ImportState::Queued => ("badge", g::t(lang, K::JobQueued)),
@@ -1001,8 +936,6 @@ fn stage_name(lang: Lang, stage: &str) -> &'static str {
1001 }936 }
1002 }937 }
1003 938
1004-/// The job's repository, once it exists and while `user` may still read it: an import into an
1005-/// org the user has since left, or a repo transferred away, is not named.
1006 async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Result<Option<Repo>> {939 async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Result<Option<Repo>> {
1007 let Some(id) = &job.repo_id else {940 let Some(id) = &job.repo_id else {
1008 return Ok(None);941 return Ok(None);
@@ -1013,7 +946,6 @@ async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Res
1013 Ok(state.store.repo_by_id(id).await?)946 Ok(state.store.repo_by_id(id).await?)
1014 }947 }
1015 948
1016-/// The user's newest import jobs, each with its repository once it exists.
1017 async fn load_job_rows(949 async fn load_job_rows(
1018 state: &AppState,950 state: &AppState,
1019 user_id: &str,951 user_id: &str,
@@ -1029,7 +961,6 @@ async fn load_job_rows(
1029 Ok(rows)961 Ok(rows)
1030 }962 }
1031 963
1032-/// The import job rows, shared by the Import history page and the recent list on the Import tab.
1033 #[component]964 #[component]
1034 async fn job_rows(cx: &Cx, lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<impl View> {965 async fn job_rows(cx: &Cx, lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<impl View> {
1035 Ok(view! {966 Ok(view! {
@@ -1066,7 +997,7 @@ async fn jobs_list(
1066 let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed);997 let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed);
1067 Ok(view! {998 Ok(view! {
1068 head(title: g::t(lang, K::JobsTitle), live: Some("/import/events"))999 head(title: g::t(lang, K::JobsTitle), live: Some("/import/events"))
1069- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())1000+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
1070 newrepo_tabs(lang: lang, active: "history")1001 newrepo_tabs(lang: lang, active: "history")
1071 <div class="sheet">1002 <div class="sheet">
1072 if retry {1003 if retry {
@@ -1090,7 +1021,6 @@ async fn jobs_list(
1090 })1021 })
1091 }1022 }
1092 1023
1093-/// What the import list shows for `user_id`: each job's id, state, source and repo, in list order.
1094 async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> {1024 async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
1095 let rows = load_job_rows(state, user_id, 50).await?;1025 let rows = load_job_rows(state, user_id, 50).await?;
1096 Ok(rows1026 Ok(rows
@@ -1110,8 +1040,6 @@ async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
1110 .join("\n"))1040 .join("\n"))
1111 }1041 }
1112 1042
1113-/// The import list's change stream: the viewer's own jobs, from the session only. It sends when the
1114-/// list would show something different (see [`Topic::Imports`]).
1115 #[route(GET "/import/events")]1043 #[route(GET "/import/events")]
1116 async fn jobs_events(cx: &Cx) -> Result<Response> {1044 async fn jobs_events(cx: &Cx) -> Result<Response> {
1117 let viewer = require_user(cx).await?;1045 let viewer = require_user(cx).await?;
@@ -1130,7 +1058,6 @@ async fn jobs_events(cx: &Cx) -> Result<Response> {
1130 .await1058 .await
1131 }1059 }
1132 1060
1133-/// Imports per page of the history.
1134 const HISTORY_ROWS: u64 = 10;1061 const HISTORY_ROWS: u64 = 10;
1135 1062
1136 #[page("/import")]1063 #[page("/import")]
@@ -1147,7 +1074,6 @@ async fn jobs_page(cx: &Cx) -> Result<impl View> {
1147 .and_then(|p| p.parse::<u64>().ok())1074 .and_then(|p| p.parse::<u64>().ok())
1148 .unwrap_or(1)1075 .unwrap_or(1)
1149 .clamp(1, pages);1076 .clamp(1, pages);
1150- // Only the shown page's repos are looked up.
1151 let user = state.store.user_by_id(&viewer.0.id).await?;1077 let user = state.store.user_by_id(&viewer.0.id).await?;
1152 let mut rows = Vec::new();1078 let mut rows = Vec::new();
1153 for job in all1079 for job in all
@@ -1206,7 +1132,7 @@ async fn job_view(
1206 }];1132 }];
1207 Ok(view! {1133 Ok(view! {
1208 head(title: job.source_ref.as_str(), sub: sub, live: live.as_deref())1134 head(title: job.source_ref.as_str(), sub: sub, live: live.as_deref())
1209- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())1135+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
1210 newrepo_tabs(lang: lang, active: "history")1136 newrepo_tabs(lang: lang, active: "history")
1211 <div class="sheet import-job" data-live-state=(state_word)>1137 <div class="sheet import-job" data-live-state=(state_word)>
1212 <section class="sec">1138 <section class="sec">
@@ -1262,7 +1188,6 @@ async fn job_view(
1262 })1188 })
1263 }1189 }
1264 1190
1265-/// The job when the viewer owns it. Anyone else gets 404.
1266 async fn owned_job(cx: &Cx, viewer: &User) -> Result<ImportJob> {1191 async fn owned_job(cx: &Cx, viewer: &User) -> Result<ImportJob> {
1267 let id = job_id(cx).to_owned();1192 let id = job_id(cx).to_owned();
1268 let state = context::<AppState>(cx);1193 let state = context::<AppState>(cx);
@@ -1288,8 +1213,6 @@ async fn job_page(cx: &Cx) -> Result<impl View> {
1288 })1213 })
1289 }1214 }
1290 1215
1291-/// The job's `changed` stream. It sends when the job differs from the version the page was
1292-/// rendered with, then on every change, and ends once the job is finished.
1293 #[route(GET "/import/{job_id}/events")]1216 #[route(GET "/import/{job_id}/events")]
1294 async fn job_events(cx: &Cx) -> Result<Response> {1217 async fn job_events(cx: &Cx) -> Result<Response> {
1295 let viewer = require_user(cx).await?;1218 let viewer = require_user(cx).await?;
@@ -1297,7 +1220,6 @@ async fn job_events(cx: &Cx) -> Result<Response> {
1297 let query = query_params::<SeenQuery>(cx)?;1220 let query = query_params::<SeenQuery>(cx)?;
1298 let state = context::<AppState>(cx);1221 let state = context::<AppState>(cx);
1299 let seen = query.v.clone().unwrap_or_default();1222 let seen = query.v.clone().unwrap_or_default();
1300- // Subscribed before the job is read again below, so a change in between is not lost.
1301 let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id));1223 let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id));
1302 let store = state.store.clone();1224 let store = state.store.clone();
1303 let id = job.id.clone();1225 let id = job.id.clone();
@@ -1337,9 +1259,6 @@ struct RetryForm {
1337 token: String,1259 token: String,
1338 }1260 }
1339 1261
1340-/// Re-queues a failed import and starts it again; what was imported before is skipped. `Ok(false)`
1341-/// when nothing was started: the job is not failed, its source or remote does not parse, or its
1342-/// repository already has an import running.
1343 async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool> {1262 async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool> {
1344 if job.state != ImportState::Failed {1263 if job.state != ImportState::Failed {
1345 return Ok(false);1264 return Ok(false);
@@ -1350,16 +1269,10 @@ async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool
1350 let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else {1269 let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else {
1351 return Ok(false);1270 return Ok(false);
1352 };1271 };
1353- if let Some(repo_id) = &job.repo_id1272+ let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default();
1354- && state.store.active_import_for_repo(repo_id).await?.is_some()1273+ if !state.store.requeue_failed_import(&job.id).await? {
1355- {
1356 return Ok(false);1274 return Ok(false);
1357 }1275 }
1358- let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default();
1359- state
1360- .store
1361- .set_import_state(&job.id, ImportState::Queued, None)
1362- .await?;
1363 state1276 state
1364 .store1277 .store
1365 .add_import_event(1278 .add_import_event(
@@ -1390,10 +1303,6 @@ async fn job_retry(cx: &Cx, Form(form): Form<RetryForm>) -> Result<SeeOther> {
1390 Err(see_other(href).into())1303 Err(see_other(href).into())
1391 }1304 }
1392 1305
1393-// ---- retry several failed imports ----
1394-
1395-/// The viewer's failed imports whose repository still exists and is readable, with the repository,
1396-/// and no import running on it. Newest first.
1397 async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(ImportJob, Repo)>> {1306 async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(ImportJob, Repo)>> {
1398 let mut rows = Vec::new();1307 let mut rows = Vec::new();
1399 for job in state.store.list_import_jobs(&viewer.id, 200).await? {1308 for job in state.store.list_import_jobs(&viewer.id, 200).await? {
@@ -1416,7 +1325,6 @@ async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(Import
1416 Ok(rows)1325 Ok(rows)
1417 }1326 }
1418 1327
1419-/// The provider's name for a job's source, as the source tabs show it.
1420 fn source_label(raw: &str) -> &'static str {1328 fn source_label(raw: &str) -> &'static str {
1421 Source::parse(raw).map_or("", Source::label)1329 Source::parse(raw).map_or("", Source::label)
1422 }1330 }
@@ -1433,7 +1341,7 @@ async fn retry_list(
1433 let empty = rows.is_empty();1341 let empty = rows.is_empty();
1434 Ok(view! {1342 Ok(view! {
1435 head(title: g::t(lang, K::RetryFailedTitle))1343 head(title: g::t(lang, K::RetryFailedTitle))
1436- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())1344+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
1437 newrepo_tabs(lang: lang, active: "history")1345 newrepo_tabs(lang: lang, active: "history")
1438 <div class="sheet">1346 <div class="sheet">
1439 <form method="post" action="/import/retry" class="fields">1347 <form method="post" action="/import/retry" class="fields">
@@ -1491,7 +1399,6 @@ struct RetrySelectedForm {
1491 csrf: String,1399 csrf: String,
1492 #[serde(default)]1400 #[serde(default)]
1493 token: String,1401 token: String,
1494- /// The ticked jobs arrive as `sel_0`, `sel_1`, ... with the job id as the value.
1495 #[serde(flatten)]1402 #[serde(flatten)]
1496 extra: HashMap<String, String>,1403 extra: HashMap<String, String>,
1497 }1404 }
@@ -1510,7 +1417,6 @@ async fn retry_submit(cx: &Cx, Form(form): Form<RetrySelectedForm>) -> Result<Se
1510 return Err(see_other("/import/retry").into());1417 return Err(see_other("/import/retry").into());
1511 }1418 }
1512 for (_, id) in picked {1419 for (_, id) in picked {
1513- // Only the viewer's own jobs; anything else is skipped without a word.
1514 let Some(job) = state.store.import_job(id).await? else {1420 let Some(job) = state.store.import_job(id).await? else {
1515 continue;1421 continue;
1516 };1422 };
crates/forge-web-account/src/pages/login.rsmodified+41 -56
@@ -2,7 +2,7 @@
2 2
3 use std::time::{Duration, Instant};3 use std::time::{Duration, Instant};
4 4
5-use forge_core::AuditAction;5+use forge_core::{AuditAction, User};
6 use forge_core::names::normalize_name;6 use forge_core::names::normalize_name;
7 use http::header::{HeaderValue, RETRY_AFTER};7 use http::header::{HeaderValue, RETRY_AFTER};
8 use serde::Deserialize;8 use serde::Deserialize;
@@ -224,17 +224,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View>
224 set_pending_login(cx, &state.key, &user.id, &next)?;224 set_pending_login(cx, &state.key, &user.id, &next)?;
225 return Err(see_other("/login/2fa").into());225 return Err(see_other("/login/2fa").into());
226 }226 }
227- login(cx, &user).await?;227+ finish_login(cx, state, &user, serde_json::Value::Null).await?;
228- audit::record(
229- &state.store,
230- Some(cx),
231- Actor::User(&user),
232- AuditAction::LoginSuccess,
233- Target::default(),
234- serde_json::Value::Null,
235- )
236- .await;
237- clear_pre_csrf(cx);
238 return Err(see_other(safe_next(Some(&form.next))).into());228 return Err(see_other(safe_next(Some(&form.next))).into());
239 }229 }
240 _ => {230 _ => {
@@ -352,18 +342,8 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
352 match user {342 match user {
353 Some(user) if verified => {343 Some(user) if verified => {
354 state.throttle.clear(&key);344 state.throttle.clear(&key);
355- login(cx, &user).await?;345+ finish_login(cx, state, &user, json!({ "second_factor": true })).await?;
356- audit::record(
357- &state.store,
358- Some(cx),
359- Actor::User(&user),
360- AuditAction::LoginSuccess,
361- Target::default(),
362- json!({ "second_factor": true }),
363- )
364- .await;
365 clear_pending_login(cx);346 clear_pending_login(cx);
366- clear_pre_csrf(cx);
367 return Err(see_other(safe_next(Some(&pending.next))).into());347 return Err(see_other(safe_next(Some(&pending.next))).into());
368 }348 }
369 _ => {349 _ => {
@@ -395,6 +375,26 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
395 })375 })
396 }376 }
397 377
378+async fn finish_login(
379+ cx: &Cx,
380+ state: &AppState,
381+ user: &User,
382+ audit_data: serde_json::Value,
383+) -> Result<()> {
384+ login(cx, user).await?;
385+ audit::record(
386+ &state.store,
387+ Some(cx),
388+ Actor::User(user),
389+ AuditAction::LoginSuccess,
390+ Target::default(),
391+ audit_data,
392+ )
393+ .await;
394+ clear_pre_csrf(cx);
395+ Ok(())
396+}
397+
398 /// Whole seconds for a `Retry-After` header, at least 1.398 /// Whole seconds for a `Retry-After` header, at least 1.
399 fn retry_after_secs(retry: Duration) -> u64 {399 fn retry_after_secs(retry: Duration) -> u64 {
400 retry.as_secs().max(1)400 retry.as_secs().max(1)
@@ -759,6 +759,14 @@ mod tests {
759 shared.to_vec()759 shared.to_vec()
760 }760 }
761 761
762+ fn live_code(shared: &[u8], ahead: u64) -> String {
763+ let now = std::time::SystemTime::now()
764+ .duration_since(std::time::UNIX_EPOCH)
765+ .unwrap()
766+ .as_secs();
767+ totp::code_at(shared, totp::step_for(now) + ahead)
768+ }
769+
762 /// Cookie header for the pending login plus the pre-session CSRF cookie.770 /// Cookie header for the pending login plus the pre-session CSRF cookie.
763 fn both(pending: &str, precsrf_cookie: &str) -> String {771 fn both(pending: &str, precsrf_cookie: &str) -> String {
764 format!("{pending}; {precsrf_cookie}")772 format!("{pending}; {precsrf_cookie}")
@@ -832,22 +840,15 @@ mod tests {
832 let (cookie, precsrf) = login_page(&router, from).await;840 let (cookie, precsrf) = login_page(&router, from).await;
833 let step = password_step(&router, from, (&cookie, &precsrf), "grace", PASSWORD).await;841 let step = password_step(&router, from, (&cookie, &precsrf), "grace", PASSWORD).await;
834 let pending = both(&pair(&step, "__Host-forge_2fa").unwrap(), &cookie);842 let pending = both(&pair(&step, "__Host-forge_2fa").unwrap(), &cookie);
835- let wrong = second_factor_step(&router, from, &pending, &precsrf, "000000").await;843+ let wrong =
836- // The chance that 000000 is the live code is about 1 in a million per window.844+ second_factor_step(&router, from, &pending, &precsrf, &live_code(&shared, 2)).await;
837- if wrong.status == 200 {845+ assert_eq!(wrong.status, 200, "wrong code: status");
838- assert!(846+ assert!(
839- wrong.body.contains("That code is not right"),847+ wrong.body.contains("That code is not right"),
840- "wrong code: message"848+ "wrong code: message"
841- );
842- }
843-
844- let now_step = totp::step_for(
845- std::time::SystemTime::now()
846- .duration_since(std::time::UNIX_EPOCH)
847- .unwrap()
848- .as_secs(),
849 );849 );
850- let code = totp::code_at(&shared, now_step);850+
851+ let code = live_code(&shared, 0);
851 let ok = second_factor_step(&router, from, &pending, &precsrf, &code).await;852 let ok = second_factor_step(&router, from, &pending, &precsrf, &code).await;
852 assert_eq!(ok.status, 303, "right code: body {}", ok.body);853 assert_eq!(ok.status, 303, "right code: body {}", ok.body);
853 assert_eq!(854 assert_eq!(
@@ -922,15 +923,7 @@ mod tests {
922 let (cookie, precsrf) = login_page(&router, from).await;923 let (cookie, precsrf) = login_page(&router, from).await;
923 let stale = secret::seal(&state.key, format!("1|{}|/", user.id).as_bytes()).unwrap();924 let stale = secret::seal(&state.key, format!("1|{}|/", user.id).as_bytes()).unwrap();
924 let pending = format!("__Host-forge_2fa={stale}");925 let pending = format!("__Host-forge_2fa={stale}");
925- let code = totp::code_at(926+ let code = live_code(&shared, 0);
926- &shared,
927- totp::step_for(
928- std::time::SystemTime::now()
929- .duration_since(std::time::UNIX_EPOCH)
930- .unwrap()
931- .as_secs(),
932- ),
933- );
934 let reply =927 let reply =
935 second_factor_step(&router, from, &both(&pending, &cookie), &precsrf, &code).await;928 second_factor_step(&router, from, &both(&pending, &cookie), &precsrf, &code).await;
936 assert_eq!(reply.status, 303, "expired: status");929 assert_eq!(reply.status, 303, "expired: status");
@@ -954,15 +947,7 @@ mod tests {
954 let reply = second_factor_step(&router, from, &pending, &precsrf, "111111").await;947 let reply = second_factor_step(&router, from, &pending, &precsrf, "111111").await;
955 assert_eq!(reply.status, 200, "limit: wrong code");948 assert_eq!(reply.status, 200, "limit: wrong code");
956 }949 }
957- let code = totp::code_at(950+ let code = live_code(&shared, 0);
958- &shared,
959- totp::step_for(
960- std::time::SystemTime::now()
961- .duration_since(std::time::UNIX_EPOCH)
962- .unwrap()
963- .as_secs(),
964- ),
965- );
966 let blocked = second_factor_step(&router, from, &pending, &precsrf, &code).await;951 let blocked = second_factor_step(&router, from, &pending, &precsrf, &code).await;
967 assert_eq!(blocked.status, 429, "limit: right code while locked");952 assert_eq!(blocked.status, 429, "limit: right code while locked");
968 assert!(blocked.body.contains("Too many attempts"), "limit: message");953 assert!(blocked.body.contains("Too many attempts"), "limit: message");
crates/forge-web-account/src/pages/new_repo.rsmodified+2 -44
@@ -1,5 +1,3 @@
1-//! Page: create a repository (GET/POST /new).
2-
3 use forge_core::mirrors::{DEFAULT_INTERVAL_MINUTES, MirrorDirection, NewMirror};1 use forge_core::mirrors::{DEFAULT_INTERVAL_MINUTES, MirrorDirection, NewMirror};
4 use forge_core::names::validate_name;2 use forge_core::names::validate_name;
5 use forge_core::time::now_stamp;3 use forge_core::time::now_stamp;
@@ -10,7 +8,6 @@ use topcoat::Result;
10 use topcoat::context::{Cx, context};8 use topcoat::context::{Cx, context};
11 use topcoat::router::content::Form;9 use topcoat::router::content::Form;
12 use topcoat::router::error::see_other;10 use topcoat::router::error::see_other;
13-// Named by the `#[query_params]` attribute below, which the unused-import lint does not see.
14 #[allow(unused_imports)]11 #[allow(unused_imports)]
15 use topcoat::router::error::bad_request;12 use topcoat::router::error::bad_request;
16 use topcoat::router::{page, query_params};13 use topcoat::router::{page, query_params};
@@ -29,7 +26,6 @@ use crate::views::{alert, csrf_field, shell, user_facing_message};
29 const MAX_DESCRIPTION_CHARS: usize = 350;26 const MAX_DESCRIPTION_CHARS: usize = 350;
30 const DEFAULT_BRANCH: &str = "main";27 const DEFAULT_BRANCH: &str = "main";
31 28
32-/// The licenses the form offers, in menu order: SPDX id, menu label and the full SPDX text.
33 const LICENSES: &[(&str, &str, &str)] = &[29 const LICENSES: &[(&str, &str, &str)] = &[
34 (30 (
35 "MIT",31 "MIT",
@@ -93,8 +89,6 @@ const LICENSES: &[(&str, &str, &str)] = &[
93 ),89 ),
94 ];90 ];
95 91
96-/// The LICENSE file for `spdx` with the copyright line filled in. `None` for an id that is not in
97-/// [`LICENSES`]. The placeholders appear only on the copyright line, so the first match is replaced.
98 fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> {92 fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> {
99 let (_, _, text) = LICENSES.iter().find(|(id, _, _)| *id == spdx)?;93 let (_, _, text) = LICENSES.iter().find(|(id, _, _)| *id == spdx)?;
100 let text = match spdx {94 let text = match spdx {
@@ -109,7 +103,6 @@ fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> {
109 Some(text)103 Some(text)
110 }104 }
111 105
112-/// The README of a new repo: the name as the heading, then the description when there is one.
113 fn readme_text(name: &str, description: &str) -> String {106 fn readme_text(name: &str, description: &str) -> String {
114 let mut text = format!("# {name}\n");107 let mut text = format!("# {name}\n");
115 if !description.is_empty() {108 if !description.is_empty() {
@@ -132,16 +125,12 @@ struct NewRepoForm {
132 visibility: String,125 visibility: String,
133 #[serde(default)]126 #[serde(default)]
134 default_branch: String,127 default_branch: String,
135- /// The checkbox sends `on` when checked and nothing when unchecked.
136 #[serde(default)]128 #[serde(default)]
137 default_labels: String,129 default_labels: String,
138- /// The "Add a README" checkbox. Present (`on`) when checked, absent otherwise.
139 #[serde(default)]130 #[serde(default)]
140 add_readme: Option<String>,131 add_readme: Option<String>,
141- /// The SPDX id from the license select. Blank means no license.
142 #[serde(default)]132 #[serde(default)]
143 license: String,133 license: String,
144- /// The optional "Mirror an existing repository" section. A blank URL means no mirror.
145 #[serde(default)]134 #[serde(default)]
146 mirror_url: String,135 mirror_url: String,
147 #[serde(default)]136 #[serde(default)]
@@ -150,13 +139,10 @@ struct NewRepoForm {
150 mirror_secret: String,139 mirror_secret: String,
151 #[serde(default)]140 #[serde(default)]
152 mirror_interval: String,141 mirror_interval: String,
153- /// The account that will own the repo: the viewer's own name, or an org they may create in.
154- /// Blank means the viewer.
155 #[serde(default)]142 #[serde(default)]
156 owner: String,143 owner: String,
157 }144 }
158 145
159-/// The form's values, echoed back when validation fails.
160 struct Draft {146 struct Draft {
161 owner: String,147 owner: String,
162 name: String,148 name: String,
@@ -188,7 +174,6 @@ impl Draft {
188 }174 }
189 }175 }
190 176
191- /// The submitted values. The mirror password is never echoed back.
192 fn from_form(form: &NewRepoForm) -> Self {177 fn from_form(form: &NewRepoForm) -> Self {
193 Draft {178 Draft {
194 owner: form.owner.trim().to_owned(),179 owner: form.owner.trim().to_owned(),
@@ -230,14 +215,13 @@ async fn new_repo_form(
230 let default_labels = draft.default_labels;215 let default_labels = draft.default_labels;
231 let add_readme = draft.add_readme;216 let add_readme = draft.add_readme;
232 let draft_license = draft.license;217 let draft_license = draft.license;
233- // A mirror URL in the draft means the form was re-rendered after a validation error.
234 let mirror_open = !draft.mirror_url.is_empty();218 let mirror_open = !draft.mirror_url.is_empty();
235 let draft_mirror_url = draft.mirror_url;219 let draft_mirror_url = draft.mirror_url;
236 let draft_mirror_username = draft.mirror_username;220 let draft_mirror_username = draft.mirror_username;
237 let draft_mirror_interval = draft.mirror_interval;221 let draft_mirror_interval = draft.mirror_interval;
238 Ok(view! {222 Ok(view! {
239 head(title: i18n::t(lang, Key::NewRepository))223 head(title: i18n::t(lang, Key::NewRepository))
240- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned())224+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories)
241 crate::pages::import::newrepo_tabs(lang: lang, active: "create")225 crate::pages::import::newrepo_tabs(lang: lang, active: "create")
242 <div class="sheet fit">226 <div class="sheet fit">
243 <form method="post" action="/new" class="fields">227 <form method="post" action="/new" class="fields">
@@ -307,8 +291,6 @@ async fn new_repo_form(
307 })291 })
308 }292 }
309 293
310-/// The accounts the viewer may create a repo under: themselves, then the orgs where
311-/// `may_create_repo_in` allows it.
312 pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> {294 pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> {
313 let mut names = vec![viewer.username.clone()];295 let mut names = vec![viewer.username.clone()];
314 for (org, _) in state.store.orgs_for_user(&viewer.id).await? {296 for (org, _) in state.store.orgs_for_user(&viewer.id).await? {
@@ -319,7 +301,6 @@ pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec
319 Ok(names)301 Ok(names)
320 }302 }
321 303
322-/// `/new?owner=acme` preselects that owner. An owner the viewer cannot pick is ignored.
323 #[query_params(error = bad_request)]304 #[query_params(error = bad_request)]
324 struct NewRepoQuery {305 struct NewRepoQuery {
325 owner: Option<String>,306 owner: Option<String>,
@@ -361,8 +342,6 @@ async fn new_repo_submit(cx: &Cx, Form(form): Form<NewRepoForm>) -> Result<impl
361 }342 }
362 }343 }
363 344
364-/// The account the new repo belongs to. Blank or the viewer's own name means the viewer. An org
365-/// name is accepted only when the viewer may create repos under it.
366 pub(crate) async fn repo_owner(345 pub(crate) async fn repo_owner(
367 state: &AppState,346 state: &AppState,
368 viewer: &User,347 viewer: &User,
@@ -383,8 +362,6 @@ pub(crate) async fn repo_owner(
383 Ok(Ok(org))362 Ok(Ok(org))
384 }363 }
385 364
386-/// Validates the form and creates the repo. `Ok(Err(message))` is a user-facing rejection;
387-/// the outer `Err` is an internal failure.
388 async fn create_repo(365 async fn create_repo(
389 cx: &Cx,366 cx: &Cx,
390 owner: &User,367 owner: &User,
@@ -423,7 +400,6 @@ async fn create_repo(
423 Ok(target) => target,400 Ok(target) => target,
424 Err(message) => return Ok(Err(message)),401 Err(message) => return Ok(Err(message)),
425 };402 };
426- // The mirror is checked before anything is created, so a refused URL leaves no repo behind.
427 let mirror = if form.mirror_url.trim().is_empty() {403 let mirror = if form.mirror_url.trim().is_empty() {
428 None404 None
429 } else {405 } else {
@@ -463,11 +439,10 @@ async fn create_repo(
463 439
464 let path = repo_path(&state.config.data_dir, &repo.id)?;440 let path = repo_path(&state.config.data_dir, &repo.id)?;
465 if let Err(e) = init_bare(&state.git, &path, branch).await {441 if let Err(e) = init_bare(&state.git, &path, branch).await {
466- // TODO: delete the repository row so a failed init does not leave a dangling name.442+ state.store.delete_repo(&repo.id).await?;
467 return Ok(Err(g::git_init_failed(lang, e)));443 return Ok(Err(g::git_init_failed(lang, e)));
468 }444 }
469 if want_files {445 if want_files {
470- // The copyright holder is the account the repo belongs to; the author is the viewer.
471 let year = jiff::Timestamp::now()446 let year = jiff::Timestamp::now()
472 .to_zoned_datetime(jiff::tz::TimeZone::UTC)447 .to_zoned_datetime(jiff::tz::TimeZone::UTC)
473 .year()448 .year()
@@ -494,7 +469,6 @@ async fn create_repo(
494 .email469 .email
495 .clone()470 .clone()
496 .unwrap_or_else(|| format!("{}@users.noreply.forge", owner.username));471 .unwrap_or_else(|| format!("{}@users.noreply.forge", owner.username));
497- // The repo exists already, so a failed commit is logged rather than shown as an error.
498 if let Err(e) = forge_git::seed::initial_commit(472 if let Err(e) = forge_git::seed::initial_commit(
499 &state.git,473 &state.git,
500 &path,474 &path,
@@ -509,8 +483,6 @@ async fn create_repo(
509 tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not write the initial commit");483 tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not write the initial commit");
510 }484 }
511 }485 }
512- // The repo already exists at this point, so a label failure is logged rather than shown as an
513- // error page for a repo that was in fact created.
514 if add_default_labels && let Err(e) = state.store.create_default_labels(&repo.id).await {486 if add_default_labels && let Err(e) = state.store.create_default_labels(&repo.id).await {
515 tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not add default labels");487 tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not add default labels");
516 }488 }
@@ -534,8 +506,6 @@ async fn create_repo(
534 Ok(Ok(format!("/{}/{}", repo.owner_name, repo.name)))506 Ok(Ok(format!("/{}/{}", repo.owner_name, repo.name)))
535 }507 }
536 508
537-/// Creates the pull mirror of a new repo and queues its first sync now. The repo is new and empty,
538-/// so a store failure here is an internal error.
539 async fn create_pull_mirror(509 async fn create_pull_mirror(
540 cx: &Cx,510 cx: &Cx,
541 state: &AppState,511 state: &AppState,
@@ -592,8 +562,6 @@ mod tests {
592 562
593 const CSRF: &str = "new-repo-test-csrf";563 const CSRF: &str = "new-repo-test-csrf";
594 564
595- /// One store and router with `tahinli` signed in. Every scenario below uses its own repo name,
596- /// so they share this site.
597 struct Site {565 struct Site {
598 store: Store,566 store: Store,
599 router: Router,567 router: Router,
@@ -622,8 +590,6 @@ mod tests {
622 }590 }
623 }591 }
624 592
625- /// POSTs `/new` as tahinli for a repo called `name` with the extra fields. Returns the status
626- /// and the repo created, if any. The form's token is the shared CSRF value.
627 async fn post_new(593 async fn post_new(
628 site: &Site,594 site: &Site,
629 name: &str,595 name: &str,
@@ -657,7 +623,6 @@ mod tests {
657 (status, repo)623 (status, repo)
658 }624 }
659 625
660- /// The default labels are added only when the box is checked.
661 #[tokio::test]626 #[tokio::test]
662 async fn default_labels_are_added_only_when_checked() {627 async fn default_labels_are_added_only_when_checked() {
663 let site = site().await;628 let site = site().await;
@@ -680,13 +645,10 @@ mod tests {
680 }645 }
681 }646 }
682 647
683- /// Mirror fields: a valid URL makes a pull mirror, a loopback URL is refused and creates
684- /// nothing, and a blank URL makes the repo without a mirror.
685 #[tokio::test]648 #[tokio::test]
686 async fn mirror_url_decides_whether_a_pull_mirror_is_made() {649 async fn mirror_url_decides_whether_a_pull_mirror_is_made() {
687 let site = site().await;650 let site = site().await;
688 651
689- // Case: a valid URL creates a pull mirror with the given settings.
690 let (status, repo) = post_new(652 let (status, repo) = post_new(
691 &site,653 &site,
692 "mirror-ok",654 "mirror-ok",
@@ -723,7 +685,6 @@ mod tests {
723 "valid mirror: the first sync is due now"685 "valid mirror: the first sync is due now"
724 );686 );
725 687
726- // Case: a loopback URL shows the form again and creates nothing.
727 let (status, repo) = post_new(688 let (status, repo) = post_new(
728 &site,689 &site,
729 "mirror-loopback",690 "mirror-loopback",
@@ -739,7 +700,6 @@ mod tests {
739 "loopback: no repo is created for a refused mirror"700 "loopback: no repo is created for a refused mirror"
740 );701 );
741 702
742- // Case: a blank URL creates the repo without a mirror.
743 let (status, repo) = post_new(&site, "mirror-blank", &[("mirror_url", " ")]).await;703 let (status, repo) = post_new(&site, "mirror-blank", &[("mirror_url", " ")]).await;
744 assert_eq!(status, 303, "blank: status");704 assert_eq!(status, 303, "blank: status");
745 let repo = repo.expect("blank: the repo is created");705 let repo = repo.expect("blank: the repo is created");
@@ -753,7 +713,6 @@ mod tests {
753 );713 );
754 }714 }
755 715
756- /// A README and a license make the first commit, and the README has the name and description.
757 #[tokio::test]716 #[tokio::test]
758 async fn readme_and_license_make_the_first_commit() {717 async fn readme_and_license_make_the_first_commit() {
759 let site = site().await;718 let site = site().await;
@@ -785,7 +744,6 @@ mod tests {
785 assert!(!license.contains("<year>"), "{license}");744 assert!(!license.contains("<year>"), "{license}");
786 }745 }
787 746
788- /// A viewer who chose Turkish gets the Turkish form.
789 #[tokio::test]747 #[tokio::test]
790 async fn the_form_is_in_turkish_for_a_turkish_viewer() {748 async fn the_form_is_in_turkish_for_a_turkish_viewer() {
791 let site = site().await;749 let site = site().await;
crates/forge-web-account/src/pages/not_found_page.rsmodified+17 -31
@@ -14,38 +14,24 @@ use crate::i18n::{self, Lang};
14 use crate::views::parts::{SubPart, head};14 use crate::views::parts::{SubPart, head};
15 use crate::views::shell;15 use crate::views::shell;
16 16
17-fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) {17+fn error_texts(lang: Lang, code: &'static str) -> (&'static str, &'static str, &'static str) {
18- match lang {18+ match (lang, code) {
19- Lang::En => (19+ (Lang::En, "404") => (
20 "Page not found",20 "Page not found",
21 "This page does not exist, or you cannot see it. Check the address, or go back to the start.",21 "This page does not exist, or you cannot see it. Check the address, or go back to the start.",
22 "Back to the start",22 "Back to the start",
23 ),23 ),
24- Lang::Tr => (24+ (Lang::En, _) => (
25- "Sayfa bulunamadı",
26- "Bu sayfa yok ya da görme izniniz yok. Adresi kontrol edin ya da başa dönün.",
27- "Başa dön",
28- ),
29- }
30-}
31-
32-#[component]
33-async fn not_found_body(cx: &Cx, lang: Lang) -> Result<impl View> {
34- let (title, hint, back) = texts(lang);
35- Ok(view! {
36- head(title: title, sub: vec![SubPart::mono("404")])
37- <p class="state">(hint) " " <a class="act" href="/">(back)</a></p>
38- })
39-}
40-
41-fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
42- match lang {
43- Lang::En => (
44 "Not allowed",25 "Not allowed",
45 "Your account cannot do this here. Ask an owner for access, or go back to the start.",26 "Your account cannot do this here. Ask an owner for access, or go back to the start.",
46 "Back to the start",27 "Back to the start",
47 ),28 ),
48- Lang::Tr => (29+ (Lang::Tr, "404") => (
30+ "Sayfa bulunamadı",
31+ "Bu sayfa yok ya da görme izniniz yok. Adresi kontrol edin ya da başa dönün.",
32+ "Başa dön",
33+ ),
34+ (Lang::Tr, _) => (
49 "İzin yok",35 "İzin yok",
50 "Hesabınız burada bunu yapamaz. Bir sahibinden erişim isteyin ya da başa dönün.",36 "Hesabınız burada bunu yapamaz. Bir sahibinden erişim isteyin ya da başa dönün.",
51 "Başa dön",37 "Başa dön",
@@ -54,10 +40,10 @@ fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
54 }40 }
55 41
56 #[component]42 #[component]
57-async fn forbidden_body(cx: &Cx, lang: Lang) -> Result<impl View> {43+async fn error_body(cx: &Cx, lang: Lang, code: &'static str) -> Result<impl View> {
58- let (title, hint, back) = forbidden_texts(lang);44+ let (title, hint, back) = error_texts(lang, code);
59 Ok(view! {45 Ok(view! {
60- head(title: title, sub: vec![SubPart::mono("403")])46+ head(title: title, sub: vec![SubPart::mono(code)])
61 <p class="state">(hint) " " <a class="act" href="/">(back)</a></p>47 <p class="state">(hint) " " <a class="act" href="/">(back)</a></p>
62 })48 })
63 }49 }
@@ -75,10 +61,10 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> {
75 }61 }
76 }62 }
77 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));63 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));
78- let title = forbidden_texts(lang).0;64+ let title = error_texts(lang, "403").0;
79 Ok(view! {65 Ok(view! {
80 (StatusCode::FORBIDDEN)66 (StatusCode::FORBIDDEN)
81- shell(title: title, viewer: viewer.as_ref(), forbidden_body(lang: lang))67+ shell(title: title, viewer: viewer.as_ref(), error_body(lang: lang, code: "403"))
82 })68 })
83 }69 }
84 70
@@ -86,9 +72,9 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> {
86 async fn not_found_page(cx: &Cx) -> Result<impl View> {72 async fn not_found_page(cx: &Cx) -> Result<impl View> {
87 let viewer = current_user(cx).await?;73 let viewer = current_user(cx).await?;
88 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));74 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));
89- let title = texts(lang).0;75+ let title = error_texts(lang, "404").0;
90 Ok(view! {76 Ok(view! {
91 (StatusCode::NOT_FOUND)77 (StatusCode::NOT_FOUND)
92- shell(title: title, viewer: viewer.as_ref(), not_found_body(lang: lang))78+ shell(title: title, viewer: viewer.as_ref(), error_body(lang: lang, code: "404"))
93 })79 })
94 }80 }
crates/forge-web-account/src/pages/org_ctx.rsmodified+9 -23
@@ -24,7 +24,7 @@ use crate::views::{alert, profile_items};
24 /// The query key that carries a notice on an org page. Its value is one of the fixed words in24 /// The query key that carries a notice on an org page. Its value is one of the fixed words in
25 /// `NOTICES`, never user text. The notice lives in the URL, not in a cookie: a live refresh of the25 /// `NOTICES`, never user text. The notice lives in the URL, not in a cookie: a live refresh of the
26 /// page reads the same URL and shows the notice again, where a cookie would be used up by it.26 /// page reads the same URL and shows the notice again, where a cookie would be used up by it.
27-pub const NOTICE_PARAM: &str = "notice";27+const NOTICE_PARAM: &str = "notice";
28 28
29 /// Notice words, the text key each one shows, and whether it is an error.29 /// Notice words, the text key each one shows, and whether it is an error.
30 pub const NOTICES: &[(&str, K, bool)] = &[30 pub const NOTICES: &[(&str, K, bool)] = &[
@@ -75,6 +75,9 @@ pub const TEAM_ROLES: [Role; 5] = [
75 /// Default repo roles for the org settings select.75 /// Default repo roles for the org settings select.
76 pub const DEFAULT_ROLES: [&str; 3] = ["none", "read", "write"];76 pub const DEFAULT_ROLES: [&str; 3] = ["none", "read", "write"];
77 77
78+/// Longest org description, in characters.
79+pub const MAX_DESCRIPTION_CHARS: usize = 2000;
80+
78 /// The org a request is about, and what the viewer may do in it.81 /// The org a request is about, and what the viewer may do in it.
79 pub struct OrgCtx {82 pub struct OrgCtx {
80 pub org: User,83 pub org: User,
@@ -155,16 +158,6 @@ pub async fn may_create_repo_in(state: &AppState, org_id: &str, user_id: &str) -
155 }158 }
156 }159 }
157 160
158-/// The stored word for a member role.
159-pub fn member_role_word(role: OrgMemberRole) -> &'static str {
160- role.as_str()
161-}
162-
163-/// The member role a form sent, if it is one of the two.
164-pub fn parse_member_role(word: &str) -> Option<OrgMemberRole> {
165- OrgMemberRole::parse(word).ok()
166-}
167-
168 /// The redirect target `back` with the notice `word` in its query, so the next view of the page161 /// The redirect target `back` with the notice `word` in its query, so the next view of the page
169 /// shows it. `back` is an org path without a query.162 /// shows it. `back` is an org path without a query.
170 pub fn notice_href(back: &str, word: &'static str) -> String {163 pub fn notice_href(back: &str, word: &'static str) -> String {
@@ -209,7 +202,7 @@ pub async fn org_tabs(
209 repo_count: u64,202 repo_count: u64,
210 package_count: usize,203 package_count: usize,
211 ) -> Result<impl View> {204 ) -> Result<impl View> {
212- let mut tabs: Vec<(String, String, bool, String, bool)> =205+ let mut tabs: Vec<(String, String, bool, Option<String>)> =
213 profile_items(lang, &name, true, false, true)206 profile_items(lang, &name, true, false, true)
214 .into_iter()207 .into_iter()
215 .map(|item| {208 .map(|item| {
@@ -218,13 +211,7 @@ pub async fn org_tabs(
218 "packages" => Some(package_count.to_string()),211 "packages" => Some(package_count.to_string()),
219 _ => None,212 _ => None,
220 };213 };
221- (214+ (item.href, item.label.to_owned(), item.key == current, count)
222- item.href,
223- item.label.to_owned(),
224- item.key == current,
225- count.clone().unwrap_or_default(),
226- count.is_some(),
227- )
228 })215 })
229 .collect();216 .collect();
230 if owner {217 if owner {
@@ -232,16 +219,15 @@ pub async fn org_tabs(
232 format!("/org/{name}/settings"),219 format!("/org/{name}/settings"),
233 g::t(lang, K::Settings).to_owned(),220 g::t(lang, K::Settings).to_owned(),
234 current == "settings",221 current == "settings",
235- String::new(),222+ None,
236- false,
237 ));223 ));
238 }224 }
239 Ok(view! {225 Ok(view! {
240 <nav class="tabs" aria-label=(name.as_str())>226 <nav class="tabs" aria-label=(name.as_str())>
241- for (href, label, on, count, has_count) in tabs.into_iter() {227+ for (href, label, on, count) in tabs.into_iter() {
242 <a href=(href.as_str()) aria-current=(on.then_some("page"))>228 <a href=(href.as_str()) aria-current=(on.then_some("page"))>
243 (label.as_str())229 (label.as_str())
244- if has_count {230+ if let Some(count) = count {
245 " " <span class="tab-count">(count.as_str())</span>231 " " <span class="tab-count">(count.as_str())</span>
246 }232 }
247 </a>233 </a>
crates/forge-web-account/src/pages/org_live.rsmodified+2 -2
@@ -20,7 +20,7 @@ use topcoat::router::response::Response;
20 use topcoat::router::{path_param, route};20 use topcoat::router::{path_param, route};
21 21
22 use crate::live::{Topic, stream_changes};22 use crate::live::{Topic, stream_changes};
23-use crate::pages::org_ctx::{load_org, member_role_word, require_member, require_owner};23+use crate::pages::org_ctx::{load_org, require_member, require_owner};
24 use crate::pages::org_teams::{team_of, visible_team_repos};24 use crate::pages::org_teams::{team_of, visible_team_repos};
25 use crate::state::AppState;25 use crate::state::AppState;
26 26
@@ -43,7 +43,7 @@ async fn members_fingerprint(store: &Store, org_id: &str) -> Result<String> {
43 "member {} {} {}",43 "member {} {} {}",
44 user.id,44 user.id,
45 user.username,45 user.username,
46- member_role_word(role)46+ role.as_str()
47 ));47 ));
48 }48 }
49 Ok(lines.join("\n"))49 Ok(lines.join("\n"))
crates/forge-web-account/src/pages/org_members.rsmodified+6 -6
@@ -19,8 +19,8 @@ use crate::audit::{self, Actor, Target};
19 use crate::i18n::orgs::{self as g, K};19 use crate::i18n::orgs::{self as g, K};
20 use crate::i18n::{self, Lang};20 use crate::i18n::{self, Lang};
21 use crate::pages::org_ctx::{21 use crate::pages::org_ctx::{
22- load_org, member_role_word, notice_href, org_notice, org_tab_counts, org_tabs,22+ load_org, notice_href, org_notice, org_tab_counts, org_tabs, require_form_csrf,
23- parse_member_role, require_form_csrf, require_member, require_owner, take_notice,23+ require_member, require_owner, take_notice,
24 };24 };
25 use crate::state::AppState;25 use crate::state::AppState;
26 use crate::views::parts::{PeopleList, PersonRow, SubPart, head, people_list};26 use crate::views::parts::{PeopleList, PersonRow, SubPart, head, people_list};
@@ -171,7 +171,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther>
171 let state = context::<AppState>(cx);171 let state = context::<AppState>(cx);
172 let back = ctx.href("/members");172 let back = ctx.href("/members");
173 173
174- let Some(role) = parse_member_role(form.role.trim()) else {174+ let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else {
175 return Ok(see_other(notice_href(&back, "invalid_role")));175 return Ok(see_other(notice_href(&back, "invalid_role")));
176 };176 };
177 let username = form.username.trim();177 let username = form.username.trim();
@@ -207,7 +207,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther>
207 id: &ctx.org.id,207 id: &ctx.org.id,
208 name: &ctx.org.username,208 name: &ctx.org.username,
209 },209 },
210- serde_json::json!({ "user": target.username, "role": member_role_word(role) }),210+ serde_json::json!({ "user": target.username, "role": role.as_str() }),
211 )211 )
212 .await;212 .await;
213 Ok(see_other(notice_href(&back, "member_added")))213 Ok(see_other(notice_href(&back, "member_added")))
@@ -222,7 +222,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe
222 let state = context::<AppState>(cx);222 let state = context::<AppState>(cx);
223 let back = ctx.href("/members");223 let back = ctx.href("/members");
224 224
225- let Some(role) = parse_member_role(form.role.trim()) else {225+ let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else {
226 return Ok(see_other(notice_href(&back, "invalid_role")));226 return Ok(see_other(notice_href(&back, "invalid_role")));
227 };227 };
228 let user_id = form.user_id.trim();228 let user_id = form.user_id.trim();
@@ -255,7 +255,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe
255 id: &ctx.org.id,255 id: &ctx.org.id,
256 name: &ctx.org.username,256 name: &ctx.org.username,
257 },257 },
258- serde_json::json!({ "user": user_id, "role": member_role_word(role) }),258+ serde_json::json!({ "user": user_id, "role": role.as_str() }),
259 )259 )
260 .await;260 .await;
261 Ok(see_other(notice_href(&back, "role_updated")))261 Ok(see_other(notice_href(&back, "role_updated")))
crates/forge-web-account/src/pages/org_new.rsmodified+2 -3
@@ -17,12 +17,11 @@ use crate::auth::{require_csrf, require_user};
17 use crate::i18n::orgs::{self as g, K};17 use crate::i18n::orgs::{self as g, K};
18 use crate::i18n::{self, Lang};18 use crate::i18n::{self, Lang};
19 use crate::live::Topic;19 use crate::live::Topic;
20+use crate::pages::org_ctx::MAX_DESCRIPTION_CHARS;
20 use crate::state::AppState;21 use crate::state::AppState;
21 use crate::views::parts::head;22 use crate::views::parts::head;
22 use crate::views::{alert, csrf_field, shell, user_facing_message};23 use crate::views::{alert, csrf_field, shell, user_facing_message};
23 24
24-const MAX_DESCRIPTION_CHARS: usize = 2000;
25-
26 #[derive(Deserialize)]25 #[derive(Deserialize)]
27 struct NewOrgForm {26 struct NewOrgForm {
28 #[serde(default)]27 #[serde(default)]
@@ -53,7 +52,7 @@ async fn new_org_form(
53 ) -> Result<impl View> {52 ) -> Result<impl View> {
54 Ok(view! {53 Ok(view! {
55 head(title: g::t(lang, K::NewOrganization), sub: Vec::new())54 head(title: g::t(lang, K::NewOrganization), sub: Vec::new())
56- crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "organizations".to_owned())55+ crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Organizations)
57 <div class="sheet fit">56 <div class="sheet fit">
58 if let Some(message) = error {57 if let Some(message) = error {
59 alert(message: message.as_str())58 alert(message: message.as_str())
crates/forge-web-account/src/pages/org_settings.rsmodified+2 -4
@@ -22,8 +22,8 @@ use crate::i18n::orgs::{self as g, K};
22 use crate::i18n::{self, Key, Lang, t};22 use crate::i18n::{self, Key, Lang, t};
23 use crate::live::Topic;23 use crate::live::Topic;
24 use crate::pages::org_ctx::{24 use crate::pages::org_ctx::{
25- DEFAULT_ROLES, load_org, notice_href, org_notice, org_tab_counts, org_tabs, require_form_csrf,25+ DEFAULT_ROLES, MAX_DESCRIPTION_CHARS, load_org, notice_href, org_notice, org_tab_counts,
26- require_owner, take_notice,26+ org_tabs, require_form_csrf, require_owner, take_notice,
27 };27 };
28 use crate::pages::settings_profile::store_avatar;28 use crate::pages::settings_profile::store_avatar;
29 use crate::state::AppState;29 use crate::state::AppState;
@@ -32,8 +32,6 @@ use crate::views::{avatar_url, shell, user_facing_message};
32 32
33 path_param!(org);33 path_param!(org);
34 34
35-const MAX_DESCRIPTION_CHARS: usize = 2000;
36-
37 #[derive(Deserialize)]35 #[derive(Deserialize)]
38 struct SettingsForm {36 struct SettingsForm {
39 #[serde(default)]37 #[serde(default)]
crates/forge-web-account/src/pages/org_teams.rsmodified+0 -12
@@ -782,18 +782,6 @@ mod tests {
782 assert_eq!(parse_team_role(""), None);782 assert_eq!(parse_team_role(""), None);
783 }783 }
784 784
785- #[test]
786- fn coverage_reads_in_words() {
787- assert_eq!(
788- g::coverage_text(Lang::En, "write", true),
789- "write on all repositories"
790- );
791- assert_eq!(
792- g::coverage_text(Lang::En, "read", false),
793- "read on linked repositories"
794- );
795- }
796-
797 #[test]785 #[test]
798 fn duplicate_and_bad_names_get_their_own_notices() {786 fn duplicate_and_bad_names_get_their_own_notices() {
799 let dup = forge_core::Error::Conflict("taken".into());787 let dup = forge_core::Error::Conflict("taken".into());
crates/forge-web-account/src/pages/profile.rsmodified+87 -181
@@ -1,11 +1,3 @@
1-//! Page: public profile at `/{username}`. Avatar, about (rendered markdown) and local time, then
2-//! the tabs: `overview` (pinned repos, or the most recently active ones when nothing is pinned,
3-//! plus a person's contribution calendar, or an organization's members and teams), `repositories`,
4-//! `snippets` (people only), `stars`, `packages` and `organizations` (the viewer's own only). The
5-//! repo tabs list what the viewer is allowed to read, 10 per page, so a page fits the screen,, with a name filter and three
6-//! sort orders; the filtering, sorting and paging run in the database. Fixed single-segment routes
7-//! are registered statically, so they win over this parameter route.
8-
9 use forge_core::authz::{Action, authorize};1 use forge_core::authz::{Action, authorize};
10 use forge_core::store::RepoSort;2 use forge_core::store::RepoSort;
11 use forge_core::store::orgs::OrgMemberRole;3 use forge_core::store::orgs::OrgMemberRole;
@@ -47,47 +39,35 @@ use crate::views::{
47 39
48 path_param!(username);40 path_param!(username);
49 41
50-/// Repos per page on the repositories and stars tabs.
51 const PER_PAGE: u64 = 10;42 const PER_PAGE: u64 = 10;
52-/// What the pin menu needs: shown to whoever may edit the pins, on the overview.43+const BATCH: u64 = 100;
53 struct PinsMenu {44 struct PinsMenu {
54 action: String,45 action: String,
55 csrf: String,46 csrf: String,
56 options: Vec<PinOption>,47 options: Vec<PinOption>,
57 }48 }
58 49
59-/// Repos the overview shows when the owner has no visible pins.
60 const POPULAR_COUNT: usize = 6;50 const POPULAR_COUNT: usize = 6;
61-/// Members an organization's overview lists; a longer list links to the members page.
62 const ORG_MEMBERS_SHOWN: usize = 12;51 const ORG_MEMBERS_SHOWN: usize = 12;
63-/// Repos the name filter reads at once. The filter runs in Rust, so it covers every repo in scope.
64-const SEARCH_CAP: u64 = 5000;
65 52
66 #[query_params(error = bad_request)]53 #[query_params(error = bad_request)]
67 struct ProfileQuery {54 struct ProfileQuery {
68 tab: Option<String>,55 tab: Option<String>,
69 q: Option<String>,56 q: Option<String>,
70- /// Set when the filter asks for the text as typed, as one piece.
71 exact: Option<String>,57 exact: Option<String>,
72- /// Set when the filter keeps upper and lower case apart.
73 case: Option<String>,58 case: Option<String>,
74 sort: Option<String>,59 sort: Option<String>,
75 page: Option<String>,60 page: Option<String>,
76- /// A calendar day whose contributions to list under the calendar on the overview.
77 day: Option<String>,61 day: Option<String>,
78- /// `too_many` after a save with more pins than the limit.
79 pins: Option<String>,62 pins: Option<String>,
80 }63 }
81 64
82-/// Sort keys of the repo tabs in the order their chips are shown, with the label of each. The
83-/// first one is the default.
84 const SORTS: [(&str, K); 3] = [65 const SORTS: [(&str, K); 3] = [
85 ("updated", K::SortRecentlyUpdated),66 ("updated", K::SortRecentlyUpdated),
86 ("name", K::Name),67 ("name", K::Name),
87 ("stars", K::SortMostStars),68 ("stars", K::SortMostStars),
88 ];69 ];
89 70
90-/// Maps the `sort` query value to a key from `SORTS`; anything unknown means the default.
91 fn sort_key(raw: Option<&str>) -> &'static str {71 fn sort_key(raw: Option<&str>) -> &'static str {
92 SORTS72 SORTS
93 .iter()73 .iter()
@@ -96,6 +76,40 @@ fn sort_key(raw: Option<&str>) -> &'static str {
96 .unwrap_or(SORTS[0].0)76 .unwrap_or(SORTS[0].0)
97 }77 }
98 78
79+#[derive(Clone, Copy, PartialEq, Eq)]
80+pub enum Tab {
81+ Overview,
82+ Repositories,
83+ Snippets,
84+ Stars,
85+ Packages,
86+ Organizations,
87+}
88+
89+impl Tab {
90+ fn from_query(raw: Option<&str>) -> Self {
91+ match raw {
92+ Some("repositories") => Self::Repositories,
93+ Some("snippets") => Self::Snippets,
94+ Some("stars") => Self::Stars,
95+ Some("packages") => Self::Packages,
96+ Some("organizations") => Self::Organizations,
97+ _ => Self::Overview,
98+ }
99+ }
100+
101+ fn key(self) -> &'static str {
102+ match self {
103+ Self::Overview => "overview",
104+ Self::Repositories => "repositories",
105+ Self::Snippets => "snippets",
106+ Self::Stars => "stars",
107+ Self::Packages => "packages",
108+ Self::Organizations => "organizations",
109+ }
110+ }
111+}
112+
99 #[page("/{username}")]113 #[page("/{username}")]
100 async fn profile_page(cx: &Cx) -> Result<impl View> {114 async fn profile_page(cx: &Cx) -> Result<impl View> {
101 let name = username(cx);115 let name = username(cx);
@@ -117,15 +131,12 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
117 131
118 let actor = viewer.as_ref().map(|(u, _)| u);132 let actor = viewer.as_ref().map(|(u, _)| u);
119 let lang = i18n::lang(cx, actor);133 let lang = i18n::lang(cx, actor);
120- // Whether the viewer is this person. Only the person sees their Organizations tab and edit links.
121 let own = !user.is_org() && actor.is_some_and(|u| u.id == user.id);134 let own = !user.is_org() && actor.is_some_and(|u| u.id == user.id);
122- let tab = tab_key(query.tab.as_deref());135+ let tab = Tab::from_query(query.tab.as_deref());
123- // An organization cannot be starred or keep snippets, so those tabs show the overview instead.136+ let tab = if (user.is_org() && matches!(tab, Tab::Stars | Tab::Snippets))
124- // The Organizations tab is the viewer's own, so anyone else gets the overview.137+ || (tab == Tab::Organizations && !own)
125- let tab = if (user.is_org() && matches!(tab, "stars" | "snippets"))
126- || (tab == "organizations" && !own)
127 {138 {
128- "overview"139+ Tab::Overview
129 } else {140 } else {
130 tab141 tab
131 };142 };
@@ -137,17 +148,14 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
137 let page = page_number(query.page.as_deref());148 let page = page_number(query.page.as_deref());
138 let sort = sort_key(query.sort.as_deref());149 let sort = sort_key(query.sort.as_deref());
139 150
140- // The tab labels count what the viewer may read, with no filter.
141 let owned = RepoScope::OwnedBy(&user.id);151 let owned = RepoScope::OwnedBy(&user.id);
142 let starred = RepoScope::StarredBy(&user.id);152 let starred = RepoScope::StarredBy(&user.id);
143 let repo_total = state.store.count_visible_repos(owned, actor).await?;153 let repo_total = state.store.count_visible_repos(owned, actor).await?;
144 let star_total = state.store.count_visible_repos(starred, actor).await?;154 let star_total = state.store.count_visible_repos(starred, actor).await?;
145 155
146- // The overview shows the owner's pins that the viewer may read. With none visible, it shows
147- // the most recently active repos instead.
148 let mut cards = Vec::new();156 let mut cards = Vec::new();
149 let mut from_pins = true;157 let mut from_pins = true;
150- if tab == "overview" {158+ if tab == Tab::Overview {
151 let mut shown = readable(159 let mut shown = readable(
152 state,160 state,
153 actor,161 actor,
@@ -171,7 +179,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
171 }179 }
172 }180 }
173 181
174- // The viewer's role in an organization, looked up once for the header, the tabs and the pins.
175 let org_role = match actor {182 let org_role = match actor {
176 Some(u) if user.is_org() => state.store.org_member_role(&user.id, &u.id).await?,183 Some(u) if user.is_org() => state.store.org_member_role(&user.id, &u.id).await?,
177 _ => None,184 _ => None,
@@ -185,14 +192,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
185 _ => false,192 _ => false,
186 };193 };
187 194
188- // An organization's pins are edited by its owners, a user's by the user.
189 let can_edit_pins = match actor {195 let can_edit_pins = match actor {
190 Some(_) if user.is_org() => org_owner,196 Some(_) if user.is_org() => org_owner,
191 Some(u) => u.id == user.id,197 Some(u) => u.id == user.id,
192 None => false,198 None => false,
193 };199 };
194 let mut pins_menu_data = None;200 let mut pins_menu_data = None;
195- if can_edit_pins && tab == "overview" {201+ if can_edit_pins && tab == Tab::Overview {
196 let options = pin_options(&state.store, &user.id).await?;202 let options = pin_options(&state.store, &user.id).await?;
197 if let (false, Some((_, session))) = (options.is_empty(), viewer.as_ref()) {203 if let (false, Some((_, session))) = (options.is_empty(), viewer.as_ref()) {
198 let action = if user.is_org() {204 let action = if user.is_org() {
@@ -209,15 +215,12 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
209 }215 }
210 let pins_error = can_edit_pins && query.pins.as_deref() == Some("too_many");216 let pins_error = can_edit_pins && query.pins.as_deref() == Some("too_many");
211 217
212- // The contribution calendar on the overview, for a person only. Its counts and day links use218+ let heat = if tab == Tab::Overview && !user.is_org() {
213- // public repos alone, so anyone may see it.
214- let heat = if tab == "overview" && !user.is_org() {
215 Some(load_calendar(state, &user, query.day.as_deref()).await?)219 Some(load_calendar(state, &user, query.day.as_deref()).await?)
216 } else {220 } else {
217 None221 None
218 };222 };
219 223
220- // The Snippets tab lists the person's snippets the viewer may read. An organization keeps none.
221 let snippets: Vec<ListRow> = if user.is_org() {224 let snippets: Vec<ListRow> = if user.is_org() {
222 Vec::new()225 Vec::new()
223 } else {226 } else {
@@ -229,18 +232,11 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
229 .map(|summary| list_row(lang, summary))232 .map(|summary| list_row(lang, summary))
230 .collect()233 .collect()
231 };234 };
232- // Snippets page like the repo tabs, so the tab fits the screen however many there are.
233 let snippet_total = snippets.len() as u64;235 let snippet_total = snippets.len() as u64;
234 let snippet_pages = snippet_total.div_ceil(PER_PAGE).max(1);236 let snippet_pages = snippet_total.div_ceil(PER_PAGE).max(1);
235 let snippet_page = page.min(snippet_pages);237 let snippet_page = page.min(snippet_pages);
236 let snippet_pager = pager_links(snippet_page, snippet_pages, |n| {238 let snippet_pager = pager_links(snippet_page, snippet_pages, |n| {
237- profile_href(239+ profile_href(&user.username, Tab::Snippets.key(), &Finder::default(), SORTS[0].0, n)
238- &user.username,
239- "snippets",
240- &Finder::default(),
241- SORTS[0].0,
242- n,
243- )
244 });240 });
245 let snippets: Vec<ListRow> = snippets241 let snippets: Vec<ListRow> = snippets
246 .into_iter()242 .into_iter()
@@ -248,10 +244,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
248 .take(PER_PAGE as usize)244 .take(PER_PAGE as usize)
249 .collect();245 .collect();
250 246
251- // The viewer's Organizations tab lists the organizations they belong to, and whether the
252- // instance lets them create one.
253 let (orgs, org_create_allowed) = match actor {247 let (orgs, org_create_allowed) = match actor {
254- Some(viewer_user) if tab == "organizations" => {248+ Some(viewer_user) if tab == Tab::Organizations => {
255 let mut cards = Vec::new();249 let mut cards = Vec::new();
256 for (org, role) in state.store.orgs_for_user(&user.id).await? {250 for (org, role) in state.store.orgs_for_user(&user.id).await? {
257 let hash = state.store.avatar_hash(&org.id).await?;251 let hash = state.store.avatar_hash(&org.id).await?;
@@ -276,8 +270,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
276 };270 };
277 271
278 let listing = match tab {272 let listing = match tab {
279- "repositories" | "stars" => {273+ Tab::Repositories | Tab::Stars => {
280- let scope = if tab == "stars" { starred } else { owned };274+ let scope = if tab == Tab::Stars { starred } else { owned };
281 let sort_kind = match sort {275 let sort_kind = match sort {
282 "stars" => RepoSort::MostStars,276 "stars" => RepoSort::MostStars,
283 "name" => RepoSort::Name,277 "name" => RepoSort::Name,
@@ -289,12 +283,20 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
289 .list_visible_repos(scope, actor, None, sort_kind, page, PER_PAGE)283 .list_visible_repos(scope, actor, None, sort_kind, page, PER_PAGE)
290 .await?284 .await?
291 } else {285 } else {
292- // The search reads each repo's name and description, so it runs here over every286+ let mut all = Vec::new();
293- // repo in scope, then takes the one page asked for.287+ let mut batch_page = 1;
294- let (all, _) = state288+ loop {
295- .store289+ let (batch, in_scope) = state
296- .list_visible_repos(scope, actor, None, sort_kind, 1, SEARCH_CAP)290+ .store
297- .await?;291+ .list_visible_repos(scope, actor, None, sort_kind, batch_page, BATCH)
292+ .await?;
293+ let fetched_none = batch.is_empty();
294+ all.extend(batch);
295+ if fetched_none || all.len() as u64 >= in_scope {
296+ break;
297+ }
298+ batch_page += 1;
299+ }
298 let matching: Vec<_> = all300 let matching: Vec<_> = all
299 .into_iter()301 .into_iter()
300 .filter(|(repo, _, _)| {302 .filter(|(repo, _, _)| {
@@ -302,6 +304,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
302 })304 })
303 .collect();305 .collect();
304 let total = matching.len() as u64;306 let total = matching.len() as u64;
307+ let page = page.min(total.div_ceil(PER_PAGE).max(1));
305 let shown = matching308 let shown = matching
306 .into_iter()309 .into_iter()
307 .skip(((page - 1) * PER_PAGE) as usize)310 .skip(((page - 1) * PER_PAGE) as usize)
@@ -313,10 +316,10 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
313 let now = now_unix();316 let now = now_unix();
314 let empty = match (tab, finder.is_empty()) {317 let empty = match (tab, finder.is_empty()) {
315 (_, false) => g::t(lang, K::NoReposMatch),318 (_, false) => g::t(lang, K::NoReposMatch),
316- ("stars", true) => g::t(lang, K::NoVisibleStarred),319+ (Tab::Stars, true) => g::t(lang, K::NoVisibleStarred),
317 _ => g::t(lang, K::NoVisibleRepos),320 _ => g::t(lang, K::NoVisibleRepos),
318 };321 };
319- let count_text = if tab == "stars" {322+ let count_text = if tab == Tab::Stars {
320 g::starred_count(lang, total)323 g::starred_count(lang, total)
321 } else {324 } else {
322 g::repo_count(lang, total)325 g::repo_count(lang, total)
@@ -331,13 +334,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
331 page,334 page,
332 pages,335 pages,
333 pager: pager_links(page, pages, |n| {336 pager: pager_links(page, pages, |n| {
334- profile_href(&user.username, tab, &finder, sort, n)337+ profile_href(&user.username, tab.key(), &finder, sort, n)
335 }),338 }),
336 sort_links: SORTS339 sort_links: SORTS
337 .iter()340 .iter()
338 .map(|(key, label)| SortLink {341 .map(|(key, label)| SortLink {
339 label: g::t(lang, *label),342 label: g::t(lang, *label),
340- href: profile_href(&user.username, tab, &finder, key, 1),343+ href: profile_href(&user.username, tab.key(), &finder, key, 1),
341 current: *key == sort,344 current: *key == sort,
342 })345 })
343 .collect(),346 .collect(),
@@ -348,8 +351,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
348 _ => Listing::default(),351 _ => Listing::default(),
349 };352 };
350 353
351- // An organization shows its members (the first few, with their avatars) and how many teams it
352- // has. Its `about` is its description.
353 let org = if user.is_org() {354 let org = if user.is_org() {
354 let members = state.store.org_members(&user.id).await?;355 let members = state.store.org_members(&user.id).await?;
355 let teams = state.store.teams_for_org(&user.id).await?.len();356 let teams = state.store.teams_for_org(&user.id).await?.len();
@@ -369,18 +370,16 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
369 None370 None
370 };371 };
371 372
372- // The Packages tab lists the registry's packages the viewer may see.
373 let package_rows = packages::package_rows(state, actor, &user).await?;373 let package_rows = packages::package_rows(state, actor, &user).await?;
374- let packages_on = tab == "packages";374+ let packages_on = tab == Tab::Packages;
375 375
376- // A repo deleted just before this redirect here shows its one-line notice once.
377 let notice = take_notice(cx);376 let notice = take_notice(cx);
378 let title = user.username.clone();377 let title = user.username.clone();
379 Ok(view! {378 Ok(view! {
380 shell(title: title.as_str(), viewer: viewer.as_ref(),379 shell(title: title.as_str(), viewer: viewer.as_ref(),
381 notice_banner_for(lang: lang, title: notice)380 notice_banner_for(lang: lang, title: notice)
382 profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time,381 profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time,
383- org: org, lang: lang, tab: tab.to_owned(), finder: finder, sort: sort, repo_total: repo_total,382+ org: org, lang: lang, tab: tab, finder: finder, sort: sort, repo_total: repo_total,
384 star_total: star_total, cards: cards, from_pins: from_pins,383 star_total: star_total, cards: cards, from_pins: from_pins,
385 pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing,384 pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing,
386 packages_on: packages_on, package_rows: package_rows,385 packages_on: packages_on, package_rows: package_rows,
@@ -391,9 +390,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
391 })390 })
392 }391 }
393 392
394-/// The profile's change stream. It follows the user's topic: repos created, changed or starred,
395-/// pins, and pushes by the user. The stream is keyed by the username in the URL, but the viewer
396-/// comes from the session, so what it sends is what that viewer may read. An unknown name is 404.
397 #[route(GET "/users/{username}/events")]393 #[route(GET "/users/{username}/events")]
398 async fn profile_events(cx: &Cx) -> Result<Response> {394 async fn profile_events(cx: &Cx) -> Result<Response> {
399 let name = username(cx);395 let name = username(cx);
@@ -412,8 +408,6 @@ async fn profile_events(cx: &Cx) -> Result<Response> {
412 .await408 .await
413 }409 }
414 410
415-/// The state the profile shows: the tab counts, the pins with their stars, and the first page of
416-/// the owner's repos as the default tab lists them.
417 async fn profile_fingerprint(411 async fn profile_fingerprint(
418 state: &AppState,412 state: &AppState,
419 user: &User,413 user: &User,
@@ -433,7 +427,6 @@ async fn profile_fingerprint(
433 .await?427 .await?
434 .to_string(),428 .to_string(),
435 ];429 ];
436- // The header's about text and avatar, read fresh: the stream's `user` is a snapshot from connect.
437 let about = state430 let about = state
438 .store431 .store
439 .user_by_id(&user.id)432 .user_by_id(&user.id)
@@ -445,13 +438,11 @@ async fn profile_fingerprint(
445 "avatar {}",438 "avatar {}",
446 state.store.avatar_hash(&user.id).await?.unwrap_or_default()439 state.store.avatar_hash(&user.id).await?.unwrap_or_default()
447 ));440 ));
448- // An organization's page shows its member and team counts.
449 if user.is_org() {441 if user.is_org() {
450 let members = state.store.org_members(&user.id).await?.len();442 let members = state.store.org_members(&user.id).await?.len();
451 let teams = state.store.teams_for_org(&user.id).await?.len();443 let teams = state.store.teams_for_org(&user.id).await?.len();
452 lines.push(format!("org {members} {teams}"));444 lines.push(format!("org {members} {teams}"));
453 } else {445 } else {
454- // The overview shows a person's calendar, so its total moves with each one.
455 let total: u64 = state446 let total: u64 = state
456 .store447 .store
457 .contribution_counts(&user.id, &calendar_since(), &user.timezone)448 .contribution_counts(&user.id, &calendar_since(), &user.timezone)
@@ -485,38 +476,30 @@ async fn profile_fingerprint(
485 Ok(lines.join("\n"))476 Ok(lines.join("\n"))
486 }477 }
487 478
488-/// What an organization's profile adds: its member count, the first members to list, and its team
489-/// count.
490 struct OrgSummary {479 struct OrgSummary {
491 total: usize,480 total: usize,
492 members: Vec<OrgMember>,481 members: Vec<OrgMember>,
493 teams: usize,482 teams: usize,
494 }483 }
495 484
496-/// A member on an organization's overview: the login name and the avatar URL.
497 struct OrgMember {485 struct OrgMember {
498 username: String,486 username: String,
499 avatar: String,487 avatar: String,
500 }488 }
501 489
502-/// A repo card on the overview: the repo and its star count.
503 struct PinCard {490 struct PinCard {
504 repo: Repo,491 repo: Repo,
505 stars: u64,492 stars: u64,
506 }493 }
507 494
508-/// One organization on the viewer's own Organizations tab, with its strings ready for the view.
509 struct OrgCard {495 struct OrgCard {
510 href: String,496 href: String,
511 avatar: String,497 avatar: String,
512 name: String,498 name: String,
513- /// Empty when the organization has no display name.
514 display_name: String,499 display_name: String,
515 role: &'static str,500 role: &'static str,
516 }501 }
517 502
518-/// One page of a repo tab: the rows, the pager, the sort chips, the match count text and the
519-/// empty-list text.
520 #[derive(Default)]503 #[derive(Default)]
521 struct Listing {504 struct Listing {
522 rows: Vec<RepoRow>,505 rows: Vec<RepoRow>,
@@ -528,25 +511,10 @@ struct Listing {
528 empty: &'static str,511 empty: &'static str,
529 }512 }
530 513
531-/// The profile tabs, by their `?tab=` key. Anything unknown is the overview.
532-fn tab_key(raw: Option<&str>) -> &'static str {
533- match raw {
534- Some("repositories") => "repositories",
535- Some("snippets") => "snippets",
536- Some("stars") => "stars",
537- Some("packages") => "packages",
538- Some("organizations") => "organizations",
539- _ => "overview",
540- }
541-}
542-
543-/// The `?page=` value, 1-based. Anything unreadable is page 1.
544 fn page_number(raw: Option<&str>) -> u64 {514 fn page_number(raw: Option<&str>) -> u64 {
545 raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1)515 raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1)
546 }516 }
547 517
548-/// The profile URL for a tab, with the name filter, a sort other than the default and the page
549-/// when they are set.
550 fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String {518 fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String {
551 let mut href = format!("/{}?tab={tab}", enc(name));519 let mut href = format!("/{}?tab={tab}", enc(name));
552 if !finder.is_empty() {520 if !finder.is_empty() {
@@ -567,9 +535,6 @@ fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -
567 href535 href
568 }536 }
569 537
570-/// Whether the viewer may read `repo`. Public repos, and repos the viewer owns or administers,
571-/// need no role lookup. Other private repos get their collaborator and org roles, and `authorize`
572-/// makes the final call either way.
573 async fn may_read(state: &AppState, actor: Option<&User>, repo: &Repo) -> Result<bool> {538 async fn may_read(state: &AppState, actor: Option<&User>, repo: &Repo) -> Result<bool> {
574 let open = repo.visibility == Visibility::Public539 let open = repo.visibility == Visibility::Public
575 || actor.is_some_and(|u| u.is_admin || u.id == repo.owner_id);540 || actor.is_some_and(|u| u.is_admin || u.id == repo.owner_id);
@@ -586,7 +551,6 @@ async fn may_read(state: &AppState, actor: Option<&User>, repo: &Repo) -> Result
586 Ok(authorize(actor, repo, role, org_role, Action::Read).is_ok())551 Ok(authorize(actor, repo, role, org_role, Action::Read).is_ok())
587 }552 }
588 553
589-/// The first `limit` repos of `repos` that the viewer may read, in their order.
590 async fn readable(554 async fn readable(
591 state: &AppState,555 state: &AppState,
592 actor: Option<&User>,556 actor: Option<&User>,
@@ -614,7 +578,7 @@ async fn profile_card(
614 local_time: String,578 local_time: String,
615 org: Option<OrgSummary>,579 org: Option<OrgSummary>,
616 lang: Lang,580 lang: Lang,
617- tab: String,581+ tab: Tab,
618 finder: Finder,582 finder: Finder,
619 sort: &'static str,583 sort: &'static str,
620 repo_total: u64,584 repo_total: u64,
@@ -640,16 +604,14 @@ async fn profile_card(
640 ) -> Result<impl View> {604 ) -> Result<impl View> {
641 let has_snippets = !snippets.is_empty();605 let has_snippets = !snippets.is_empty();
642 let (snippet_page, snippet_pages, (snippet_links, snippet_prev, snippet_next)) = snippet_paging;606 let (snippet_page, snippet_pages, (snippet_links, snippet_prev, snippet_next)) = snippet_paging;
643- let snippets_on = tab == "snippets";607+ let snippets_on = tab == Tab::Snippets;
644- let orgs_on = tab == "organizations";608+ let orgs_on = tab == Tab::Organizations;
645 let has_orgs = !orgs.is_empty();609 let has_orgs = !orgs.is_empty();
646 let packages_events = packages::events_href(&user.username);610 let packages_events = packages::events_href(&user.username);
647 let has_packages = !package_rows.is_empty();611 let has_packages = !package_rows.is_empty();
648 let src = avatar_url(&user.username, avatar.as_deref());612 let src = avatar_url(&user.username, avatar.as_deref());
649 let has_about = !about_html.is_empty();613 let has_about = !about_html.is_empty();
650 let is_org = user.is_org();614 let is_org = user.is_org();
651- // An organization's header avatar is smaller. The tab bar comes from the shared list, with the
652- // counts that go on its labels.
653 let avatar_px = if is_org { "96" } else { "256" };615 let avatar_px = if is_org { "96" } else { "256" };
654 let avatar_class = if is_org {616 let avatar_class = if is_org {
655 "profile-avatar org-avatar"617 "profile-avatar org-avatar"
@@ -665,9 +627,9 @@ async fn profile_card(
665 ("packages", package_rows.len().to_string()),627 ("packages", package_rows.len().to_string()),
666 ];628 ];
667 let base = format!("/{}", enc(&user.username));629 let base = format!("/{}", enc(&user.username));
668- let overview_on = tab == "overview";630+ let overview_on = tab == Tab::Overview;
669- let repos_on = tab == "repositories";631+ let repos_on = tab == Tab::Repositories;
670- let stars_on = tab == "stars";632+ let stars_on = tab == Tab::Stars;
671 let list_on = repos_on || stars_on;633 let list_on = repos_on || stars_on;
672 let pinned_heading = if from_pins {634 let pinned_heading = if from_pins {
673 g::t(lang, K::Pinned)635 g::t(lang, K::Pinned)
@@ -677,7 +639,6 @@ async fn profile_card(
677 let has_cards = !cards.is_empty();639 let has_cards = !cards.is_empty();
678 let edit_label = mi::t(lang, MK::EditProfile);640 let edit_label = mi::t(lang, MK::EditProfile);
679 let org_edit_label = mi::t(lang, MK::EditOrganization);641 let org_edit_label = mi::t(lang, MK::EditOrganization);
680- // The display name is the heading when set; the username then moves under it.
681 let has_name = user.display_name.is_some();642 let has_name = user.display_name.is_some();
682 let heading = user643 let heading = user
683 .display_name644 .display_name
@@ -700,8 +661,6 @@ async fn profile_card(
700 let members_more = org661 let members_more = org
701 .as_ref()662 .as_ref()
702 .is_some_and(|summary| org_member && summary.total > summary.members.len());663 .is_some_and(|summary| org_member && summary.total > summary.members.len());
703- // The sub line: the username under a display name, then whether this is an organization or the
704- // person's local time.
705 let mut sub = Vec::new();664 let mut sub = Vec::new();
706 if has_name {665 if has_name {
707 sub.push(SubPart::text(user.username.as_str()));666 sub.push(SubPart::text(user.username.as_str()));
@@ -734,7 +693,7 @@ async fn profile_card(
734 <a class="button" href="/org/new">(g::t(lang, K::NewOrganization))</a>693 <a class="button" href="/org/new">(g::t(lang, K::NewOrganization))</a>
735 }694 }
736 )695 )
737- profile_tabs(username: user.username.clone(), items: tab_items, current: tab.clone(), counts: tab_counts)696+ profile_tabs(username: user.username.clone(), items: tab_items, current: tab, counts: tab_counts)
738 <div class="sheet" data-live=(format!("/users/{}/events", user.username))>697 <div class="sheet" data-live=(format!("/users/{}/events", user.username))>
739 if has_about {698 if has_about {
740 <section class="sec profile-about markdown-body">(Unescaped::new_unchecked(about_html))</section>699 <section class="sec profile-about markdown-body">(Unescaped::new_unchecked(about_html))</section>
@@ -806,7 +765,7 @@ async fn profile_card(
806 <div class="sheet-tools">765 <div class="sheet-tools">
807 <strong>(count_text.as_str())</strong>766 <strong>(count_text.as_str())</strong>
808 <form method="get" action=(base.as_str()) role="search">767 <form method="get" action=(base.as_str()) role="search">
809- <input type="hidden" name="tab" value=(tab.as_str())>768+ <input type="hidden" name="tab" value=(tab.key())>
810 <input type="hidden" name="sort" value=(sort)>769 <input type="hidden" name="sort" value=(sort)>
811 finder_field(lang: lang, finder: finder, placeholder: filter_label, id: Some("profile-q"))770 finder_field(lang: lang, finder: finder, placeholder: filter_label, id: Some("profile-q"))
812 </form>771 </form>
@@ -879,14 +838,12 @@ async fn profile_card(
879 })838 })
880 }839 }
881 840
882-/// The viewer's own profile tabs on a page that makes something of theirs (a repository, a
883-/// snippet, an organization): the same tabs and counts as their profile, with `current` marked.
884 #[component]841 #[component]
885 pub async fn own_profile_tabs(842 pub async fn own_profile_tabs(
886 cx: &Cx,843 cx: &Cx,
887 lang: Lang,844 lang: Lang,
888 username: String,845 username: String,
889- current: String,846+ current: Tab,
890 ) -> Result<impl View> {847 ) -> Result<impl View> {
891 let items = crate::views::profile_items(lang, &username, false, true, false);848 let items = crate::views::profile_items(lang, &username, false, true, false);
892 let mut counts = Vec::new();849 let mut counts = Vec::new();
@@ -920,53 +877,34 @@ pub async fn own_profile_tabs(
920 })877 })
921 }878 }
922 879
923-/// The profile tab bar: one link per item, the current tab marked, and a count after the label of
924-/// each tab that has one in `counts`, by the item's key. A person's, an organization's and an
925-/// organization's member pages all render it.
926 #[component]880 #[component]
927 pub async fn profile_tabs(881 pub async fn profile_tabs(
928 cx: &Cx,882 cx: &Cx,
929 username: String,883 username: String,
930 items: Vec<NavItem>,884 items: Vec<NavItem>,
931- current: String,885+ current: Tab,
932 counts: Vec<(&'static str, String)>,886 counts: Vec<(&'static str, String)>,
933 ) -> Result<impl View> {887 ) -> Result<impl View> {
934- let rows: Vec<(String, String, bool, String, bool)> = items888+ let rows: Vec<(String, String, bool, Option<String>)> = items
935 .into_iter()889 .into_iter()
936 .map(|item| {890 .map(|item| {
937- let on = item.key == current;891+ let on = item.key == current.key();
938 let count = counts892 let count = counts
939 .iter()893 .iter()
940 .find(|(key, _)| *key == item.key)894 .find(|(key, _)| *key == item.key)
941 .map(|(_, count)| count.clone());895 .map(|(_, count)| count.clone());
942- let has_count = count.is_some();896+ (item.href, item.label.to_owned(), on, count)
943- (
944- item.href,
945- item.label.to_owned(),
946- on,
947- count.unwrap_or_default(),
948- has_count,
949- )
950 })897 })
951 .collect();898 .collect();
952 Ok(view! {899 Ok(view! {
953 <nav class="tabs" aria-label=(username.as_str())>900 <nav class="tabs" aria-label=(username.as_str())>
954- for (href, label, on, count, has_count) in rows.into_iter() {901+ for (href, label, on, count) in rows.into_iter() {
955- if on {902+ <a href=(href.as_str()) aria-current=(on.then_some("page"))>
956- <a href=(href.as_str()) aria-current="page">903+ (label.as_str())
957- (label.as_str())904+ if let Some(count) = count {
958- if has_count {905+ " " <span class="tab-count">(count.as_str())</span>
959- " " <span class="tab-count">(count.as_str())</span>906+ }
960- }907+ </a>
961- </a>
962- } else {
963- <a href=(href.as_str())>
964- (label.as_str())
965- if has_count {
966- " " <span class="tab-count">(count.as_str())</span>
967- }
968- </a>
969- }
970 }908 }
971 </nav>909 </nav>
972 })910 })
@@ -1003,7 +941,6 @@ mod tests {
1003 }941 }
1004 }942 }
1005 943
1006- /// Creates a session for `user_id` and returns the cookie header value.
1007 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {944 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
1008 crate::test_support::create_session(store, user_id, token, CSRF).await;945 crate::test_support::create_session(store, user_id, token, CSRF).await;
1009 format!("__Host-{SESSION_COOKIE}={token}")946 format!("__Host-{SESSION_COOKIE}={token}")
@@ -1020,7 +957,6 @@ mod tests {
1020 (status, String::from_utf8_lossy(&bytes).into_owned())957 (status, String::from_utf8_lossy(&bytes).into_owned())
1021 }958 }
1022 959
1023- /// Tahinli has a public repo, a private repo and a private repo that carol collaborates on.
1024 async fn seeded() -> Site {960 async fn seeded() -> Site {
1025 let site = site().await;961 let site = site().await;
1026 let tahinli = site962 let tahinli = site
@@ -1061,14 +997,10 @@ mod tests {
1061 site997 site
1062 }998 }
1063 999
1064- /// One seeded site covers the repo list for each kind of viewer, the about text, the
1065- /// edit button, the unknown-user 404 and the fixed routes. Each signed-in viewer gets its
1066- /// own session token.
1067 #[tokio::test]1000 #[tokio::test]
1068 async fn profile_visibility_routing_and_edit_button() {1001 async fn profile_visibility_routing_and_edit_button() {
1069 let site = seeded().await;1002 let site = seeded().await;
1070 1003
1071- // About is rendered and sanitized.
1072 let (status, anon) = get(&site.router, "/tahinli", None).await;1004 let (status, anon) = get(&site.router, "/tahinli", None).await;
1073 assert_eq!(status, 200, "about");1005 assert_eq!(status, 200, "about");
1074 assert!(anon.contains("<h1"), "about: heading rendered: {anon}");1006 assert!(anon.contains("<h1"), "about: heading rendered: {anon}");
@@ -1080,7 +1012,6 @@ mod tests {
1080 assert!(!anon.contains("<script>"), "about: script stripped: {anon}");1012 assert!(!anon.contains("<script>"), "about: script stripped: {anon}");
1081 assert!(!anon.contains("alert(1)"), "about: script body stripped");1013 assert!(!anon.contains("alert(1)"), "about: script body stripped");
1082 1014
1083- // Anonymous visitors see only public repos and no edit button.
1084 assert!(anon.contains("tahinli/open-repo"), "anonymous: public repo");1015 assert!(anon.contains("tahinli/open-repo"), "anonymous: public repo");
1085 assert!(1016 assert!(
1086 !anon.contains("tahinli/secret-repo"),1017 !anon.contains("tahinli/secret-repo"),
@@ -1095,7 +1026,6 @@ mod tests {
1095 "anonymous: edit button"1026 "anonymous: edit button"
1096 );1027 );
1097 1028
1098- // Another user sees the same public-only list and no edit button.
1099 let bob = site1029 let bob = site
1100 .store1030 .store
1101 .create_user("bob", None, "not-a-real-hash", false)1031 .create_user("bob", None, "not-a-real-hash", false)
@@ -1120,7 +1050,6 @@ mod tests {
1120 "other user: edit button"1050 "other user: edit button"
1121 );1051 );
1122 1052
1123- // The owner sees every repo and the edit button.
1124 let tahinli = user_id(&site.store, "tahinli").await;1053 let tahinli = user_id(&site.store, "tahinli").await;
1125 let cookie = sign_in(&site.store, &tahinli, "visibility-owner-token").await;1054 let cookie = sign_in(&site.store, &tahinli, "visibility-owner-token").await;
1126 let (_, owner) = get(&site.router, "/tahinli", Some(&cookie)).await;1055 let (_, owner) = get(&site.router, "/tahinli", Some(&cookie)).await;
@@ -1131,7 +1060,6 @@ mod tests {
1131 "owner: edit button"1060 "owner: edit button"
1132 );1061 );
1133 1062
1134- // A collaborator sees the repo they were added to, not the private one.
1135 let carol = user_id(&site.store, "carol").await;1063 let carol = user_id(&site.store, "carol").await;
1136 let cookie = sign_in(&site.store, &carol, "visibility-carol-token").await;1064 let cookie = sign_in(&site.store, &carol, "visibility-carol-token").await;
1137 let (_, collab) = get(&site.router, "/tahinli", Some(&cookie)).await;1065 let (_, collab) = get(&site.router, "/tahinli", Some(&cookie)).await;
@@ -1144,14 +1072,12 @@ mod tests {
1144 "collaborator: private repo"1072 "collaborator: private repo"
1145 );1073 );
1146 1074
1147- // Unknown users 404, and the lookup ignores case.
1148 let (status, _) = get(&site.router, "/nobody-here", None).await;1075 let (status, _) = get(&site.router, "/nobody-here", None).await;
1149 assert_eq!(status, 404, "unknown user");1076 assert_eq!(status, 404, "unknown user");
1150 let (status, body) = get(&site.router, "/TAHINLI", None).await;1077 let (status, body) = get(&site.router, "/TAHINLI", None).await;
1151 assert_eq!(status, 200, "case-insensitive lookup");1078 assert_eq!(status, 200, "case-insensitive lookup");
1152 assert!(body.contains("tahinli"), "case-insensitive lookup");1079 assert!(body.contains("tahinli"), "case-insensitive lookup");
1153 1080
1154- // Fixed routes are not shadowed by the profile.
1155 for uri in [1081 for uri in [
1156 "/new",1082 "/new",
1157 "/login",1083 "/login",
@@ -1170,11 +1096,9 @@ mod tests {
1170 "{uri} was served by the profile page"1096 "{uri} was served by the profile page"
1171 );1097 );
1172 }1098 }
1173- // The fixed login page still renders its form, not a profile.
1174 let (status, body) = get(&site.router, "/login", None).await;1099 let (status, body) = get(&site.router, "/login", None).await;
1175 assert_eq!(status, 200, "fixed login page");1100 assert_eq!(status, 200, "fixed login page");
1176 assert!(body.contains("<form"), "fixed login page renders its form");1101 assert!(body.contains("<form"), "fixed login page renders its form");
1177- // Two-segment repo routes keep working and still 404 for a missing repo.
1178 let (status, body) = get(&site.router, "/tahinli/missing", None).await;1102 let (status, body) = get(&site.router, "/tahinli/missing", None).await;
1179 assert_eq!(status, 404, "missing repo");1103 assert_eq!(status, 404, "missing repo");
1180 assert!(1104 assert!(
@@ -1183,14 +1107,11 @@ mod tests {
1183 );1107 );
1184 }1108 }
1185 1109
1186- /// Stars, the org sidebar and org pins, on one seeded site. The org scenarios use their
1187- /// own org names and session tokens.
1188 #[tokio::test]1110 #[tokio::test]
1189 async fn stars_org_sidebar_and_org_pins() {1111 async fn stars_org_sidebar_and_org_pins() {
1190 let site = seeded().await;1112 let site = seeded().await;
1191 let tahinli = user_id(&site.store, "tahinli").await;1113 let tahinli = user_id(&site.store, "tahinli").await;
1192 1114
1193- // The stars tab lists only starred repos the viewer may read.
1194 let mira = site1115 let mira = site
1195 .store1116 .store
1196 .create_user("mira", None, "not-a-real-hash", false)1117 .create_user("mira", None, "not-a-real-hash", false)
@@ -1212,8 +1133,6 @@ mod tests {
1212 "stars: private starred repo"1133 "stars: private starred repo"
1213 );1134 );
1214 1135
1215- // Members and teams pages have no sidebar; their tab bar leads to both, and a member gets no
1216- // settings link. Owners edit the organization from its profile.
1217 let kaan = site1136 let kaan = site
1218 .store1137 .store
1219 .create_user("kaan", None, "not-a-real-hash", false)1138 .create_user("kaan", None, "not-a-real-hash", false)
@@ -1255,7 +1174,6 @@ mod tests {
1255 !member_profile.contains("href=\"/org/forge-org/settings\""),1174 !member_profile.contains("href=\"/org/forge-org/settings\""),
1256 "org profile: member has no edit button"1175 "org profile: member has no edit button"
1257 );1176 );
1258- // Settings keeps a sidebar of its own pages, and its back link goes to the profile.
1259 let (_, settings) = get(&site.router, "/org/forge-org/settings", Some(&owner_cookie)).await;1177 let (_, settings) = get(&site.router, "/org/forge-org/settings", Some(&owner_cookie)).await;
1260 assert!(1178 assert!(
1261 !settings.contains("/org/forge-org/settings/pins"),1179 !settings.contains("/org/forge-org/settings/pins"),
@@ -1270,7 +1188,6 @@ mod tests {
1270 "org settings: Overview tab goes to the profile"1188 "org settings: Overview tab goes to the profile"
1271 );1189 );
1272 1190
1273- // Org pins show on the org profile, with an edit link for owners only.
1274 let acme = site.store.create_org("acme", &tahinli).await.unwrap();1191 let acme = site.store.create_org("acme", &tahinli).await.unwrap();
1275 let lib = site1192 let lib = site
1276 .store1193 .store
@@ -1306,8 +1223,6 @@ mod tests {
1306 );1223 );
1307 }1224 }
1308 1225
1309- /// Pins, the popular-repos fallback and the display name, on one seeded site. The
1310- /// scenarios run in order, and each one sets the pins or name the next one reads.
1311 #[tokio::test]1226 #[tokio::test]
1312 async fn pins_fallback_and_display_name() {1227 async fn pins_fallback_and_display_name() {
1313 let site = seeded().await;1228 let site = seeded().await;
@@ -1317,7 +1232,6 @@ mod tests {
1317 let open = id_of("open-repo");1232 let open = id_of("open-repo");
1318 let secret = id_of("secret-repo");1233 let secret = id_of("secret-repo");
1319 1234
1320- // Pins: anonymous visitors see the public pin only; the owner sees both.
1321 site.store1235 site.store
1322 .set_profile_pins(&tahinli, &[open, secret.clone()])1236 .set_profile_pins(&tahinli, &[open, secret.clone()])
1323 .await1237 .await
@@ -1359,7 +1273,6 @@ mod tests {
1359 "pins: owner edits them on the profile"1273 "pins: owner edits them on the profile"
1360 );1274 );
1361 1275
1362- // Fallback: with no visible pin, the overview shows popular repos instead.
1363 site.store1276 site.store
1364 .set_profile_pins(&tahinli, &[secret])1277 .set_profile_pins(&tahinli, &[secret])
1365 .await1278 .await
@@ -1372,7 +1285,6 @@ mod tests {
1372 "fallback: private repo hidden"1285 "fallback: private repo hidden"
1373 );1286 );
1374 1287
1375- // Display name: the heading uses it with the username below; a blank name falls back.
1376 site.store1288 site.store
1377 .set_display_name(&tahinli, "Ahmet Kaan Gümüş")1289 .set_display_name(&tahinli, "Ahmet Kaan Gümüş")
1378 .await1290 .await
@@ -1400,7 +1312,6 @@ mod tests {
1400 );1312 );
1401 }1313 }
1402 1314
1403- /// The calendar sits on the overview. An old `?tab=contributions` link falls through to it.
1404 #[tokio::test]1315 #[tokio::test]
1405 async fn overview_holds_the_calendar() {1316 async fn overview_holds_the_calendar() {
1406 let site = seeded().await;1317 let site = seeded().await;
@@ -1416,7 +1327,6 @@ mod tests {
1416 assert!(day.contains("class=\"heat\""), "day link: calendar");1327 assert!(day.contains("class=\"heat\""), "day link: calendar");
1417 }1328 }
1418 1329
1419- /// The calendar's stream is the profile's own: an unknown name is 404.
1420 #[tokio::test]1330 #[tokio::test]
1421 async fn profile_events_is_404_for_an_unknown_user() {1331 async fn profile_events_is_404_for_an_unknown_user() {
1422 let site = seeded().await;1332 let site = seeded().await;
@@ -1428,7 +1338,6 @@ mod tests {
1428 body.matches(needle).count()1338 body.matches(needle).count()
1429 }1339 }
1430 1340
1431- /// A user with 35 public repos, `bulk-00` to `bulk-34`.
1432 async fn bulk_site() -> Site {1341 async fn bulk_site() -> Site {
1433 let site = site().await;1342 let site = site().await;
1434 let tahinli = site1343 let tahinli = site
@@ -1455,12 +1364,10 @@ mod tests {
1455 store.user_by_username(name).await.unwrap().unwrap().id1364 store.user_by_username(name).await.unwrap().unwrap().id
1456 }1365 }
1457 1366
1458- /// Pagination and the name filter on one 35-repo site.
1459 #[tokio::test]1367 #[tokio::test]
1460 async fn repositories_tab_paging_and_name_filter() {1368 async fn repositories_tab_paging_and_name_filter() {
1461 let site = bulk_site().await;1369 let site = bulk_site().await;
1462 1370
1463- // Ten repos per page, the last five on page four.
1464 let (status, first) = get(&site.router, "/tahinli?tab=repositories&sort=name", None).await;1371 let (status, first) = get(&site.router, "/tahinli?tab=repositories&sort=name", None).await;
1465 assert_eq!(status, 200, "paging: first page");1372 assert_eq!(status, 200, "paging: first page");
1466 assert_eq!(1373 assert_eq!(
@@ -1490,7 +1397,6 @@ mod tests {
1490 "paging: first repo not on page two"1397 "paging: first repo not on page two"
1491 );1398 );
1492 1399
1493- // The name filter is a case-insensitive substring match.
1494 let (_, body) = get(&site.router, "/tahinli?tab=repositories&q=BULK-1", None).await;1400 let (_, body) = get(&site.router, "/tahinli?tab=repositories&q=BULK-1", None).await;
1495 assert_eq!(1401 assert_eq!(
1496 count(&body, "class=\"name repo-name\""),1402 count(&body, "class=\"name repo-name\""),
crates/forge-web-account/src/pages/profile_calendar.rsmodified+11 -16
@@ -20,6 +20,14 @@ pub(crate) fn calendar_since() -> String {
20 forge_core::time::stamp_ago(Duration::from_secs((CALENDAR_DAYS + 1) * 86_400))20 forge_core::time::stamp_ago(Duration::from_secs((CALENDAR_DAYS + 1) * 86_400))
21 }21 }
22 22
23+fn ymd(date: civil::Date) -> (i64, i64, i64) {
24+ (
25+ i64::from(date.year()),
26+ i64::from(date.month()),
27+ i64::from(date.day()),
28+ )
29+}
30+
23 /// The day the `day` query asks for: a strict `YYYY-MM-DD` date from the calendar's first day to31 /// The day the `day` query asks for: a strict `YYYY-MM-DD` date from the calendar's first day to
24 /// today. Anything else (malformed, a future day, or before the calendar) is ignored.32 /// today. Anything else (malformed, a future day, or before the calendar) is ignored.
25 pub(crate) fn selected_day(33 pub(crate) fn selected_day(
@@ -33,12 +41,7 @@ pub(crate) fn selected_day(
33 if date.to_string() != text {41 if date.to_string() != text {
34 return None;42 return None;
35 }43 }
36- let ymd = (44+ (first..=today).contains(&ymd(date)).then_some(date)
37- i64::from(date.year()),
38- i64::from(date.month()),
39- i64::from(date.day()),
40- );
41- (first..=today).contains(&ymd).then_some(date)
42 }45 }
43 46
44 /// The contributions the user made on their local day `date`, newest first.47 /// The contributions the user made on their local day `date`, newest first.
@@ -58,11 +61,7 @@ pub(crate) async fn day_detail(
58 .contributions_between(&user.id, &from, &to)61 .contributions_between(&user.id, &from, &to)
59 .await?;62 .await?;
60 Ok(Some(DayDetail {63 Ok(Some(DayDetail {
61- date: (64+ date: ymd(date),
62- i64::from(date.year()),
63- i64::from(date.month()),
64- i64::from(date.day()),
65- ),
66 items,65 items,
67 }))66 }))
68 }67 }
@@ -74,11 +73,7 @@ pub(crate) async fn load_calendar(
74 day: Option<&str>,73 day: Option<&str>,
75 ) -> Result<(Calendar, Option<DayDetail>)> {74 ) -> Result<(Calendar, Option<DayDetail>)> {
76 let local_now = forge_core::tz::local_datetime(Timestamp::now(), &user.timezone);75 let local_now = forge_core::tz::local_datetime(Timestamp::now(), &user.timezone);
77- let today = (76+ let today = ymd(local_now.date());
78- i64::from(local_now.year()),
79- i64::from(local_now.month()),
80- i64::from(local_now.day()),
81- );
82 let counts = state77 let counts = state
83 .store78 .store
84 .contribution_counts(&user.id, &calendar_since(), &user.timezone)79 .contribution_counts(&user.id, &calendar_since(), &user.timezone)
crates/forge-web-account/src/pages/register.rsmodified+13 -11
@@ -215,11 +215,10 @@ async fn create_account(
215 ) -> Result<std::result::Result<User, String>> {215 ) -> Result<std::result::Result<User, String>> {
216 let username = match validate_username(&form.username) {216 let username = match validate_username(&form.username) {
217 Ok((name, _)) => name,217 Ok((name, _)) => name,
218- Err(e) => {218+ Err(e) => match user_facing_message(&e) {
219- return Ok(Err(219+ Some(message) => return Ok(Err(message)),
220- user_facing_message(&e).unwrap_or_else(|| "invalid username".into())220+ None => return Err(e.into()),
221- ));221+ },
222- }
223 };222 };
224 if let Some(message) = check_new_password(lang, &form.password, &form.confirm) {223 if let Some(message) = check_new_password(lang, &form.password, &form.confirm) {
225 return Ok(Err(message));224 return Ok(Err(message));
@@ -229,9 +228,10 @@ async fn create_account(
229 None => {228 None => {
230 let address = form.email.trim().to_owned();229 let address = form.email.trim().to_owned();
231 if let Err(e) = validate_email(&address) {230 if let Err(e) = validate_email(&address) {
232- return Ok(Err(231+ match user_facing_message(&e) {
233- user_facing_message(&e).unwrap_or_else(|| "invalid email address".into())232+ Some(message) => return Ok(Err(message)),
234- ));233+ None => return Err(e.into()),
234+ }
235 }235 }
236 address236 address
237 }237 }
@@ -423,11 +423,13 @@ async fn verify_resend(cx: &Cx, Form(form): Form<ResendForm>) -> Result<SeeOther
423 }423 }
424 if let Some(address) = viewer.0.email.clone()424 if let Some(address) = viewer.0.email.clone()
425 && !state.store.email_is_verified(&viewer.0.id).await?425 && !state.store.email_is_verified(&viewer.0.id).await?
426- && !account::send_verify(state, &viewer.0, &address).await?
427 {426 {
428- return Ok(see_other("/settings/security?saved=verify_wait"));427+ if !account::send_verify(state, &viewer.0, &address).await? {
428+ return Ok(see_other("/settings/security?saved=verify_wait"));
429+ }
430+ return Ok(see_other("/settings/security?saved=verify_sent"));
429 }431 }
430- Ok(see_other("/settings/security?saved=verify_sent"))432+ Ok(see_other("/settings/security"))
431 }433 }
432 434
433 #[cfg(test)]435 #[cfg(test)]
crates/forge-web-account/src/pages/releases_tests.rsmodified+730 -884
@@ -1,12 +1,11 @@
1-//! Router-level tests for releases: permissions, drafts, tags, asset upload and download, the
2-//! download counter, the size cap and deletion. Each test runs against a real bare repo.
3-
4 use std::path::{Path, PathBuf};1 use std::path::{Path, PathBuf};
5 2
6 use forge_core::releases::Release;3 use forge_core::releases::Release;
7 use forge_core::{Repo, Role, Store, User, Visibility};4 use forge_core::{Repo, Role, Store, User, Visibility};
8 use forge_git::repo::{init_bare, repo_path};5 use forge_git::repo::{init_bare, repo_path};
6+use futures_util::StreamExt;
9 use topcoat::router::request::Request;7 use topcoat::router::request::Request;
8+use topcoat::router::response::Response;
10 use topcoat::router::{Body, HeaderMap, Router, to_bytes};9 use topcoat::router::{Body, HeaderMap, Router, to_bytes};
11 10
12 use crate::auth::SESSION_COOKIE;11 use crate::auth::SESSION_COOKIE;
@@ -15,6 +14,8 @@ use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
15 use crate::test_support::{app_router, create_session, test_state};14 use crate::test_support::{app_router, create_session, test_state};
16 15
17 const CSRF: &str = "releases-test-csrf";16 const CSRF: &str = "releases-test-csrf";
17+const FORM_TYPE: &str = "application/x-www-form-urlencoded";
18+const CHANGED: &[u8] = b"event: changed\ndata: 1\n\n";
18 19
19 fn git(dir: &Path, args: &[&str]) -> String {20 fn git(dir: &Path, args: &[&str]) -> String {
20 let out = std::process::Command::new("git")21 let out = std::process::Command::new("git")
@@ -89,9 +90,6 @@ fn form(pairs: &[(&str, &str)]) -> Vec<u8> {
89 .into_bytes()90 .into_bytes()
90 }91 }
91 92
92-const FORM_TYPE: &str = "application/x-www-form-urlencoded";
93-
94-/// One multipart body: `csrf` first, then a `file` field with the given name and bytes.
95 fn upload_body(file_name: &str, data: &[u8]) -> (String, Vec<u8>) {93 fn upload_body(file_name: &str, data: &[u8]) -> (String, Vec<u8>) {
96 crate::pages::settings_profile::tests::multipart(&[94 crate::pages::settings_profile::tests::multipart(&[
97 ("csrf", None, CSRF.as_bytes()),95 ("csrf", None, CSRF.as_bytes()),
@@ -111,8 +109,6 @@ struct Fixture {
111 bob_cookie: String,109 bob_cookie: String,
112 }110 }
113 111
114-/// Tahinli owns the public repo `tahinli/proj` with `main` holding one commit. Bob is a Read
115-/// collaborator. `max_mb` replaces the asset size limit when given.
116 async fn fixture(max_mb: Option<u64>) -> Fixture {112 async fn fixture(max_mb: Option<u64>) -> Fixture {
117 let tmp = tempfile::tempdir().expect("tempdir");113 let tmp = tempfile::tempdir().expect("tempdir");
118 let mut state = test_state(tmp.path()).await;114 let mut state = test_state(tmp.path()).await;
@@ -183,8 +179,7 @@ impl Fixture {
183 .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())179 .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
184 }180 }
185 181
186- /// Creates a release row directly, bypassing the form.182+ async fn release(&self, tag: &str, draft: bool) -> Release {
187- async fn release(&self, tag: &str, draft: bool) -> forge_core::releases::Release {
188 self.store183 self.store
189 .create_release(&forge_core::releases::NewRelease {184 .create_release(&forge_core::releases::NewRelease {
190 repo_id: &self.repo.id,185 repo_id: &self.repo.id,
@@ -212,9 +207,20 @@ impl Fixture {
212 )207 )
213 .await208 .await
214 }209 }
210+
211+ async fn download(&self, path: &str) -> Reply {
212+ send(
213+ &self.app,
214+ "GET",
215+ &format!("/tahinli/proj/releases/download/{path}"),
216+ None,
217+ None,
218+ Vec::new(),
219+ )
220+ .await
221+ }
215 }222 }
216 223
217-/// The release's own fields, unchanged, with no tag change.
218 fn keep(rel: &Release) -> EditRelease {224 fn keep(rel: &Release) -> EditRelease {
219 EditRelease {225 EditRelease {
220 title: rel.title.clone(),226 title: rel.title.clone(),
@@ -226,7 +232,6 @@ fn keep(rel: &Release) -> EditRelease {
226 }232 }
227 }233 }
228 234
229-/// Adds a commit on top of `main` and points branch `next` at it. Returns the new commit.
230 fn second_commit(fx: &Fixture) -> String {235 fn second_commit(fx: &Fixture) -> String {
231 let tree = git(&fx.bare, &["rev-parse", "refs/heads/main^{tree}"]);236 let tree = git(&fx.bare, &["rev-parse", "refs/heads/main^{tree}"]);
232 let next = git(237 let next = git(
@@ -237,771 +242,656 @@ fn second_commit(fx: &Fixture) -> String {
237 next242 next
238 }243 }
239 244
240-// Each test below builds one fixture and runs its scenarios in order. Scenarios use their own
241-// tags and releases so they do not interfere, and the blob-count check in the size-cap test runs
242-// first, before any blob exists in its fixture.
243-
244 #[tokio::test]245 #[tokio::test]
245 async fn drafts_and_permissions_share_one_repo() {246 async fn drafts_and_permissions_share_one_repo() {
246 let fx = fixture(None).await;247 let fx = fixture(None).await;
247 248
248- // Drafts: readers see the published release only, owners see the draft too.249+ let published = fx.release("v1.0", false).await;
249- {250+ let draft = fx.release("v2.0", true).await;
250- let published = fx.release("v1.0", false).await;251+ let draft_asset = fx
251- let draft = fx.release("v2.0", true).await;252+ .upload(&draft.id, "secret.bin", b"x", &fx.tahinli_cookie)
252- let draft_asset = fx
253- .upload(&draft.id, "secret.bin", b"x", &fx.tahinli_cookie)
254- .await;
255- assert_eq!(draft_asset.status, 303, "writer uploads to a draft");
256-
257- let list = send(
258- &fx.app,
259- "GET",
260- "/tahinli/proj/releases",
261- None,
262- None,
263- Vec::new(),
264- )
265- .await;
266- assert_eq!(list.status, 200);
267- assert!(list.text().contains("Release v1.0"));
268- assert!(
269- !list.text().contains("Release v2.0"),
270- "anonymous list hides drafts"
271- );
272-
273- let anon_draft = send(
274- &fx.app,
275- "GET",
276- "/tahinli/proj/releases/tag/v2.0",
277- None,
278- None,
279- Vec::new(),
280- )
281- .await;
282- assert_eq!(anon_draft.status, 404, "anonymous draft page");
283- let anon_download = send(
284- &fx.app,
285- "GET",
286- "/tahinli/proj/releases/download/v2.0/secret.bin",
287- None,
288- None,
289- Vec::new(),
290- )
291- .await;
292- assert_eq!(
293- anon_download.status, 404,
294- "a draft asset is not downloadable by readers"
295- );
296-
297- let writer_draft = send(
298- &fx.app,
299- "GET",
300- "/tahinli/proj/releases/tag/v2.0",
301- Some(&fx.tahinli_cookie),
302- None,
303- Vec::new(),
304- )
305- .await;
306- assert_eq!(writer_draft.status, 200, "the owner sees the draft");
307- let writer_list = send(
308- &fx.app,
309- "GET",
310- "/tahinli/proj/releases",
311- Some(&fx.tahinli_cookie),
312- None,
313- Vec::new(),
314- )
315- .await;
316- assert!(writer_list.text().contains("Release v2.0"));
317- assert_eq!(published.tag, "v1.0");
318- }
319-
320- // Readers cannot create, edit, upload or delete.
321- {
322- let rel = fx.release("v3.0", false).await;
323-
324- let create = send(
325- &fx.app,
326- "POST",
327- "/tahinli/proj/releases/new",
328- Some(&fx.bob_cookie),
329- Some(FORM_TYPE),
330- form(&[
331- ("csrf", CSRF),
332- ("tag", "v9"),
333- ("target", "main"),
334- ("title", "x"),
335- ]),
336- )
337- .await;
338- assert_ne!(create.status, 303, "a reader cannot create a release");
339- assert!(
340- fx.tag_target("v9").is_none(),
341- "no tag is created for a refused release"
342- );
343-
344- let edit = send(
345- &fx.app,
346- "POST",
347- &format!("/tahinli/proj/releases/{}/edit", rel.id),
348- Some(&fx.bob_cookie),
349- Some(FORM_TYPE),
350- form(&[("csrf", CSRF), ("title", "hacked"), ("body", "")]),
351- )
352- .await;
353- assert_ne!(edit.status, 303, "a reader cannot edit");
354- assert_eq!(
355- fx.store
356- .release(&rel.id)
357- .await
358- .expect("read")
359- .expect("row")
360- .title,
361- "Release v3.0"
362- );
363-
364- let upload = fx.upload(&rel.id, "a.bin", b"data", &fx.bob_cookie).await;
365- assert_ne!(upload.status, 303, "a reader cannot upload");
366- assert!(
367- fx.store
368- .list_release_assets(&rel.id)
369- .await
370- .expect("assets")
371- .is_empty()
372- );
373-
374- let delete = send(
375- &fx.app,
376- "POST",
377- &format!("/tahinli/proj/releases/{}/delete", rel.id),
378- Some(&fx.bob_cookie),
379- Some(FORM_TYPE),
380- form(&[("csrf", CSRF), ("confirm", "on")]),
381- )
382 .await;253 .await;
383- assert_ne!(delete.status, 303, "a reader cannot delete");254+ assert_eq!(draft_asset.status, 303, "writer uploads to a draft");
384- assert!(fx.store.release(&rel.id).await.expect("read").is_some());255+
385- }256+ let list = send(
257+ &fx.app,
258+ "GET",
259+ "/tahinli/proj/releases",
260+ None,
261+ None,
262+ Vec::new(),
263+ )
264+ .await;
265+ assert_eq!(list.status, 200);
266+ assert!(list.text().contains("Release v1.0"));
267+ assert!(
268+ !list.text().contains("Release v2.0"),
269+ "anonymous list hides drafts"
270+ );
386 271
387- // The repo home's head names the latest release and links to it and to the releases tab.272+ let anon_draft = send(
388- {273+ &fx.app,
389- fx.release("v0.9-beta", false).await;274+ "GET",
390- let home = send(&fx.app, "GET", "/tahinli/proj", None, None, Vec::new()).await;275+ "/tahinli/proj/releases/tag/v2.0",
391- assert_eq!(home.status, 200);276+ None,
392- assert!(home.text().contains("/tahinli/proj/releases/tag/v0.9-beta"));277+ None,
393- assert!(278+ Vec::new(),
394- home.text().contains("/tahinli/proj/releases"),279+ )
395- "the tabs link to releases"280+ .await;
396- );281+ assert_eq!(anon_draft.status, 404, "anonymous draft page");
397- }282+ let anon_download = fx.download("v2.0/secret.bin").await;
398-}283+ assert_eq!(
284+ anon_download.status, 404,
285+ "a draft asset is not downloadable by readers"
286+ );
399 287
400-#[tokio::test]288+ let writer_draft = send(
401-async fn creating_a_release_takes_and_validates_its_tag_and_target() {289+ &fx.app,
402- let fx = fixture(None).await;290+ "GET",
291+ "/tahinli/proj/releases/tag/v2.0",
292+ Some(&fx.tahinli_cookie),
293+ None,
294+ Vec::new(),
295+ )
296+ .await;
297+ assert_eq!(writer_draft.status, 200, "the owner sees the draft");
298+ let writer_list = send(
299+ &fx.app,
300+ "GET",
301+ "/tahinli/proj/releases",
302+ Some(&fx.tahinli_cookie),
303+ None,
304+ Vec::new(),
305+ )
306+ .await;
307+ assert!(writer_list.text().contains("Release v2.0"));
308+ assert_eq!(published.tag, "v1.0");
309+
310+ let rel = fx.release("v3.0", false).await;
311+
312+ let create = send(
313+ &fx.app,
314+ "POST",
315+ "/tahinli/proj/releases/new",
316+ Some(&fx.bob_cookie),
317+ Some(FORM_TYPE),
318+ form(&[
319+ ("csrf", CSRF),
320+ ("tag", "v9"),
321+ ("target", "main"),
322+ ("title", "x"),
323+ ]),
324+ )
325+ .await;
326+ assert_ne!(create.status, 303, "a reader cannot create a release");
327+ assert!(
328+ fx.tag_target("v9").is_none(),
329+ "no tag is created for a refused release"
330+ );
403 331
404- // A missing tag is created as a lightweight tag on the branch head.332+ let edit = send(
405- {333+ &fx.app,
406- let reply = send(334+ "POST",
407- &fx.app,335+ &format!("/tahinli/proj/releases/{}/edit", rel.id),
408- "POST",336+ Some(&fx.bob_cookie),
409- "/tahinli/proj/releases/new",337+ Some(FORM_TYPE),
410- Some(&fx.tahinli_cookie),338+ form(&[("csrf", CSRF), ("title", "hacked"), ("body", "")]),
411- Some(FORM_TYPE),339+ )
412- form(&[340+ .await;
413- ("csrf", CSRF),341+ assert_ne!(edit.status, 303, "a reader cannot edit");
414- ("tag", "v1.0"),342+ assert_eq!(
415- ("target", "main"),343+ fx.store
416- ("title", "First"),344+ .release(&rel.id)
417- ("body", "hello"),
418- ]),
419- )
420- .await;
421- assert_eq!(reply.status, 303, "body: {}", reply.text());
422- assert_eq!(
423- reply.location.as_deref(),
424- Some("/tahinli/proj/releases/tag/v1.0")
425- );
426- let tip = fx.main_tip();
427- assert_eq!(fx.tag_target("v1.0").as_deref(), Some(tip.as_str()));
428- let release = fx
429- .store
430- .release_by_tag(&fx.repo.id, "v1.0")
431 .await345 .await
432 .expect("read")346 .expect("read")
433- .expect("release");347+ .expect("row")
434- assert_eq!(release.target_oid, tip);348+ .title,
435- assert!(release.published_at.is_some());349+ "Release v3.0"
436- }350+ );
437-
438- // An existing tag is used as it is and never moved.
439- {
440- git(&fx.bare, &["tag", "v0.9", "refs/heads/main"]);
441- let before = fx.tag_target("v0.9");
442- let reply = send(
443- &fx.app,
444- "POST",
445- "/tahinli/proj/releases/new",
446- Some(&fx.tahinli_cookie),
447- Some(FORM_TYPE),
448- form(&[
449- ("csrf", CSRF),
450- ("tag", "v0.9"),
451- ("target", "main"),
452- ("title", "Old"),
453- ]),
454- )
455- .await;
456- assert_eq!(reply.status, 303, "existing tag");
457- assert_eq!(fx.tag_target("v0.9"), before, "existing tag is not moved");
458- }
459-
460- // Create refuses a bad tag or a missing target before touching git, and takes a commit id as
461- // a target.
462- {
463- let input = |tag: &str, target: &str| CreateRelease {
464- tag: tag.to_owned(),
465- target: Some(target.to_owned()),
466- title: "x".to_owned(),
467- body: String::new(),
468- draft: false,
469- prerelease: false,
470- };
471- let refused =
472- release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input("a/b", "main")).await;
473- assert!(
474- matches!(refused, Err(ReleaseError::Invalid(_))),
475- "bad tag: {refused:?}"
476- );
477- assert!(fx.tag_target("a/b").is_none(), "bad tag");
478 351
479- let tip = fx.main_tip();352+ let upload = fx.upload(&rel.id, "a.bin", b"data", &fx.bob_cookie).await;
480- let made = release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input("v7", &tip))353+ assert_ne!(upload.status, 303, "a reader cannot upload");
354+ assert!(
355+ fx.store
356+ .list_release_assets(&rel.id)
481 .await357 .await
482- .expect("a commit id works as a target");358+ .expect("assets")
483- assert_eq!(made.target_oid, tip, "commit id target");359+ .is_empty()
484- assert_eq!(360+ );
485- fx.tag_target("v7").as_deref(),
486- Some(tip.as_str()),
487- "commit id target"
488- );
489 361
490- let missing = release_ops::create(362+ let delete = send(
491- &fx.state,363+ &fx.app,
492- &fx.repo,364+ "POST",
493- &fx.tahinli,365+ &format!("/tahinli/proj/releases/{}/delete", rel.id),
494- input("v8", "1111111111111111111111111111111111111111"),366+ Some(&fx.bob_cookie),
495- )367+ Some(FORM_TYPE),
496- .await;368+ form(&[("csrf", CSRF), ("confirm", "on")]),
497- assert!(369+ )
498- matches!(missing, Err(ReleaseError::Invalid(_))),370+ .await;
499- "missing target: {missing:?}"371+ assert_ne!(delete.status, 303, "a reader cannot delete");
500- );372+ assert!(fx.store.release(&rel.id).await.expect("read").is_some());
501- assert!(fx.tag_target("v8").is_none(), "missing target");373+
502- }374+ fx.release("v0.9-beta", false).await;
375+ let home = send(&fx.app, "GET", "/tahinli/proj", None, None, Vec::new()).await;
376+ assert_eq!(home.status, 200);
377+ assert!(home.text().contains("/tahinli/proj/releases/tag/v0.9-beta"));
378+ assert!(
379+ home.text().contains("/tahinli/proj/releases"),
380+ "the tabs link to releases"
381+ );
503 }382 }
504 383
505 #[tokio::test]384 #[tokio::test]
506-async fn retagging_rules_hold_for_published_and_draft_releases() {385+async fn creating_and_retagging_releases_take_tags_and_targets() {
507 let fx = fixture(None).await;386 let fx = fixture(None).await;
508 387
509- // A published release moves to a new tag and keeps the old git tag.388+ let reply = send(
510- {389+ &fx.app,
511- git(&fx.bare, &["tag", "v1.0", "refs/heads/main"]);390+ "POST",
512- let rel = fx.release("v1.0", false).await;391+ "/tahinli/proj/releases/new",
513- let edit = EditRelease {392+ Some(&fx.tahinli_cookie),
514- tag: Some("v1.1".to_owned()),393+ Some(FORM_TYPE),
515- ..keep(&rel)394+ form(&[
516- };395+ ("csrf", CSRF),
517- let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)396+ ("tag", "v1.0"),
518- .await397+ ("target", "main"),
519- .expect("retag");398+ ("title", "First"),
520- assert_eq!(moved.tag, "v1.1");399+ ("body", "hello"),
521- assert_eq!(moved.target_oid, fx.main_tip());400+ ]),
522- assert_eq!(401+ )
523- fx.tag_target("v1.1").as_deref(),402+ .await;
524- Some(fx.main_tip().as_str())403+ assert_eq!(reply.status, 303, "body: {}", reply.text());
525- );404+ assert_eq!(
526- assert!(fx.tag_target("v1.0").is_some(), "the old git tag is kept");405+ reply.location.as_deref(),
527- assert!(406+ Some("/tahinli/proj/releases/tag/v1.0")
528- fx.store407+ );
529- .release_by_tag(&fx.repo.id, "v1.0")408+ let tip = fx.main_tip();
530- .await409+ assert_eq!(fx.tag_target("v1.0").as_deref(), Some(tip.as_str()));
531- .expect("read")410+ let release = fx
532- .is_none(),411+ .store
533- "the old tag no longer names a release"412+ .release_by_tag(&fx.repo.id, "v1.0")
534- );413+ .await
535- }414+ .expect("read")
415+ .expect("release");
416+ assert_eq!(release.target_oid, tip);
417+ assert!(release.published_at.is_some());
418+
419+ git(&fx.bare, &["tag", "v0.9", "refs/heads/main"]);
420+ let before = fx.tag_target("v0.9");
421+ let reply = send(
422+ &fx.app,
423+ "POST",
424+ "/tahinli/proj/releases/new",
425+ Some(&fx.tahinli_cookie),
426+ Some(FORM_TYPE),
427+ form(&[
428+ ("csrf", CSRF),
429+ ("tag", "v0.9"),
430+ ("target", "main"),
431+ ("title", "Old"),
432+ ]),
433+ )
434+ .await;
435+ assert_eq!(reply.status, 303, "existing tag");
436+ assert_eq!(fx.tag_target("v0.9"), before, "existing tag is not moved");
437+
438+ let input = |tag: &str, target: &str| CreateRelease {
439+ tag: tag.to_owned(),
440+ target: Some(target.to_owned()),
441+ title: "x".to_owned(),
442+ body: String::new(),
443+ draft: false,
444+ prerelease: false,
445+ };
446+ let refused =
447+ release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input("a/b", "main")).await;
448+ assert!(
449+ matches!(refused, Err(ReleaseError::Invalid(_))),
450+ "bad tag: {refused:?}"
451+ );
452+ assert!(fx.tag_target("a/b").is_none(), "bad tag");
536 453
537- // A published tag cannot be moved in place, but a draft can.454+ let made = release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input("v7", &tip))
538- {455+ .await
539- git(&fx.bare, &["tag", "v2.0", "refs/heads/main"]);456+ .expect("a commit id works as a target");
540- let next = second_commit(&fx);457+ assert_eq!(made.target_oid, tip, "commit id target");
541- let published = fx.release("v2.0", false).await;458+ assert_eq!(
542- let move_published = EditRelease {459+ fx.tag_target("v7").as_deref(),
543- target: Some("next".to_owned()),460+ Some(tip.as_str()),
544- ..keep(&published)461+ "commit id target"
545- };462+ );
546- let refused =
547- release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &published, move_published).await;
548- assert!(
549- matches!(refused, Err(ReleaseError::Invalid(_))),
550- "{refused:?}"
551- );
552- assert_eq!(
553- fx.tag_target("v2.0").as_deref(),
554- Some(fx.main_tip().as_str()),
555- "published tag stays put"
556- );
557 463
558- let draft = fx464+ let missing = release_ops::create(
559- .store465+ &fx.state,
560- .create_release(&forge_core::releases::NewRelease {466+ &fx.repo,
561- repo_id: &fx.repo.id,467+ &fx.tahinli,
562- tag: "v3.0",468+ input("v8", "1111111111111111111111111111111111111111"),
563- target_oid: &fx.main_tip(),469+ )
564- title: "draft",470+ .await;
565- body: "",471+ assert!(
566- draft: true,472+ matches!(missing, Err(ReleaseError::Invalid(_))),
567- prerelease: false,473+ "missing target: {missing:?}"
568- author_id: &fx.tahinli.id,474+ );
569- })475+ assert!(fx.tag_target("v8").is_none(), "missing target");
570- .await476+
571- .expect("draft");477+ git(&fx.bare, &["tag", "r1.0", "refs/heads/main"]);
572- git(&fx.bare, &["tag", "v3.0", "refs/heads/main"]);478+ let rel = fx.release("r1.0", false).await;
573- let move_draft = EditRelease {479+ let edit = EditRelease {
574- target: Some("next".to_owned()),480+ tag: Some("r1.1".to_owned()),
575- ..keep(&draft)481+ ..keep(&rel)
576- };482+ };
577- let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, move_draft)483+ let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)
484+ .await
485+ .expect("retag");
486+ assert_eq!(moved.tag, "r1.1");
487+ assert_eq!(moved.target_oid, fx.main_tip());
488+ assert_eq!(
489+ fx.tag_target("r1.1").as_deref(),
490+ Some(fx.main_tip().as_str())
491+ );
492+ assert!(fx.tag_target("r1.0").is_some(), "the old git tag is kept");
493+ assert!(
494+ fx.store
495+ .release_by_tag(&fx.repo.id, "r1.0")
578 .await496 .await
579- .expect("draft moves");497+ .expect("read")
580- assert_eq!(moved.target_oid, next);498+ .is_none(),
581- assert_eq!(fx.tag_target("v3.0"), Some(next));499+ "the old tag no longer names a release"
582- }500+ );
583 501
584- // Retagging adopts an existing tag and refuses clashes and bad names.502+ git(&fx.bare, &["tag", "r2.0", "refs/heads/main"]);
585- {503+ let next = second_commit(&fx);
586- git(&fx.bare, &["tag", "v0.9", "refs/heads/main"]);504+ let published = fx.release("r2.0", false).await;
587- let next = second_commit(&fx);505+ let move_published = EditRelease {
588- let draft = fx.release("v5", true).await;506+ target: Some("next".to_owned()),
589-507+ ..keep(&published)
590- let clash_target = EditRelease {508+ };
591- tag: Some("v0.9".to_owned()),509+ let refused =
592- target: Some("next".to_owned()),510+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &published, move_published).await;
593- ..keep(&draft)511+ assert!(
594- };512+ matches!(refused, Err(ReleaseError::Invalid(_))),
595- let refused =513+ "{refused:?}"
596- release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, clash_target).await;514+ );
597- assert!(515+ assert_eq!(
598- matches!(refused, Err(ReleaseError::Invalid(_))),516+ fx.tag_target("r2.0").as_deref(),
599- "{refused:?}"517+ Some(fx.main_tip().as_str()),
600- );518+ "published tag stays put"
519+ );
601 520
602- let adopt = EditRelease {521+ git(&fx.bare, &["tag", "r3.0", "refs/heads/main"]);
603- tag: Some("v0.9".to_owned()),522+ let draft = fx.release("r3.0", true).await;
604- ..keep(&draft)523+ let move_draft = EditRelease {
605- };524+ target: Some("next".to_owned()),
606- let adopted = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, adopt)525+ ..keep(&draft)
607- .await526+ };
608- .expect("adopt");527+ let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, move_draft)
609- assert_eq!(adopted.tag, "v0.9");528+ .await
610- assert_eq!(adopted.target_oid, fx.main_tip());529+ .expect("draft moves");
611- assert_ne!(adopted.target_oid, next);530+ assert_eq!(moved.target_oid, next);
612-531+ assert_eq!(fx.tag_target("r3.0"), Some(next));
613- let other = fx.release("v6", false).await;532+
614- let taken = EditRelease {533+ git(&fx.bare, &["tag", "r0.9", "refs/heads/main"]);
615- tag: Some("v0.9".to_owned()),534+ let next = second_commit(&fx);
616- ..keep(&other)535+ let draft = fx.release("r5", true).await;
617- };536+
618- let clash = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, taken).await;537+ let clash_target = EditRelease {
619- assert!(matches!(clash, Err(ReleaseError::Conflict(_))), "{clash:?}");538+ tag: Some("r0.9".to_owned()),
620-539+ target: Some("next".to_owned()),
621- let bad_name = EditRelease {540+ ..keep(&draft)
622- tag: Some("a/b".to_owned()),541+ };
623- ..keep(&other)542+ let refused =
624- };543+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, clash_target).await;
625- let invalid = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, bad_name).await;544+ assert!(
626- assert!(545+ matches!(refused, Err(ReleaseError::Invalid(_))),
627- matches!(invalid, Err(ReleaseError::Invalid(_))),546+ "{refused:?}"
628- "{invalid:?}"547+ );
629- );548+
630- }549+ let adopt = EditRelease {
550+ tag: Some("r0.9".to_owned()),
551+ ..keep(&draft)
552+ };
553+ let adopted = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, adopt)
554+ .await
555+ .expect("adopt");
556+ assert_eq!(adopted.tag, "r0.9");
557+ assert_eq!(adopted.target_oid, fx.main_tip());
558+ assert_ne!(adopted.target_oid, next);
559+
560+ let other = fx.release("r6", false).await;
561+ let taken = EditRelease {
562+ tag: Some("r0.9".to_owned()),
563+ ..keep(&other)
564+ };
565+ let clash = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, taken).await;
566+ assert!(matches!(clash, Err(ReleaseError::Conflict(_))), "{clash:?}");
567+
568+ let bad_name = EditRelease {
569+ tag: Some("a/b".to_owned()),
570+ ..keep(&other)
571+ };
572+ let invalid = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, bad_name).await;
573+ assert!(
574+ matches!(invalid, Err(ReleaseError::Invalid(_))),
575+ "{invalid:?}"
576+ );
631 }577 }
632 578
633 #[tokio::test]579 #[tokio::test]
634 async fn the_edit_page_and_its_form_follow_the_publish_state() {580 async fn the_edit_page_and_its_form_follow_the_publish_state() {
635 let fx = fixture(None).await;581 let fx = fixture(None).await;
636 582
637- // The edit page shows tag and target controls, and hides the target once published.583+ let draft = fx.release("v1.0", true).await;
638- {584+ let published = fx.release("v2.0", false).await;
639- let draft = fx.release("v1.0", true).await;585+
640- let published = fx.release("v2.0", false).await;586+ let page = send(
641-587+ &fx.app,
642- let page = send(588+ "GET",
643- &fx.app,589+ &format!("/tahinli/proj/releases/{}/edit", draft.id),
644- "GET",590+ Some(&fx.tahinli_cookie),
645- &format!("/tahinli/proj/releases/{}/edit", draft.id),591+ None,
646- Some(&fx.tahinli_cookie),592+ Vec::new(),
647- None,593+ )
648- Vec::new(),594+ .await;
649- )595+ assert_eq!(page.status, 200, "body: {}", page.text());
650- .await;596+ let html = page.text();
651- assert_eq!(page.status, 200, "body: {}", page.text());597+ assert!(html.contains("name=\"tag\" value=\"v1.0\""), "{html}");
652- let html = page.text();598+ assert!(html.contains("name=\"target\""), "a draft shows the target");
653- assert!(html.contains("name=\"tag\" value=\"v1.0\""), "{html}");599+
654- assert!(html.contains("name=\"target\""), "a draft shows the target");600+ let page = send(
655-601+ &fx.app,
656- let page = send(602+ "GET",
657- &fx.app,603+ &format!("/tahinli/proj/releases/{}/edit", published.id),
658- "GET",604+ Some(&fx.tahinli_cookie),
659- &format!("/tahinli/proj/releases/{}/edit", published.id),605+ None,
660- Some(&fx.tahinli_cookie),606+ Vec::new(),
661- None,607+ )
662- Vec::new(),608+ .await;
663- )609+ let html = page.text();
664- .await;610+ assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}");
665- let html = page.text();611+ assert!(
666- assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}");612+ !html.contains("name=\"target\""),
667- assert!(613+ "published hides the target"
668- !html.contains("name=\"target\""),614+ );
669- "published hides the target"
670- );
671- }
672 615
673- // A published release can be retagged through the form and keeps its commit.616+ git(&fx.bare, &["tag", "v4.0", "refs/heads/main"]);
674- {617+ let published = fx.release("v4.0", false).await;
675- git(&fx.bare, &["tag", "v4.0", "refs/heads/main"]);618+ let reply = send(
676- let published = fx.release("v4.0", false).await;619+ &fx.app,
677- let reply = send(620+ "POST",
678- &fx.app,621+ &format!("/tahinli/proj/releases/{}/edit", published.id),
679- "POST",622+ Some(&fx.tahinli_cookie),
680- &format!("/tahinli/proj/releases/{}/edit", published.id),623+ Some(FORM_TYPE),
681- Some(&fx.tahinli_cookie),624+ form(&[
682- Some(FORM_TYPE),625+ ("csrf", CSRF),
683- form(&[626+ ("tag", "v4.1"),
684- ("csrf", CSRF),627+ ("target", ""),
685- ("tag", "v4.1"),628+ ("title", "Release v4.0"),
686- ("target", ""),629+ ("body", "notes"),
687- ("title", "Release v4.0"),630+ ]),
688- ("body", "notes"),631+ )
689- ]),632+ .await;
690- )633+ assert_eq!(reply.status, 303, "body: {}", reply.text());
691- .await;634+ assert!(reply.location.unwrap_or_default().contains("notice=saved"));
692- assert_eq!(reply.status, 303, "body: {}", reply.text());635+ let moved = fx
693- assert!(reply.location.unwrap_or_default().contains("notice=saved"));636+ .store
694- let moved = fx637+ .release(&published.id)
695- .store638+ .await
696- .release(&published.id)639+ .expect("read")
697- .await640+ .expect("row");
698- .expect("read")641+ assert_eq!(moved.tag, "v4.1");
699- .expect("row");642+ assert_eq!(fx.tag_target("v4.1"), Some(fx.main_tip()));
700- assert_eq!(moved.tag, "v4.1");643+ assert_eq!(
701- assert_eq!(fx.tag_target("v4.1"), Some(fx.main_tip()));644+ fx.tag_target("v4.0"),
702- assert_eq!(645+ Some(fx.main_tip()),
703- fx.tag_target("v4.0"),646+ "old git tag kept"
704- Some(fx.main_tip()),647+ );
705- "old git tag kept"
706- );
707- }
708 648
709- // A published target move is refused on the page, and the typed values stay.649+ git(&fx.bare, &["tag", "v5.0", "refs/heads/main"]);
710- {650+ second_commit(&fx);
711- git(&fx.bare, &["tag", "v5.0", "refs/heads/main"]);651+ fx.release("v5.0", false).await;
712- second_commit(&fx);652+ let published = fx
713- fx.release("v5.0", false).await;653+ .store
714- let published = fx654+ .release_by_tag(&fx.repo.id, "v5.0")
715- .store655+ .await
716- .release_by_tag(&fx.repo.id, "v5.0")656+ .expect("read")
717- .await657+ .expect("row");
718- .expect("read")658+ let reply = send(
719- .expect("row");659+ &fx.app,
720- let reply = send(660+ "POST",
721- &fx.app,661+ &format!("/tahinli/proj/releases/{}/edit", published.id),
722- "POST",662+ Some(&fx.tahinli_cookie),
723- &format!("/tahinli/proj/releases/{}/edit", published.id),663+ Some(FORM_TYPE),
724- Some(&fx.tahinli_cookie),664+ form(&[
725- Some(FORM_TYPE),665+ ("csrf", CSRF),
726- form(&[666+ ("tag", "v5.0"),
727- ("csrf", CSRF),667+ ("target", "next"),
728- ("tag", "v5.0"),668+ ("title", "Typed title"),
729- ("target", "next"),669+ ("body", "notes"),
730- ("title", "Typed title"),670+ ]),
731- ("body", "notes"),671+ )
732- ]),672+ .await;
733- )673+ assert_eq!(
734- .await;674+ reply.status,
735- assert_eq!(675+ 200,
736- reply.status,676+ "a refused save re-renders: {}",
737- 200,677+ reply.text()
738- "a refused save re-renders: {}",678+ );
739- reply.text()679+ let html = reply.text();
740- );680+ assert!(html.contains("pick a new tag"), "{html}");
741- let html = reply.text();681+ assert!(
742- assert!(html.contains("pick a new tag"), "{html}");682+ html.contains("Typed title"),
743- assert!(683+ "the typed title stays: {html}"
744- html.contains("Typed title"),684+ );
745- "the typed title stays: {html}"685+ assert_eq!(fx.tag_target("v5.0"), Some(fx.main_tip()));
746- );
747- assert_eq!(fx.tag_target("v5.0"), Some(fx.main_tip()));
748- }
749 }686 }
750 687
751 #[tokio::test]688 #[tokio::test]
752 async fn asset_upload_replace_download_delete_and_csrf_rules() {689 async fn asset_upload_replace_download_delete_and_csrf_rules() {
753 let fx = fixture(None).await;690 let fx = fixture(None).await;
754 691
755- // Upload then download round-trips the bytes and counts each download.692+ let rel = fx.release("v1.0", false).await;
756- {693+ let payload = b"<html>not rendered</html>";
757- let rel = fx.release("v1.0", false).await;694+ let reply = fx
758- let payload = b"<html>not rendered</html>";695+ .upload(&rel.id, "app.bin", payload, &fx.tahinli_cookie)
759- let reply = fx696+ .await;
760- .upload(&rel.id, "app.bin", payload, &fx.tahinli_cookie)697+ assert_eq!(reply.status, 303, "body: {}", reply.text());
761- .await;698+ assert!(
762- assert_eq!(reply.status, 303, "body: {}", reply.text());699+ reply
763- assert!(700+ .location
764- reply701+ .unwrap_or_default()
765- .location702+ .contains("notice=asset-uploaded")
766- .unwrap_or_default()703+ );
767- .contains("notice=asset-uploaded")
768- );
769-
770- let row = fx
771- .store
772- .release_asset(&rel.id, "app.bin")
773- .await
774- .expect("read")
775- .expect("asset row");
776- assert_eq!(row.size, payload.len() as u64);
777- let digest = {
778- use sha2::{Digest, Sha256};
779- hex::encode(Sha256::digest(payload))
780- };
781- assert_eq!(row.sha256, digest);
782-
783- for expected in 1..=2u64 {
784- let got = send(
785- &fx.app,
786- "GET",
787- "/tahinli/proj/releases/download/v1.0/app.bin",
788- None,
789- None,
790- Vec::new(),
791- )
792- .await;
793- assert_eq!(got.status, 200);
794- assert_eq!(got.body, payload);
795- assert_eq!(
796- got.headers
797- .get("content-disposition")
798- .and_then(|v| v.to_str().ok()),
799- Some("attachment; filename=\"app.bin\"")
800- );
801- assert_eq!(
802- got.headers
803- .get("x-content-type-options")
804- .and_then(|v| v.to_str().ok()),
805- Some("nosniff")
806- );
807- let counted = fx
808- .store
809- .release_asset(&rel.id, "app.bin")
810- .await
811- .expect("read")
812- .expect("row");
813- assert_eq!(counted.download_count, expected, "download counter");
814- }
815- }
816 704
817- // A same-name upload replaces the file and keeps its download counter.705+ let row = fx
818- {706+ .store
819- let rel = fx.release("v1.1", false).await;707+ .release_asset(&rel.id, "app.bin")
820- let first = fx708+ .await
821- .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)709+ .expect("read")
822- .await;710+ .expect("asset row");
823- assert_eq!(first.status, 303);711+ assert_eq!(row.size, payload.len() as u64);
824- let before = fx712+ let digest = {
713+ use sha2::{Digest, Sha256};
714+ hex::encode(Sha256::digest(payload))
715+ };
716+ assert_eq!(row.sha256, digest);
717+
718+ for expected in 1..=2u64 {
719+ let got = fx.download("v1.0/app.bin").await;
720+ assert_eq!(got.status, 200);
721+ assert_eq!(got.body, payload);
722+ assert_eq!(
723+ got.headers
724+ .get("content-disposition")
725+ .and_then(|v| v.to_str().ok()),
726+ Some("attachment; filename=\"app.bin\"")
727+ );
728+ assert_eq!(
729+ got.headers
730+ .get("x-content-type-options")
731+ .and_then(|v| v.to_str().ok()),
732+ Some("nosniff")
733+ );
734+ let counted = fx
825 .store735 .store
826 .release_asset(&rel.id, "app.bin")736 .release_asset(&rel.id, "app.bin")
827 .await737 .await
828 .expect("read")738 .expect("read")
829 .expect("row");739 .expect("row");
830- fx.store740+ assert_eq!(counted.download_count, expected, "download counter");
831- .count_asset_download(&before.id)
832- .await
833- .expect("count");
834-
835- let second = fx
836- .upload(&rel.id, "app.bin", b"second bytes", &fx.tahinli_cookie)
837- .await;
838- assert!(
839- second
840- .location
841- .unwrap_or_default()
842- .contains("notice=asset-replaced"),
843- "a same-name upload replaces instead of refusing"
844- );
845- let assets = fx.store.list_release_assets(&rel.id).await.expect("assets");
846- assert_eq!(assets.len(), 1, "still one asset of that name");
847- let after = &assets[0];
848- assert_ne!(after.id, before.id, "the new file has its own blob");
849- assert_eq!(after.size, 12);
850- assert_eq!(after.download_count, 1, "the download counter survives");
851- assert!(
852- fx.state
853- .blobs
854- .read(&asset_key(&before.id))
855- .await
856- .expect("read")
857- .is_none(),
858- "the replaced blob is deleted"
859- );
860- let got = send(
861- &fx.app,
862- "GET",
863- "/tahinli/proj/releases/download/v1.1/app.bin",
864- None,
865- None,
866- Vec::new(),
867- )
868- .await;
869- assert_eq!(got.body, b"second bytes");
870 }741 }
871 742
872- // Replacing by asset name keeps the name, whatever the new file is called.743+ let rel = fx.release("v1.1", false).await;
873- {744+ let first = fx
874- let rel = fx.release("v1.2", false).await;745+ .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)
875- let first = fx
876- .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)
877- .await;
878- assert_eq!(first.status, 303);
879-
880- let page = send(
881- &fx.app,
882- "GET",
883- &format!("/tahinli/proj/releases/{}/edit", rel.id),
884- Some(&fx.tahinli_cookie),
885- None,
886- Vec::new(),
887- )
888 .await;746 .await;
889- assert!(747+ assert_eq!(first.status, 303);
890- page.text().contains("name=\"name\" value=\"app.bin\""),748+ let before = fx
891- "each asset has a replace form"749+ .store
892- );750+ .release_asset(&rel.id, "app.bin")
751+ .await
752+ .expect("read")
753+ .expect("row");
754+ fx.store
755+ .count_asset_download(&before.id)
756+ .await
757+ .expect("count");
893 758
894- let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[759+ let second = fx
895- ("csrf", None, CSRF.as_bytes()),760+ .upload(&rel.id, "app.bin", b"second bytes", &fx.tahinli_cookie)
896- ("name", None, "app.bin".as_bytes()),
897- (
898- "file",
899- Some(("renamed-build.zip", "application/octet-stream")),
900- "second bytes".as_bytes(),
901- ),
902- ]);
903- let reply = send(
904- &fx.app,
905- "POST",
906- &format!("/tahinli/proj/releases/{}/assets", rel.id),
907- Some(&fx.tahinli_cookie),
908- Some(&content_type),
909- body,
910- )
911- .await;
912- assert_eq!(reply.status, 303, "body: {}", reply.text());
913- assert!(
914- reply
915- .location
916- .unwrap_or_default()
917- .contains("notice=asset-replaced")
918- );
919- let assets = fx.store.list_release_assets(&rel.id).await.expect("assets");
920- assert_eq!(assets.len(), 1, "still one asset");
921- assert_eq!(assets[0].name, "app.bin");
922- assert_eq!(assets[0].size, 12);
923- let got = send(
924- &fx.app,
925- "GET",
926- "/tahinli/proj/releases/download/v1.2/app.bin",
927- None,
928- None,
929- Vec::new(),
930- )
931 .await;761 .await;
932- assert_eq!(got.body, b"second bytes");762+ assert!(
933- }763+ second
764+ .location
765+ .unwrap_or_default()
766+ .contains("notice=asset-replaced"),
767+ "a same-name upload replaces instead of refusing"
768+ );
769+ let assets = fx.store.list_release_assets(&rel.id).await.expect("assets");
770+ assert_eq!(assets.len(), 1, "still one asset of that name");
771+ let after = &assets[0];
772+ assert_ne!(after.id, before.id, "the new file has its own blob");
773+ assert_eq!(after.size, 12);
774+ assert_eq!(after.download_count, 1, "the download counter survives");
775+ assert!(
776+ fx.state
777+ .blobs
778+ .read(&asset_key(&before.id))
779+ .await
780+ .expect("read")
781+ .is_none(),
782+ "the replaced blob is deleted"
783+ );
784+ let got = fx.download("v1.1/app.bin").await;
785+ assert_eq!(got.body, b"second bytes");
934 786
935- // A wrong CSRF token on upload is refused and stores nothing.787+ let rel = fx.release("v1.2", false).await;
936- {788+ let first = fx
937- let rel = fx.release("v1.3", false).await;789+ .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)
938- let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[
939- ("csrf", None, b"wrong"),
940- ("file", Some(("a.bin", "application/octet-stream")), b"data"),
941- ]);
942- let reply = send(
943- &fx.app,
944- "POST",
945- &format!("/tahinli/proj/releases/{}/assets", rel.id),
946- Some(&fx.tahinli_cookie),
947- Some(&content_type),
948- body,
949- )
950 .await;790 .await;
951- assert_ne!(reply.status, 303, "csrf mismatch");791+ assert_eq!(first.status, 303);
952- assert!(792+
953- fx.store793+ let page = send(
954- .list_release_assets(&rel.id)794+ &fx.app,
955- .await795+ "GET",
956- .expect("assets")796+ &format!("/tahinli/proj/releases/{}/edit", rel.id),
957- .is_empty()797+ Some(&fx.tahinli_cookie),
958- );798+ None,
959- }799+ Vec::new(),
800+ )
801+ .await;
802+ assert!(
803+ page.text().contains("name=\"name\" value=\"app.bin\""),
804+ "each asset has a replace form"
805+ );
960 806
961- // Deleting a release keeps its git tag and removes its assets and blobs.807+ let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[
962- {808+ ("csrf", None, CSRF.as_bytes()),
963- git(&fx.bare, &["tag", "v1.4", "refs/heads/main"]);809+ ("name", None, "app.bin".as_bytes()),
964- let rel = fx.release("v1.4", false).await;810+ (
965- let up = fx811+ "file",
966- .upload(&rel.id, "gone.bin", b"bytes", &fx.tahinli_cookie)812+ Some(("renamed-build.zip", "application/octet-stream")),
967- .await;813+ "second bytes".as_bytes(),
968- assert_eq!(up.status, 303);814+ ),
969- let asset = fx815+ ]);
970- .store816+ let reply = send(
971- .release_asset(&rel.id, "gone.bin")817+ &fx.app,
818+ "POST",
819+ &format!("/tahinli/proj/releases/{}/assets", rel.id),
820+ Some(&fx.tahinli_cookie),
821+ Some(&content_type),
822+ body,
823+ )
824+ .await;
825+ assert_eq!(reply.status, 303, "body: {}", reply.text());
826+ assert!(
827+ reply
828+ .location
829+ .unwrap_or_default()
830+ .contains("notice=asset-replaced")
831+ );
832+ let assets = fx.store.list_release_assets(&rel.id).await.expect("assets");
833+ assert_eq!(assets.len(), 1, "still one asset");
834+ assert_eq!(assets[0].name, "app.bin");
835+ assert_eq!(assets[0].size, 12);
836+ let got = fx.download("v1.2/app.bin").await;
837+ assert_eq!(got.body, b"second bytes");
838+
839+ let rel = fx.release("v1.3", false).await;
840+ let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[
841+ ("csrf", None, b"wrong"),
842+ ("file", Some(("a.bin", "application/octet-stream")), b"data"),
843+ ]);
844+ let reply = send(
845+ &fx.app,
846+ "POST",
847+ &format!("/tahinli/proj/releases/{}/assets", rel.id),
848+ Some(&fx.tahinli_cookie),
849+ Some(&content_type),
850+ body,
851+ )
852+ .await;
853+ assert_ne!(reply.status, 303, "csrf mismatch");
854+ assert!(
855+ fx.store
856+ .list_release_assets(&rel.id)
972 .await857 .await
973- .expect("read")858+ .expect("assets")
974- .expect("row");859+ .is_empty()
975- let blob = crate::blobs::asset_key(&asset.id);860+ );
976- assert!(fx.state.blobs.read(&blob).await.expect("read").is_some());
977 861
978- let reply = send(862+ git(&fx.bare, &["tag", "v1.4", "refs/heads/main"]);
979- &fx.app,863+ let rel = fx.release("v1.4", false).await;
980- "POST",864+ let up = fx
981- &format!("/tahinli/proj/releases/{}/delete", rel.id),865+ .upload(&rel.id, "gone.bin", b"bytes", &fx.tahinli_cookie)
982- Some(&fx.tahinli_cookie),
983- Some(FORM_TYPE),
984- form(&[("csrf", CSRF), ("confirm", "on")]),
985- )
986 .await;866 .await;
987- assert_eq!(reply.status, 303);867+ assert_eq!(up.status, 303);
988- assert!(fx.store.release(&rel.id).await.expect("read").is_none());868+ let asset = fx
989- assert!(fx.tag_target("v1.4").is_some(), "the git tag survives");869+ .store
990- assert!(870+ .release_asset(&rel.id, "gone.bin")
991- fx.state.blobs.read(&blob).await.expect("read").is_none(),871+ .await
992- "the blob is gone"872+ .expect("read")
993- );873+ .expect("row");
994- let download = send(874+ let blob = asset_key(&asset.id);
995- &fx.app,875+ assert!(fx.state.blobs.read(&blob).await.expect("read").is_some());
996- "GET",876+
997- "/tahinli/proj/releases/download/v1.4/gone.bin",877+ let reply = send(
998- None,878+ &fx.app,
999- None,879+ "POST",
1000- Vec::new(),880+ &format!("/tahinli/proj/releases/{}/delete", rel.id),
1001- )881+ Some(&fx.tahinli_cookie),
1002- .await;882+ Some(FORM_TYPE),
1003- assert_eq!(download.status, 404, "a deleted asset does not download");883+ form(&[("csrf", CSRF), ("confirm", "on")]),
1004- }884+ )
885+ .await;
886+ assert_eq!(reply.status, 303);
887+ assert!(fx.store.release(&rel.id).await.expect("read").is_none());
888+ assert!(fx.tag_target("v1.4").is_some(), "the git tag survives");
889+ assert!(
890+ fx.state.blobs.read(&blob).await.expect("read").is_none(),
891+ "the blob is gone"
892+ );
893+ let download = fx.download("v1.4/gone.bin").await;
894+ assert_eq!(download.status, 404, "a deleted asset does not download");
1005 }895 }
1006 896
1007 #[tokio::test]897 #[tokio::test]
@@ -1009,175 +899,131 @@ async fn the_size_cap_refuses_new_and_replacement_uploads() {
1009 let fx = fixture(Some(1)).await;899 let fx = fixture(Some(1)).await;
1010 let big = vec![7u8; 1024 * 1024 + 4096];900 let big = vec![7u8; 1024 * 1024 + 4096];
1011 901
1012- // Runs first: no blob may exist yet, so the blob directory must stay empty.902+ let rel = fx.release("v1.0", false).await;
1013- {903+ let reply = fx
1014- let rel = fx.release("v1.0", false).await;904+ .upload(&rel.id, "big.bin", &big, &fx.tahinli_cookie)
1015- let reply = fx905+ .await;
1016- .upload(&rel.id, "big.bin", &big, &fx.tahinli_cookie)906+ assert_eq!(reply.status, 303);
1017- .await;907+ assert!(
1018- assert_eq!(reply.status, 303);908+ reply
1019- assert!(909+ .location
1020- reply910+ .unwrap_or_default()
1021- .location911+ .contains("notice=asset-too-large"),
1022- .unwrap_or_default()912+ "the cap refuses the file"
1023- .contains("notice=asset-too-large"),913+ );
1024- "the cap refuses the file"914+ assert!(
1025- );915+ fx.store
1026- assert!(916+ .list_release_assets(&rel.id)
1027- fx.store
1028- .list_release_assets(&rel.id)
1029- .await
1030- .expect("assets")
1031- .is_empty()
1032- );
1033- let assets_dir = fx.state.config.data_dir.join("blobs").join("assets");
1034- let leftovers = std::fs::read_dir(&assets_dir)
1035- .map(|entries| entries.count())
1036- .unwrap_or(0);
1037- assert_eq!(leftovers, 0, "no partial blob is left behind");
1038- }
1039-
1040- // A refused replacement keeps the old file.
1041- {
1042- let rel = fx.release("v1.1", false).await;
1043- fx.upload(&rel.id, "app.bin", b"keep me", &fx.tahinli_cookie)
1044- .await;
1045- let reply = fx
1046- .upload(&rel.id, "app.bin", &big, &fx.tahinli_cookie)
1047- .await;
1048- assert!(
1049- reply
1050- .location
1051- .unwrap_or_default()
1052- .contains("notice=asset-too-large"),
1053- "an oversized replacement is refused"
1054- );
1055- let row = fx
1056- .store
1057- .release_asset(&rel.id, "app.bin")
1058 .await917 .await
1059- .expect("read")918+ .expect("assets")
1060- .expect("row");919+ .is_empty()
1061- assert_eq!(row.size, 7, "the old size stays");920+ );
1062- let got = send(921+ let assets_dir = fx.state.config.data_dir.join("blobs").join("assets");
1063- &fx.app,922+ let leftovers = std::fs::read_dir(&assets_dir)
1064- "GET",923+ .map(|entries| entries.count())
1065- "/tahinli/proj/releases/download/v1.1/app.bin",924+ .unwrap_or(0);
1066- None,925+ assert_eq!(leftovers, 0, "no partial blob is left behind");
1067- None,926+
1068- Vec::new(),927+ let rel = fx.release("v1.1", false).await;
1069- )928+ fx.upload(&rel.id, "app.bin", b"keep me", &fx.tahinli_cookie)
1070 .await;929 .await;
1071- assert_eq!(got.body, b"keep me", "the old bytes stay");930+ let reply = fx
1072- }931+ .upload(&rel.id, "app.bin", &big, &fx.tahinli_cookie)
932+ .await;
933+ assert!(
934+ reply
935+ .location
936+ .unwrap_or_default()
937+ .contains("notice=asset-too-large"),
938+ "an oversized replacement is refused"
939+ );
940+ let row = fx
941+ .store
942+ .release_asset(&rel.id, "app.bin")
943+ .await
944+ .expect("read")
945+ .expect("row");
946+ assert_eq!(row.size, 7, "the old size stays");
947+ let got = fx.download("v1.1/app.bin").await;
948+ assert_eq!(got.body, b"keep me", "the old bytes stay");
1073 }949 }
1074 950
1075-/// The live streams of the release list and a release page: a change from another session wakes951+async fn open(fx: &Fixture, uri: &str, cookie: Option<&str>) -> Response {
1076-/// them, and a reader without the access the page needs gets the page's 404.952+ let mut builder = Request::builder().method("GET").uri(uri);
1077-mod live_tests {953+ if let Some(cookie) = cookie {
1078- use super::*;954+ builder = builder.header("cookie", cookie);
1079- use futures_util::StreamExt;
1080- use topcoat::router::response::Response;
1081-
1082- /// Sends a GET for a stream. The body is not read here: a stream never ends.
1083- async fn open(fx: &Fixture, uri: &str, cookie: Option<&str>) -> Response {
1084- let mut builder = Request::builder().method("GET").uri(uri);
1085- if let Some(cookie) = cookie {
1086- builder = builder.header("cookie", cookie);
1087- }
1088- fx.app
1089- .handle(builder.body(Body::empty()).expect("request"))
1090- .await
1091 }955 }
956+ fx.app
957+ .handle(builder.body(Body::empty()).expect("request"))
958+ .await
959+}
1092 960
1093- const CHANGED: &[u8] = b"event: changed\ndata: 1\n\n";961+#[tokio::test]
1094-962+async fn live_streams_wake_on_changes_and_hide_drafts() {
1095- #[tokio::test]963+ let fx = fixture(None).await;
1096- async fn an_edit_wakes_the_release_list_and_the_release_page() {
1097- let fx = fixture(None).await;
1098- let rel = fx.release("v1.0", false).await;
1099- let list = open(&fx, "/tahinli/proj/releases/events", None).await;
1100- assert_eq!(list.status().as_u16(), 200);
1101- let mut list = list.into_body().into_data_stream();
1102- let page = open(&fx, "/tahinli/proj/releases/tag/v1.0/events", None).await;
1103- assert_eq!(page.status().as_u16(), 200);
1104- let mut page = page.into_body().into_data_stream();
1105- let retry = list.next().await.expect("a frame").expect("data");
1106- assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1107- let retry = page.next().await.expect("a frame").expect("data");
1108- assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1109-
1110- let edit = EditRelease {
1111- title: "Renamed".to_owned(),
1112- ..keep(&rel)
1113- };
1114- release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)
1115- .await
1116- .expect("edited");
1117-
1118- assert_eq!(
1119- &list.next().await.expect("a frame").expect("data")[..],
1120- CHANGED
1121- );
1122- assert_eq!(
1123- &page.next().await.expect("a frame").expect("data")[..],
1124- CHANGED
1125- );
1126- }
1127 964
1128- #[tokio::test]965+ let rel = fx.release("v1.0", false).await;
1129- async fn an_asset_upload_and_a_download_each_wake_the_list() {966+ let list = open(&fx, "/tahinli/proj/releases/events", None).await;
1130- let fx = fixture(None).await;967+ assert_eq!(list.status().as_u16(), 200);
1131- let rel = fx.release("v1.0", false).await;968+ let mut list = list.into_body().into_data_stream();
1132- let mut list = open(&fx, "/tahinli/proj/releases/events", None)969+ let page = open(&fx, "/tahinli/proj/releases/tag/v1.0/events", None).await;
1133- .await970+ assert_eq!(page.status().as_u16(), 200);
1134- .into_body()971+ let mut page = page.into_body().into_data_stream();
1135- .into_data_stream();972+ let retry = list.next().await.expect("a frame").expect("data");
1136- let retry = list.next().await.expect("a frame").expect("data");973+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1137- assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");974+ let retry = page.next().await.expect("a frame").expect("data");
1138-975+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1139- let uploaded = fx976+
1140- .upload(&rel.id, "app.tar.gz", b"bytes", &fx.tahinli_cookie)977+ let edit = EditRelease {
1141- .await;978+ title: "Renamed".to_owned(),
1142- assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());979+ ..keep(&rel)
1143- assert_eq!(980+ };
1144- &list.next().await.expect("a frame").expect("data")[..],981+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)
1145- CHANGED982+ .await
1146- );983+ .expect("edited");
984+ assert_eq!(
985+ &list.next().await.expect("a frame").expect("data")[..],
986+ CHANGED
987+ );
988+ assert_eq!(
989+ &page.next().await.expect("a frame").expect("data")[..],
990+ CHANGED
991+ );
1147 992
1148- let download = send(993+ let rel = fx.release("v1.1", false).await;
1149- &fx.app,994+ let mut list = open(&fx, "/tahinli/proj/releases/events", None)
1150- "GET",995+ .await
1151- "/tahinli/proj/releases/download/v1.0/app.tar.gz",996+ .into_body()
1152- None,997+ .into_data_stream();
1153- None,998+ let retry = list.next().await.expect("a frame").expect("data");
1154- Vec::new(),999+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1155- )1000+ let uploaded = fx
1001+ .upload(&rel.id, "app.tar.gz", b"bytes", &fx.tahinli_cookie)
1156 .await;1002 .await;
1157- assert_eq!(download.status, 200);1003+ assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());
1158- assert_eq!(1004+ assert_eq!(
1159- &list.next().await.expect("a frame").expect("data")[..],1005+ &list.next().await.expect("a frame").expect("data")[..],
1160- CHANGED1006+ CHANGED
1161- );1007+ );
1162- }1008+ let download = fx.download("v1.1/app.tar.gz").await;
1163-1009+ assert_eq!(download.status, 200);
1164- #[tokio::test]1010+ assert_eq!(
1165- async fn a_draft_is_not_streamed_to_a_reader_and_its_page_is_404() {1011+ &list.next().await.expect("a frame").expect("data")[..],
1166- let fx = fixture(None).await;1012+ CHANGED
1167- fx.release("v2.0", true).await;1013+ );
1168- let uri = "/tahinli/proj/releases/tag/v2.0/events";
1169 1014
1170- assert_eq!(open(&fx, uri, None).await.status().as_u16(), 404);1015+ fx.release("v2.0", true).await;
1171- assert_eq!(1016+ let uri = "/tahinli/proj/releases/tag/v2.0/events";
1172- open(&fx, uri, Some(&fx.bob_cookie)).await.status().as_u16(),1017+ assert_eq!(open(&fx, uri, None).await.status().as_u16(), 404);
1173- 4041018+ assert_eq!(
1174- );1019+ open(&fx, uri, Some(&fx.bob_cookie)).await.status().as_u16(),
1175- assert_eq!(1020+ 404
1176- open(&fx, uri, Some(&fx.tahinli_cookie))1021+ );
1177- .await1022+ assert_eq!(
1178- .status()1023+ open(&fx, uri, Some(&fx.tahinli_cookie))
1179- .as_u16(),1024+ .await
1180- 2001025+ .status()
1181- );1026+ .as_u16(),
1182- }1027+ 200
1028+ );
1183 }1029 }
crates/forge-web-account/src/pages/settings_appearance.rsmodified+72 -192
@@ -1,8 +1,3 @@
1-//! Page: appearance (`/settings/appearance`). The colour theme, the language, the sound alerts, and
2-//! for each of the light and dark themes a background and an accent colour, all stored per user.
3-//! Every change saves at once, so the form has no Save button. Anonymous visitors set the theme from
4-//! the footer instead (see `pages/theme_cookie.rs`). Every POST checks the CSRF token first.
5-
6 use std::collections::HashMap;1 use std::collections::HashMap;
7 2
8 use forge_core::AuditAction;3 use forge_core::AuditAction;
@@ -29,18 +24,10 @@ use crate::state::AppState;
29 use crate::views::parts::{SubPart, head};24 use crate::views::parts::{SubPart, head};
30 use crate::views::shell;25 use crate::views::shell;
31 26
32-/// Language codes offered on the page. `auto` follows the browser. Other codes must be
33-/// translated in `i18n/mod.rs` before they are added here.
34 pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"];27 pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"];
35 28
36-/// Theme codes, in display order.
37-const THEME_CODES: &[&str] = &["auto", "light", "dark"];
38-
39-/// The colour tabs, in display order: the light theme's colours, then the dark theme's.
40 const TAB_CODES: &[&str] = &["light", "dark"];29 const TAB_CODES: &[&str] = &["light", "dark"];
41 30
42-/// Reads a field that is present as a string, even an empty one. The plain `Option<String>`
43-/// reading would turn an empty value into `None`, which is the same as a missing field.
44 fn present_string<'de, D: Deserializer<'de>>(31 fn present_string<'de, D: Deserializer<'de>>(
45 de: D,32 de: D,
46 ) -> std::result::Result<Option<String>, D::Error> {33 ) -> std::result::Result<Option<String>, D::Error> {
@@ -55,9 +42,6 @@ struct AppearanceForm {
55 theme: String,42 theme: String,
56 #[serde(default)]43 #[serde(default)]
57 language: String,44 language: String,
58- /// The four colour fields are optional so a form loaded before a field existed still saves.
59- /// When a field is absent, its stored value is kept. A present but empty or unknown value
60- /// stays `Some("")` or an unknown id, and is rejected.
61 #[serde(default, deserialize_with = "present_string")]45 #[serde(default, deserialize_with = "present_string")]
62 accent_light: Option<String>,46 accent_light: Option<String>,
63 #[serde(default, deserialize_with = "present_string")]47 #[serde(default, deserialize_with = "present_string")]
@@ -68,8 +52,6 @@ struct AppearanceForm {
68 base_dark: Option<String>,52 base_dark: Option<String>,
69 #[serde(default, deserialize_with = "present_string")]53 #[serde(default, deserialize_with = "present_string")]
70 sidebar_side: Option<String>,54 sidebar_side: Option<String>,
71- /// Present when the form that holds the sound switch was posted: an unchecked switch posts
72- /// nothing, so this tells off from a post that never showed the switch.
73 #[serde(default, deserialize_with = "present_string")]55 #[serde(default, deserialize_with = "present_string")]
74 sound_shown: Option<String>,56 sound_shown: Option<String>,
75 #[serde(default, deserialize_with = "present_string")]57 #[serde(default, deserialize_with = "present_string")]
@@ -80,12 +62,9 @@ struct Choice {
80 value: &'static str,62 value: &'static str,
81 label: &'static str,63 label: &'static str,
82 selected: bool,64 selected: bool,
83- /// The hue a preset moves the stripe knob to, as text; empty when the preset has none.
84 hue: String,65 hue: String,
85 }66 }
86 67
87-/// Where a row's sliders sit: the hue, the vividness, and the hex box's colour. `custom` says the
88-/// stored choice is that colour, rather than a preset whose hue the knob was moved to.
89 struct Stripe {68 struct Stripe {
90 hue: u16,69 hue: u16,
91 vivid: u8,70 vivid: u8,
@@ -93,12 +72,9 @@ struct Stripe {
93 hex: String,72 hex: String,
94 }73 }
95 74
96-/// The vividness a row starts at when its stored id gives none (a legacy `hue-N`): 50 for an accent,
97-/// 30 for a background. These are the defaults of `accent::custom_of`.
98 const ACCENT_VIVID: u8 = 50;75 const ACCENT_VIVID: u8 = 50;
99 const BASE_VIVID: u8 = 30;76 const BASE_VIVID: u8 = 30;
100 77
101-/// The lightness a row's hex box uses, in one theme: the accent's, or the background's.
102 fn row_lightness(base: bool, dark: bool) -> f64 {78 fn row_lightness(base: bool, dark: bool) -> f64 {
103 match (base, dark) {79 match (base, dark) {
104 (false, true) => 0.75,80 (false, true) => 0.75,
@@ -108,8 +84,6 @@ fn row_lightness(base: bool, dark: bool) -> f64 {
108 }84 }
109 }85 }
110 86
111-/// The `#RRGGBB` a row's hex box shows for a hue and vividness: the colour the sliders stand for,
112-/// at the row's lightness. The chroma is the one the stylesheet gives that vividness.
113 fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String {87 fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String {
114 let v = f64::from(vivid);88 let v = f64::from(vivid);
115 let chroma = if base {89 let chroma = if base {
@@ -122,36 +96,14 @@ fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String {
122 custom_colour::colour(row_lightness(base, dark), chroma, f64::from(hue))96 custom_colour::colour(row_lightness(base, dark), chroma, f64::from(hue))
123 }97 }
124 98
125-/// The colour choices of one theme: a background and an accent, each a row of presets and the hue,
126-/// vividness and hex controls. `dark` picks the field names and the swatch attributes that belong to
127-/// the dark theme.
128-struct ColourGroup {
129- dark: bool,
130- background: &'static str,
131- accent: &'static str,
132- custom: &'static str,
133- hue: &'static str,
134- vividness: &'static str,
135- hex: &'static str,
136- bases: Vec<Choice>,
137- accents: Vec<Choice>,
138- base_stripe: Stripe,
139- accent_stripe: Stripe,
140-}
141-
142-/// One row of a colour panel: its presets, then the Custom choice beside the hue, vividness and hex
143-/// controls. `base` picks the background's chips and the accent's when false.
144 struct ColourRow {99 struct ColourRow {
100+ lang: Lang,
145 dark: bool,101 dark: bool,
146 base: bool,102 base: bool,
147 legend: &'static str,103 legend: &'static str,
148 field: &'static str,104 field: &'static str,
149 choices: Vec<Choice>,105 choices: Vec<Choice>,
150 stripe: Stripe,106 stripe: Stripe,
151- custom_label: &'static str,
152- hue_label: &'static str,
153- vivid_label: &'static str,
154- hex_label: &'static str,
155 }107 }
156 108
157 struct AppearancePage {109 struct AppearancePage {
@@ -160,16 +112,13 @@ struct AppearancePage {
160 theme: Vec<Choice>,112 theme: Vec<Choice>,
161 language: Vec<Choice>,113 language: Vec<Choice>,
162 colours: &'static str,114 colours: &'static str,
163- /// The tab that opens first: the light or the dark colours.
164 tab: &'static str,115 tab: &'static str,
165 tabs: Vec<Choice>,116 tabs: Vec<Choice>,
166- light: ColourGroup,117+ light: [ColourRow; 2],
167- dark: ColourGroup,118+ dark: [ColourRow; 2],
168- /// Whether the run-finished tone is on: the sound switch's checked state.
169 sound_on: bool,119 sound_on: bool,
170 }120 }
171 121
172-/// The label of a language code. The two native names stay as they are in every language.
173 fn language_label(lang: Lang, code: &str) -> &'static str {122 fn language_label(lang: Lang, code: &str) -> &'static str {
174 match code {123 match code {
175 "auto" => g::t(lang, K::MatchBrowser),124 "auto" => g::t(lang, K::MatchBrowser),
@@ -179,8 +128,6 @@ fn language_label(lang: Lang, code: &str) -> &'static str {
179 }128 }
180 }129 }
181 130
182-/// The label of a theme code. Light is the default for everyone who has not chosen, so it is
183-/// marked as the default.
184 fn theme_label(lang: Lang, code: &str) -> &'static str {131 fn theme_label(lang: Lang, code: &str) -> &'static str {
185 match code {132 match code {
186 "light" => match lang {133 "light" => match lang {
@@ -208,7 +155,6 @@ fn choices(
208 .collect()155 .collect()
209 }156 }
210 157
211-/// The label of a colour tab: the light or the dark theme.
212 fn tab_label(lang: Lang, code: &str) -> &'static str {158 fn tab_label(lang: Lang, code: &str) -> &'static str {
213 if code == "dark" {159 if code == "dark" {
214 g::t(lang, K::Dark)160 g::t(lang, K::Dark)
@@ -217,7 +163,6 @@ fn tab_label(lang: Lang, code: &str) -> &'static str {
217 }163 }
218 }164 }
219 165
220-/// Fills in the hue each preset moves the stripe knob to.
221 fn with_hues(mut list: Vec<Choice>, hue: fn(&str) -> Option<u16>) -> Vec<Choice> {166 fn with_hues(mut list: Vec<Choice>, hue: fn(&str) -> Option<u16>) -> Vec<Choice> {
222 for choice in &mut list {167 for choice in &mut list {
223 choice.hue = hue(choice.value).map(|h| h.to_string()).unwrap_or_default();168 choice.hue = hue(choice.value).map(|h| h.to_string()).unwrap_or_default();
@@ -225,8 +170,6 @@ fn with_hues(mut list: Vec<Choice>, hue: fn(&str) -> Option<u16>) -> Vec<Choice>
225 list170 list
226 }171 }
227 172
228-/// The id a row shows as selected. A custom hue stays as stored; a preset is resolved, so an id
229-/// that is no longer offered shows the default, as the page renders it on `<html>`.
230 fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str {173 fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str {
231 if hue_of(stored).is_some() {174 if hue_of(stored).is_some() {
232 stored175 stored
@@ -235,9 +178,6 @@ fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str {
235 }178 }
236 }179 }
237 180
238-/// The sliders of one row. A stored custom id (`hue-H-vV`, or the legacy `hue-H`) sets the hue and
239-/// vividness; a preset puts the hue knob on the preset's hue at the default vividness, and nothing
240-/// is selected as custom.
241 fn stripe(stored: &str, preset: Option<u16>, base: bool, dark: bool) -> Stripe {181 fn stripe(stored: &str, preset: Option<u16>, base: bool, dark: bool) -> Stripe {
242 let default_vivid = if base { BASE_VIVID } else { ACCENT_VIVID };182 let default_vivid = if base { BASE_VIVID } else { ACCENT_VIVID };
243 let (hue, vivid, custom) = match custom_of(stored, default_vivid) {183 let (hue, vivid, custom) = match custom_of(stored, default_vivid) {
@@ -252,50 +192,59 @@ fn stripe(stored: &str, preset: Option<u16>, base: bool, dark: bool) -> Stripe {
252 }192 }
253 }193 }
254 194
255-/// One theme's colour choices, with the stored background and accent selected.195+fn colour_group(lang: Lang, dark: bool, base: &str, accent_id: &str) -> [ColourRow; 2] {
256-fn colour_group(lang: Lang, dark: bool, base: &str, accent_id: &str) -> ColourGroup {
257 let base_codes: Vec<&'static str> = accent::base_ids().collect();196 let base_codes: Vec<&'static str> = accent::base_ids().collect();
258 let accent_codes: Vec<&'static str> = accent::ids().collect();197 let accent_codes: Vec<&'static str> = accent::ids().collect();
259 let base_shown = shown(base, accent::resolve_base(base).id);198 let base_shown = shown(base, accent::resolve_base(base).id);
260 let accent_shown = shown(accent_id, accent::resolve(accent_id).id);199 let accent_shown = shown(accent_id, accent::resolve(accent_id).id);
261- ColourGroup {200+ let (base_field, accent_field) = if dark {
262- dark,201+ ("base_dark", "accent_dark")
263- background: g::t(lang, K::BackgroundLabel),202+ } else {
264- accent: g::t(lang, K::AccentRowLabel),203+ ("base_light", "accent_light")
265- custom: g::t(lang, K::CustomLabel),204+ };
266- hue: g::t(lang, K::HueLabel),205+ [
267- vividness: g::t(lang, K::VividnessLabel),206+ ColourRow {
268- hex: g::t(lang, K::HexLabel),207+ lang,
269- bases: with_hues(208+ dark,
270- choices(&base_codes, base_shown, |id| base_name(lang, id)),209+ base: true,
271- preset_base_hue,210+ legend: g::t(lang, K::BackgroundLabel),
272- ),211+ field: base_field,
273- accents: with_hues(212+ choices: with_hues(
274- choices(&accent_codes, accent_shown, |id| accent_name(lang, id)),213+ choices(&base_codes, base_shown, |id| base_name(lang, id)),
275- preset_accent_hue,214+ preset_base_hue,
276- ),215+ ),
277- base_stripe: stripe(base, preset_base_hue(base_shown), true, dark),216+ stripe: stripe(base, preset_base_hue(base_shown), true, dark),
278- accent_stripe: stripe(accent_id, preset_accent_hue(accent_shown), false, dark),217+ },
279- }218+ ColourRow {
219+ lang,
220+ dark,
221+ base: false,
222+ legend: g::t(lang, K::AccentRowLabel),
223+ field: accent_field,
224+ choices: with_hues(
225+ choices(&accent_codes, accent_shown, |id| accent_name(lang, id)),
226+ preset_accent_hue,
227+ ),
228+ stripe: stripe(accent_id, preset_accent_hue(accent_shown), false, dark),
229+ },
230+ ]
280 }231 }
281 232
282-/// One row of a colour panel: its presets as round radios, then the Custom choice, a hue slider, a
283-/// vividness slider and a hex box. The Custom radio carries `hue-H-vV`, and nav.js keeps it, the
284-/// sliders and the hex box in step while the row is used.
285 #[component]233 #[component]
286 async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> {234 async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> {
287 let ColourRow {235 let ColourRow {
236+ lang,
288 dark,237 dark,
289 base,238 base,
290 legend,239 legend,
291 field,240 field,
292 choices,241 choices,
293 stripe,242 stripe,
294- custom_label,
295- hue_label,
296- vivid_label,
297- hex_label,
298 } = row;243 } = row;
244+ let custom_label = g::t(lang, K::CustomLabel);
245+ let hue_label = g::t(lang, K::HueLabel);
246+ let vivid_label = g::t(lang, K::VividnessLabel);
247+ let hex_label = g::t(lang, K::HexLabel);
299 let value = custom_id(stripe.hue, stripe.vivid);248 let value = custom_id(stripe.hue, stripe.vivid);
300 let hue_value = stripe.hue.to_string();249 let hue_value = stripe.hue.to_string();
301 let vivid_value = stripe.vivid.to_string();250 let vivid_value = stripe.vivid.to_string();
@@ -350,57 +299,6 @@ async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> {
350 })299 })
351 }300 }
352 301
353-/// One theme's panel: a Background row and an Accent row.
354-#[component]
355-async fn colour_panel(cx: &Cx, group: ColourGroup) -> Result<impl View> {
356- let ColourGroup {
357- dark,
358- background,
359- accent,
360- custom,
361- hue,
362- vividness,
363- hex,
364- bases,
365- accents,
366- base_stripe,
367- accent_stripe,
368- } = group;
369- let base_field = if dark { "base_dark" } else { "base_light" };
370- let accent_field = if dark { "accent_dark" } else { "accent_light" };
371- let panel = if dark { "dark" } else { "light" };
372- let base_row = ColourRow {
373- dark,
374- base: true,
375- legend: background,
376- field: base_field,
377- choices: bases,
378- stripe: base_stripe,
379- custom_label: custom,
380- hue_label: hue,
381- vivid_label: vividness,
382- hex_label: hex,
383- };
384- let accent_row = ColourRow {
385- dark,
386- base: false,
387- legend: accent,
388- field: accent_field,
389- choices: accents,
390- stripe: accent_stripe,
391- custom_label: custom,
392- hue_label: hue,
393- vivid_label: vividness,
394- hex_label: hex,
395- };
396- Ok(view! {
397- <div class="colour-panel" data-colour-panel=(panel)>
398- colour_row(row: base_row)
399- colour_row(row: accent_row)
400- </div>
401- })
402-}
403-
404 #[component]302 #[component]
405 async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {303 async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
406 let AppearancePage {304 let AppearancePage {
@@ -411,8 +309,8 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
411 colours,309 colours,
412 tab,310 tab,
413 tabs,311 tabs,
414- light,312+ light: [light_base, light_accent],
415- dark,313+ dark: [dark_base, dark_accent],
416 sound_on,314 sound_on,
417 } = page;315 } = page;
418 Ok(view! {316 Ok(view! {
@@ -456,8 +354,14 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
456 }354 }
457 </div>355 </div>
458 </div>356 </div>
459- colour_panel(group: light)357+ <div class="colour-panel" data-colour-panel="light">
460- colour_panel(group: dark)358+ colour_row(row: light_base)
359+ colour_row(row: light_accent)
360+ </div>
361+ <div class="colour-panel" data-colour-panel="dark">
362+ colour_row(row: dark_base)
363+ colour_row(row: dark_accent)
364+ </div>
461 </fieldset>365 </fieldset>
462 </section>366 </section>
463 <section class="sec">367 <section class="sec">
@@ -486,7 +390,6 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
486 })390 })
487 }391 }
488 392
489-/// Rejects a theme or a language that is not offered. Nothing is saved for either of them.
490 fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> {393 fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> {
491 if !THEMES.contains(&theme) {394 if !THEMES.contains(&theme) {
492 return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into()));395 return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into()));
@@ -497,8 +400,6 @@ fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<(
497 Ok(())400 Ok(())
498 }401 }
499 402
500-/// The accent a save stores for one theme. An absent field keeps the stored id. A present one
501-/// must be an offered accent, so an empty or unknown value is rejected.
502 fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {403 fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
503 match posted {404 match posted {
504 None => Ok(stored.to_owned()),405 None => Ok(stored.to_owned()),
@@ -507,8 +408,6 @@ fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::
507 }408 }
508 }409 }
509 410
510-/// The background a save stores for one theme. An absent field keeps the stored id. A present
511-/// one must be an offered base, so an empty or unknown value is rejected.
512 fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {411 fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
513 match posted {412 match posted {
514 None => Ok(stored.to_owned()),413 None => Ok(stored.to_owned()),
@@ -517,8 +416,6 @@ fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Re
517 }416 }
518 }417 }
519 418
520-/// The sidebar side a save stores. An absent field keeps the stored side. A present one must be
521-/// `left` or `right`, so an empty or unknown value is rejected.
522 fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {419 fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
523 match posted {420 match posted {
524 None => Ok(stored.to_owned()),421 None => Ok(stored.to_owned()),
@@ -527,15 +424,11 @@ fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core:
527 }424 }
528 }425 }
529 426
530-/// The side a viewer's stored value stands for. Anything but `right` is `left`, the default, which
531-/// is also what the shell renders on `<html>` (see `views/mod.rs`).
532 #[cfg(test)]427 #[cfg(test)]
533 pub fn sidebar_stored(stored: &str) -> &'static str {428 pub fn sidebar_stored(stored: &str) -> &'static str {
534 if stored == "right" { "right" } else { "left" }429 if stored == "right" { "right" } else { "left" }
535 }430 }
536 431
537-/// Builds the page for a viewer. Each choice shows the stored value, or the default when the
538-/// stored id is no longer offered, which is what the page renders on `<html>` too.
539 fn page_for(432 fn page_for(
540 viewer: &(User, Session),433 viewer: &(User, Session),
541 lang: Lang,434 lang: Lang,
@@ -543,8 +436,6 @@ fn page_for(
543 ) -> AppearancePage {436 ) -> AppearancePage {
544 let user = &viewer.0;437 let user = &viewer.0;
545 let sound_on = prefs.get(SOUND).is_some_and(|v| v == "on");438 let sound_on = prefs.get(SOUND).is_some_and(|v| v == "on");
546- // The tab that opens first is the dark colours for a dark theme. The page script moves it to
547- // the one the viewer sees when the theme follows the system.
548 let tab = if user.theme == "dark" {439 let tab = if user.theme == "dark" {
549 "dark"440 "dark"
550 } else {441 } else {
@@ -553,7 +444,7 @@ fn page_for(
553 AppearancePage {444 AppearancePage {
554 lang,445 lang,
555 csrf: viewer.1.csrf_token.clone(),446 csrf: viewer.1.csrf_token.clone(),
556- theme: choices(THEME_CODES, &user.theme, |code| theme_label(lang, code)),447+ theme: choices(THEMES, &user.theme, |code| theme_label(lang, code)),
557 language: choices(LANGUAGE_CODES, &user.language, |code| {448 language: choices(LANGUAGE_CODES, &user.language, |code| {
558 language_label(lang, code)449 language_label(lang, code)
559 }),450 }),
@@ -566,8 +457,6 @@ fn page_for(
566 }457 }
567 }458 }
568 459
569-/// A sound value a save stores. Absent (`None`) stores nothing. A present value must
570-/// be one offered, so an empty or unknown value is rejected.
571 fn pref_choice(460 fn pref_choice(
572 lang: Lang,461 lang: Lang,
573 posted: Option<&str>,462 posted: Option<&str>,
@@ -612,8 +501,6 @@ async fn appearance_save(cx: &Cx, Form(form): Form<AppearanceForm>) -> Result<Se
612 let base_light = base_choice(lang, form.base_light.as_deref(), &user.base_light)?;501 let base_light = base_choice(lang, form.base_light.as_deref(), &user.base_light)?;
613 let base_dark = base_choice(lang, form.base_dark.as_deref(), &user.base_dark)?;502 let base_dark = base_choice(lang, form.base_dark.as_deref(), &user.base_dark)?;
614 let sidebar_side = sidebar_choice(lang, form.sidebar_side.as_deref(), &user.sidebar_side)?;503 let sidebar_side = sidebar_choice(lang, form.sidebar_side.as_deref(), &user.sidebar_side)?;
615- // An unchecked switch posts nothing, so a form that showed it and sent no `sound` means off. A
616- // post that never showed it leaves the stored sound alone.
617 let posted_sound = match (&form.sound_shown, &form.sound) {504 let posted_sound = match (&form.sound_shown, &form.sound) {
618 (Some(_), None) => Some("off"),505 (Some(_), None) => Some("off"),
619 (_, Some(value)) => Some(value.as_str()),506 (_, Some(value)) => Some(value.as_str()),
@@ -738,7 +625,6 @@ mod tests {
738 "base upper case {id}"625 "base upper case {id}"
739 );626 );
740 }627 }
741- // Removed presets, and hue values that are out of range or not canonical, are refused.
742 for id in [628 for id in [
743 "teal",629 "teal",
744 "moss",630 "moss",
@@ -772,7 +658,6 @@ mod tests {
772 );658 );
773 }659 }
774 660
775- // An absent colour keeps the stored value.
776 assert_eq!(661 assert_eq!(
777 accent_choice(Lang::En, None, "plum").unwrap(),662 accent_choice(Lang::En, None, "plum").unwrap(),
778 "plum",663 "plum",
@@ -796,11 +681,9 @@ mod tests {
796 assert!(base_err.to_string().contains("background"), "{base_err}");681 assert!(base_err.to_string().contains("background"), "{base_err}");
797 }682 }
798 683
799- /// The colour groups mark the stored theme, accent and base as selected. A custom hue
800- /// fills its stripe and checks no preset; a preset moves the knob to its own hue.
801 #[test]684 #[test]
802 fn stored_colours_are_selected_and_hues_drive_the_stripes() {685 fn stored_colours_are_selected_and_hues_drive_the_stripes() {
803- let options = choices(THEME_CODES, "dark", |code| theme_label(Lang::En, code));686+ let options = choices(THEMES, "dark", |code| theme_label(Lang::En, code));
804 let selected: Vec<&str> = options687 let selected: Vec<&str> = options
805 .iter()688 .iter()
806 .filter(|c| c.selected)689 .filter(|c| c.selected)
@@ -822,44 +705,42 @@ mod tests {
822 "accent: default first"705 "accent: default first"
823 );706 );
824 707
825- let group = colour_group(Lang::En, true, "ink", "plum");708+ let [base_row, _] = colour_group(Lang::En, true, "ink", "plum");
826- let bases: Vec<&str> = group709+ let bases: Vec<&str> = base_row
827- .bases710+ .choices
828 .iter()711 .iter()
829 .filter(|c| c.selected)712 .filter(|c| c.selected)
830 .map(|c| c.value)713 .map(|c| c.value)
831 .collect();714 .collect();
832 assert_eq!(bases, ["ink"], "base: selected");715 assert_eq!(bases, ["ink"], "base: selected");
833 assert_eq!(716 assert_eq!(
834- group.bases[0].value,717+ base_row.choices[0].value,
835 forge_web_app::accent_palette::BASE_DEFAULT,718 forge_web_app::accent_palette::BASE_DEFAULT,
836 "base: default first"719 "base: default first"
837 );720 );
838 721
839- // A custom hue fills the stripe and checks no preset.722+ let [base_row, accent_row] = colour_group(Lang::En, false, "hue-200", "hue-40");
840- let group = colour_group(Lang::En, false, "hue-200", "hue-40");723+ assert!(base_row.stripe.custom, "custom base hue");
841- assert!(group.base_stripe.custom, "custom base hue");724+ assert_eq!(base_row.stripe.hue, 200, "custom base hue value");
842- assert_eq!(group.base_stripe.hue, 200, "custom base hue value");725+ assert!(accent_row.stripe.custom, "custom accent hue");
843- assert!(group.accent_stripe.custom, "custom accent hue");726+ assert_eq!(accent_row.stripe.hue, 40, "custom accent hue value");
844- assert_eq!(group.accent_stripe.hue, 40, "custom accent hue value");
845 assert!(727 assert!(
846- group.bases.iter().all(|c| !c.selected),728+ base_row.choices.iter().all(|c| !c.selected),
847 "custom hue: no base preset checked"729 "custom hue: no base preset checked"
848 );730 );
849 assert!(731 assert!(
850- group.accents.iter().all(|c| !c.selected),732+ accent_row.choices.iter().all(|c| !c.selected),
851 "custom hue: no accent preset checked"733 "custom hue: no accent preset checked"
852 );734 );
853 735
854- // A preset moves the knob to its own hue.736+ let [base_row, accent_row] = colour_group(Lang::En, true, "ink", "plum");
855- let group = colour_group(Lang::En, true, "ink", "plum");
856 let plum_hue = preset_accent_hue("plum").unwrap();737 let plum_hue = preset_accent_hue("plum").unwrap();
857 let ink_hue = preset_base_hue("ink").unwrap();738 let ink_hue = preset_base_hue("ink").unwrap();
858- assert!(!group.accent_stripe.custom, "preset accent: not custom");739+ assert!(!accent_row.stripe.custom, "preset accent: not custom");
859- assert_eq!(group.accent_stripe.hue, plum_hue, "preset accent: knob hue");740+ assert_eq!(accent_row.stripe.hue, plum_hue, "preset accent: knob hue");
860- assert!(!group.base_stripe.custom, "preset base: not custom");741+ assert!(!base_row.stripe.custom, "preset base: not custom");
861- assert_eq!(group.base_stripe.hue, ink_hue, "preset base: knob hue");742+ assert_eq!(base_row.stripe.hue, ink_hue, "preset base: knob hue");
862- let plum = group.accents.iter().find(|c| c.value == "plum").unwrap();743+ let plum = accent_row.choices.iter().find(|c| c.value == "plum").unwrap();
863 assert!(plum.selected, "preset accent: checked");744 assert!(plum.selected, "preset accent: checked");
864 assert_eq!(plum.hue, plum_hue.to_string(), "preset accent: hue value");745 assert_eq!(plum.hue, plum_hue.to_string(), "preset accent: hue value");
865 746
@@ -870,11 +751,10 @@ mod tests {
870 assert_eq!(hue_of("sage"), None, "hue: preset id");751 assert_eq!(hue_of("sage"), None, "hue: preset id");
871 }752 }
872 753
873- /// A stored `hue-95-v80` fills the hue and vividness sliders, and the Custom value is that id again.
874 #[test]754 #[test]
875 fn a_stored_hue_and_vividness_fill_the_sliders() {755 fn a_stored_hue_and_vividness_fill_the_sliders() {
876- let group = colour_group(Lang::En, true, "hue-95-v80", "hue-95-v80");756+ let [base_row, accent_row] = colour_group(Lang::En, true, "hue-95-v80", "hue-95-v80");
877- let accent = &group.accent_stripe;757+ let accent = &accent_row.stripe;
878 assert_eq!((accent.hue, accent.vivid), (95, 80), "accent: sliders");758 assert_eq!((accent.hue, accent.vivid), (95, 80), "accent: sliders");
879 assert!(accent.custom, "accent: custom");759 assert!(accent.custom, "accent: custom");
880 assert_eq!(760 assert_eq!(
@@ -883,7 +763,7 @@ mod tests {
883 "accent: value"763 "accent: value"
884 );764 );
885 assert_eq!(765 assert_eq!(
886- (group.base_stripe.hue, group.base_stripe.vivid),766+ (base_row.stripe.hue, base_row.stripe.vivid),
887 (95, 80),767 (95, 80),
888 "base: sliders"768 "base: sliders"
889 );769 );
crates/forge-web-account/src/pages/settings_export.rsmodified+9 -11
@@ -59,6 +59,10 @@ fn signature(exports: &[DataExport]) -> String {
59 .join(",")59 .join(",")
60 }60 }
61 61
62+fn is_building(exports: &[DataExport]) -> bool {
63+ exports.iter().any(|e| e.state == ExportState::Building)
64+}
65+
62 /// The rail of the Data page: the archives, and the delete-account topic.66 /// The rail of the Data page: the archives, and the delete-account topic.
63 fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> {67 fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> {
64 vec![68 vec![
@@ -85,7 +89,7 @@ async fn export_sheet(
85 csrf: &str,89 csrf: &str,
86 exports: Vec<DataExport>,90 exports: Vec<DataExport>,
87 ) -> Result<impl View> {91 ) -> Result<impl View> {
88- let building = exports.iter().any(|e| e.state == ExportState::Building);92+ let building = is_building(&exports);
89 let live = building.then(|| {93 let live = building.then(|| {
90 format!(94 format!(
91 "/settings/export/events?v={}",95 "/settings/export/events?v={}",
@@ -93,10 +97,6 @@ async fn export_sheet(
93 )97 )
94 });98 });
95 let empty = exports.is_empty();99 let empty = exports.is_empty();
96- let deletes: Vec<String> = exports
97- .iter()
98- .map(|e| format!("/settings/export/{}/delete", e.id))
99- .collect();
100 Ok(view! {100 Ok(view! {
101 <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>101 <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>
102 <section class="sec">102 <section class="sec">
@@ -104,7 +104,8 @@ async fn export_sheet(
104 if empty {104 if empty {
105 <p class="state">(g::t(lang, K::ExportNone))</p>105 <p class="state">(g::t(lang, K::ExportNone))</p>
106 }106 }
107- for (export, delete) in exports.iter().zip(deletes.iter()) {107+ for export in exports.iter() {
108+ let delete = format!("/settings/export/{}/delete", export.id);
108 <div class="export-row">109 <div class="export-row">
109 <div class="line">110 <div class="line">
110 <span class="name">(g::t(lang, K::ExportRequested)) " " rel_time(lang: lang, stamp: export.created_at.as_str())</span>111 <span class="name">(g::t(lang, K::ExportRequested)) " " rel_time(lang: lang, stamp: export.created_at.as_str())</span>
@@ -217,7 +218,7 @@ async fn data_body(
217 } else {218 } else {
218 g::t(lang, K::ExportTitle)219 g::t(lang, K::ExportTitle)
219 };220 };
220- let building = exports.iter().any(|e| e.state == ExportState::Building);221+ let building = is_building(&exports);
221 Ok(view! {222 Ok(view! {
222 head(title: title, sub: Vec::<SubPart>::new(),223 head(title: title, sub: Vec::<SubPart>::new(),
223 if !delete {224 if !delete {
@@ -267,9 +268,6 @@ async fn page_view(
267 None => StatusCode::OK,268 None => StatusCode::OK,
268 };269 };
269 let csrf = viewer.1.csrf_token.clone();270 let csrf = viewer.1.csrf_token.clone();
270- // `view!` expects the `cx` binding that `#[page]` and `#[component]` provide. This plain
271- // helper has to bind it itself.
272- let cx = cx;
273 Ok(view! {271 Ok(view! {
274 (status)272 (status)
275 (headers)273 (headers)
@@ -349,7 +347,7 @@ async fn export_events(cx: &Cx) -> Result<Response> {
349 loop {347 loop {
350 let exports = store.list_exports(&user_id).await.ok()?;348 let exports = store.list_exports(&user_id).await.ok()?;
351 let sig = signature(&exports);349 let sig = signature(&exports);
352- let building = exports.iter().any(|e| e.state == ExportState::Building);350+ let building = is_building(&exports);
353 if sig != seen {351 if sig != seen {
354 seen = sig;352 seen = sig;
355 return Some((changed_event("export".to_owned()), (wake, seen, !building)));353 return Some((changed_event("export".to_owned()), (wake, seen, !building)));
crates/forge-web-account/src/pages/settings_gpg.rsmodified+4 -13
@@ -8,14 +8,14 @@ use topcoat::Result;
8 use topcoat::context::{Cx, context};8 use topcoat::context::{Cx, context};
9 use topcoat::router::content::Form;9 use topcoat::router::content::Form;
10 use topcoat::router::error::{SeeOther, not_found, see_other};10 use topcoat::router::error::{SeeOther, not_found, see_other};
11-use topcoat::router::{page, query_params, route};11+use topcoat::router::{page, route};
12 use topcoat::view::{View, component, view};12 use topcoat::view::{View, component, view};
13 13
14 use crate::audit::{self, Actor, Target};14 use crate::audit::{self, Actor, Target};
15-use crate::auth::{require_csrf, require_user};15+use crate::auth::require_csrf;
16 use crate::i18n::s;16 use crate::i18n::s;
17 use crate::i18n::{self, Key, Lang, t};17 use crate::i18n::{self, Key, Lang, t};
18-use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};18+use crate::pages::settings_keys::{KeyKind, KeysDraft, kind_page, keys_page_view};
19 use crate::signatures;19 use crate::signatures;
20 use crate::state::AppState;20 use crate::state::AppState;
21 use crate::views::parts::confirm_act;21 use crate::views::parts::confirm_act;
@@ -86,16 +86,7 @@ pub(crate) async fn gpg_section(
86 86
87 #[page("/settings/gpg")]87 #[page("/settings/gpg")]
88 async fn gpg_page(cx: &Cx) -> Result<impl View> {88 async fn gpg_page(cx: &Cx) -> Result<impl View> {
89- let viewer = require_user(cx).await?;89+ kind_page(cx, KeyKind::Gpg).await
90- let lang = i18n::lang(cx, Some(&viewer.0));
91- let state = context::<AppState>(cx);
92- let draft = KeysDraft {
93- add: query_params::<AddQuery>(cx)?.add.is_some(),
94- ..KeysDraft::default()
95- };
96- Ok(view! {
97- keys_page_view(lang: lang, state: state, viewer: &viewer, kind: KeyKind::Gpg, draft: draft)
98- })
99 }90 }
100 91
101 #[page(POST "/settings/gpg")]92 #[page(POST "/settings/gpg")]
crates/forge-web-account/src/pages/settings_keys.rsmodified+11 -6
@@ -19,7 +19,7 @@ use crate::i18n::{self, Key, Lang, t, unsupported_key_type};
19 use crate::pages::settings_gpg::gpg_section;19 use crate::pages::settings_gpg::gpg_section;
20 use crate::pages::settings_tokens::tokens_section;20 use crate::pages::settings_tokens::tokens_section;
21 use crate::state::AppState;21 use crate::state::AppState;
22-use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail};22+use crate::views::parts::{RailItem, confirm_act, head, rail};
23 use crate::views::{added_status, alert, shell, user_facing_message};23 use crate::views::{added_status, alert, shell, user_facing_message};
24 24
25 /// Algorithms accepted for web-registered keys. `ssh-rsa` is rejected with its own message.25 /// Algorithms accepted for web-registered keys. `ssh-rsa` is rejected with its own message.
@@ -32,6 +32,7 @@ const ACCEPTED: &[&str] = &[
32 "sk-ecdsa-sha2-nistp256@openssh.com",32 "sk-ecdsa-sha2-nistp256@openssh.com",
33 ];33 ];
34 const MAX_KEY_CHARS: usize = 16 * 1024;34 const MAX_KEY_CHARS: usize = 16 * 1024;
35+const MAX_TITLE_CHARS: usize = 100;
35 36
36 /// Why a pasted key line is refused. `message` says it in the viewer's language.37 /// Why a pasted key line is refused. `message` says it in the viewer's language.
37 #[derive(Debug, PartialEq, Eq)]38 #[derive(Debug, PartialEq, Eq)]
@@ -221,7 +222,6 @@ pub(crate) async fn keys_page_view(
221 current: k == kind,222 current: k == kind,
222 })223 })
223 .collect();224 .collect();
224- let sub = Vec::<SubPart>::new();
225 let add_href = format!("{}?add=1", kind.href());225 let add_href = format!("{}?add=1", kind.href());
226 let add_open = draft.add226 let add_open = draft.add
227 || draft.ssh_error.is_some()227 || draft.ssh_error.is_some()
@@ -231,7 +231,7 @@ pub(crate) async fn keys_page_view(
231 let parents = vec![(pk_title(lang).to_owned(), "/settings/keys".to_owned())];231 let parents = vec![(pk_title(lang).to_owned(), "/settings/keys".to_owned())];
232 Ok(view! {232 Ok(view! {
233 shell(title: kind.title(lang), viewer: Some(viewer), parents: parents,233 shell(title: kind.title(lang), viewer: Some(viewer), parents: parents,
234- head(title: kind.title(lang), sub: sub,234+ head(title: kind.title(lang),
235 <a class="button primary" href=(add_href)>(kind.add_label(lang))</a>235 <a class="button primary" href=(add_href)>(kind.add_label(lang))</a>
236 )236 )
237 <div class="work">237 <div class="work">
@@ -301,8 +301,7 @@ async fn ssh_section(
301 })301 })
302 }302 }
303 303
304-#[page("/settings/keys")]304+pub(crate) async fn kind_page(cx: &Cx, kind: KeyKind) -> Result<impl View> {
305-async fn keys_page(cx: &Cx) -> Result<impl View> {
306 let viewer = require_user(cx).await?;305 let viewer = require_user(cx).await?;
307 let lang = i18n::lang(cx, Some(&viewer.0));306 let lang = i18n::lang(cx, Some(&viewer.0));
308 let state = context::<AppState>(cx);307 let state = context::<AppState>(cx);
@@ -311,10 +310,15 @@ async fn keys_page(cx: &Cx) -> Result<impl View> {
311 ..KeysDraft::default()310 ..KeysDraft::default()
312 };311 };
313 Ok(view! {312 Ok(view! {
314- keys_page_view(lang: lang, state: state, viewer: &viewer, kind: KeyKind::Ssh, draft: draft)313+ keys_page_view(lang: lang, state: state, viewer: &viewer, kind: kind, draft: draft)
315 })314 })
316 }315 }
317 316
317+#[page("/settings/keys")]
318+async fn keys_page(cx: &Cx) -> Result<impl View> {
319+ kind_page(cx, KeyKind::Ssh).await
320+}
321+
318 #[page(POST "/settings/keys")]322 #[page(POST "/settings/keys")]
319 async fn keys_add(cx: &Cx, Form(form): Form<AddKeyForm>) -> Result<impl View> {323 async fn keys_add(cx: &Cx, Form(form): Form<AddKeyForm>) -> Result<impl View> {
320 let viewer = require_csrf(cx, &form.csrf).await?;324 let viewer = require_csrf(cx, &form.csrf).await?;
@@ -330,6 +334,7 @@ async fn keys_add(cx: &Cx, Form(form): Form<AddKeyForm>) -> Result<impl View> {
330 "" => parsed.algorithm.clone(),334 "" => parsed.algorithm.clone(),
331 t => t.to_owned(),335 t => t.to_owned(),
332 };336 };
337+ let title: String = title.chars().take(MAX_TITLE_CHARS).collect();
333 match store338 match store
334 .add_ssh_key(339 .add_ssh_key(
335 &viewer.0.id,340 &viewer.0.id,
crates/forge-web-account/src/pages/settings_live.rsmodified+18 -89
@@ -1,26 +1,3 @@
1-//! Live settings. The signed-in user's own settings pages (`/settings/...`) follow
2-//! [`Topic::Account`] of their own user through `GET /settings/events`. The settings section of the
3-//! sidebar names that stream (see `views::section_for`), so every page under `/settings` follows it
4-//! without an attribute of its own. Public profile viewers follow [`Topic::User`] and never wake.
5-//!
6-//! Writes reach the topic two ways:
7-//! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance
8-//! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so
9-//! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees.
10-//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), a
11-//! key or token used by git, the API, SSH or a package client, and an admin action that ends
12-//! sessions. Those call [`bump_account`].
13-//!
14-//! The settings stream sends `changed` on each wake and carries no data: the page re-reads itself.
15-//! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page
16-//! leaves for the login page.
17-//!
18-//! Every page also holds `/-/alive` (see [`alive_response`]). That stream follows
19-//! [`Topic::ServerSettings`] for every viewer, anonymous included: a `settings` event when a live
20-//! server setting changes, so the open page re-renders. For a signed-in viewer it also sends a
21-//! `theme` event with the appearance attributes when they change, so a tab applies a theme, accent
22-//! or sidebar change made elsewhere without a reload.
23-
24 use std::collections::VecDeque;1 use std::collections::VecDeque;
25 2
26 use forge_core::server_settings::{self, FIELDS, Kind};3 use forge_core::server_settings::{self, FIELDS, Kind};
@@ -36,8 +13,6 @@ use crate::auth::current_user;
36 use crate::live::{LiveHub, Topic, events_response, stream_wakes};13 use crate::live::{LiveHub, Topic, events_response, stream_wakes};
37 use crate::state::AppState;14 use crate::state::AppState;
38 15
39-/// The change stream of the viewer's settings. The viewer comes from the session only, so a user
40-/// can follow only their own settings. Without a session: 401.
41 #[route(GET "/settings/events")]16 #[route(GET "/settings/events")]
42 async fn settings_events(cx: &Cx) -> Result<Response> {17 async fn settings_events(cx: &Cx) -> Result<Response> {
43 let Some((user, _)) = current_user(cx).await? else {18 let Some((user, _)) = current_user(cx).await? else {
@@ -49,22 +24,16 @@ async fn settings_events(cx: &Cx) -> Result<Response> {
49 stream_wakes(cx, hub, &[Topic::Account(user.id)])24 stream_wakes(cx, hub, &[Topic::Account(user.id)])
50 }25 }
51 26
52-/// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value means27+#[derive(Default, PartialEq)]
53-/// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so28+struct AccountState {
54-/// a tab that applies it shows what a fresh load of the page would show. The last pair, `custom_css`,29+ appearance: String,
55-/// is the stylesheet of the hue choices (empty for presets only); `nav.js` applies only `data-*`30+ language: String,
56-/// pairs, so it reads this one itself.31+ identity: String,
57-/// The account state the alive stream compares: the appearance (see below), the language32+}
58-/// preference, which changes the page text rather than its attributes, and the identity the33+
59-/// header shows (the username, the avatar's hash, admin rights) with whether the viewer's session34+async fn account_state(state: &AppState, user_id: &str, session_id: &str) -> Result<AccountState> {
60-/// still exists. A session revoked elsewhere makes that last part change.
61-pub async fn account_state(
62- state: &AppState,
63- user_id: &str,
64- session_id: &str,
65-) -> Result<AccountState> {
66 let Some(user) = state.store.user_by_id(user_id).await? else {35 let Some(user) = state.store.user_by_id(user_id).await? else {
67- return Ok((String::new(), String::new(), String::new()));36+ return Ok(AccountState::default());
68 };37 };
69 let theme = match crate::theme::Theme::from_stored(&user.theme) {38 let theme = match crate::theme::Theme::from_stored(&user.theme) {
70 crate::theme::Theme::Auto => "",39 crate::theme::Theme::Auto => "",
@@ -79,7 +48,6 @@ pub async fn account_state(
79 let accent_dark = crate::accent::accent_id(&user.accent_dark);48 let accent_dark = crate::accent::accent_id(&user.accent_dark);
80 let base_light = crate::accent::base_id(&user.base_light);49 let base_light = crate::accent::base_id(&user.base_light);
81 let base_dark = crate::accent::base_id(&user.base_dark);50 let base_dark = crate::accent::base_id(&user.base_dark);
82- // The stylesheet of the hue choices, empty when there is none (see `views::shell`).
83 let custom_css =51 let custom_css =
84 crate::accent::custom_css_href(accent_light, accent_dark, base_light, base_dark)52 crate::accent::custom_css_href(accent_light, accent_dark, base_light, base_dark)
85 .unwrap_or_default();53 .unwrap_or_default();
@@ -97,15 +65,13 @@ pub async fn account_state(
97 "{}\n{avatar}\n{}\n{session_open}",65 "{}\n{avatar}\n{}\n{session_open}",
98 user.username, user.is_admin66 user.username, user.is_admin
99 );67 );
100- Ok((appearance, user.language.clone(), identity))68+ Ok(AccountState {
69+ appearance,
70+ language: user.language.clone(),
71+ identity,
72+ })
101 }73 }
102 74
103-/// The account state the alive stream compares: appearance, language, identity (see
104-/// [`account_state`]).
105-pub type AccountState = (String, String, String);
106-
107-/// The viewer's account as the alive stream follows it: the user and session ids, the wake of its
108-/// topic, and the account state last sent.
109 struct AccountFollow {75 struct AccountFollow {
110 user_id: String,76 user_id: String,
111 session_id: String,77 session_id: String,
@@ -113,25 +79,19 @@ struct AccountFollow {
113 last: AccountState,79 last: AccountState,
114 }80 }
115 81
116-/// What the alive stream holds between events.
117 struct Alive {82 struct Alive {
118 state: AppState,83 state: AppState,
119- /// Present for a signed-in viewer only.
120 account: Option<AccountFollow>,84 account: Option<AccountFollow>,
121 server_wake: watch::Receiver<u64>,85 server_wake: watch::Receiver<u64>,
122- /// The server settings fingerprint last sent or seen (see [`settings_fingerprint`]).
123 settings_last: String,86 settings_last: String,
124 queue: VecDeque<Event>,87 queue: VecDeque<Event>,
125 }88 }
126 89
127-/// What woke the alive stream.
128 enum Wake {90 enum Wake {
129 Account,91 Account,
130 Settings,92 Settings,
131 }93 }
132 94
133-/// The server settings the pages render, as one fingerprint: the values of every `Kind::Live`
134-/// setting, in field order. A `settings` event goes out when it differs from the last one sent.
135 pub fn settings_fingerprint(state: &AppState) -> String {95 pub fn settings_fingerprint(state: &AppState) -> String {
136 let live = state.live();96 let live = state.live();
137 FIELDS97 FIELDS
@@ -142,7 +102,6 @@ pub fn settings_fingerprint(state: &AppState) -> String {
142 .join("\n")102 .join("\n")
143 }103 }
144 104
145-/// Waits for the viewer's account topic. A stream with no signed-in viewer waits on nothing.
146 async fn wait_account(account: &mut Option<AccountFollow>) -> bool {105 async fn wait_account(account: &mut Option<AccountFollow>) -> bool {
147 match account {106 match account {
148 Some(follow) => follow.wake.changed().await.is_ok(),107 Some(follow) => follow.wake.changed().await.is_ok(),
@@ -150,15 +109,7 @@ async fn wait_account(account: &mut Option<AccountFollow>) -> bool {
150 }109 }
151 }110 }
152 111
153-/// The response of `GET /-/alive`, the stream every page holds. Every viewer follows the server
154-/// settings topic: a change to a live setting sends a `settings` event, and the page re-renders
155-/// (see `nav.js`). A signed-in viewer also follows their account topic: each time the appearance
156-/// differs from the last one sent it gets a `theme` event carrying the new attributes, a language
157-/// change a `language` event, and a change of the header's identity (username, avatar, admin) or a
158-/// revoked session an `account` event. The stream still opens with `retry`, and its open still
159-/// means the server is back.
160 pub async fn alive_response(cx: &Cx) -> Result<Response> {112 pub async fn alive_response(cx: &Cx) -> Result<Response> {
161- // A router with no app state (the asset tests) has nothing to follow: the stream only stays open.
162 let Some(state) = try_context::<AppState>(cx).cloned() else {113 let Some(state) = try_context::<AppState>(cx).cloned() else {
163 return events_response(cx, stream::pending::<Result<Event>>());114 return events_response(cx, stream::pending::<Result<Event>>());
164 };115 };
@@ -169,14 +120,10 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> {
169 events_response(cx, events)120 events_response(cx, events)
170 }121 }
171 122
172-/// The events of the alive stream for `viewer` (the user and session ids, when signed in). See
173-/// [`alive_response`]. The caller holds the stream slot; `pages::shell_events` merges it with the
174-/// shell's other streams.
175 pub async fn alive_stream(123 pub async fn alive_stream(
176 state: AppState,124 state: AppState,
177 viewer: Option<(String, String)>,125 viewer: Option<(String, String)>,
178 ) -> Result<BoxStream<'static, Result<Event>>> {126 ) -> Result<BoxStream<'static, Result<Event>>> {
179- // Subscribed before each baseline is read, so a change in between is not lost.
180 let server_wake = state.live.subscribe(&Topic::ServerSettings);127 let server_wake = state.live.subscribe(&Topic::ServerSettings);
181 let settings_last = settings_fingerprint(&state);128 let settings_last = settings_fingerprint(&state);
182 let account = match viewer {129 let account = match viewer {
@@ -202,8 +149,6 @@ pub async fn alive_stream(
202 Ok(stream::unfold(alive, next_alive_event).boxed())149 Ok(stream::unfold(alive, next_alive_event).boxed())
203 }150 }
204 151
205-/// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends
206-/// nothing. None when a topic is gone, which ends the stream.
207 async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {152 async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {
208 loop {153 loop {
209 if let Some(event) = alive.queue.pop_front() {154 if let Some(event) = alive.queue.pop_front() {
@@ -251,16 +196,13 @@ async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {
251 };196 };
252 let last = &mut follow.last;197 let last = &mut follow.last;
253 if now != *last {198 if now != *last {
254- // One change can move several parts: each gets its own event.199+ if now.appearance != last.appearance {
255- if now.0 != last.0 {200+ queue.push_back(Event::new().event("theme").data(now.appearance.clone()));
256- queue.push_back(Event::new().event("theme").data(now.0.clone()));
257 }201 }
258- if now.1 != last.1 {202+ if now.language != last.language {
259- // The page text is re-rendered by the client (a soft refresh, see `nav.js`).
260 queue.push_back(Event::new().event("language").data("1"));203 queue.push_back(Event::new().event("language").data("1"));
261 }204 }
262- if now.2 != last.2 {205+ if now.identity != last.identity {
263- // The header or the session changed: the page re-renders (see `nav.js`).
264 queue.push_back(Event::new().event("account").data("1"));206 queue.push_back(Event::new().event("account").data("1"));
265 }207 }
266 *last = now;208 *last = now;
@@ -284,8 +226,6 @@ mod tests {
284 226
285 const CSRF: &str = "settings-live-csrf";227 const CSRF: &str = "settings-live-csrf";
286 228
287- /// The settings stream needs a session, and the settings pages name it (and not the old
288- /// theme stream).
289 #[tokio::test]229 #[tokio::test]
290 async fn the_settings_stream_needs_a_session_and_the_sidebar_names_it() {230 async fn the_settings_stream_needs_a_session_and_the_sidebar_names_it() {
291 let dir = tempfile::tempdir().expect("tempdir");231 let dir = tempfile::tempdir().expect("tempdir");
@@ -369,10 +309,6 @@ mod tests {
369 );309 );
370 }310 }
371 311
372- /// Two live streams on one app. The settings stream sends one changed event per write to
373- /// the account. The alive stream sends the appearance only when it changes: a bump that
374- /// changes nothing sends nothing, and a theme and language change sends the theme event
375- /// first, then the language event.
376 #[tokio::test]312 #[tokio::test]
377 async fn the_settings_stream_sends_changes_and_the_alive_stream_sends_appearance() {313 async fn the_settings_stream_sends_changes_and_the_alive_stream_sends_appearance() {
378 let dir = tempfile::tempdir().expect("tempdir");314 let dir = tempfile::tempdir().expect("tempdir");
@@ -390,7 +326,6 @@ mod tests {
390 .expect("prefs");326 .expect("prefs");
391 let router = app_router(state);327 let router = app_router(state);
392 328
393- // Settings stream: a retry hint first, then one changed event per write.
394 let request = Request::builder()329 let request = Request::builder()
395 .method("GET")330 .method("GET")
396 .uri("/settings/events")331 .uri("/settings/events")
@@ -414,7 +349,6 @@ mod tests {
414 "settings stream: changed event"349 "settings stream: changed event"
415 );350 );
416 351
417- // Alive stream: no event for a bump that changes no appearance.
418 let request = Request::builder()352 let request = Request::builder()
419 .method("GET")353 .method("GET")
420 .uri("/-/alive")354 .uri("/-/alive")
@@ -427,7 +361,6 @@ mod tests {
427 assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}");361 assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}");
428 362
429 live.bump(&Topic::Account(owner.id.clone()));363 live.bump(&Topic::Account(owner.id.clone()));
430- // One change of theme and language: the theme event first, then the language event.
431 store364 store
432 .set_ui_prefs(&owner.id, "dark", "tr")365 .set_ui_prefs(&owner.id, "dark", "tr")
433 .await366 .await
@@ -451,8 +384,6 @@ mod tests {
451 );384 );
452 }385 }
453 386
454- /// An anonymous page holds `/-/alive` too. A live server setting that changes, then a bump of the
455- /// server settings topic, sends one `settings` event.
456 #[tokio::test]387 #[tokio::test]
457 async fn the_alive_stream_sends_settings_to_anonymous_viewers() {388 async fn the_alive_stream_sends_settings_to_anonymous_viewers() {
458 let dir = tempfile::tempdir().expect("tempdir");389 let dir = tempfile::tempdir().expect("tempdir");
@@ -485,8 +416,6 @@ mod tests {
485 );416 );
486 }417 }
487 418
488- /// A new avatar on the signed-in viewer's account reaches the alive stream as one `account` event,
489- /// so the header re-renders.
490 #[tokio::test]419 #[tokio::test]
491 async fn the_alive_stream_sends_account_when_the_header_changes() {420 async fn the_alive_stream_sends_account_when_the_header_changes() {
492 let dir = tempfile::tempdir().expect("tempdir");421 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web-account/src/pages/settings_profile.rsmodified+9 -16
@@ -6,7 +6,7 @@ use std::sync::{Arc, OnceLock};
6 6
7 use forge_core::AuditAction;7 use forge_core::AuditAction;
8 use forge_core::names::capitalization_change;8 use forge_core::names::capitalization_change;
9-use forge_core::store::MAX_DISPLAY_NAME_CHARS;9+use forge_core::store::{MAX_ABOUT_CHARS, MAX_DISPLAY_NAME_CHARS};
10 use forge_core::tz::{all_timezones, validate_timezone};10 use forge_core::tz::{all_timezones, validate_timezone};
11 use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar};11 use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar};
12 use serde::Deserialize;12 use serde::Deserialize;
@@ -27,9 +27,6 @@ use crate::state::AppState;
27 use crate::views::parts::{SubPart, confirm_act, head, reveal};27 use crate::views::parts::{SubPart, confirm_act, head, reveal};
28 use crate::views::{alert, avatar_url, shell, user_facing_message};28 use crate::views::{alert, avatar_url, shell, user_facing_message};
29 29
30-/// Longest "about" text, in characters.
31-pub const MAX_ABOUT_CHARS: usize = 2000;
32-
33 /// Multipart framing overhead allowed on top of the image itself.30 /// Multipart framing overhead allowed on top of the image itself.
34 const MULTIPART_OVERHEAD: usize = 64 * 1024;31 const MULTIPART_OVERHEAD: usize = 64 * 1024;
35 32
@@ -210,13 +207,13 @@ async fn profile_body(cx: &Cx, page: ProfilePage) -> Result<impl View> {
210 }207 }
211 208
212 /// Collects what the profile page shows. `draft` fills the forms; `errors` shows under each section.209 /// Collects what the profile page shows. `draft` fills the forms; `errors` shows under each section.
213-async fn page_data(210+fn page_data(
214 viewer: &(User, Session),211 viewer: &(User, Session),
215 lang: Lang,212 lang: Lang,
216 draft: Draft,213 draft: Draft,
217 errors: Errors,214 errors: Errors,
218 notice: Option<&'static str>,215 notice: Option<&'static str>,
219-) -> Result<ProfilePage> {216+) -> ProfilePage {
220 let hash = viewer.0.avatar_hash.clone();217 let hash = viewer.0.avatar_hash.clone();
221 let zones = all_timezones()218 let zones = all_timezones()
222 .into_iter()219 .into_iter()
@@ -225,7 +222,7 @@ async fn page_data(
225 Zone { name, selected }222 Zone { name, selected }
226 })223 })
227 .collect();224 .collect();
228- Ok(ProfilePage {225+ ProfilePage {
229 lang,226 lang,
230 csrf: viewer.1.csrf_token.clone(),227 csrf: viewer.1.csrf_token.clone(),
231 draft,228 draft,
@@ -234,7 +231,7 @@ async fn page_data(
234 avatar_src: avatar_url(&viewer.0.username, hash.as_deref()),231 avatar_src: avatar_url(&viewer.0.username, hash.as_deref()),
235 has_avatar: hash.is_some(),232 has_avatar: hash.is_some(),
236 zones,233 zones,
237- })234+ }
238 }235 }
239 236
240 fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {237 fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {
@@ -330,8 +327,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
330 draft,327 draft,
331 Errors::default(),328 Errors::default(),
332 notice_for(lang, saved.as_deref()),329 notice_for(lang, saved.as_deref()),
333- )330+ );
334- .await?;
335 Ok(view! {331 Ok(view! {
336 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))332 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))
337 })333 })
@@ -374,7 +370,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie
374 about,370 about,
375 timezone: form.timezone,371 timezone: form.timezone,
376 };372 };
377- let page = page_data(&viewer, lang, draft, errors, None).await?;373+ let page = page_data(&viewer, lang, draft, errors, None);
378 return Ok(view! {374 return Ok(view! {
379 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))375 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))
380 });376 });
@@ -382,10 +378,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie
382 };378 };
383 379
384 store380 store
385- .set_profile(&viewer.0.id, &about, &form.timezone)381+ .save_profile(&viewer.0.id, &form.display_name, &about, &form.timezone)
386- .await?;
387- store
388- .set_display_name(&viewer.0.id, &form.display_name)
389 .await?;382 .await?;
390 if display != viewer.0.username {383 if display != viewer.0.username {
391 store.set_username_display(&viewer.0.id, &display).await?;384 store.set_username_display(&viewer.0.id, &display).await?;
@@ -444,7 +437,7 @@ async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result<impl View> {
444 avatar: Some(message),437 avatar: Some(message),
445 ..Errors::default()438 ..Errors::default()
446 };439 };
447- let page = page_data(&viewer, lang, Draft::from_user(&viewer.0), errors, None).await?;440+ let page = page_data(&viewer, lang, Draft::from_user(&viewer.0), errors, None);
448 Ok(view! {441 Ok(view! {
449 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))442 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))
450 })443 })
crates/forge-web-account/src/pages/settings_security.rsmodified+65 -96
@@ -25,8 +25,9 @@ use crate::auth::{
25 use crate::i18n::packages::{self as pk, K as PK};25 use crate::i18n::packages::{self as pk, K as PK};
26 use crate::i18n::releases_ci::{self as rc, K as RC};26 use crate::i18n::releases_ci::{self as rc, K as RC};
27 use crate::i18n::s;27 use crate::i18n::s;
28-use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t};28+use crate::i18n::{self, Key, Lang, t};
29 use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel};29 use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel};
30+use crate::pages::register::check_new_password;
30 use crate::pages::settings_export;31 use crate::pages::settings_export;
31 use crate::pages::settings_sessions::session_label;32 use crate::pages::settings_sessions::session_label;
32 use crate::state::AppState;33 use crate::state::AppState;
@@ -34,9 +35,6 @@ use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
34 use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail};35 use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail};
35 use crate::views::{added_status, alert, rel_time, shell, user_facing_message};36 use crate::views::{added_status, alert, rel_time, shell, user_facing_message};
36 37
37-/// Shortest and longest new passwords, in characters.
38-const MIN_PASSWORD_CHARS: usize = 10;
39-const MAX_PASSWORD_CHARS: usize = 1024;
40 /// Recovery codes issued by each enrollment or regeneration.38 /// Recovery codes issued by each enrollment or regeneration.
41 const RECOVERY_CODE_COUNT: usize = 10;39 const RECOVERY_CODE_COUNT: usize = 10;
42 /// At or below this many unused recovery codes the page warns and suggests regenerating.40 /// At or below this many unused recovery codes the page warns and suggests regenerating.
@@ -176,12 +174,6 @@ struct SecurityPage {
176 email_sent: Option<String>,174 email_sent: Option<String>,
177 /// Whether this server can send mail at all. The resend link shows only when it can.175 /// Whether this server can send mail at all. The resend link shows only when it can.
178 mail_ready: bool,176 mail_ready: bool,
179- notice: Option<&'static str>,
180- password_error: Option<String>,
181- email_error: Option<String>,
182- two_factor_error: Option<String>,
183- two_factor_panel: TwoFactorPanel,
184- codes: Option<Vec<String>>,
185 /// Secret (base32) and `otpauth://` URI while enrollment is waiting for a code.177 /// Secret (base32) and `otpauth://` URI while enrollment is waiting for a code.
186 pending: Option<(String, String)>,178 pending: Option<(String, String)>,
187 /// When the password last changed, shown as a live time, when known.179 /// When the password last changed, shown as a live time, when known.
@@ -193,8 +185,7 @@ struct SecurityPage {
193 sessions: Vec<Session>,185 sessions: Vec<Session>,
194 /// The id of the session that is viewing the page.186 /// The id of the session that is viewing the page.
195 current_session_id: String,187 current_session_id: String,
196- /// The topic asked for in the address, when no error or notice picks one.188+ shown: Shown,
197- part: Option<String>,
198 }189 }
199 190
200 /// The rail's kinds of security, one per topic. `active` names the topic that is shown, or191 /// The rail's kinds of security, one per topic. `active` names the topic that is shown, or
@@ -258,11 +249,7 @@ pub(crate) async fn security_rail_for(
258 viewer: &(User, Session),249 viewer: &(User, Session),
259 active: &str,250 active: &str,
260 ) -> forge_core::Result<Vec<RailItem>> {251 ) -> forge_core::Result<Vec<RailItem>> {
261- let two_factor_on = state252+ let two_factor_on = two_factor_enabled(&state.store, &viewer.0.id).await?;
262- .store
263- .totp_state(&viewer.0.id)
264- .await?
265- .is_some_and(|totp| totp.enabled);
266 let passkey_count = state.store.list_passkeys(&viewer.0.id).await?.len();253 let passkey_count = state.store.list_passkeys(&viewer.0.id).await?.len();
267 let session_count = state.store.list_sessions(&viewer.0.id).await?.len();254 let session_count = state.store.list_sessions(&viewer.0.id).await?.len();
268 Ok(security_rail_items(255 Ok(security_rail_items(
@@ -284,20 +271,24 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V
284 email_status,271 email_status,
285 email_sent,272 email_sent,
286 mail_ready,273 mail_ready,
287- notice,
288- password_error,
289- email_error,
290- two_factor_error,
291- two_factor_panel,
292- codes,
293 pending,274 pending,
294 password_changed,275 password_changed,
295 two_factor,276 two_factor,
296 passkeys,277 passkeys,
297 sessions,278 sessions,
298 current_session_id,279 current_session_id,
299- part,280+ shown,
300 } = page;281 } = page;
282+ let Shown {
283+ notice,
284+ password_error,
285+ email_error,
286+ two_factor_error,
287+ two_factor_panel,
288+ codes,
289+ part,
290+ ..
291+ } = shown;
301 let two_factor_on = two_factor.is_some();292 let two_factor_on = two_factor.is_some();
302 let passkey_count = passkeys.items.len();293 let passkey_count = passkeys.items.len();
303 let session_count = sessions.len();294 let session_count = sessions.len();
@@ -310,13 +301,11 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V
310 let email_open = email_error.is_some();301 let email_open = email_error.is_some();
311 let email_set = !email.is_empty();302 let email_set = !email.is_empty();
312 let show_resend = email_set && !email_verified && mail_ready;303 let show_resend = email_set && !email_verified && mail_ready;
313- let regenerate_error = two_factor_error304+ let (regenerate_error, disable_error, setup_error) = match two_factor_panel {
314- .clone()305+ TwoFactorPanel::Regenerate => (two_factor_error, None, None),
315- .filter(|_| two_factor_panel == TwoFactorPanel::Regenerate);306+ TwoFactorPanel::Disable => (None, two_factor_error, None),
316- let disable_error = two_factor_error307+ TwoFactorPanel::Setup => (None, None, two_factor_error),
317- .clone()308+ };
318- .filter(|_| two_factor_panel == TwoFactorPanel::Disable);
319- let setup_error = two_factor_error.filter(|_| two_factor_panel == TwoFactorPanel::Setup);
320 let regenerate_open = regenerate_error.is_some();309 let regenerate_open = regenerate_error.is_some();
321 let disable_open = disable_error.is_some();310 let disable_open = disable_error.is_some();
322 // One topic shows at a time: the one with an error or fresh codes, else the one asked for.311 // One topic shows at a time: the one with an error or fresh codes, else the one asked for.
@@ -629,6 +618,10 @@ async fn build_page(
629 }618 }
630 status619 status
631 };620 };
621+ let email = shown
622+ .email_draft
623+ .clone()
624+ .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default());
632 Ok(SecurityPage {625 Ok(SecurityPage {
633 lang,626 lang,
634 passkeys: build_panel(state, &viewer.0.id).await?,627 passkeys: build_panel(state, &viewer.0.id).await?,
@@ -637,30 +630,19 @@ async fn build_page(
637 email_status,630 email_status,
638 email_sent,631 email_sent,
639 mail_ready: mail_can_send(state).await,632 mail_ready: mail_can_send(state).await,
640- email: shown633+ email,
641- .email_draft
642- .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default()),
643- notice: shown.notice,
644- password_error: shown.password_error,
645- email_error: shown.email_error,
646- two_factor_error: shown.two_factor_error,
647- two_factor_panel: shown.two_factor_panel,
648- codes: shown.codes,
649 pending,634 pending,
650 password_changed,635 password_changed,
651 two_factor,636 two_factor,
652 sessions: state.store.list_sessions(&viewer.0.id).await?,637 sessions: state.store.list_sessions(&viewer.0.id).await?,
653 current_session_id: viewer.1.id.clone(),638 current_session_id: viewer.1.id.clone(),
654- part: shown.part,639+ shown,
655 })640 })
656 }641 }
657 642
658 /// Renders the page. A throttled check answers 429 with `Retry-After`.643 /// Renders the page. A throttled check answers 429 with `Retry-After`.
659 async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result<impl View> {644 async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result<impl View> {
660 let state = context::<AppState>(cx);645 let state = context::<AppState>(cx);
661- // `view!` expects the `cx` binding that `#[page]` and `#[component]` provide. This plain
662- // helper has to bind it itself.
663- let cx = cx;
664 let mut headers = HeaderMap::new();646 let mut headers = HeaderMap::new();
665 let status = match shown.throttled {647 let status = match shown.throttled {
666 Some(retry) => {648 Some(retry) => {
@@ -722,6 +704,31 @@ fn second_factor_blocked(state: &AppState, user_id: &str) -> Option<Duration> {
722 )704 )
723 }705 }
724 706
707+async fn check_second_factor(
708+ state: &AppState,
709+ lang: Lang,
710+ user_id: &str,
711+ code: &str,
712+) -> forge_core::Result<std::result::Result<(), Refused>> {
713+ if let Some(retry) = second_factor_blocked(state, user_id) {
714+ return Ok(Err(Refused {
715+ message: t(lang, Key::ErrThrottled),
716+ retry: Some(retry),
717+ }));
718+ }
719+ let key = throttle::two_factor_key(user_id);
720+ if verify_second_factor(&state.store, &state.key, user_id, code).await? {
721+ state.throttle.clear(&key);
722+ Ok(Ok(()))
723+ } else {
724+ state.throttle.record_failure(&key, Instant::now());
725+ Ok(Err(Refused {
726+ message: t(lang, Key::ErrWrongCode),
727+ retry: None,
728+ }))
729+ }
730+}
731+
725 /// Fresh recovery codes and their hashes. The plain codes are for display only.732 /// Fresh recovery codes and their hashes. The plain codes are for display only.
726 fn new_recovery_codes() -> (Vec<String>, Vec<String>) {733 fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
727 let codes: Vec<String> = (0..RECOVERY_CODE_COUNT)734 let codes: Vec<String> = (0..RECOVERY_CODE_COUNT)
@@ -731,21 +738,6 @@ fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
731 (codes, hashes)738 (codes, hashes)
732 }739 }
733 740
734-/// Why a new password is refused, or `None` when it is acceptable.
735-fn check_new_password(lang: Lang, new: &str, confirm: &str) -> Option<String> {
736- let len = new.chars().count();
737- if len < MIN_PASSWORD_CHARS {
738- return Some(password_too_short(lang, MIN_PASSWORD_CHARS));
739- }
740- if len > MAX_PASSWORD_CHARS {
741- return Some(password_too_long(lang, MAX_PASSWORD_CHARS));
742- }
743- if new != confirm {
744- return Some(t(lang, Key::ErrPasswordsDiffer).into());
745- }
746- None
747-}
748-
749 #[page("/settings/security")]741 #[page("/settings/security")]
750 async fn security_page(cx: &Cx) -> Result<impl View> {742 async fn security_page(cx: &Cx) -> Result<impl View> {
751 let viewer = require_user(cx).await?;743 let viewer = require_user(cx).await?;
@@ -953,18 +945,11 @@ async fn two_factor_disable(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
953 shown.throttled = refused.retry;945 shown.throttled = refused.retry;
954 return respond(cx, viewer, shown).await;946 return respond(cx, viewer, shown).await;
955 }947 }
956- if let Some(retry) = second_factor_blocked(state, &user_id) {948+ if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
957- shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into());949+ shown.two_factor_error = Some(refused.message.into());
958- shown.throttled = Some(retry);950+ shown.throttled = refused.retry;
959- return respond(cx, viewer, shown).await;
960- }
961- let key = throttle::two_factor_key(&user_id);
962- if !verify_second_factor(&state.store, &state.key, &user_id, &form.code).await? {
963- state.throttle.record_failure(&key, Instant::now());
964- shown.two_factor_error = Some(t(lang, Key::ErrWrongCode).into());
965 return respond(cx, viewer, shown).await;951 return respond(cx, viewer, shown).await;
966 }952 }
967- state.throttle.clear(&key);
968 state.store.disable_totp(&user_id).await?;953 state.store.disable_totp(&user_id).await?;
969 audit::record(954 audit::record(
970 &state.store,955 &state.store,
@@ -993,17 +978,10 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result<
993 return settings_export::respond_delete(cx, viewer, error, refused.retry).await;978 return settings_export::respond_delete(cx, viewer, error, refused.retry).await;
994 }979 }
995 if two_factor_enabled(&state.store, &user_id).await? {980 if two_factor_enabled(&state.store, &user_id).await? {
996- if let Some(retry) = second_factor_blocked(state, &user_id) {981+ if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
997- let error = Some(t(lang, Key::ErrThrottled).into());982+ let error = Some(refused.message.into());
998- return settings_export::respond_delete(cx, viewer, error, Some(retry)).await;983+ return settings_export::respond_delete(cx, viewer, error, refused.retry).await;
999- }
1000- let key = throttle::two_factor_key(&user_id);
1001- if !verify_second_factor(&state.store, &state.key, &user_id, &form.code).await? {
1002- state.throttle.record_failure(&key, Instant::now());
1003- let error = Some(t(lang, Key::ErrWrongCode).into());
1004- return settings_export::respond_delete(cx, viewer, error, None).await;
1005 }984 }
1006- state.throttle.clear(&key);
1007 }985 }
1008 let ghost = state.store.ensure_ghost_user().await?;986 let ghost = state.store.ensure_ghost_user().await?;
1009 match state.store.delete_user(&user_id, &ghost.id).await {987 match state.store.delete_user(&user_id, &ghost.id).await {
@@ -1051,18 +1029,11 @@ async fn two_factor_recovery(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl
1051 shown.throttled = refused.retry;1029 shown.throttled = refused.retry;
1052 return respond(cx, viewer, shown).await;1030 return respond(cx, viewer, shown).await;
1053 }1031 }
1054- if let Some(retry) = second_factor_blocked(state, &user_id) {1032+ if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
1055- shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into());1033+ shown.two_factor_error = Some(refused.message.into());
1056- shown.throttled = Some(retry);1034+ shown.throttled = refused.retry;
1057- return respond(cx, viewer, shown).await;
1058- }
1059- let key = throttle::two_factor_key(&user_id);
1060- if !verify_second_factor(&state.store, &state.key, &user_id, &form.code).await? {
1061- state.throttle.record_failure(&key, Instant::now());
1062- shown.two_factor_error = Some(t(lang, Key::ErrWrongCode).into());
1063 return respond(cx, viewer, shown).await;1035 return respond(cx, viewer, shown).await;
1064 }1036 }
1065- state.throttle.clear(&key);
1066 let (codes, hashes) = new_recovery_codes();1037 let (codes, hashes) = new_recovery_codes();
1067 state1038 state
1068 .store1039 .store
@@ -1291,7 +1262,7 @@ mod tests {
1291 )1262 )
1292 .await;1263 .await;
1293 assert!(1264 assert!(
1294- reply.body.contains("at least 10 characters"),1265+ reply.body.contains("at least 12 characters"),
1295 "short password"1266 "short password"
1296 );1267 );
1297 let mismatch = format!(1268 let mismatch = format!(
@@ -1586,9 +1557,8 @@ mod tests {
1586 &wrong,1557 &wrong,
1587 )1558 )
1588 .await;1559 .await;
1589- if reply.status == 200 && !reply.body.contains("Recovery codes") {1560+ assert_eq!(reply.status, 200);
1590- assert!(reply.body.contains("That code is not right"), "wrong code");1561+ assert!(reply.body.contains("That code is not right"), "wrong code");
1591- }
1592 let state = fx1562 let state = fx
1593 .state1563 .state
1594 .store1564 .store
@@ -1596,9 +1566,8 @@ mod tests {
1596 .await1566 .await
1597 .unwrap()1567 .unwrap()
1598 .unwrap();1568 .unwrap();
1599- if !state.enabled {1569+ assert!(!state.enabled, "wrong code does not enable");
1600- assert!(state.sealed_secret.is_some(), "wrong code keeps the secret");1570+ assert!(state.sealed_secret.is_some(), "wrong code keeps the secret");
1601- }
1602 1571
1603 // An over-long device name is refused before the code is checked, so the code is1572 // An over-long device name is refused before the code is checked, so the code is
1604 // not spent on it.1573 // not spent on it.
crates/forge-web-account/src/pages/settings_tokens.rsmodified+4 -13
@@ -13,17 +13,17 @@ use topcoat::context::{Cx, context};
13 use topcoat::router::content::Form;13 use topcoat::router::content::Form;
14 use topcoat::router::error::{SeeOther, see_other};14 use topcoat::router::error::{SeeOther, see_other};
15 use topcoat::router::response::response_headers;15 use topcoat::router::response::response_headers;
16-use topcoat::router::{page, query_params, route};16+use topcoat::router::{page, route};
17 use topcoat::view::{View, component, view};17 use topcoat::view::{View, component, view};
18 18
19 use crate::api::packages::PACKAGES_SCOPE;19 use crate::api::packages::PACKAGES_SCOPE;
20 use crate::audit::{self, Actor, Target};20 use crate::audit::{self, Actor, Target};
21-use crate::auth::{require_csrf, require_user};21+use crate::auth::require_csrf;
22 use crate::i18n::packages::{self as pk, K as PK};22 use crate::i18n::packages::{self as pk, K as PK};
23 use crate::i18n::releases_ci::{self as rc, K as RC};23 use crate::i18n::releases_ci::{self as rc, K as RC};
24 use crate::i18n::s;24 use crate::i18n::s;
25 use crate::i18n::{self, Key, Lang, t, token_name_length};25 use crate::i18n::{self, Key, Lang, t, token_name_length};
26-use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view};26+use crate::pages::settings_keys::{KeyKind, KeysDraft, kind_page, keys_page_view};
27 use crate::state::AppState;27 use crate::state::AppState;
28 use crate::views::parts::confirm_act;28 use crate::views::parts::confirm_act;
29 use crate::views::{alert, rel_time, rel_time_or_never};29 use crate::views::{alert, rel_time, rel_time_or_never};
@@ -132,16 +132,7 @@ pub(crate) async fn tokens_section(
132 132
133 #[page("/settings/tokens")]133 #[page("/settings/tokens")]
134 async fn tokens_page(cx: &Cx) -> Result<impl View> {134 async fn tokens_page(cx: &Cx) -> Result<impl View> {
135- let viewer = require_user(cx).await?;135+ kind_page(cx, KeyKind::Tokens).await
136- let lang = i18n::lang(cx, Some(&viewer.0));
137- let state = context::<AppState>(cx);
138- let draft = KeysDraft {
139- add: query_params::<AddQuery>(cx)?.add.is_some(),
140- ..KeysDraft::default()
141- };
142- Ok(view! {
143- keys_page_view(lang: lang, state: state, viewer: &viewer, kind: KeyKind::Tokens, draft: draft)
144- })
145 }136 }
146 137
147 #[page(POST "/settings/tokens")]138 #[page(POST "/settings/tokens")]
crates/forge-web-account/src/pages/setup.rsmodified+9 -7
@@ -99,8 +99,9 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View>
99 }99 }
100 100
101 let lang = i18n::lang(cx, None);101 let lang = i18n::lang(cx, None);
102- let problem = match validate_username(&form.username) {102+ let checked = validate_username(&form.username);
103- Err(e) => user_facing_message(&e),103+ let problem = match &checked {
104+ Err(e) => user_facing_message(e),
104 Ok(_) if form.password.chars().count() < MIN_PASSWORD_CHARS => {105 Ok(_) if form.password.chars().count() < MIN_PASSWORD_CHARS => {
105 Some(password_too_short(lang, MIN_PASSWORD_CHARS))106 Some(password_too_short(lang, MIN_PASSWORD_CHARS))
106 }107 }
@@ -118,7 +119,7 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View>
118 });119 });
119 }120 }
120 121
121- let (username, _) = validate_username(&form.username)?;122+ let (username, _) = checked?;
122 let email = form.email.trim();123 let email = form.email.trim();
123 let email = (!email.is_empty()).then_some(email);124 let email = (!email.is_empty()).then_some(email);
124 let hash = hash_password_async(form.password.clone()).await?;125 let hash = hash_password_async(form.password.clone()).await?;
@@ -130,10 +131,6 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View>
130 else {131 else {
131 return Err(not_found().into());132 return Err(not_found().into());
132 };133 };
133- if let Some(address) = email {
134- // The first admin confirms the address like anyone else. Nothing waits on the mail.
135- crate::mail::account::send_verify(state, &user, address).await?;
136- }
137 audit::record(134 audit::record(
138 &state.store,135 &state.store,
139 Some(cx),136 Some(cx),
@@ -149,6 +146,11 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View>
149 .await;146 .await;
150 login(cx, &user).await?;147 login(cx, &user).await?;
151 clear_pre_csrf(cx);148 clear_pre_csrf(cx);
149+ if let Some(address) = email {
150+ if let Err(e) = crate::mail::account::send_verify(state, &user, address).await {
151+ tracing::warn!(error = %e, "could not queue the address check");
152+ }
153+ }
152 Err(see_other("/").into())154 Err(see_other("/").into())
153 }155 }
154 156
crates/forge-web-account/src/pages/shell_events.rsmodified+27 -3
@@ -38,13 +38,37 @@ async fn shell_events(cx: &Cx) -> Result<Response> {
38 .map(|(user, session)| (user.id.clone(), session.id.clone()));38 .map(|(user, session)| (user.id.clone(), session.id.clone()));
39 let mut parts: Vec<BoxStream<'static, Result<Event>>> =39 let mut parts: Vec<BoxStream<'static, Result<Event>>> =
40 vec![alive_stream(state.clone(), ids).await?];40 vec![alive_stream(state.clone(), ids).await?];
41- if let Some((user, _)) = viewer {41+ if let Some((user, session)) = viewer {
42- parts.push(unread_changes(&state, &user.id).await?.boxed());42+ let unread = unread_changes(&state, &user.id).await?.boxed();
43- parts.push(activity_changes(state.clone(), user.clone(), "activity").boxed());43+ let activity = activity_changes(state.clone(), user.clone(), "activity").boxed();
44+ parts.push(while_signed_in(&state, &user.id, &session.id, unread));
45+ parts.push(while_signed_in(&state, &user.id, &session.id, activity));
44 }46 }
45 events_response(cx, stream::select_all(parts))47 events_response(cx, stream::select_all(parts))
46 }48 }
47 49
50+fn while_signed_in(
51+ state: &AppState,
52+ user_id: &str,
53+ session_id: &str,
54+ part: BoxStream<'static, Result<Event>>,
55+) -> BoxStream<'static, Result<Event>> {
56+ let (state, user_id, session_id) = (state.clone(), user_id.to_owned(), session_id.to_owned());
57+ part.take_while(move |_| {
58+ let (state, user_id, session_id) = (state.clone(), user_id.clone(), session_id.clone());
59+ async move { session_open(&state, &user_id, &session_id).await }
60+ })
61+ .boxed()
62+}
63+
64+async fn session_open(state: &AppState, user_id: &str, session_id: &str) -> bool {
65+ state
66+ .store
67+ .list_sessions(user_id)
68+ .await
69+ .is_ok_and(|sessions| sessions.iter().any(|session| session.id == session_id))
70+}
71+
48 #[cfg(test)]72 #[cfg(test)]
49 mod tests {73 mod tests {
50 use topcoat::router::request::Request;74 use topcoat::router::request::Request;
crates/forge-web-account/src/pages/snippets.rsmodified+48 -130
@@ -1,9 +1,3 @@
1-//! Pages for snippets: `/snippets` (list), `/snippets/new`, `/snippets/{id}` (view),
2-//! `/snippets/{id}/edit`, `/snippets/{id}/revisions` and `POST /snippets/{id}/delete`.
3-//! Visibility decides who may read: a private snippet answers 404 to everyone but its owner.
4-//! Only the owner edits or deletes, and every save and delete is audited. Files are served on the
5-//! user-content origin (see `snippet_raw.rs`), and the page links to them.
6-
7 use std::collections::HashMap;1 use std::collections::HashMap;
8 2
9 use forge_core::store::snippets::{3 use forge_core::store::snippets::{
@@ -32,22 +26,17 @@ use crate::views::{alert, empty_state, rel_time, shell, user_facing_message};
32 26
33 path_param!(id);27 path_param!(id);
34 28
35-/// What the form shows for one file slot.
36 struct Slot {29 struct Slot {
37 number: usize,30 number: usize,
38 name: String,31 name: String,
39 content: String,32 content: String,
40 }33 }
41 34
42-/// The editable state of a snippet, as typed or as saved.
43 #[derive(Clone, Default)]35 #[derive(Clone, Default)]
44 struct Draft {36 struct Draft {
45 title: String,37 title: String,
46 description: String,38 description: String,
47 visibility: String,39 visibility: String,
48- /// Each file with the number of its form fields (`name_<n>`, `content_<n>`). The number stays
49- /// with the file when another is added or removed: the browser restores typed text by field
50- /// name, so a renumbered card would get the wrong text back.
51 files: Vec<(usize, SnippetFile)>,40 files: Vec<(usize, SnippetFile)>,
52 }41 }
53 42
@@ -68,8 +57,6 @@ impl Draft {
68 }57 }
69 }58 }
70 59
71- /// Reads the form. Every card the page rendered is kept, blank ones too, so "Add file" never
72- /// takes a card away; blank cards are dropped only when saving (see `saved_files`).
73 fn from_form(form: &HashMap<String, String>) -> Self {60 fn from_form(form: &HashMap<String, String>) -> Self {
74 let field = |key: String| form.get(&key).cloned().unwrap_or_default();61 let field = |key: String| form.get(&key).cloned().unwrap_or_default();
75 let mut files = Vec::new();62 let mut files = Vec::new();
@@ -89,7 +76,6 @@ impl Draft {
89 }76 }
90 }77 }
91 78
92- /// The files to save: cards with neither a name nor contents are dropped.
93 fn saved_files(&self) -> Vec<SnippetFile> {79 fn saved_files(&self) -> Vec<SnippetFile> {
94 self.files80 self.files
95 .iter()81 .iter()
@@ -99,17 +85,14 @@ impl Draft {
99 .collect()85 .collect()
100 }86 }
101 87
102- /// Drops the card whose fields are `number`. Other cards keep their numbers.
103 fn remove(&mut self, number: usize) {88 fn remove(&mut self, number: usize) {
104 self.files.retain(|(n, _)| *n != number);89 self.files.retain(|(n, _)| *n != number);
105 }90 }
106 91
107- /// The position of the file whose fields are `number`, if there is one.
108 fn position(&self, number: usize) -> Option<usize> {92 fn position(&self, number: usize) -> Option<usize> {
109 self.files.iter().position(|(n, _)| *n == number)93 self.files.iter().position(|(n, _)| *n == number)
110 }94 }
111 95
112- /// Adds an empty card under the lowest free field number, unless the snippet is full.
113 fn add_blank(&mut self) {96 fn add_blank(&mut self) {
114 if self.files.len() >= MAX_FILES {97 if self.files.len() >= MAX_FILES {
115 return;98 return;
@@ -124,7 +107,6 @@ impl Draft {
124 }107 }
125 }108 }
126 109
127- /// The cards to render: one per file, or one empty card for a new snippet.
128 fn slots(&self) -> Vec<Slot> {110 fn slots(&self) -> Vec<Slot> {
129 if self.files.is_empty() {111 if self.files.is_empty() {
130 return vec![Slot {112 return vec![Slot {
@@ -136,7 +118,6 @@ impl Draft {
136 self.files118 self.files
137 .iter()119 .iter()
138 .map(|(number, file)| {120 .map(|(number, file)| {
139- // A browser drops one newline right after <textarea>, so keep a leading one.
140 let content = if file.content.starts_with('\n') {121 let content = if file.content.starts_with('\n') {
141 format!("\n{}", file.content)122 format!("\n{}", file.content)
142 } else {123 } else {
@@ -152,9 +133,6 @@ impl Draft {
152 }133 }
153 }134 }
154 135
155-/// Applies an "Add file" or "Remove file" click to the draft. Returns the tab to show next, or
156-/// None for a save, which leaves the draft as typed. Adding shows the new last file; removing
157-/// shows the file before the removed one.
158 fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option<usize> {136 fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option<usize> {
159 if form.get("op").map(String::as_str) == Some("add") {137 if form.get("op").map(String::as_str) == Some("add") {
160 draft.add_blank();138 draft.add_blank();
@@ -169,7 +147,6 @@ fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option<
169 }147 }
170 }148 }
171 149
172-/// The tab that was checked when a save failed, so the user stays on the file they were editing.
173 fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize {150 fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize {
174 form.get("tab")151 form.get("tab")
175 .and_then(|tab| tab.parse().ok())152 .and_then(|tab| tab.parse().ok())
@@ -177,17 +154,18 @@ fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize {
177 .unwrap_or(0)154 .unwrap_or(0)
178 }155 }
179 156
180-/// One file as the view page shows it. `body` is trusted HTML when `markdown` or `highlighted`157+enum FileBody {
181-/// is set, and plain text otherwise.158+ Markdown(String),
159+ Highlighted(String),
160+ Plain(String),
161+}
162+
182 struct FileView {163 struct FileView {
183 name: String,164 name: String,
184 raw: String,165 raw: String,
185- markdown: bool,166+ body: FileBody,
186- highlighted: bool,
187- body: String,
188 }167 }
189 168
190-/// One revision as the history page shows it.
191 struct RevisionView {169 struct RevisionView {
192 number: usize,170 number: usize,
193 author: String,171 author: String,
@@ -195,18 +173,15 @@ struct RevisionView {
195 file_names: String,173 file_names: String,
196 }174 }
197 175
198-/// One row of the list page and of a profile's Snippets tab.
199 pub(crate) struct ListRow {176 pub(crate) struct ListRow {
200 id: String,177 id: String,
201 title: String,178 title: String,
202 owner: String,179 owner: String,
203 visibility: &'static str,180 visibility: &'static str,
204- /// The file count and the last update, as one line.
205 files: String,181 files: String,
206 updated_at: String,182 updated_at: String,
207 }183 }
208 184
209-/// The list row for a snippet summary, with its strings ready for the view.
210 pub(crate) fn list_row(lang: Lang, summary: SnippetSummary) -> ListRow {185 pub(crate) fn list_row(lang: Lang, summary: SnippetSummary) -> ListRow {
211 ListRow {186 ListRow {
212 id: summary.id,187 id: summary.id,
@@ -233,25 +208,21 @@ fn extension(name: &str) -> String {
233 }208 }
234 209
235 fn file_view(state: &AppState, snippet: &Snippet, file: &SnippetFile) -> FileView {210 fn file_view(state: &AppState, snippet: &Snippet, file: &SnippetFile) -> FileView {
236- let markdown = matches!(extension(&file.name).as_str(), "md" | "markdown");211+ let body = if matches!(extension(&file.name).as_str(), "md" | "markdown") {
237- let (body, highlighted) = if markdown {212+ FileBody::Markdown(render_markdown(&file.content, None))
238- (render_markdown(&file.content, None), false)
239 } else {213 } else {
240 match highlight_lines(&file.name, &file.content) {214 match highlight_lines(&file.name, &file.content) {
241- Some(lines) => (lines.join("\n"), true),215+ Some(lines) => FileBody::Highlighted(lines.join("\n")),
242- None => (file.content.clone(), false),216+ None => FileBody::Plain(file.content.clone()),
243 }217 }
244 };218 };
245 FileView {219 FileView {
246 name: file.name.clone(),220 name: file.name.clone(),
247 raw: snippet_raw_url(state, snippet, &file.name),221 raw: snippet_raw_url(state, snippet, &file.name),
248- markdown,
249- highlighted,
250 body,222 body,
251 }223 }
252 }224 }
253 225
254-/// The snippet if the viewer may read it, else 404.
255 pub(crate) async fn readable(226 pub(crate) async fn readable(
256 cx: &Cx,227 cx: &Cx,
257 viewer_id: Option<&str>,228 viewer_id: Option<&str>,
@@ -264,7 +235,6 @@ pub(crate) async fn readable(
264 }235 }
265 }236 }
266 237
267-/// The snippet if the user owns it, else 404. Edits and deletes go through this check.
268 async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> {238 async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> {
269 let store = &context::<AppState>(cx).store;239 let store = &context::<AppState>(cx).store;
270 match store.get_snippet(snippet_id).await? {240 match store.get_snippet(snippet_id).await? {
@@ -273,7 +243,23 @@ async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> {
273 }243 }
274 }244 }
275 245
276-/// The snippet rows, one linked line each: title, owner, visibility, file count and update time.246+async fn record_snippet(cx: &Cx, user: &User, action: AuditAction, snippet: &Snippet) {
247+ audit::record(
248+ &context::<AppState>(cx).store,
249+ Some(cx),
250+ Actor::User(user),
251+ action,
252+ Target {
253+ kind: "snippet",
254+ id: &snippet.id,
255+ name: &snippet.title,
256+ },
257+ serde_json::Value::Null,
258+ )
259+ .await;
260+ bump_snippet(context::<AppState>(cx), &snippet.id);
261+}
262+
277 #[component]263 #[component]
278 pub(crate) async fn snippet_rows(cx: &Cx, lang: Lang, rows: Vec<ListRow>) -> Result<impl View> {264 pub(crate) async fn snippet_rows(cx: &Cx, lang: Lang, rows: Vec<ListRow>) -> Result<impl View> {
279 Ok(view! {265 Ok(view! {
@@ -312,10 +298,6 @@ async fn snippet_list_body(
312 })298 })
313 }299 }
314 300
315-/// The files card: a tab strip with one tab per file and the "Add file" tab at its end, then one
316-/// panel per file. Every panel stays in the form so all fields submit; CSS shows only the panel
317-/// of the checked tab. A tab is a radio plus a label, so the strip works with JavaScript off.
318-/// The panel's remove button is shown only when there is more than one file.
319 #[component]301 #[component]
320 async fn snippet_files(302 async fn snippet_files(
321 cx: &Cx,303 cx: &Cx,
@@ -387,24 +369,22 @@ async fn snippet_files(
387 })369 })
388 }370 }
389 371
390-/// The new and edit form. Save is the first submit button, so Enter in a field saves; "Add file"
391-/// and the remove buttons submit the same form with `formnovalidate` and never save.
392 #[component]372 #[component]
393 async fn snippet_form(373 async fn snippet_form(
394 cx: &Cx,374 cx: &Cx,
395 lang: Lang,375 lang: Lang,
396 csrf: &str,376 csrf: &str,
397 action: &str,377 action: &str,
398- title: &str,378+ draft: &Draft,
399- description: &str,
400- visibility: &str,
401- slots: Vec<Slot>,
402 active: usize,379 active: usize,
403 error: Option<String>,380 error: Option<String>,
404 ) -> Result<impl View> {381 ) -> Result<impl View> {
405- let public = visibility == "public";382+ let title = draft.title.as_str();
406- let unlisted = visibility == "unlisted";383+ let description = draft.description.as_str();
407- let private = visibility == "private";384+ let public = draft.visibility == "public";
385+ let unlisted = draft.visibility == "unlisted";
386+ let private = draft.visibility == "private";
387+ let slots = draft.slots();
408 let removable = slots.len() > 1;388 let removable = slots.len() > 1;
409 let can_add = slots.len() < MAX_FILES;389 let can_add = slots.len() < MAX_FILES;
410 let counter = g::files_limit(390 let counter = g::files_limit(
@@ -480,7 +460,7 @@ async fn snippet_body(
480 }460 }
481 )461 )
482 if is_owner {462 if is_owner {
483- crate::pages::profile::own_profile_tabs(lang: lang, username: owner.to_owned(), current: "snippets".to_owned())463+ crate::pages::profile::own_profile_tabs(lang: lang, username: owner.to_owned(), current: crate::pages::profile::Tab::Snippets)
484 }464 }
485 <div class="sheet" data-live=(live.as_deref())>465 <div class="sheet" data-live=(live.as_deref())>
486 <section class="sec">466 <section class="sec">
@@ -488,8 +468,6 @@ async fn snippet_body(
488 <p>(description)</p>468 <p>(description)</p>
489 }469 }
490 <p class="hint">(g::updated_before(lang)) rel_time(lang: lang, stamp: updated_at) (g::updated_after(lang))</p>470 <p class="hint">(g::updated_before(lang)) rel_time(lang: lang, stamp: updated_at) (g::updated_after(lang))</p>
491- if !is_owner {
492- }
493 </section>471 </section>
494 for file in files.into_iter() {472 for file in files.into_iter() {
495 <section class="sec snippet-file">473 <section class="sec snippet-file">
@@ -497,12 +475,12 @@ async fn snippet_body(
497 <strong>(file.name.clone())</strong>475 <strong>(file.name.clone())</strong>
498 <a class="act" href=(file.raw.clone())>(g::t(lang, K::Raw))</a>476 <a class="act" href=(file.raw.clone())>(g::t(lang, K::Raw))</a>
499 </div>477 </div>
500- if file.markdown {478+ if let FileBody::Markdown(html) = &file.body {
501- <div class="markdown-body">(Unescaped::new_unchecked(file.body.clone()))</div>479+ <div class="markdown-body">(Unescaped::new_unchecked(html.clone()))</div>
502- } else if file.highlighted {480+ } else if let FileBody::Highlighted(html) = &file.body {
503- <pre class="code snippet-code"><code>(Unescaped::new_unchecked(file.body.clone()))</code></pre>481+ <pre class="code snippet-code"><code>(Unescaped::new_unchecked(html.clone()))</code></pre>
504- } else {482+ } else if let FileBody::Plain(text) = &file.body {
505- <pre class="code snippet-code"><code>(file.body.clone())</code></pre>483+ <pre class="code snippet-code"><code>(text.clone())</code></pre>
506 }484 }
507 </section>485 </section>
508 }486 }
@@ -527,7 +505,7 @@ async fn revisions_body(
527 <a class="button" href=(back)>(g::t(lang, K::BackToSnippet))</a>505 <a class="button" href=(back)>(g::t(lang, K::BackToSnippet))</a>
528 )506 )
529 if let Some(owner) = owner_tabs {507 if let Some(owner) = owner_tabs {
530- crate::pages::profile::own_profile_tabs(lang: lang, username: owner, current: "snippets".to_owned())508+ crate::pages::profile::own_profile_tabs(lang: lang, username: owner, current: crate::pages::profile::Tab::Snippets)
531 }509 }
532 <div class="sheet" data-live=(live.as_deref())>510 <div class="sheet" data-live=(live.as_deref())>
533 if revisions.is_empty() {511 if revisions.is_empty() {
@@ -556,19 +534,14 @@ async fn snippet_form_page(
556 active: usize,534 active: usize,
557 ) -> Result<impl View> {535 ) -> Result<impl View> {
558 let csrf = viewer.1.csrf_token.clone();536 let csrf = viewer.1.csrf_token.clone();
559- let slots = draft.slots();
560- let title = draft.title.clone();
561- let description = draft.description.clone();
562- let visibility = draft.visibility.clone();
563 let tab_user = viewer.0.username.clone();537 let tab_user = viewer.0.username.clone();
564 Ok(view! {538 Ok(view! {
565 shell(title: heading, viewer: Some(viewer),539 shell(title: heading, viewer: Some(viewer),
566 head(title: heading)540 head(title: heading)
567- crate::pages::profile::own_profile_tabs(lang: lang, username: tab_user, current: "snippets".to_owned())541+ crate::pages::profile::own_profile_tabs(lang: lang, username: tab_user, current: crate::pages::profile::Tab::Snippets)
568 <div class="sheet">542 <div class="sheet">
569 snippet_form(lang: lang, csrf: csrf.as_str(), action: action,543 snippet_form(lang: lang, csrf: csrf.as_str(), action: action,
570- title: title.as_str(), description: description.as_str(),544+ draft: &draft, active: active, error: error)
571- visibility: visibility.as_str(), slots: slots, active: active, error: error)
572 </div>545 </div>
573 )546 )
574 })547 })
@@ -634,20 +607,7 @@ async fn snippet_create(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
634 };607 };
635 match saved {608 match saved {
636 Ok(snippet) => {609 Ok(snippet) => {
637- audit::record(610+ record_snippet(cx, &user, AuditAction::SnippetCreated, &snippet).await;
638- store,
639- Some(cx),
640- Actor::User(&user),
641- AuditAction::SnippetCreated,
642- Target {
643- kind: "snippet",
644- id: &snippet.id,
645- name: &snippet.title,
646- },
647- serde_json::Value::Null,
648- )
649- .await;
650- bump_snippet(context::<AppState>(cx), &snippet.id);
651 return Err(see_other(format!("/snippets/{}", snippet.id)).into());611 return Err(see_other(format!("/snippets/{}", snippet.id)).into());
652 }612 }
653 Err(message) => error = Some(message),613 Err(message) => error = Some(message),
@@ -737,20 +697,7 @@ async fn snippet_update(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
737 };697 };
738 match saved {698 match saved {
739 Ok(snippet) => {699 Ok(snippet) => {
740- audit::record(700+ record_snippet(cx, &user, AuditAction::SnippetUpdated, &snippet).await;
741- store,
742- Some(cx),
743- Actor::User(&user),
744- AuditAction::SnippetUpdated,
745- Target {
746- kind: "snippet",
747- id: &snippet.id,
748- name: &snippet.title,
749- },
750- serde_json::Value::Null,
751- )
752- .await;
753- bump_snippet(context::<AppState>(cx), &snippet.id);
754 return Err(see_other(format!("/snippets/{}", snippet.id)).into());701 return Err(see_other(format!("/snippets/{}", snippet.id)).into());
755 }702 }
756 Err(message) => error = Some(message),703 Err(message) => error = Some(message),
@@ -774,7 +721,6 @@ async fn snippet_revisions(cx: &Cx) -> Result<impl View> {
774 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));721 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));
775 let store = &context::<AppState>(cx).store;722 let store = &context::<AppState>(cx).store;
776 let revisions: Vec<SnippetRevision> = store.list_snippet_revisions(&snippet.id).await?;723 let revisions: Vec<SnippetRevision> = store.list_snippet_revisions(&snippet.id).await?;
777- // Stored oldest first; the page shows the newest first with its number.
778 let rows: Vec<RevisionView> = revisions724 let rows: Vec<RevisionView> = revisions
779 .into_iter()725 .into_iter()
780 .enumerate()726 .enumerate()
@@ -807,20 +753,7 @@ async fn snippet_delete(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
807 let snippet = owned(cx, &user, &snippet_id).await?;753 let snippet = owned(cx, &user, &snippet_id).await?;
808 let store = &context::<AppState>(cx).store;754 let store = &context::<AppState>(cx).store;
809 if store.delete_snippet(&user.id, &snippet.id).await? {755 if store.delete_snippet(&user.id, &snippet.id).await? {
810- audit::record(756+ record_snippet(cx, &user, AuditAction::SnippetDeleted, &snippet).await;
811- store,
812- Some(cx),
813- Actor::User(&user),
814- AuditAction::SnippetDeleted,
815- Target {
816- kind: "snippet",
817- id: &snippet.id,
818- name: &snippet.title,
819- },
820- serde_json::Value::Null,
821- )
822- .await;
823- bump_snippet(context::<AppState>(cx), &snippet.id);
824 }757 }
825 Ok(see_other("/snippets"))758 Ok(see_other("/snippets"))
826 }759 }
@@ -836,11 +769,8 @@ mod tests {
836 .collect()769 .collect()
837 }770 }
838 771
839- /// Saving drops blank cards but editing keeps them, and a leading newline survives the
840- /// textarea.
841 #[test]772 #[test]
842 fn draft_saves_drop_blank_cards_and_keep_leading_newlines() {773 fn draft_saves_drop_blank_cards_and_keep_leading_newlines() {
843- // Case: every rendered card is kept while editing; a save drops the blank ones.
844 let draft = Draft::from_form(&form(&[774 let draft = Draft::from_form(&form(&[
845 ("title", "t"),775 ("title", "t"),
846 ("visibility", "public"),776 ("visibility", "public"),
@@ -864,7 +794,6 @@ mod tests {
864 );794 );
865 assert_eq!(saved[1].name, "b.rs", "blank cards: the kept file");795 assert_eq!(saved[1].name, "b.rs", "blank cards: the kept file");
866 796
867- // Case: a leading newline in a file survives the textarea.
868 let mut draft = Draft::blank();797 let mut draft = Draft::blank();
869 draft.files = vec![(798 draft.files = vec![(
870 0,799 0,
@@ -876,11 +805,8 @@ mod tests {
876 assert_eq!(draft.slots()[0].content, "\n\nx", "leading newline");805 assert_eq!(draft.slots()[0].content, "\n\nx", "leading newline");
877 }806 }
878 807
879- /// The card steps: a new form shows one card, add and remove move the cards, the shown tab
880- /// follows the step, and a save or a failed save keeps the posted tab.
881 #[test]808 #[test]
882 fn card_steps_add_remove_and_show_the_right_tab() {809 fn card_steps_add_remove_and_show_the_right_tab() {
883- // Case: a new form shows one empty card.
884 let draft = Draft::blank();810 let draft = Draft::blank();
885 let slots = draft.slots();811 let slots = draft.slots();
886 assert_eq!(slots.len(), 1, "new form: one card");812 assert_eq!(slots.len(), 1, "new form: one card");
@@ -890,7 +816,6 @@ mod tests {
890 "new form: the card is empty"816 "new form: the card is empty"
891 );817 );
892 818
893- // Case: add appends a card until the snippet is full.
894 let mut draft = Draft::blank();819 let mut draft = Draft::blank();
895 for _ in 0..MAX_FILES + 3 {820 for _ in 0..MAX_FILES + 3 {
896 draft.add_blank();821 draft.add_blank();
@@ -903,7 +828,6 @@ mod tests {
903 "add: numbers run from zero"828 "add: numbers run from zero"
904 );829 );
905 830
906- // Case: removing a card keeps the other field numbers.
907 let mut draft = Draft::blank();831 let mut draft = Draft::blank();
908 draft.add_blank();832 draft.add_blank();
909 draft.add_blank();833 draft.add_blank();
@@ -918,7 +842,6 @@ mod tests {
918 "remove: the other card's name"842 "remove: the other card's name"
919 );843 );
920 844
921- // Case: add and remove clicks are told apart from a save.
922 let add = form(&[("op", "add"), ("name_0", "a")]);845 let add = form(&[("op", "add"), ("name_0", "a")]);
923 let mut draft = Draft::from_form(&add);846 let mut draft = Draft::from_form(&add);
924 assert_eq!(apply_slot_step(&mut draft, &add), Some(1), "add click: tab");847 assert_eq!(apply_slot_step(&mut draft, &add), Some(1), "add click: tab");
@@ -937,7 +860,6 @@ mod tests {
937 "save: not a card step"860 "save: not a card step"
938 );861 );
939 862
940- // Case: add shows the new last file.
941 let mut draft = Draft::blank();863 let mut draft = Draft::blank();
942 let add = form(&[("op", "add"), ("name_0", "a")]);864 let add = form(&[("op", "add"), ("name_0", "a")]);
943 assert_eq!(865 assert_eq!(
@@ -952,19 +874,16 @@ mod tests {
952 );874 );
953 assert_eq!(draft.slots().len(), 2, "add shows: two cards");875 assert_eq!(draft.slots().len(), 2, "add shows: two cards");
954 876
955- // Case: removing a card shows the file before it, and the first one when it is first.
956 let mut draft = Draft::blank();877 let mut draft = Draft::blank();
957 for _ in 0..3 {878 for _ in 0..3 {
958 draft.add_blank();879 draft.add_blank();
959 }880 }
960- // Files 0..=2 at positions 0..=2; removing the file at position 2 shows position 1.
961 let remove = form(&[("remove", "2")]);881 let remove = form(&[("remove", "2")]);
962 assert_eq!(882 assert_eq!(
963 apply_slot_step(&mut draft, &remove),883 apply_slot_step(&mut draft, &remove),
964 Some(1),884 Some(1),
965 "remove shows: before"885 "remove shows: before"
966 );886 );
967- // Removing the first file shows the new first one.
968 let remove = form(&[("remove", "0")]);887 let remove = form(&[("remove", "0")]);
969 assert_eq!(888 assert_eq!(
970 apply_slot_step(&mut draft, &remove),889 apply_slot_step(&mut draft, &remove),
@@ -972,7 +891,6 @@ mod tests {
972 "remove shows: first"891 "remove shows: first"
973 );892 );
974 893
975- // Case: a failed save keeps the posted tab, and falls back to the first.
976 let mut draft = Draft::blank();894 let mut draft = Draft::blank();
977 for _ in 0..3 {895 for _ in 0..3 {
978 draft.add_blank();896 draft.add_blank();
crates/forge-web-app/src/api/releases.rsmodified+1 -1
@@ -264,7 +264,7 @@ async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result<Response> {
264 .and_then(|value| value.to_str().ok())264 .and_then(|value| value.to_str().ok())
265 .map(str::to_owned);265 .map(str::to_owned);
266 let max_bytes = state266 let max_bytes = state
267- .config267+ .live()
268 .releases268 .releases
269 .max_asset_mb269 .max_asset_mb
270 .saturating_mul(1024 * 1024);270 .saturating_mul(1024 * 1024);
crates/forge-web-app/src/live.rsmodified+10 -0
@@ -388,6 +388,16 @@ pub fn changed_event(status: String) -> Result<Event> {
388 Ok(Event::new().event("changed").data(status))388 Ok(Event::new().event("changed").data(status))
389 }389 }
390 390
391+pub fn wake_stream(
392+ wake: watch::Receiver<u64>,
393+ status: &'static str,
394+) -> impl Stream<Item = Result<Event>> + Send + 'static {
395+ stream::unfold(wake, move |mut wake| async move {
396+ wake.changed().await.ok()?;
397+ Some((changed_event(status.to_owned()), wake))
398+ })
399+}
400+
391 /// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event401 /// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event
392 /// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when402 /// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when
393 /// the status differs from the last one sent. The stream ends after the terminal status is sent,403 /// the status differs from the last one sent. The stream ends after the terminal status is sent,
crates/forge-web-app/src/package_ops.rsmodified+6 -0
@@ -43,6 +43,12 @@ impl From<Error> for PackageError {
43 }43 }
44 }44 }
45 45
46+impl From<PackageError> for Error {
47+ fn from(e: PackageError) -> Self {
48+ Self::Database(format!("{e:?}"))
49+ }
50+}
51+
46 /// The user or org a registry path names. `None` when no such account exists.52 /// The user or org a registry path names. `None` when no such account exists.
47 pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> {53 pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> {
48 Ok(state.store.user_by_username(name).await?)54 Ok(state.store.user_by_username(name).await?)
crates/forge-web-app/src/views/mod.rsmodified+11 -0
@@ -1121,6 +1121,17 @@ pub async fn alert(cx: &Cx, message: &str) -> Result<impl View> {
1121 })1121 })
1122 }1122 }
1123 1123
1124+#[component]
1125+pub async fn notice_line(cx: &Cx, text: &str, is_error: bool) -> Result<impl View> {
1126+ Ok(view! {
1127+ if is_error {
1128+ alert(message: text)
1129+ } else {
1130+ <p class="state" role="status">(text)</p>
1131+ }
1132+ })
1133+}
1134+
1124 /// What a list shows when it has nothing yet: one line saying so, an optional hint, and an optional1135 /// What a list shows when it has nothing yet: one line saying so, an optional hint, and an optional
1125 /// next step as the child (a button, a link, or a command to copy). Pages use it so every empty list1136 /// next step as the child (a button, a link, or a command to copy). Pages use it so every empty list
1126 /// reads the same way.1137 /// reads the same way.
crates/forge-web-base/src/i18n/merge_queue.rsmodified+8 -0
@@ -32,6 +32,8 @@ pub enum K {
32 ReasonPermission,32 ReasonPermission,
33 ReasonBlocked,33 ReasonBlocked,
34 ReasonNoBranch,34 ReasonNoBranch,
35+ ReasonDraft,
36+ ReasonHeadMissing,
35 ErrQueueRequired,37 ErrQueueRequired,
36 ErrQueueAlready,38 ErrQueueAlready,
37 }39 }
@@ -66,6 +68,8 @@ pub const ALL: &[K] = &[
66 K::ReasonPermission,68 K::ReasonPermission,
67 K::ReasonBlocked,69 K::ReasonBlocked,
68 K::ReasonNoBranch,70 K::ReasonNoBranch,
71+ K::ReasonDraft,
72+ K::ReasonHeadMissing,
69 K::ErrQueueRequired,73 K::ErrQueueRequired,
70 K::ErrQueueAlready,74 K::ErrQueueAlready,
71 ];75 ];
@@ -128,6 +132,10 @@ pub fn t(lang: Lang, key: K) -> &'static str {
128 (ReasonBlocked, Tr) => "bir birleştirme denetimi artık geçmiyor",132 (ReasonBlocked, Tr) => "bir birleştirme denetimi artık geçmiyor",
129 (ReasonNoBranch, En) => "the branch is gone",133 (ReasonNoBranch, En) => "the branch is gone",
130 (ReasonNoBranch, Tr) => "dal artık yok",134 (ReasonNoBranch, Tr) => "dal artık yok",
135+ (ReasonDraft, En) => "it is a draft",
136+ (ReasonDraft, Tr) => "taslak",
137+ (ReasonHeadMissing, En) => "the source branch is gone",
138+ (ReasonHeadMissing, Tr) => "kaynak dal artık yok",
131 (ErrQueueRequired, En) => {139 (ErrQueueRequired, En) => {
132 "This branch requires the merge queue. Add the pull request to the queue instead."140 "This branch requires the merge queue. Add the pull request to the queue instead."
133 }141 }
crates/forge-web-pages/src/pages/admin_runners.rsmodified+32 -87
@@ -11,6 +11,7 @@ use forge_ci::proto::RunnerSample;
11 use forge_core::AuditAction;11 use forge_core::AuditAction;
12 use forge_core::ci::{12 use forge_core::ci::{
13 CiRunner, FieldKind, JobState, RUNNER_FIELDS, RestartMode, RunnerJob, runner_field,13 CiRunner, FieldKind, JobState, RUNNER_FIELDS, RestartMode, RunnerJob, runner_field,
14+ validate_runner_field,
14 };15 };
15 use forge_core::store::health::runner_is_online;16 use forge_core::store::health::runner_is_online;
16 use serde::Deserialize;17 use serde::Deserialize;
@@ -31,7 +32,7 @@ use crate::ci::metrics_chart::{self, Bucket};
31 use crate::ci::runner_log::Line;32 use crate::ci::runner_log::Line;
32 use crate::i18n::admin::{self as g, K};33 use crate::i18n::admin::{self as g, K};
33 use crate::i18n::releases_ci as rc;34 use crate::i18n::releases_ci as rc;
34-use crate::i18n::{self, Key, Lang};35+use crate::i18n::{self, Key, Lang, s};
35 use crate::live::events_response;36 use crate::live::events_response;
36 use crate::pages::admin_users::admin_only;37 use crate::pages::admin_users::admin_only;
37 use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text};38 use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text};
@@ -54,14 +55,6 @@ struct RunnersQuery {
54 notice: Option<String>,55 notice: Option<String>,
55 }56 }
56 57
57-/// Picks the English or Turkish text. The runner page strings live here, not in `i18n::admin`.
58-fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
59- match lang {
60- Lang::En => en,
61- Lang::Tr => tr,
62- }
63-}
64-
65 /// Extra notice words: (word, English, Turkish, is an error).58 /// Extra notice words: (word, English, Turkish, is an error).
66 const EXTRA_NOTICES: [(&str, &str, &str, bool); 8] = [59 const EXTRA_NOTICES: [(&str, &str, &str, bool); 8] = [
67 ("saved", "Saved.", "Kaydedildi.", false),60 ("saved", "Saved.", "Kaydedildi.", false),
@@ -460,15 +453,19 @@ async fn load_meter(cx: &Cx, lang: Lang, running: u32, max: u32) -> Result<impl
460 let running_text = running.to_string();453 let running_text = running.to_string();
461 let meter_max = max.max(1).to_string();454 let meter_max = max.max(1).to_string();
462 let use_pips = (1..=PIP_MAX).contains(&max);455 let use_pips = (1..=PIP_MAX).contains(&max);
463- let pips: Vec<&'static str> = (0..max)456+ let pips: Vec<&'static str> = if use_pips {
464- .map(|slot| {457+ (0..max)
465- if slot < running {458+ .map(|slot| {
466- "runner-pip is-on"459+ if slot < running {
467- } else {460+ "runner-pip is-on"
468- "runner-pip"461+ } else {
469- }462+ "runner-pip"
470- })463+ }
471- .collect();464+ })
465+ .collect()
466+ } else {
467+ Vec::new()
468+ };
472 let pips_label = match lang {469 let pips_label = match lang {
473 Lang::En => format!("{running} of {max} jobs running"),470 Lang::En => format!("{running} of {max} jobs running"),
474 Lang::Tr => format!("{running}/{max} iş çalışıyor"),471 Lang::Tr => format!("{running}/{max} iş çalışıyor"),
@@ -696,7 +693,6 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> {
696 .clone()693 .clone()
697 .or_else(|| overridden.clone())694 .or_else(|| overridden.clone())
698 .or_else(|| reported.cloned());695 .or_else(|| reported.cloned());
699- // Restart fields wait for a start; a live concurrency waits for the next check-in.
700 let pending = match (&overridden, field.kind) {696 let pending = match (&overridden, field.kind) {
701 (Some(want), FieldKind::Restart) => reported != Some(want),697 (Some(want), FieldKind::Restart) => reported != Some(want),
702 (Some(want), FieldKind::Live) if field.key == "concurrency" => {698 (Some(want), FieldKind::Live) if field.key == "concurrency" => {
@@ -722,10 +718,6 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> {
722 .collect()718 .collect()
723 }719 }
724 720
725-fn sel(on: bool) -> Option<&'static str> {
726- on.then_some("selected")
727-}
728-
729 /// The detail page tabs: slug and the config keys on it. `overview`, `jobs`, `identity` and `logs`721 /// The detail page tabs: slug and the config keys on it. `overview`, `jobs`, `identity` and `logs`
730 /// are read-only.722 /// are read-only.
731 const TABS: [(&str, &[&str]); 8] = [723 const TABS: [(&str, &[&str]); 8] = [
@@ -942,7 +934,6 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField>
942 options: if choices.is_empty() {934 options: if choices.is_empty() {
943 Vec::new()935 Vec::new()
944 } else {936 } else {
945- // An unreported field gets a blank first option, so saving the tab leaves it alone.
946 std::iter::once(("", s(lang, "(from runner.toml)", "(runner.toml'dan)")))937 std::iter::once(("", s(lang, "(from runner.toml)", "(runner.toml'dan)")))
947 .filter(|_| f.value.is_empty())938 .filter(|_| f.value.is_empty())
948 .chain(choices)939 .chain(choices)
@@ -1096,10 +1087,9 @@ async fn runner_job_rows(
1096 let (running, finished): (Vec<&RunnerJob>, Vec<&RunnerJob>) = jobs1087 let (running, finished): (Vec<&RunnerJob>, Vec<&RunnerJob>) = jobs
1097 .iter()1088 .iter()
1098 .partition(|job| job.job.state == JobState::Running);1089 .partition(|job| job.job.state == JobState::Running);
1099- let to_row = |job: &RunnerJob| runner_job_row(lang, job);
1100 Ok((1090 Ok((
1101- running.into_iter().map(to_row).collect(),1091+ running.into_iter().map(|job| runner_job_row(lang, job)).collect(),
1102- finished.into_iter().map(to_row).collect(),1092+ finished.into_iter().map(|job| runner_job_row(lang, job)).collect(),
1103 ))1093 ))
1104 }1094 }
1105 1095
@@ -1175,26 +1165,6 @@ fn n(value: f64) -> String {
1175 format!("{value:.1}")1165 format!("{value:.1}")
1176 }1166 }
1177 1167
1178-fn cpu_of(b: &Bucket) -> f64 {
1179- b.cpu
1180-}
1181-
1182-fn mem_of(b: &Bucket) -> f64 {
1183- b.mem_used
1184-}
1185-
1186-fn disk_of(b: &Bucket) -> f64 {
1187- b.disk_used
1188-}
1189-
1190-fn rx_of(b: &Bucket) -> f64 {
1191- b.rx
1192-}
1193-
1194-fn tx_of(b: &Bucket) -> f64 {
1195- b.tx
1196-}
1197-
1198 /// A rate in bytes per second as `80 KiB/s`, one decimal below ten units.1168 /// A rate in bytes per second as `80 KiB/s`, one decimal below ten units.
1199 fn rate_text(bytes: f64) -> String {1169 fn rate_text(bytes: f64) -> String {
1200 const KIB: f64 = 1024.0;1170 const KIB: f64 = 1024.0;
@@ -1350,7 +1320,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
1350 let cpu = mx_chart(1320 let cpu = mx_chart(
1351 &points,1321 &points,
1352 100.0,1322 100.0,
1353- &[(cpu_of, "mx-line")],1323+ &[(|b: &Bucket| b.cpu, "mx-line")],
1354 true,1324 true,
1355 &|v| format!("{v:.0}%"),1325 &|v| format!("{v:.0}%"),
1356 &|b| {1326 &|b| {
@@ -1366,7 +1336,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
1366 let mem = mx_chart(1336 let mem = mx_chart(
1367 &points,1337 &points,
1368 mem_total,1338 mem_total,
1369- &[(mem_of, "mx-line")],1339+ &[(|b: &Bucket| b.mem_used, "mx-line")],
1370 false,1340 false,
1371 &|v| bytes_text(v as u64),1341 &|v| bytes_text(v as u64),
1372 &|b| vec![memory_text(lang, b.mem_used, b.mem_total)],1342 &|b| vec![memory_text(lang, b.mem_used, b.mem_total)],
@@ -1377,7 +1347,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
1377 let disk = mx_chart(1347 let disk = mx_chart(
1378 &points,1348 &points,
1379 disk_total,1349 disk_total,
1380- &[(disk_of, "mx-line")],1350+ &[(|b: &Bucket| b.disk_used, "mx-line")],
1381 false,1351 false,
1382 &|v| bytes_text(v as u64),1352 &|v| bytes_text(v as u64),
1383 &|b| vec![storage_text(lang, b.disk_used, b.disk_total)],1353 &|b| vec![storage_text(lang, b.disk_used, b.disk_total)],
@@ -1388,7 +1358,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
1388 let net = mx_chart(1358 let net = mx_chart(
1389 &points,1359 &points,
1390 net_top,1360 net_top,
1391- &[(rx_of, "mx-line"), (tx_of, "mx-line mx-line-sent")],1361+ &[(|b: &Bucket| b.rx, "mx-line"), (|b: &Bucket| b.tx, "mx-line mx-line-sent")],
1392 false,1362 false,
1393 &rate_text,1363 &rate_text,
1394 &|b| {1364 &|b| {
@@ -1423,11 +1393,6 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
1423 }1393 }
1424 }1394 }
1425 1395
1426-/// `aria-current` for the open tab of the detail page's tab row.
1427-fn current(on: bool) -> Option<&'static str> {
1428- on.then_some("page")
1429-}
1430-
1431 #[component]1396 #[component]
1432 async fn runner_detail_view(1397 async fn runner_detail_view(
1433 cx: &Cx,1398 cx: &Cx,
@@ -1487,8 +1452,6 @@ async fn runner_detail_view(
1487 let jobs_href = format!("{}?tab=jobs", row.detail_href);1452 let jobs_href = format!("{}?tab=jobs", row.detail_href);
1488 let save_action = format!("{}/settings", row.detail_href);1453 let save_action = format!("{}/settings", row.detail_href);
1489 let reset_action = row.config_action.clone();1454 let reset_action = row.config_action.clone();
1490- // The facts under each graph's caption. Memory's total is in its caption once a sample exists,
1491- // so the memory facts name the total only when there is none.
1492 let cpu_facts = format!("{cpus} {}", s(lang, "CPUs", "CPU"));1455 let cpu_facts = format!("{cpus} {}", s(lang, "CPUs", "CPU"));
1493 let budget_facts = format!(1456 let budget_facts = format!(
1494 "{} {budget_text} · {} {reserved_text} · {} {free_text}",1457 "{} {budget_text} · {} {reserved_text} · {} {free_text}",
@@ -1502,7 +1465,6 @@ async fn runner_detail_view(
1502 budget_facts1465 budget_facts
1503 };1466 };
1504 let facts = [cpu_facts, mem_facts, String::new(), String::new()];1467 let facts = [cpu_facts, mem_facts, String::new(), String::new()];
1505- // A runner that has reported nothing has no figures to show, only the note below.
1506 let has_host = !metrics.empty || runner.reported.cpus.is_some();1468 let has_host = !metrics.empty || runner.reported.cpus.is_some();
1507 Ok(view! {1469 Ok(view! {
1508 head(title: runner.name.as_str(), sub: sub, live: Some("/admin/runners/events"),1470 head(title: runner.name.as_str(), sub: sub, live: Some("/admin/runners/events"),
@@ -1523,7 +1485,7 @@ async fn runner_detail_view(
1523 }1485 }
1524 <nav class="tabs" aria-label=(s(lang, "Configuration", "Yapılandırma"))>1486 <nav class="tabs" aria-label=(s(lang, "Configuration", "Yapılandırma"))>
1525 for (slug, _) in TABS.iter() {1487 for (slug, _) in TABS.iter() {
1526- <a href=(format!("{}?tab={}", row.detail_href, slug)) aria-current=(current(*slug == tab))>(tab_label(lang, slug))</a>1488+ <a href=(format!("{}?tab={}", row.detail_href, slug)) aria-current=((*slug == tab).then_some("page"))>(tab_label(lang, slug))</a>
1527 }1489 }
1528 </nav>1490 </nav>
1529 <div class="sheet">1491 <div class="sheet">
@@ -1637,7 +1599,7 @@ async fn runner_detail_view(
1637 if f.input == "select" {1599 if f.input == "select" {
1638 <select id=(format!("rf-{}", f.key)) name=(f.key)>1600 <select id=(format!("rf-{}", f.key)) name=(f.key)>
1639 for (value, text, on) in f.options.iter() {1601 for (value, text, on) in f.options.iter() {
1640- <option value=(*value) selected=(sel(*on))>(*text)</option>1602+ <option value=(*value) selected=((*on).then_some("selected"))>(*text)</option>
1641 }1603 }
1642 </select>1604 </select>
1643 } else if f.input == "number" {1605 } else if f.input == "number" {
@@ -1765,8 +1727,7 @@ async fn runner_save_settings(
1765 return Ok(back_to_list("missing"));1727 return Ok(back_to_list("missing"));
1766 };1728 };
1767 let current = field_rows(&runner);1729 let current = field_rows(&runner);
1768- let mut saved_live = false;1730+ let mut changes = Vec::new();
1769- let mut saved_restart = false;
1770 for key in tab_keys(tab) {1731 for key in tab_keys(tab) {
1771 let (Some(field), Some(posted), Some(now)) = (1732 let (Some(field), Some(posted), Some(now)) = (
1772 runner_field(key),1733 runner_field(key),
@@ -1778,6 +1739,14 @@ async fn runner_save_settings(
1778 if field.kind == FieldKind::ReadOnly || posted.trim() == now.value {1739 if field.kind == FieldKind::ReadOnly || posted.trim() == now.value {
1779 continue;1740 continue;
1780 }1741 }
1742+ if validate_runner_field(field.key, posted).is_err() {
1743+ return Ok(back("invalid"));
1744+ }
1745+ changes.push((field, posted));
1746+ }
1747+ let mut saved_live = false;
1748+ let mut saved_restart = false;
1749+ for (field, posted) in changes {
1781 match state1750 match state
1782 .store1751 .store
1783 .set_runner_field(id, field.key, Some(posted.as_str()))1752 .set_runner_field(id, field.key, Some(posted.as_str()))
@@ -1971,7 +1940,6 @@ async fn runner_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<SeeOth
1971 Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")),1940 Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")),
1972 Err(e) => return Err(e.into()),1941 Err(e) => return Err(e.into()),
1973 }1942 }
1974- // Wakes a runner that is waiting on a claim, and the live runners pages.
1975 state.ci_waker.notify_waiters();1943 state.ci_waker.notify_waiters();
1976 state.ci_live.bump_runners();1944 state.ci_live.bump_runners();
1977 tracing::info!(actor_id = %viewer.0.id, runner_id = %id, mode = mode.as_str(), "ci runner restart requested");1945 tracing::info!(actor_id = %viewer.0.id, runner_id = %id, mode = mode.as_str(), "ci runner restart requested");
@@ -2110,13 +2078,11 @@ mod tests {
2110 assert!(body.contains("event: go\ndata: /admin/runners"), "{body}");2078 assert!(body.contains("event: go\ndata: /admin/runners"), "{body}");
2111 }2079 }
2112 2080
2113- // Scenario: the page gates, the one-time token, and labels as chips with a state badge.
2114 #[tokio::test]2081 #[tokio::test]
2115 async fn gates_token_once_and_labels_render_as_chips() {2082 async fn gates_token_once_and_labels_render_as_chips() {
2116 let dir = tempfile::tempdir().expect("tempdir");2083 let dir = tempfile::tempdir().expect("tempdir");
2117 let (store, router) = fixture(dir.path()).await;2084 let (store, router) = fixture(dir.path()).await;
2118 2085
2119- // Anonymous and non-admin users get 404 on every runner route.
2120 let (anon, _) = send(&router, "GET", "/admin/runners", None, None).await;2086 let (anon, _) = send(&router, "GET", "/admin/runners", None, None).await;
2121 assert_eq!(anon, 404, "anonymous gets 404 here, not a login redirect");2087 assert_eq!(anon, 404, "anonymous gets 404 here, not a login redirect");
2122 let (user, _) = send(&router, "GET", "/admin/runners", Some(USER_TOKEN), None).await;2088 let (user, _) = send(&router, "GET", "/admin/runners", Some(USER_TOKEN), None).await;
@@ -2140,7 +2106,6 @@ mod tests {
2140 .await;2106 .await;
2141 assert_eq!(del, 404);2107 assert_eq!(del, 404);
2142 2108
2143- // An admin post without a valid CSRF token is forbidden and changes nothing.
2144 let (tok, _) = send(2109 let (tok, _) = send(
2145 &router,2110 &router,
2146 "POST",2111 "POST",
@@ -2170,7 +2135,6 @@ mod tests {
2170 assert_eq!(dis, 403);2135 assert_eq!(dis, 403);
2171 assert!(store.list_runners().await.expect("list").is_empty());2136 assert!(store.list_runners().await.expect("list").is_empty());
2172 2137
2173- // The token is shown once, in the box and in the command, and never in the list.
2174 let (status, created) = send(2138 let (status, created) = send(
2175 &router,2139 &router,
2176 "POST",2140 "POST",
@@ -2192,12 +2156,9 @@ mod tests {
2192 "token in the box and the command"2156 "token in the box and the command"
2193 );2157 );
2194 let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;2158 let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await;
2195- // The empty list shows the register command with a placeholder, never the token.
2196 assert!(!list.contains(&token), "the list never shows the token");2159 assert!(!list.contains(&token), "the list never shows the token");
2197- // Only the hash is stored, so the list and the database hold no plain token.
2198 assert!(store.list_runners().await.expect("list").is_empty());2160 assert!(store.list_runners().await.expect("list").is_empty());
2199 2161
2200- // Labels are one plain line joined by " · ", and the dot follows disabling.
2201 store2162 store
2202 .register_runner(2163 .register_runner(
2203 &token,2164 &token,
@@ -2210,7 +2171,6 @@ mod tests {
2210 assert_eq!(status, 200);2171 assert_eq!(status, 200);
2211 assert!(page.contains(r#"<span class="runner-labels">linux · x86_64</span>"#));2172 assert!(page.contains(r#"<span class="runner-labels">linux · x86_64</span>"#));
2212 assert!(!page.contains("linux, x86_64"), "labels are not joined");2173 assert!(!page.contains("linux, x86_64"), "labels are not joined");
2213- // Never seen, so offline; not disabled, so no disabled word.
2214 assert!(page.contains(r#"class="runner-dot is-offline""#));2174 assert!(page.contains(r#"class="runner-dot is-offline""#));
2215 assert!(!page.contains(r#"<span class="val">idle · disabled</span>"#));2175 assert!(!page.contains(r#"<span class="val">idle · disabled</span>"#));
2216 2176
@@ -2224,7 +2184,6 @@ mod tests {
2224 assert!(page.contains(r#"<span class="val">idle</span>"#));2184 assert!(page.contains(r#"<span class="val">idle</span>"#));
2225 }2185 }
2226 2186
2227- // Scenario: restart is capability-gated and audited, then the runner is disabled, enabled and deleted.
2228 #[tokio::test]2187 #[tokio::test]
2229 async fn restart_then_disable_and_delete_follow_one_runner() {2188 async fn restart_then_disable_and_delete_follow_one_runner() {
2230 let dir = tempfile::tempdir().expect("tempdir");2189 let dir = tempfile::tempdir().expect("tempdir");
@@ -2232,7 +2191,6 @@ mod tests {
2232 let runner = one_runner(&store, &router).await;2191 let runner = one_runner(&store, &router).await;
2233 let restart = format!("/admin/runners/{}/restart", runner.id);2192 let restart = format!("/admin/runners/{}/restart", runner.id);
2234 2193
2235- // Not logged in as an admin, or a bad token, changes nothing.
2236 let (status, _) = send(&router, "POST", &restart, Some(USER_TOKEN), csrf_form("")).await;2194 let (status, _) = send(&router, "POST", &restart, Some(USER_TOKEN), csrf_form("")).await;
2237 assert_eq!(status, 404);2195 assert_eq!(status, 404);
2238 let (status, _) = send(2196 let (status, _) = send(
@@ -2245,7 +2203,6 @@ mod tests {
2245 .await;2203 .await;
2246 assert_eq!(status, 403);2204 assert_eq!(status, 403);
2247 2205
2248- // A runner that never advertised the capability: the button is off and the post refused.
2249 let runner_page = format!("/admin/runners/{}", runner.id);2206 let runner_page = format!("/admin/runners/{}", runner.id);
2250 let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await;2207 let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await;
2251 assert!(list.contains("Runner too old, update it first"), "{list}");2208 assert!(list.contains("Runner too old, update it first"), "{list}");
@@ -2260,7 +2217,6 @@ mod tests {
2260 assert_eq!(status, 303);2217 assert_eq!(status, 303);
2261 assert_eq!(store.runner_restart(&runner.id).await.unwrap(), None);2218 assert_eq!(store.runner_restart(&runner.id).await.unwrap(), None);
2262 2219
2263- // With the capability the page offers both choices, and the post is stored and audited.
2264 store2220 store
2265 .record_runner_report(2221 .record_runner_report(
2266 &runner.id,2222 &runner.id,
@@ -2301,7 +2257,6 @@ mod tests {
2301 && e.data.contains("drain"))2257 && e.data.contains("drain"))
2302 );2258 );
2303 2259
2304- // The runner comes back with a new boot id and the pending state goes away.
2305 store2260 store
2306 .record_runner_report(2261 .record_runner_report(
2307 &runner.id,2262 &runner.id,
@@ -2315,7 +2270,6 @@ mod tests {
2315 let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await;2270 let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await;
2316 assert!(!list.contains("restart pending"));2271 assert!(!list.contains("restart pending"));
2317 2272
2318- // Disable, then enable again.
2319 let disable = format!("/admin/runners/{}/disabled", runner.id);2273 let disable = format!("/admin/runners/{}/disabled", runner.id);
2320 let (status, _) = send(2274 let (status, _) = send(
2321 &router,2275 &router,
@@ -2337,7 +2291,6 @@ mod tests {
2337 .await;2291 .await;
2338 assert!(!store.list_runners().await.expect("list")[0].disabled);2292 assert!(!store.list_runners().await.expect("list")[0].disabled);
2339 2293
2340- // Delete it, then a second delete reports that the id is gone.
2341 let delete = format!("/admin/runners/{}/delete", runner.id);2294 let delete = format!("/admin/runners/{}/delete", runner.id);
2342 let (status, _) = send(&router, "POST", &delete, Some(ADMIN_TOKEN), csrf_form("")).await;2295 let (status, _) = send(&router, "POST", &delete, Some(ADMIN_TOKEN), csrf_form("")).await;
2343 assert_eq!(status, 303);2296 assert_eq!(status, 303);
@@ -2354,8 +2307,6 @@ mod tests {
2354 assert!(page.contains("No runner has that id"));2307 assert!(page.contains("No runner has that id"));
2355 }2308 }
2356 2309
2357- // Scenario: settings save per tab and per field, concurrency and config reset, and every
2358- // config, settings, events and detail route is admin only.
2359 #[tokio::test]2310 #[tokio::test]
2360 async fn settings_save_per_field_reset_and_stay_admin_only() {2311 async fn settings_save_per_field_reset_and_stay_admin_only() {
2361 let dir = tempfile::tempdir().expect("tempdir");2312 let dir = tempfile::tempdir().expect("tempdir");
@@ -2365,7 +2316,6 @@ mod tests {
2365 let settings = format!("/admin/runners/{}/settings", runner.id);2316 let settings = format!("/admin/runners/{}/settings", runner.id);
2366 let detail_uri = format!("/admin/runners/{}", runner.id);2317 let detail_uri = format!("/admin/runners/{}", runner.id);
2367 2318
2368- // Non-admins get 404 on every route, and a bad CSRF token is forbidden.
2369 let (status, _) = send(2319 let (status, _) = send(
2370 &router,2320 &router,
2371 "POST",2321 "POST",
@@ -2409,7 +2359,6 @@ mod tests {
2409 .await;2359 .await;
2410 assert_eq!(status, 404);2360 assert_eq!(status, 404);
2411 2361
2412- // One post saves the changed fields of a tab; blank fields stay unset.
2413 let (status, _) = send(2362 let (status, _) = send(
2414 &router,2363 &router,
2415 "POST",2364 "POST",
@@ -2441,7 +2390,6 @@ mod tests {
2441 );2390 );
2442 assert!(page.contains("Reset to runner.toml"));2391 assert!(page.contains("Reset to runner.toml"));
2443 2392
2444- // Concurrency: set it, show it in the list and the detail page, and refuse bad values.
2445 let (status, _) = send(2393 let (status, _) = send(
2446 &router,2394 &router,
2447 "POST",2395 "POST",
@@ -2467,7 +2415,6 @@ mod tests {
2467 assert!(list.contains("Reset to runner.toml"));2415 assert!(list.contains("Reset to runner.toml"));
2468 assert!(list.contains(r#"data-live="/admin/runners/events""#));2416 assert!(list.contains(r#"data-live="/admin/runners/events""#));
2469 2417
2470- // Out of range, wrong kind of field and a read-only field change nothing.
2471 for form in [2418 for form in [
2472 "&key=concurrency&value=65",2419 "&key=concurrency&value=65",
2473 "&key=concurrency&value=0",2420 "&key=concurrency&value=0",
@@ -2484,7 +2431,6 @@ mod tests {
2484 Some(3)2431 Some(3)
2485 );2432 );
2486 2433
2487- // A config field saved from the detail page shows there, live.
2488 let (status, _) = send(2434 let (status, _) = send(
2489 &router,2435 &router,
2490 "POST",2436 "POST",
@@ -2506,7 +2452,6 @@ mod tests {
2506 assert!(detail.contains("Concurrency"));2452 assert!(detail.contains("Concurrency"));
2507 assert!(detail.contains(r#"data-live="/admin/runners/events""#));2453 assert!(detail.contains(r#"data-live="/admin/runners/events""#));
2508 2454
2509- // Reset both overrides; the runner goes back to its runner.toml values.
2510 let (_, _) = send(2455 let (_, _) = send(
2511 &router,2456 &router,
2512 "POST",2457 "POST",
crates/forge-web-pages/src/pages/admin_users.rsmodified+29 -31
@@ -166,6 +166,19 @@ impl UserRow {
166 }166 }
167 }167 }
168 168
169+#[component]
170+async fn row_body(cx: &Cx, lang: Lang, row: &UserRow) -> Result<impl View> {
171+ Ok(view! {
172+ <span class="name">(row.username.as_str())</span>
173+ <span class="val">
174+ if !row.email.is_empty() {
175+ (row.email.as_str()) " · "
176+ }
177+ (row.role.as_str()) " · " rel_time(lang: lang, stamp: row.created_at.as_str())
178+ </span>
179+ })
180+}
181+
169 #[component]182 #[component]
170 async fn users_view(183 async fn users_view(
171 cx: &Cx,184 cx: &Cx,
@@ -262,23 +275,11 @@ async fn users_view(
262 for row in rows.into_iter() {275 for row in rows.into_iter() {
263 if row.linkable {276 if row.linkable {
264 <a class="line" href=(row.href.as_str()) data-kb-row="">277 <a class="line" href=(row.href.as_str()) data-kb-row="">
265- <span class="name">(row.username.as_str())</span>278+ row_body(lang: lang, row: &row)
266- <span class="val">
267- if !row.email.is_empty() {
268- (row.email.as_str()) " · "
269- }
270- (row.role.as_str()) " · " rel_time(lang: lang, stamp: row.created_at.as_str())
271- </span>
272 </a>279 </a>
273 } else {280 } else {
274 <div class="line" data-kb-row="">281 <div class="line" data-kb-row="">
275- <span class="name">(row.username.as_str())</span>282+ row_body(lang: lang, row: &row)
276- <span class="val">
277- if !row.email.is_empty() {
278- (row.email.as_str()) " · "
279- }
280- (row.role.as_str()) " · " rel_time(lang: lang, stamp: row.created_at.as_str())
281- </span>
282 </div>283 </div>
283 }284 }
284 }285 }
@@ -592,21 +593,26 @@ async fn org_delete_note(
592 })593 })
593 }594 }
594 595
595-#[page("/admin/users/{user_id}/delete")]596+async fn delete_target(store: &Store, viewer: &User, target_id: &str) -> Result<User> {
596-async fn user_delete_page(cx: &Cx) -> Result<impl View> {597+ let Some(target) = store.user_by_id(target_id).await? else {
597- let viewer = admin_only(cx).await?;
598- let lang = i18n::lang(cx, Some(&viewer.0));
599- let store = &context::<AppState>(cx).store;
600- let target_id = path_param_segment(cx, "user_id").to_owned();
601- let Some(target) = store.user_by_id(&target_id).await? else {
602 return Err(not_found().into());598 return Err(not_found().into());
603 };599 };
604- if target.id == viewer.0.id {600+ if target.id == viewer.id {
605 return Err(see_other("/settings/security").into());601 return Err(see_other("/settings/security").into());
606 }602 }
607 if is_ghost(&target) {603 if is_ghost(&target) {
608 return Err(not_found().into());604 return Err(not_found().into());
609 }605 }
606+ Ok(target)
607+}
608+
609+#[page("/admin/users/{user_id}/delete")]
610+async fn user_delete_page(cx: &Cx) -> Result<impl View> {
611+ let viewer = admin_only(cx).await?;
612+ let lang = i18n::lang(cx, Some(&viewer.0));
613+ let store = &context::<AppState>(cx).store;
614+ let target_id = path_param_segment(cx, "user_id").to_owned();
615+ let target = delete_target(store, &viewer.0, &target_id).await?;
610 let (repos, outcome) = review_target(store, &target, lang).await?;616 let (repos, outcome) = review_target(store, &target, lang).await?;
611 let (impact, refusal) = match outcome {617 let (impact, refusal) = match outcome {
612 Ok(impact) => (Some(impact), None),618 Ok(impact) => (Some(impact), None),
@@ -637,15 +643,7 @@ async fn user_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View>
637 let lang = i18n::lang(cx, Some(&viewer.0));643 let lang = i18n::lang(cx, Some(&viewer.0));
638 let store = &context::<AppState>(cx).store;644 let store = &context::<AppState>(cx).store;
639 let target_id = path_param_segment(cx, "user_id").to_owned();645 let target_id = path_param_segment(cx, "user_id").to_owned();
640- let Some(target) = store.user_by_id(&target_id).await? else {646+ let target = delete_target(store, &viewer.0, &target_id).await?;
641- return Err(not_found().into());
642- };
643- if target.id == viewer.0.id {
644- return Err(see_other("/settings/security").into());
645- }
646- if is_ghost(&target) {
647- return Err(not_found().into());
648- }
649 if target.is_org() {647 if target.is_org() {
650 // The note with its links is on the GET page: send the browser there.648 // The note with its links is on the GET page: send the browser there.
651 return Err(see_other(&format!("/admin/users/{}/delete", enc(&target.id))).into());649 return Err(see_other(&format!("/admin/users/{}/delete", enc(&target.id))).into());
crates/forge-web-pages/src/pages/ci_job.rsmodified+22 -23
@@ -25,7 +25,6 @@ use topcoat::Result;
25 use topcoat::context::{Cx, context};25 use topcoat::context::{Cx, context};
26 use topcoat::router::content::sse::{Event, last_event_id};26 use topcoat::router::content::sse::{Event, last_event_id};
27 use topcoat::router::error::not_found;27 use topcoat::router::error::not_found;
28-use topcoat::router::request::uri;
29 use topcoat::router::response::Response;28 use topcoat::router::response::Response;
30 use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_param, route};29 use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_param, route};
31 use topcoat::view::{View, component, view};30 use topcoat::view::{View, component, view};
@@ -37,8 +36,8 @@ use crate::i18n::{
37 };36 };
38 use crate::live::{changed_event, events_response};37 use crate::live::{changed_event, events_response};
39 use crate::pages::ci_runs::{38 use crate::pages::ci_runs::{
40- age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href,39+ age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, query_value,
41- state_text,40+ run_href, state_text,
42 };41 };
43 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};42 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
44 use crate::state::AppState;43 use crate::state::AppState;
@@ -644,7 +643,7 @@ async fn job_events(cx: &Cx) -> Result<Response> {
644 let (job, _) = job_of(state, &ctx, &id).await?;643 let (job, _) = job_of(state, &ctx, &id).await?;
645 let offset = last_event_id(cx)644 let offset = last_event_id(cx)
646 .and_then(|id| id.parse::<u64>().ok())645 .and_then(|id| id.parse::<u64>().ok())
647- .or_else(|| from_query(cx))646+ .or_else(|| query_value(cx, "from")?.parse().ok())
648 .unwrap_or(0);647 .unwrap_or(0);
649 // Subscribed before the first read, so a change in between is sent.648 // Subscribed before the first read, so a change in between is sent.
650 let wake = state.ci_live.subscribe_job(&job.id);649 let wake = state.ci_live.subscribe_job(&job.id);
@@ -659,24 +658,13 @@ async fn job_events(cx: &Cx) -> Result<Response> {
659 primed: false,658 primed: false,
660 pending_fingerprint: None,659 pending_fingerprint: None,
661 pending_log: None,660 pending_log: None,
662- plain: uri(cx)661+ plain: query_value(cx, "plain").as_deref() == Some("1"),
663- .query()
664- .is_some_and(|query| query.split('&').any(|pair| pair == "plain=1")),
665 viewer: ctx.viewer.as_ref().map(|(user, _)| user.clone()),662 viewer: ctx.viewer.as_ref().map(|(user, _)| user.clone()),
666 repo_id: ctx.repo.id.clone(),663 repo_id: ctx.repo.id.clone(),
667 };664 };
668 events_response(cx, job_stream(follow))665 events_response(cx, job_stream(follow))
669 }666 }
670 667
671-/// The `from` offset of the events URL, if it is a number.
672-fn from_query(cx: &Cx) -> Option<u64> {
673- uri(cx).query().and_then(|query| {
674- form_urlencoded::parse(query.as_bytes())
675- .find(|(key, _)| key == "from")
676- .and_then(|(_, value)| value.parse::<u64>().ok())
677- })
678-}
679-
680 /// One job's stream state. Each read of the status and the log happens after a wake, and a read that668 /// One job's stream state. Each read of the status and the log happens after a wake, and a read that
681 /// sent log bytes is followed by another read at once, so a long append drains in order.669 /// sent log bytes is followed by another read at once, so a long append drains in order.
682 struct JobFollow {670 struct JobFollow {
@@ -864,14 +852,26 @@ fn artifact_response(
864 let mut res = Response::new(Body::new(StreamBody::new(chunks)));852 let mut res = Response::new(Body::new(StreamBody::new(chunks)));
865 *res.status_mut() = StatusCode::OK;853 *res.status_mut() = StatusCode::OK;
866 let headers = res.headers_mut();854 let headers = res.headers_mut();
867- headers.insert(
868- CONTENT_TYPE,
869- HeaderValue::from_static("application/octet-stream"),
870- );
871 headers.insert(CONTENT_LENGTH, HeaderValue::from(size));855 headers.insert(CONTENT_LENGTH, HeaderValue::from(size));
856+ attachment_headers(
857+ headers,
858+ "application/octet-stream",
859+ &artifact.name,
860+ "private, no-cache",
861+ );
862+ Ok(res)
863+}
864+
865+pub(crate) fn attachment_headers(
866+ headers: &mut http::HeaderMap,
867+ content_type: &'static str,
868+ file_name: &str,
869+ cache: &'static str,
870+) {
871+ headers.insert(CONTENT_TYPE, HeaderValue::from_static(content_type));
872 if let Ok(value) = HeaderValue::from_str(&format!(872 if let Ok(value) = HeaderValue::from_str(&format!(
873 "attachment; filename=\"{}\"",873 "attachment; filename=\"{}\"",
874- attachment_name(&artifact.name)874+ attachment_name(file_name)
875 )) {875 )) {
876 headers.insert(CONTENT_DISPOSITION, value);876 headers.insert(CONTENT_DISPOSITION, value);
877 }877 }
@@ -881,9 +881,8 @@ fn artifact_response(
881 );881 );
882 headers.insert(882 headers.insert(
883 HeaderName::from_static("cache-control"),883 HeaderName::from_static("cache-control"),
884- HeaderValue::from_static("private, no-cache"),884+ HeaderValue::from_static(cache),
885 );885 );
886- Ok(res)
887 }886 }
888 887
889 #[cfg(test)]888 #[cfg(test)]
crates/forge-web-pages/src/pages/ci_runs.rsmodified+12 -52
@@ -29,7 +29,7 @@ use topcoat::router::content::sse::Event;
29 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};29 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
30 use topcoat::router::request::uri;30 use topcoat::router::request::uri;
31 use topcoat::router::response::{IntoResponse, Response};31 use topcoat::router::response::{IntoResponse, Response};
32-use topcoat::router::{HeaderValue, page, path_param, route};32+use topcoat::router::{page, path_param, route};
33 use topcoat::view::{View, component, view};33 use topcoat::view::{View, component, view};
34 34
35 use crate::auth::{current_user, require_csrf};35 use crate::auth::{current_user, require_csrf};
@@ -44,7 +44,7 @@ use crate::live::{Status, changed_event, changed_stream, events_response};
44 use crate::pages::admin_runners::confirm_post;44 use crate::pages::admin_runners::confirm_post;
45 use crate::pages::ci_estimate::{self, Est, Step};45 use crate::pages::ci_estimate::{self, Est, Step};
46 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};46 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};
47-use crate::pages::ci_job::{Tail, log_from, log_tail_of};47+use crate::pages::ci_job::{Tail, attachment_headers, log_from, log_tail_of};
48 use crate::pages::refs::load_refs;48 use crate::pages::refs::load_refs;
49 use crate::pages::repo::repo_head;49 use crate::pages::repo::repo_head;
50 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};50 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
@@ -155,12 +155,8 @@ fn badge_info(state: &AppState, title: &str, default_branch: &str) -> BadgeInfo
155 BadgeInfo { image, snippet }155 BadgeInfo { image, snippet }
156 }156 }
157 157
158-/// The notice from `?notice=<word>`. Anything else is ignored.
159 fn notice_from_query(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> {158 fn notice_from_query(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> {
160- let query = uri(cx).query()?;159+ let word = query_value(cx, "notice")?;
161- let word = form_urlencoded::parse(query.as_bytes())
162- .find(|(key, _)| key == "notice")
163- .map(|(_, value)| value.into_owned())?;
164 NOTICES160 NOTICES
165 .iter()161 .iter()
166 .find(|(name, _, _)| *name == word)162 .find(|(name, _, _)| *name == word)
@@ -173,13 +169,8 @@ fn notice_redirect(href: &str, word: &str) -> SeeOther {
173 169
174 /// The page number from `?page=`. Anything unreadable or out of range is page 1.170 /// The page number from `?page=`. Anything unreadable or out of range is page 1.
175 fn page_from_query(cx: &Cx) -> u32 {171 fn page_from_query(cx: &Cx) -> u32 {
176- uri(cx)172+ query_value(cx, "page")
177- .query()173+ .and_then(|value| value.parse::<u32>().ok())
178- .and_then(|query| {
179- form_urlencoded::parse(query.as_bytes())
180- .find(|(key, _)| key == "page")
181- .and_then(|(_, value)| value.parse::<u32>().ok())
182- })
183 .filter(|page| (1..=MAX_PAGE).contains(page))174 .filter(|page| (1..=MAX_PAGE).contains(page))
184 .unwrap_or(1)175 .unwrap_or(1)
185 }176 }
@@ -1436,7 +1427,6 @@ fn job_steps(
1436 lines1427 lines
1437 }1428 }
1438 1429
1439-/// "test OOM" for a failed run: the first failed job's message, or its name and state.
1440 /// One row's meta line: `#50 · e62e309 · tahinli · ` then the age, then the failure hint if any.1430 /// One row's meta line: `#50 · e62e309 · tahinli · ` then the age, then the failure hint if any.
1441 struct RowMeta {1431 struct RowMeta {
1442 head: String,1432 head: String,
@@ -2131,7 +2121,7 @@ fn step_from_query(cx: &Cx) -> Option<i64> {
2131 }2121 }
2132 2122
2133 /// The value of one query parameter, if the URL has it.2123 /// The value of one query parameter, if the URL has it.
2134-fn query_value(cx: &Cx, key: &str) -> Option<String> {2124+pub(crate) fn query_value(cx: &Cx, key: &str) -> Option<String> {
2135 let query = uri(cx).query()?;2125 let query = uri(cx).query()?;
2136 form_urlencoded::parse(query.as_bytes())2126 form_urlencoded::parse(query.as_bytes())
2137 .find(|(name, _)| name == key)2127 .find(|(name, _)| name == key)
@@ -2213,18 +2203,12 @@ async fn runs_sheet(cx: &Cx, lang: Lang, list: &ListView) -> Result<impl View> {
2213 </svg>2203 </svg>
2214 if let Some(est) = row.est.as_ref() {2204 if let Some(est) = row.est.as_ref() {
2215 <progress class="ci-est" max="100" value=(est.pct.as_str()) data-est="true" data-since=(row.since.as_deref()) data-expected=(est.expected.as_str())></progress>2205 <progress class="ci-est" max="100" value=(est.pct.as_str()) data-est="true" data-since=(row.since.as_deref()) data-expected=(est.expected.as_str())></progress>
2216- <span class="val"><span class="ci-row-meta">(row.meta.head.as_str())<time datetime=(row.meta.at.as_str()) data-rel="true">(row.meta.age.as_str())</time>(row.meta.hint.as_str())</span>
2217- if !row.duration.is_empty() {
2218- " · " <span class="ci-row-dur" data-since=(row.since.as_deref()) data-expected=(est.expected.as_str()) data-left=(est.left.as_str()) data-over=(est.over.as_str()) data-lm=(est.minutes.as_str())>(row.duration.as_str())</span>
2219- }
2220- </span>
2221- } else {
2222- <span class="val"><span class="ci-row-meta">(row.meta.head.as_str())<time datetime=(row.meta.at.as_str()) data-rel="true">(row.meta.age.as_str())</time>(row.meta.hint.as_str())</span>
2223- if !row.duration.is_empty() {
2224- " · " <span class="ci-row-dur" data-since=(row.since.as_deref())>(row.duration.as_str())</span>
2225- }
2226- </span>
2227 }2206 }
2207+ <span class="val"><span class="ci-row-meta">(row.meta.head.as_str())<time datetime=(row.meta.at.as_str()) data-rel="true">(row.meta.age.as_str())</time>(row.meta.hint.as_str())</span>
2208+ if !row.duration.is_empty() {
2209+ " · " <span class="ci-row-dur" data-since=(row.since.as_deref()) data-expected=(row.est.as_ref().map(|est| est.expected.as_str())) data-left=(row.est.as_ref().map(|est| est.left.as_str())) data-over=(row.est.as_ref().map(|est| est.over.as_str())) data-lm=(row.est.as_ref().map(|est| est.minutes.as_str()))>(row.duration.as_str())</span>
2210+ }
2211+ </span>
2228 </a>2212 </a>
2229 if let Some((action, token)) = row.rerun.as_ref() {2213 if let Some((action, token)) = row.rerun.as_ref() {
2230 <form method="post" action=(action.as_str()) class="act-form ci-row-rerun-form" data-kb-rerun="">2214 <form method="post" action=(action.as_str()) class="act-form ci-row-rerun-form" data-kb-rerun="">
@@ -3066,32 +3050,8 @@ async fn run_artifacts_zip(cx: &Cx) -> Result<Response> {
3066 .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))?3050 .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))?
3067 .map_err(forge_core::Error::Io)?;3051 .map_err(forge_core::Error::Io)?;
3068 let mut res = Response::new(topcoat::router::Body::from(zipped));3052 let mut res = Response::new(topcoat::router::Body::from(zipped));
3069- let headers = res.headers_mut();
3070- headers.insert(
3071- http::header::CONTENT_TYPE,
3072- HeaderValue::from_static("application/zip"),
3073- );
3074 let file = format!("{}-run-{}-artifacts.zip", ctx.repo.name, run.number);3053 let file = format!("{}-run-{}-artifacts.zip", ctx.repo.name, run.number);
3075- if let Ok(value) = HeaderValue::from_str(&format!(3054+ attachment_headers(res.headers_mut(), "application/zip", &file, "private, no-cache");
3076- "attachment; filename=\"{}\"",
3077- file.chars()
3078- .map(|c| if c.is_ascii_graphic() && c != '"' && c != '\\' {
3079- c
3080- } else {
3081- '_'
3082- })
3083- .collect::<String>()
3084- )) {
3085- headers.insert(http::header::CONTENT_DISPOSITION, value);
3086- }
3087- headers.insert(
3088- http::header::HeaderName::from_static("x-content-type-options"),
3089- HeaderValue::from_static("nosniff"),
3090- );
3091- headers.insert(
3092- http::header::HeaderName::from_static("cache-control"),
3093- HeaderValue::from_static("private, no-cache"),
3094- );
3095 Ok(res)3055 Ok(res)
3096 }3056 }
3097 3057
crates/forge-web-pages/src/pages/issue_meta.rsmodified+41 -32
@@ -144,16 +144,7 @@ pub fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> {
144 /// sent to log in, a bad token is 403, and a viewer without Triage (or an archived repo) is 403.144 /// sent to log in, a bad token is 403, and a viewer without Triage (or an archived repo) is 403.
145 pub async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<User> {145 pub async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<User> {
146 let (user, _session) = require_csrf(cx, csrf).await?;146 let (user, _session) = require_csrf(cx, csrf).await?;
147- if ctx.repo.archived147+ if !can_triage(ctx) {
148- || authorize(
149- Some(&user),
150- &ctx.repo,
151- ctx.role,
152- ctx.org_role,
153- Action::Triage,
154- )
155- .is_err()
156- {
157 return Err(forbidden().into());148 return Err(forbidden().into());
158 }149 }
159 Ok(user)150 Ok(user)
@@ -208,6 +199,42 @@ pub async fn action_error_at(
208 })199 })
209 }200 }
210 201
202+pub async fn finish_write<T>(
203+ cx: &Cx,
204+ ctx: RepoCtx,
205+ lang: Lang,
206+ back: String,
207+ result: forge_core::Result<T>,
208+) -> Result<impl View> {
209+ match result {
210+ Ok(_) => {
211+ context::<AppState>(cx).live.bump_repo_issues(&ctx.repo.id);
212+ Err(see_other(back).into())
213+ }
214+ Err(e) => {
215+ let message = refusal_message(e)?;
216+ Ok(view! {
217+ shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
218+ action_error_at(lang: lang, message: message, back: back))
219+ })
220+ }
221+ }
222+}
223+
224+async fn save_refused(
225+ cx: &Cx,
226+ ctx: RepoCtx,
227+ lang: Lang,
228+ back: String,
229+ e: forge_core::Error,
230+) -> Result<impl View> {
231+ let message = refusal_message(e)?;
232+ Ok(view! {
233+ shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
234+ action_error_at(lang: lang, message: message, back: back))
235+ })
236+}
237+
211 /// Sets the labels on an item. The form repeats `label` once per label id.238 /// Sets the labels on an item. The form repeats `label` once per label id.
212 #[page(POST "/{owner}/{repo}/issues/{number}/labels")]239 #[page(POST "/{owner}/{repo}/issues/{number}/labels")]
213 async fn issue_labels_save(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {240 async fn issue_labels_save(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
@@ -231,11 +258,7 @@ async fn labels_save(cx: &Cx, kind: ItemKind, fields: Vec<(String, String)>) ->
231 let before = item_labels(state, &item.id).await;258 let before = item_labels(state, &item.id).await;
232 let result = state.store.set_issue_labels(&item.id, &user.id, &ids).await;259 let result = state.store.set_issue_labels(&item.id, &user.id, &ids).await;
233 if let Err(e) = result {260 if let Err(e) = result {
234- let message = refusal_message(e)?;261+ return save_refused(cx, ctx, lang, back, e).await;
235- return Ok(view! {
236- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
237- action_error_at(lang: lang, message: message, back: back))
238- });
239 }262 }
240 bump_live(state, &ctx.repo.id, &item, kind);263 bump_live(state, &ctx.repo.id, &item, kind);
241 let after = item_labels(state, &item.id).await;264 let after = item_labels(state, &item.id).await;
@@ -279,11 +302,7 @@ async fn assignees_save(
279 .set_issue_assignees(&item.id, &user.id, &usernames)302 .set_issue_assignees(&item.id, &user.id, &usernames)
280 .await;303 .await;
281 if let Err(e) = result {304 if let Err(e) = result {
282- let message = refusal_message(e)?;305+ return save_refused(cx, ctx, lang, back, e).await;
283- return Ok(view! {
284- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
285- action_error_at(lang: lang, message: message, back: back))
286- });
287 }306 }
288 bump_live(state, &ctx.repo.id, &item, kind);307 bump_live(state, &ctx.repo.id, &item, kind);
289 let after = assignee_names(state, &item.id).await;308 let after = assignee_names(state, &item.id).await;
@@ -345,13 +364,7 @@ async fn lock_save(cx: &Cx, kind: ItemKind, fields: Vec<(String, String)>) -> Re
345 .await;364 .await;
346 let changed = match result {365 let changed = match result {
347 Ok(changed) => changed,366 Ok(changed) => changed,
348- Err(e) => {367+ Err(e) => return save_refused(cx, ctx, lang, back, e).await,
349- let message = refusal_message(e)?;
350- return Ok(view! {
351- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
352- action_error_at(lang: lang, message: message, back: back))
353- });
354- }
355 };368 };
356 if changed {369 if changed {
357 bump_live(state, &ctx.repo.id, &item, kind);370 bump_live(state, &ctx.repo.id, &item, kind);
@@ -396,11 +409,7 @@ async fn milestone_save(
396 .set_issue_milestone(&item.id, &user.id, milestone)409 .set_issue_milestone(&item.id, &user.id, milestone)
397 .await;410 .await;
398 if let Err(e) = result {411 if let Err(e) = result {
399- let message = refusal_message(e)?;412+ return save_refused(cx, ctx, lang, back, e).await;
400- return Ok(view! {
401- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
402- action_error_at(lang: lang, message: message, back: back))
403- });
404 }413 }
405 let after = match milestone {414 let after = match milestone {
406 Some(id) => milestone_title(state, &ctx.repo.id, id).await,415 Some(id) => milestone_title(state, &ctx.repo.id, id).await,
crates/forge-web-pages/src/pages/issue_parts.rsmodified+8 -4
@@ -52,6 +52,13 @@ impl ItemKind {
52 ItemKind::Pull => "pulls",52 ItemKind::Pull => "pulls",
53 }53 }
54 }54 }
55+
56+ pub fn anchor(self, number: i64) -> String {
57+ match self {
58+ ItemKind::Issue => format!("issue-{number}"),
59+ ItemKind::Pull => format!("pull-{number}"),
60+ }
61+ }
55 }62 }
56 63
57 64
@@ -752,10 +759,7 @@ pub async fn load_discussion(
752 } else {759 } else {
753 item.body.as_str()760 item.body.as_str()
754 };761 };
755- let body_anchor = match kind {762+ let body_anchor = kind.anchor(number);
756- ItemKind::Issue => format!("issue-{number}"),
757- ItemKind::Pull => format!("pull-{number}"),
758- };
759 let opened = When::new(lang, &item.created_at, &tz, now);763 let opened = When::new(lang, &item.created_at, &tz, now);
760 let body_edits = state.store.edit_count(EditTarget::Issue, &[item.id.as_str()]).await?;764 let body_edits = state.store.edit_count(EditTarget::Issue, &[item.id.as_str()]).await?;
761 let body_history = body_edits765 let body_history = body_edits
crates/forge-web-pages/src/pages/issues_list.rsmodified+23 -18
@@ -29,7 +29,7 @@ use crate::templates::{self, Template};
29 use crate::views::parts::{RailItem, SubPart, rail};29 use crate::views::parts::{RailItem, SubPart, rail};
30 use crate::views::{30 use crate::views::{
31 alert, avatar_url_unknown, csrf_field, enc, iso_time, now_unix, relative_time, repo_href,31 alert, avatar_url_unknown, csrf_field, enc, iso_time, now_unix, relative_time, repo_href,
32- shell, user_facing_message, user_link,32+ shell, stamp_unix, user_facing_message, user_link,
33 };33 };
34 use crate::webhooks::emit::{Sender, emit_issue};34 use crate::webhooks::emit::{Sender, emit_issue};
35 35
@@ -238,12 +238,6 @@ pub fn list_href(base: &str, params: &[(&str, &str)]) -> String {
238 }238 }
239 }239 }
240 240
241-/// Unix seconds of a stored RFC 3339 stamp. An unreadable stamp gives 0.
242-pub fn stamp_unix(stamp: &str) -> i64 {
243- time::OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339)
244- .map_or(0, |t| t.unix_timestamp())
245-}
246-
247 pub struct AssigneeView {241 pub struct AssigneeView {
248 pub name: String,242 pub name: String,
249 pub avatar: String,243 pub avatar: String,
@@ -879,6 +873,22 @@ async fn new_issue_page(cx: &Cx) -> Result<impl View> {
879 })873 })
880 }874 }
881 875
876+async fn set_picked_labels(
877+ state: &AppState,
878+ repo_id: &str,
879+ issue_id: &str,
880+ actor_id: &str,
881+ picked: &[String],
882+) -> forge_core::Result<()> {
883+ let repo_labels = state.store.list_labels(repo_id).await?;
884+ let ids: Vec<String> = repo_labels
885+ .iter()
886+ .filter(|l| picked.contains(&l.id))
887+ .map(|l| l.id.clone())
888+ .collect();
889+ state.store.set_issue_labels(issue_id, actor_id, &ids).await
890+}
891+
882 #[page(POST "/{owner}/{repo}/issues/new")]892 #[page(POST "/{owner}/{repo}/issues/new")]
883 async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {893 async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
884 let owner = owner(cx);894 let owner = owner(cx);
@@ -900,17 +910,12 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
900 .store910 .store
901 .create_issue(&ctx.repo.id, &viewer.0.id, &title, &typed_body)911 .create_issue(&ctx.repo.id, &viewer.0.id, &title, &typed_body)
902 .await?;912 .await?;
903- if can_triage(&ctx) && !picked.is_empty() {913+ if can_triage(&ctx)
904- let repo_labels = state.store.list_labels(&ctx.repo.id).await?;914+ && !picked.is_empty()
905- let ids: Vec<String> = repo_labels915+ && let Err(e) = set_picked_labels(state, &ctx.repo.id, &issue.id, &viewer.0.id, &picked)
906- .iter()916+ .await
907- .filter(|l| picked.contains(&l.id))917+ {
908- .map(|l| l.id.clone())918+ tracing::error!(error = %e, issue_id = %issue.id, "new issue: labels not set");
909- .collect();
910- state
911- .store
912- .set_issue_labels(&issue.id, &viewer.0.id, &ids)
913- .await?;
914 }919 }
915 state.live.bump_issue(&ctx.repo.id, &issue.id);920 state.live.bump_issue(&ctx.repo.id, &issue.id);
916 // The author's contribution calendar counts the issue.921 // The author's contribution calendar counts the issue.
crates/forge-web-pages/src/pages/notifications.rsmodified+86 -101
@@ -158,6 +158,23 @@ impl Entry {
158 }158 }
159 }159 }
160 160
161+fn item_class(unread: bool) -> &'static str {
162+ if unread {
163+ "notif-row unread"
164+ } else {
165+ "notif-row"
166+ }
167+}
168+
169+fn times(lang: Lang, updated_at: &str, tz: &str, now: i64) -> (String, String, String) {
170+ let unix = stamp_unix(updated_at);
171+ (
172+ iso_time(unix),
173+ forge_core::tz::format_in_tz(unix, tz),
174+ relative_time(lang, unix, now),
175+ )
176+}
177+
161 /// The row for an issue or pull inbox entry.178 /// The row for an issue or pull inbox entry.
162 fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {179 fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {
163 let (kind_label, icon_class) = match (note.is_pull, note.issue_state) {180 let (kind_label, icon_class) = match (note.is_pull, note.issue_state) {
@@ -170,13 +187,9 @@ fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {
170 .last_actor_name187 .last_actor_name
171 .as_deref()188 .as_deref()
172 .map(|name| display_name(lang, name));189 .map(|name| display_name(lang, name));
173- let unix = stamp_unix(&note.updated_at);190+ let (iso, absolute, relative) = times(lang, &note.updated_at, tz, now);
174 RowView {191 RowView {
175- item_class: if note.unread {192+ item_class: item_class(note.unread),
176- "notif-row unread"
177- } else {
178- "notif-row"
179- },
180 icon_class,193 icon_class,
181 kind_label,194 kind_label,
182 open_href: format!("/notifications/{}/open", percent_encode(&note.id)),195 open_href: format!("/notifications/{}/open", percent_encode(&note.id)),
@@ -187,9 +200,9 @@ fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {
187 ),200 ),
188 reason: reason_label(lang, note.reason),201 reason: reason_label(lang, note.reason),
189 activity: g::activity_line(lang, activity_verb(&note.last_activity), actor.as_deref()),202 activity: g::activity_line(lang, activity_verb(&note.last_activity), actor.as_deref()),
190- iso: iso_time(unix),203+ iso,
191- absolute: forge_core::tz::format_in_tz(unix, tz),204+ absolute,
192- relative: relative_time(lang, unix, now),205+ relative,
193 unread: note.unread,206 unread: note.unread,
194 }207 }
195 }208 }
@@ -204,13 +217,9 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64)
204 .last_actor_name217 .last_actor_name
205 .as_deref()218 .as_deref()
206 .map(|name| display_name(lang, name));219 .map(|name| display_name(lang, name));
207- let unix = stamp_unix(&note.updated_at);220+ let (iso, absolute, relative) = times(lang, &note.updated_at, tz, now);
208 RowView {221 RowView {
209- item_class: if note.unread {222+ item_class: item_class(note.unread),
210- "notif-row unread"
211- } else {
212- "notif-row"
213- },
214 icon_class: "notif-icon discussion",223 icon_class: "notif-icon discussion",
215 kind_label: g::t(lang, K::KindDiscussion),224 kind_label: g::t(lang, K::KindDiscussion),
216 open_href: format!(225 open_href: format!(
@@ -227,9 +236,9 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64)
227 ),236 ),
228 reason,237 reason,
229 activity: g::activity_line(lang, activity, actor.as_deref()),238 activity: g::activity_line(lang, activity, actor.as_deref()),
230- iso: iso_time(unix),239+ iso,
231- absolute: forge_core::tz::format_in_tz(unix, tz),240+ absolute,
232- relative: relative_time(lang, unix, now),241+ relative,
233 unread: note.unread,242 unread: note.unread,
234 }243 }
235 }244 }
@@ -237,14 +246,10 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64)
237 /// The row for a repo's security alerts: how many alerts a scan opened since the viewer last read246 /// The row for a repo's security alerts: how many alerts a scan opened since the viewer last read
238 /// the row. It links to the repo's security page through the open route.247 /// the row. It links to the repo's security page through the open route.
239 fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowView {248 fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowView {
240- let unix = stamp_unix(&note.updated_at);249+ let (iso, absolute, relative) = times(lang, &note.updated_at, tz, now);
241 let count = note.new_alerts;250 let count = note.new_alerts;
242 RowView {251 RowView {
243- item_class: if note.unread {252+ item_class: item_class(note.unread),
244- "notif-row unread"
245- } else {
246- "notif-row"
247- },
248 icon_class: "notif-icon advisory",253 icon_class: "notif-icon advisory",
249 kind_label: g::t(lang, K::KindSecurityAlerts),254 kind_label: g::t(lang, K::KindSecurityAlerts),
250 open_href: format!(255 open_href: format!(
@@ -258,9 +263,9 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie
258 title_line: format!("{}/{}", note.repo_owner, note.repo_name),263 title_line: format!("{}/{}", note.repo_owner, note.repo_name),
259 reason: g::t(lang, K::ReasonSecurity),264 reason: g::t(lang, K::ReasonSecurity),
260 activity: g::new_alerts(lang, count),265 activity: g::new_alerts(lang, count),
261- iso: iso_time(unix),266+ iso,
262- absolute: forge_core::tz::format_in_tz(unix, tz),267+ absolute,
263- relative: relative_time(lang, unix, now),268+ relative,
264 unread: note.unread,269 unread: note.unread,
265 }270 }
266 }271 }
@@ -268,13 +273,9 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie
268 /// The row for an admin alert: the headline as the title and the explanation as the activity. It273 /// The row for an admin alert: the headline as the title and the explanation as the activity. It
269 /// opens the health page.274 /// opens the health page.
270 fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView {275 fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView {
271- let unix = stamp_unix(&note.updated_at);276+ let (iso, absolute, relative) = times(lang, &note.updated_at, tz, now);
272 RowView {277 RowView {
273- item_class: if note.unread {278+ item_class: item_class(note.unread),
274- "notif-row unread"
275- } else {
276- "notif-row"
277- },
278 icon_class: if note.resolved {279 icon_class: if note.resolved {
279 "notif-icon admin-resolved"280 "notif-icon admin-resolved"
280 } else {281 } else {
@@ -286,13 +287,29 @@ fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView {
286 title_line: alert_text::title(lang, &note.kind, &note.subject, note.resolved),287 title_line: alert_text::title(lang, &note.kind, &note.subject, note.resolved),
287 reason: g::t(lang, K::ReasonAdmin),288 reason: g::t(lang, K::ReasonAdmin),
288 activity: alert_text::body(lang, &note.kind, &note.subject, &note.detail, note.resolved),289 activity: alert_text::body(lang, &note.kind, &note.subject, &note.detail, note.resolved),
289- iso: iso_time(unix),290+ iso,
290- absolute: forge_core::tz::format_in_tz(unix, tz),291+ absolute,
291- relative: relative_time(lang, unix, now),292+ relative,
292 unread: note.unread,293 unread: note.unread,
293 }294 }
294 }295 }
295 296
297+fn group_slot(
298+ groups: &mut Vec<RepoGroup>,
299+ index: &mut HashMap<String, usize>,
300+ key: &str,
301+ make: impl FnOnce() -> RepoGroup,
302+) -> usize {
303+ match index.get(key) {
304+ Some(slot) => *slot,
305+ None => {
306+ groups.push(make());
307+ index.insert(key.to_owned(), groups.len() - 1);
308+ groups.len() - 1
309+ }
310+ }
311+}
312+
296 /// Whether the viewer may see an inbox entry: its repo must be readable, and security alerts need313 /// Whether the viewer may see an inbox entry: its repo must be readable, and security alerts need
297 /// the repo's managers, the same rule as the security page. `readable` caches the repo checks.314 /// the repo's managers, the same rule as the security page. `readable` caches the repo checks.
298 /// Admin alerts need no repo.315 /// Admin alerts need no repo.
@@ -309,14 +326,14 @@ async fn entry_visible(
309 let visible = match readable.get(repo_id) {326 let visible = match readable.get(repo_id) {
310 Some(visible) => *visible,327 Some(visible) => *visible,
311 None => {328 None => {
312- let visible = can_read(state, user, repo_id).await?;329+ let visible = repo_allows(state, user, repo_id, Action::Read).await?;
313 readable.insert(repo_id.to_owned(), visible);330 readable.insert(repo_id.to_owned(), visible);
314 visible331 visible
315 }332 }
316 };333 };
317 Ok(visible334 Ok(visible
318 && (!matches!(entry, Entry::Advisory(_))335 && (!matches!(entry, Entry::Advisory(_))
319- || can_manage_alerts(state, user, repo_id).await?))336+ || repo_allows(state, user, repo_id, Action::Write).await?))
320 }337 }
321 #[page("/notifications")]338 #[page("/notifications")]
322 async fn inbox(cx: &Cx) -> Result<impl View> {339 async fn inbox(cx: &Cx) -> Result<impl View> {
@@ -386,48 +403,30 @@ async fn inbox(cx: &Cx) -> Result<impl View> {
386 let mut groups: Vec<RepoGroup> = Vec::new();403 let mut groups: Vec<RepoGroup> = Vec::new();
387 let mut index: HashMap<String, usize> = HashMap::new();404 let mut index: HashMap<String, usize> = HashMap::new();
388 for entry in merged {405 for entry in merged {
389- let repo_id = entry.repo_id().to_owned();406+ if let Entry::Admin(note) = &entry {
390- if let Entry::Admin(_) = &entry {407+ let slot = group_slot(&mut groups, &mut index, ADMIN_GROUP, || RepoGroup {
391- // Admin alerts need no repo access.408+ heading: alert_text::inbox_heading(lang).to_owned(),
392- let slot = match index.get(&repo_id) {409+ href: "/admin/health".to_owned(),
393- Some(slot) => *slot,410+ mark_action: format!("/notifications/mark_all_read?repo={ADMIN_GROUP}"),
394- None => {411+ rows: Vec::new(),
395- groups.push(RepoGroup {412+ });
396- heading: alert_text::inbox_heading(lang).to_owned(),413+ groups[slot].rows.push(admin_row(lang, note, &tz, now));
397- href: "/admin/health".to_owned(),
398- mark_action: format!("/notifications/mark_all_read?repo={ADMIN_GROUP}"),
399- rows: Vec::new(),
400- });
401- index.insert(repo_id.clone(), groups.len() - 1);
402- groups.len() - 1
403- }
404- };
405- if let Entry::Admin(note) = &entry {
406- groups[slot].rows.push(admin_row(lang, note, &tz, now));
407- }
408 continue;414 continue;
409 }415 }
410 if !entry_visible(state, user, &mut readable, &entry).await? {416 if !entry_visible(state, user, &mut readable, &entry).await? {
411 hidden.push(entry);417 hidden.push(entry);
412 continue;418 continue;
413 }419 }
414- let slot = match index.get(&repo_id) {420+ let repo_id = entry.repo_id().to_owned();
415- Some(slot) => *slot,421+ let slot = group_slot(&mut groups, &mut index, &repo_id, || RepoGroup {
416- None => {422+ heading: format!("{}/{}", entry.repo_owner(), entry.repo_name()),
417- let heading = format!("{}/{}", entry.repo_owner(), entry.repo_name());423+ href: repo_href(entry.repo_owner(), entry.repo_name(), "", ""),
418- groups.push(RepoGroup {424+ mark_action: format!(
419- href: repo_href(entry.repo_owner(), entry.repo_name(), "", ""),425+ "/notifications/mark_all_read?repo={}",
420- mark_action: format!(426+ percent_encode(&repo_id)
421- "/notifications/mark_all_read?repo={}",427+ ),
422- percent_encode(&repo_id)428+ rows: Vec::new(),
423- ),429+ });
424- heading,
425- rows: Vec::new(),
426- });
427- index.insert(repo_id.clone(), groups.len() - 1);
428- groups.len() - 1
429- }
430- };
431 let row = match entry {430 let row = match entry {
432 Entry::Issue(note) => issue_row(lang, &note, &tz, now),431 Entry::Issue(note) => issue_row(lang, &note, &tz, now),
433 Entry::Discussion(note) => discussion_row(lang, &note, &tz, now),432 Entry::Discussion(note) => discussion_row(lang, &note, &tz, now),
@@ -572,7 +571,7 @@ async fn open_notification(cx: &Cx) -> Result<SeeOther> {
572 };571 };
573 state.store.mark_read(&user.id, id).await?;572 state.store.mark_read(&user.id, id).await?;
574 publish_unread(state, &user.id).await;573 publish_unread(state, &user.id).await;
575- if !can_read(state, &user, &target.repo_id).await? {574+ if !repo_allows(state, &user, &target.repo_id, Action::Read).await? {
576 return Err(not_found().into());575 return Err(not_found().into());
577 }576 }
578 let section = if target.is_pull { "pulls" } else { "issues" };577 let section = if target.is_pull { "pulls" } else { "issues" };
@@ -600,7 +599,7 @@ async fn open_discussion_notification(cx: &Cx) -> Result<SeeOther> {
600 .mark_discussion_notification_read(&user.id, id)599 .mark_discussion_notification_read(&user.id, id)
601 .await?;600 .await?;
602 publish_unread(state, &user.id).await;601 publish_unread(state, &user.id).await;
603- if !can_read(state, &user, &note.repo_id).await? {602+ if !repo_allows(state, &user, &note.repo_id, Action::Read).await? {
604 return Err(not_found().into());603 return Err(not_found().into());
605 }604 }
606 let href = repo_href(605 let href = repo_href(
@@ -641,7 +640,7 @@ async fn open_advisory_notification(cx: &Cx) -> Result<SeeOther> {
641 .mark_advisory_notification_read(&user.id, repo_id)640 .mark_advisory_notification_read(&user.id, repo_id)
642 .await?;641 .await?;
643 publish_unread(state, &user.id).await;642 publish_unread(state, &user.id).await;
644- if !can_manage_alerts(state, &user, repo_id).await? {643+ if !repo_allows(state, &user, repo_id, Action::Write).await? {
645 return Err(not_found().into());644 return Err(not_found().into());
646 }645 }
647 Ok(see_other(repo_href(646 Ok(see_other(repo_href(
@@ -673,13 +672,7 @@ async fn open_admin_notification(cx: &Cx) -> Result<SeeOther> {
673 let (user, _) = require_user(cx).await?;672 let (user, _) = require_user(cx).await?;
674 let state = context::<AppState>(cx);673 let state = context::<AppState>(cx);
675 let id = admin_note(cx);674 let id = admin_note(cx);
676- let owned = state675+ if !user.is_admin || state.store.admin_notice(&user.id, id).await?.is_none() {
677- .store
678- .list_admin_notices(&user.id, false, None, 200)
679- .await?
680- .into_iter()
681- .any(|note| note.id == id);
682- if !owned || !user.is_admin {
683 return Err(not_found().into());676 return Err(not_found().into());
684 }677 }
685 state.store.mark_admin_notice_read(&user.id, id).await?;678 state.store.mark_admin_notice_read(&user.id, id).await?;
@@ -865,22 +858,14 @@ async fn set_watch(cx: &Cx, Form(form): Form<WatchForm>) -> Result<SeeOther> {
865 )))858 )))
866 }859 }
867 860
868-/// Whether the viewer may manage the repo's security alerts: Write on the repo, the same rule as861+/// Whether the viewer may do `action` on the repo right now, by their current collaborator role.
869-/// the security page. Rows for a repo the viewer may not manage are hidden from the inbox.862+/// Security alerts need Write, the same rule as the security page.
870-async fn can_manage_alerts(state: &AppState, user: &User, repo_id: &str) -> Result<bool> {863+pub async fn repo_allows(
871- let Some(repo) = state.store.repo_by_id(repo_id).await? else {864+ state: &AppState,
872- return Ok(false);865+ user: &User,
873- };866+ repo_id: &str,
874- let role: Option<Role> = state.store.collaborator_role(&repo.id, &user.id).await?;867+ action: Action,
875- let org_role = state868+) -> Result<bool> {
876- .store
877- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
878- .await?;
879- Ok(authorize(Some(user), &repo, role, org_role, Action::Write).is_ok())
880-}
881-
882-/// Whether the viewer may read the repo right now, by their current collaborator role.
883-pub async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Result<bool> {
884 let Some(repo) = state.store.repo_by_id(repo_id).await? else {869 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
885 return Ok(false);870 return Ok(false);
886 };871 };
@@ -889,7 +874,7 @@ pub async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Result<bo
889 .store874 .store
890 .org_repo_role(&repo.owner_id, &user.id, &repo.id)875 .org_repo_role(&repo.owner_id, &user.id, &repo.id)
891 .await?;876 .await?;
892- Ok(authorize(Some(user), &repo, role, org_role, Action::Read).is_ok())877+ Ok(authorize(Some(user), &repo, role, org_role, action).is_ok())
893 }878 }
894 879
895 /// The sidebar box of an issue or pull for a signed-in viewer. Viewing the thread marks the880 /// The sidebar box of an issue or pull for a signed-in viewer. Viewing the thread marks the
crates/forge-web-pages/src/pages/packages.rsmodified+29 -45
@@ -4,7 +4,7 @@
4 //! rendered by the profile page.4 //! rendered by the profile page.
5 5
6 use forge_core::User;6 use forge_core::User;
7-use forge_core::packages::{KIND_CARGO, KIND_OCI, Package};7+use forge_core::packages::{KIND_CARGO, KIND_OCI, Package, PackageVersion};
8 use futures_util::{Stream, stream};8 use futures_util::{Stream, stream};
9 use serde::Deserialize;9 use serde::Deserialize;
10 use tokio::sync::watch;10 use tokio::sync::watch;
@@ -70,9 +70,7 @@ pub async fn package_rows(
70 if summary.version_count == 0 {70 if summary.version_count == 0 {
71 continue;71 continue;
72 }72 }
73- let readable = package_ops::may_read(state, viewer, owner, &summary.package)73+ let readable = package_ops::may_read(state, viewer, owner, &summary.package).await?;
74- .await
75- .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?;
76 if !readable {74 if !readable {
77 continue;75 continue;
78 }76 }
@@ -112,8 +110,12 @@ async fn package_page(cx: &Cx) -> Result<impl View> {
112 };110 };
113 let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await {111 let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await {
114 Ok(package) => package,112 Ok(package) => package,
113+ Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg).into()),
115 Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await {114 Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await {
116 Ok(package) => package,115 Ok(package) => package,
116+ Err(PackageError::Internal(msg)) => {
117+ return Err(forge_core::Error::Database(msg).into());
118+ }
117 Err(_) => return Err(not_found().into()),119 Err(_) => return Err(not_found().into()),
118 },120 },
119 };121 };
@@ -159,17 +161,6 @@ async fn package_page(cx: &Cx) -> Result<impl View> {
159 let publish_cmd = format!("cargo publish --registry {}", owner.username);161 let publish_cmd = format!("cargo publish --registry {}", owner.username);
160 let login_cmd = format!("cargo login --registry {}", owner.username);162 let login_cmd = format!("cargo login --registry {}", owner.username);
161 let versions_tab = query.tab.as_deref() == Some("versions");163 let versions_tab = query.tab.as_deref() == Some("versions");
162- let version_rows: Vec<(String, String, bool, String)> = versions
163- .iter()
164- .map(|v| {
165- (
166- v.version.clone(),
167- v.created_at.clone(),
168- v.yanked,
169- v.checksum.clone(),
170- )
171- })
172- .collect();
173 let readme_href = format!(164 let readme_href = format!(
174 "{}?tab=readme",165 "{}?tab=readme",
175 package_href(&owner.username, &package.name)166 package_href(&owner.username, &package.name)
@@ -199,7 +190,7 @@ async fn package_page(cx: &Cx) -> Result<impl View> {
199 add_cmd,190 add_cmd,
200 publish_cmd,191 publish_cmd,
201 login_cmd,192 login_cmd,
202- version_rows,193+ versions,
203 lang,194 lang,
204 };195 };
205 Ok(view! {196 Ok(view! {
@@ -235,7 +226,7 @@ async fn tag_delete(cx: &Cx, Form(form): Form<TagDeleteForm>) -> Result<SeeOther
235 };226 };
236 let allowed = package_ops::may_publish(state, &viewer, &owner)227 let allowed = package_ops::may_publish(state, &viewer, &owner)
237 .await228 .await
238- .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?;229+ .map_err(forge_core::Error::from)?;
239 if !allowed {230 if !allowed {
240 return Err(forbidden().into());231 return Err(forbidden().into());
241 }232 }
@@ -266,7 +257,7 @@ struct PackagePage {
266 add_cmd: String,257 add_cmd: String,
267 publish_cmd: String,258 publish_cmd: String,
268 login_cmd: String,259 login_cmd: String,
269- version_rows: Vec<(String, String, bool, String)>,260+ versions: Vec<PackageVersion>,
270 lang: Lang,261 lang: Lang,
271 }262 }
272 263
@@ -289,7 +280,7 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> {
289 add_cmd,280 add_cmd,
290 publish_cmd,281 publish_cmd,
291 login_cmd,282 login_cmd,
292- version_rows,283+ versions,
293 ..284 ..
294 } = page;285 } = page;
295 let has_readme = !readme_html.is_empty();286 let has_readme = !readme_html.is_empty();
@@ -299,8 +290,14 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> {
299 let readme_on = !versions_tab;290 let readme_on = !versions_tab;
300 let readme_current: Option<&str> = readme_on.then_some("page");291 let readme_current: Option<&str> = readme_on.then_some("page");
301 let versions_current: Option<&str> = versions_tab.then_some("page");292 let versions_current: Option<&str> = versions_tab.then_some("page");
302- let has_versions = !version_rows.is_empty();293+ let has_versions = !versions.is_empty();
303 let install = pk::t(lang, K::Install);294 let install = pk::t(lang, K::Install);
295+ let install_cmds = [
296+ (pk::t(lang, K::InstallRegistryConfig), "pkg-config", config_block),
297+ (pk::t(lang, K::InstallAdd), "pkg-add", add_cmd),
298+ (pk::t(lang, K::InstallPublish), "pkg-publish", publish_cmd),
299+ (pk::t(lang, K::InstallLogin), "pkg-login", login_cmd),
300+ ];
304 let copy_label = pk::t(lang, K::CopyCommand);301 let copy_label = pk::t(lang, K::CopyCommand);
305 let readme_label = pk::t(lang, K::Readme);302 let readme_label = pk::t(lang, K::Readme);
306 let versions_label = pk::t(lang, K::PackageVersions);303 let versions_label = pk::t(lang, K::PackageVersions);
@@ -334,42 +331,29 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> {
334 <p>(description.as_str())</p>331 <p>(description.as_str())</p>
335 }332 }
336 <h2>(install)</h2>333 <h2>(install)</h2>
337- <p class="hint">(pk::t(lang, K::InstallRegistryConfig))</p>334+ for (hint, id, cmd) in install_cmds {
338- <div class="copy-box">335+ <p class="hint">(hint)</p>
339- <code id="pkg-config">(config_block.as_str())</code>336+ <div class="copy-box">
340- <button type="button" data-copy="pkg-config">(copy_label)</button>337+ <code id=(id)>(cmd.as_str())</code>
341- </div>338+ <button type="button" data-copy=(id)>(copy_label)</button>
342- <p class="hint">(pk::t(lang, K::InstallAdd))</p>339+ </div>
343- <div class="copy-box">340+ }
344- <code id="pkg-add">(add_cmd.as_str())</code>
345- <button type="button" data-copy="pkg-add">(copy_label)</button>
346- </div>
347- <p class="hint">(pk::t(lang, K::InstallPublish))</p>
348- <div class="copy-box">
349- <code id="pkg-publish">(publish_cmd.as_str())</code>
350- <button type="button" data-copy="pkg-publish">(copy_label)</button>
351- </div>
352- <p class="hint">(pk::t(lang, K::InstallLogin))</p>
353- <div class="copy-box">
354- <code id="pkg-login">(login_cmd.as_str())</code>
355- <button type="button" data-copy="pkg-login">(copy_label)</button>
356- </div>
357 </section>341 </section>
358 if versions_tab {342 if versions_tab {
359 if has_versions {343 if has_versions {
360- for (version, date, yanked, checksum) in version_rows.iter() {344+ for v in versions.iter() {
361 <details class="row-open" data-kb-row="">345 <details class="row-open" data-kb-row="">
362 <summary class="line">346 <summary class="line">
363 <span class="name">347 <span class="name">
364- (version.as_str())348+ (v.version.as_str())
365- if *yanked {349+ if v.yanked {
366 " " <span class="badge">(pk::t(lang, K::VersionYanked))</span>350 " " <span class="badge">(pk::t(lang, K::VersionYanked))</span>
367 }351 }
368 </span>352 </span>
369- <span class="val">rel_time(lang: lang, stamp: date.as_str())</span>353+ <span class="val">rel_time(lang: lang, stamp: v.created_at.as_str())</span>
370 </summary>354 </summary>
371 <div class="opened">355 <div class="opened">
372- <code class="hint">(checksum.as_str())</code>356+ <code class="hint">(v.checksum.as_str())</code>
373 </div>357 </div>
374 </details>358 </details>
375 }359 }
crates/forge-web-pages/src/pages/packages_oci.rsmodified+5 -19
@@ -39,9 +39,7 @@ pub async fn model(
39 ) -> forge_core::Result<OciPage> {39 ) -> forge_core::Result<OciPage> {
40 let tags = state.store.oci_tags(&package.id).await?;40 let tags = state.store.oci_tags(&package.id).await?;
41 let can_delete = match viewer {41 let can_delete = match viewer {
42- Some(user) => package_ops::may_publish(state, user, owner)42+ Some(user) => package_ops::may_publish(state, user, owner).await?,
43- .await
44- .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?,
45 None => false,43 None => false,
46 };44 };
47 let base = state.config.base_url.trim_end_matches('/');45 let base = state.config.base_url.trim_end_matches('/');
@@ -99,18 +97,6 @@ pub async fn oci_package_view(cx: &Cx, page: OciPage) -> Result<impl View> {
99 let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name));97 let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name));
100 let private = package.private;98 let private = package.private;
101 let tag_count = tags.len().to_string();99 let tag_count = tags.len().to_string();
102- let rows: Vec<(String, String, String, String, String)> = tags
103- .iter()
104- .map(|t| {
105- (
106- t.tag.clone(),
107- short_digest(&t.digest),
108- t.digest.clone(),
109- human_size(lang, t.size),
110- t.created_at.clone(),
111- )
112- })
113- .collect();
114 // The head holds the name, the owner, the newest tag and the private note; the install and tag100 // The head holds the name, the owner, the newest tag and the private note; the install and tag
115 // topics sit in one sheet below it.101 // topics sit in one sheet below it.
116 let mut sub = vec![SubPart::text(format!(102 let mut sub = vec![SubPart::text(format!(
@@ -150,13 +136,13 @@ pub async fn oci_package_view(cx: &Cx, page: OciPage) -> Result<impl View> {
150 <h2>(pk::t(lang, K::ContainerTags)) " " <span class="tab-count">(tag_count.as_str())</span></h2>136 <h2>(pk::t(lang, K::ContainerTags)) " " <span class="tab-count">(tag_count.as_str())</span></h2>
151 if has_tags {137 if has_tags {
152 <div>138 <div>
153- for (tag, short, full, size, created) in rows.iter() {139+ for t in tags.iter() {
154 <div class="line" data-kb-row="">140 <div class="line" data-kb-row="">
155- <span class="name"><code>(tag.as_str())</code></span>141+ <span class="name"><code>(t.tag.as_str())</code></span>
156- <span class="val"><code>(short.as_str())</code> " · " (size.as_str()) " · " rel_time(lang: lang, stamp: created.as_str()) " · " <code>(full.as_str())</code></span>142+ <span class="val"><code>(short_digest(&t.digest))</code> " · " (human_size(lang, t.size)) " · " rel_time(lang: lang, stamp: t.created_at.as_str()) " · " <code>(t.digest.as_str())</code></span>
157 if can_delete {143 if can_delete {
158 confirm_act(lang: lang, label: pk::t(lang, K::DeleteTag), action: delete_action.as_str(), csrf: csrf.as_str(),144 confirm_act(lang: lang, label: pk::t(lang, K::DeleteTag), action: delete_action.as_str(), csrf: csrf.as_str(),
159- fields: vec![("package".to_owned(), package.name.clone()), ("tag".to_owned(), tag.clone())])145+ fields: vec![("package".to_owned(), package.name.clone()), ("tag".to_owned(), t.tag.clone())])
160 }146 }
161 </div>147 </div>
162 }148 }
crates/forge-web-pages/src/pages/pull_reviews.rsmodified+3 -20
@@ -80,7 +80,7 @@ pub fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> {
80 }80 }
81 81
82 /// The message for the `review_error` query value of the request, when it is a known code.82 /// The message for the `review_error` query value of the request, when it is a known code.
83-fn error_from(lang: Lang, cx: &Cx) -> Option<&'static str> {83+pub fn error_from(lang: Lang, cx: &Cx) -> Option<&'static str> {
84 let request = uri(cx);84 let request = uri(cx);
85 let query = request.query()?;85 let query = request.query()?;
86 let (_, code) =86 let (_, code) =
@@ -569,16 +569,7 @@ async fn review_comment_resolve(cx: &Cx, Form(form): Form<ReviewForm>) -> Result
569 let pr = pull_for(state, &ctx, number).await?;569 let pr = pull_for(state, &ctx, number).await?;
570 let comment = comment_on_pull(state, &pr, &user, comment_id(cx)).await?;570 let comment = comment_on_pull(state, &pr, &user, comment_id(cx)).await?;
571 let is_pr_author = pr.issue.author_id == user.id;571 let is_pr_author = pr.issue.author_id == user.id;
572- if !is_pr_author572+ if !is_pr_author && !ctx.can_write() {
573- && authorize(
574- Some(&user),
575- &ctx.repo,
576- ctx.role,
577- ctx.org_role,
578- Action::Write,
579- )
580- .is_err()
581- {
582 return Err(forbidden().into());573 return Err(forbidden().into());
583 }574 }
584 let root = root_of(&comment);575 let root = root_of(&comment);
@@ -788,15 +779,7 @@ async fn review_dismiss(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOthe
788 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;779 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
789 let (user, session) = require_user(cx).await?;780 let (user, session) = require_user(cx).await?;
790 check_write(&ctx, &session, &form.csrf)?;781 check_write(&ctx, &session, &form.csrf)?;
791- if authorize(782+ if !ctx.can_write() {
792- Some(&user),
793- &ctx.repo,
794- ctx.role,
795- ctx.org_role,
796- Action::Write,
797- )
798- .is_err()
799- {
800 return Err(forbidden().into());783 return Err(forbidden().into());
801 }784 }
802 let state = context::<AppState>(cx);785 let state = context::<AppState>(cx);
crates/forge-web-pages/src/pages/releases.rsmodified+68 -57
@@ -152,6 +152,13 @@ fn notice_redirect(href: &str, word: &str) -> SeeOther {
152 see_other(format!("{href}?notice={word}"))152 see_other(format!("{href}?notice={word}"))
153 }153 }
154 154
155+async fn csrf_token(cx: &Cx) -> Result<String> {
156+ Ok(match crate::auth::current_user(cx).await? {
157+ Some((_, session)) => session.csrf_token.clone(),
158+ None => String::new(),
159+ })
160+}
161+
155 /// A byte count for people: "512 B", "1.5 KiB", "3.2 MiB".162 /// A byte count for people: "512 B", "1.5 KiB", "3.2 MiB".
156 pub fn size_text(bytes: u64) -> String {163 pub fn size_text(bytes: u64) -> String {
157 const KIB: f64 = 1024.0;164 const KIB: f64 = 1024.0;
@@ -186,6 +193,20 @@ fn asset_link(title: &str, tag: &str, asset: &ReleaseAsset) -> AssetLink {
186 }193 }
187 }194 }
188 195
196+fn asset_links(title: &str, tag: &str, assets: &[ReleaseAsset]) -> Vec<AssetLink> {
197+ assets
198+ .iter()
199+ .map(|asset| asset_link(title, tag, asset))
200+ .collect()
201+}
202+
203+fn when_of(release: &Release) -> &str {
204+ release
205+ .published_at
206+ .as_deref()
207+ .unwrap_or(&release.created_at)
208+}
209+
189 /// One release card on the list page.210 /// One release card on the list page.
190 pub struct ReleaseCard {211 pub struct ReleaseCard {
191 pub title: String,212 pub title: String,
@@ -215,25 +236,18 @@ fn card_of(
215 latest_id: Option<&str>,236 latest_id: Option<&str>,
216 ) -> ReleaseCard {237 ) -> ReleaseCard {
217 let title = title_of(ctx);238 let title = title_of(ctx);
218- let when = release
219- .published_at
220- .as_deref()
221- .unwrap_or(&release.created_at);
222 ReleaseCard {239 ReleaseCard {
223 title: release.title.clone(),240 title: release.title.clone(),
224 tag: release.tag.clone(),241 tag: release.tag.clone(),
225 href: tag_href(&title, &release.tag),242 href: tag_href(&title, &release.tag),
226 edit_href: release_edit_href(&title, &release.id),243 edit_href: release_edit_href(&title, &release.id),
227 body: release.body.clone(),244 body: release.body.clone(),
228- when: When::new(ctx.lang, when, ctx.viewer_tz(), now_unix()),245+ when: When::new(ctx.lang, when_of(release), ctx.viewer_tz(), now_unix()),
229 author: release.author_name.clone(),246 author: release.author_name.clone(),
230 draft: release.draft,247 draft: release.draft,
231 prerelease: release.prerelease,248 prerelease: release.prerelease,
232 latest: latest_id == Some(release.id.as_str()),249 latest: latest_id == Some(release.id.as_str()),
233- assets: assets250+ assets: asset_links(&title, &release.tag, assets),
234- .iter()
235- .map(|asset| asset_link(&title, &release.tag, asset))
236- .collect(),
237 }251 }
238 }252 }
239 253
@@ -250,10 +264,7 @@ pub async fn latest_release_for_home(
250 Ok(Some(LatestRelease {264 Ok(Some(LatestRelease {
251 tag: release.tag.clone(),265 tag: release.tag.clone(),
252 href: tag_href(&title, &release.tag),266 href: tag_href(&title, &release.tag),
253- assets: assets267+ assets: asset_links(&title, &release.tag, &assets),
254- .iter()
255- .map(|asset| asset_link(&title, &release.tag, asset))
256- .collect(),
257 }))268 }))
258 }269 }
259 270
@@ -269,6 +280,27 @@ struct FormDraft {
269 error: Option<String>,280 error: Option<String>,
270 }281 }
271 282
283+impl FormDraft {
284+ fn from_fields(
285+ tag: &str,
286+ target: &str,
287+ title: &str,
288+ body: &str,
289+ prerelease: bool,
290+ draft: bool,
291+ ) -> Self {
292+ Self {
293+ tag: tag.trim().to_owned(),
294+ target: target.trim().to_owned(),
295+ title: title.trim().to_owned(),
296+ body: body.trim_end().to_owned(),
297+ prerelease,
298+ draft,
299+ error: None,
300+ }
301+ }
302+}
303+
272 /// The new-release form fields.304 /// The new-release form fields.
273 #[derive(Deserialize)]305 #[derive(Deserialize)]
274 struct CreateForm {306 struct CreateForm {
@@ -636,10 +668,7 @@ async fn release_new_page(cx: &Cx) -> Result<impl View> {
636 require_write(&ctx)?;668 require_write(&ctx)?;
637 let lang = i18n::lang(cx, viewer_user(&ctx));669 let lang = i18n::lang(cx, viewer_user(&ctx));
638 let state = context::<AppState>(cx);670 let state = context::<AppState>(cx);
639- let csrf = match crate::auth::current_user(cx).await? {671+ let csrf = csrf_token(cx).await?;
640- Some((_, session)) => session.csrf_token.clone(),
641- None => String::new(),
642- };
643 let draft = FormDraft {672 let draft = FormDraft {
644 target: ctx.repo.default_branch.clone(),673 target: ctx.repo.default_branch.clone(),
645 draft: false,674 draft: false,
@@ -664,15 +693,14 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi
664 require_write(&ctx)?;693 require_write(&ctx)?;
665 let lang = i18n::lang(cx, viewer_user(&ctx));694 let lang = i18n::lang(cx, viewer_user(&ctx));
666 let state = context::<AppState>(cx);695 let state = context::<AppState>(cx);
667- let draft = FormDraft {696+ let draft = FormDraft::from_fields(
668- tag: form.tag.trim().to_owned(),697+ &form.tag,
669- target: form.target.trim().to_owned(),698+ &form.target,
670- title: form.title.trim().to_owned(),699+ &form.title,
671- body: form.body.trim_end().to_owned(),700+ &form.body,
672- prerelease: form.prerelease.is_some(),701+ form.prerelease.is_some(),
673- draft: form.draft.is_some(),702+ form.draft.is_some(),
674- error: None,703+ );
675- };
676 match create_checked(state, &ctx, &user, &draft, lang).await? {704 match create_checked(state, &ctx, &user, &draft, lang).await? {
677 Ok(release) => {705 Ok(release) => {
678 let title = title_of(&ctx);706 let title = title_of(&ctx);
@@ -752,15 +780,8 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
752 }780 }
753 let title = title_of(&ctx);781 let title = title_of(&ctx);
754 let assets = state.store.list_release_assets(&release.id).await?;782 let assets = state.store.list_release_assets(&release.id).await?;
755- let links: Vec<AssetLink> = assets783+ let links = asset_links(&title, &release.tag, &assets);
756- .iter()784+ let when = When::new(ctx.lang, when_of(&release), ctx.viewer_tz(), now_unix());
757- .map(|asset| asset_link(&title, &release.tag, asset))
758- .collect();
759- let when = release
760- .published_at
761- .as_deref()
762- .unwrap_or(&release.created_at);
763- let when = When::new(ctx.lang, when, ctx.viewer_tz(), now_unix());
764 let body_html = render_markdown(&release.body, None);785 let body_html = render_markdown(&release.body, None);
765 let page_title = format!("{title} \u{b7} {}", release.title);786 let page_title = format!("{title} \u{b7} {}", release.title);
766 let archive_tar = format!("/{title}/archive/{}.tar.gz", enc(&release.tag));787 let archive_tar = format!("/{title}/archive/{}.tar.gz", enc(&release.tag));
@@ -784,10 +805,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
784 let notice = notice_from_query(cx, lang);805 let notice = notice_from_query(cx, lang);
785 let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id));806 let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id));
786 let live = releases_live::tag_live_url(&title, &release.tag);807 let live = releases_live::tag_live_url(&title, &release.tag);
787- let csrf = match crate::auth::current_user(cx).await? {808+ let csrf = csrf_token(cx).await?;
788- Some((_, session)) => session.csrf_token.clone(),
789- None => String::new(),
790- };
791 Ok(view! {809 Ok(view! {
792 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),810 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
793 repo_head(head: head, title: Some(card.title.clone()),811 repo_head(head: head, title: Some(card.title.clone()),
@@ -958,10 +976,7 @@ async fn edit_parts(
958 )976 )
959 })977 })
960 .collect();978 .collect();
961- let links: Vec<AssetLink> = assets979+ let links = asset_links(&title, &release.tag, &assets);
962- .iter()
963- .map(|asset| asset_link(&title, &release.tag, asset))
964- .collect();
965 let refs = load_refs(ctx.path.clone()).await?;980 let refs = load_refs(ctx.path.clone()).await?;
966 Ok(EditParts {981 Ok(EditParts {
967 page_title: format!("{title} \u{b7} {}", g::edit_title(lang, &release.tag)),982 page_title: format!("{title} \u{b7} {}", g::edit_title(lang, &release.tag)),
@@ -994,10 +1009,7 @@ async fn release_edit_page(cx: &Cx) -> Result<impl View> {
994 if release.repo_id != ctx.repo.id {1009 if release.repo_id != ctx.repo.id {
995 return Err(not_found().into());1010 return Err(not_found().into());
996 }1011 }
997- let csrf = match crate::auth::current_user(cx).await? {1012+ let csrf = csrf_token(cx).await?;
998- Some((_, session)) => session.csrf_token.clone(),
999- None => String::new(),
1000- };
1001 let draft = FormDraft {1013 let draft = FormDraft {
1002 tag: release.tag.clone(),1014 tag: release.tag.clone(),
1003 title: release.title.clone(),1015 title: release.title.clone(),
@@ -1032,15 +1044,14 @@ async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View
1032 let Some(before) = state.store.release(&id).await? else {1044 let Some(before) = state.store.release(&id).await? else {
1033 return Err(not_found().into());1045 return Err(not_found().into());
1034 };1046 };
1035- let draft = FormDraft {1047+ let draft = FormDraft::from_fields(
1036- tag: form.tag.trim().to_owned(),1048+ &form.tag,
1037- target: form.target.trim().to_owned(),1049+ &form.target,
1038- title: form.title.trim().to_owned(),1050+ &form.title,
1039- body: form.body.trim_end().to_owned(),1051+ &form.body,
1040- prerelease: form.prerelease.is_some(),1052+ form.prerelease.is_some(),
1041- draft: form.draft.is_some(),1053+ form.draft.is_some(),
1042- error: None,1054+ );
1043- };
1044 let edit = EditRelease {1055 let edit = EditRelease {
1045 title: draft.title.clone(),1056 title: draft.title.clone(),
1046 body: draft.body.clone(),1057 body: draft.body.clone(),
@@ -1135,7 +1146,7 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> {
1135 let state = context::<AppState>(cx);1146 let state = context::<AppState>(cx);
1136 let href = release_edit_href(&title_of(&ctx), &id);1147 let href = release_edit_href(&title_of(&ctx), &id);
1137 let max_bytes = state1148 let max_bytes = state
1138- .config1149+ .live()
1139 .releases1150 .releases
1140 .max_asset_mb1151 .max_asset_mb
1141 .saturating_mul(1024 * 1024);1152 .saturating_mul(1024 * 1024);
crates/forge-web-pages/src/pages/releases_live.rsmodified+12 -15
@@ -36,8 +36,13 @@ pub fn tag_live_url(title: &str, tag: &str) -> String {
36 format!("/{title}/releases/tag/{}/events", enc(tag))36 format!("/{title}/releases/tag/{}/events", enc(tag))
37 }37 }
38 38
39-// Fingerprints. Each reads what the page shows; any change to it changes the string. `writer`39+async fn asset_lines(store: &Store, release_id: &str) -> Result<Vec<String>> {
40-// decides whether drafts are part of it, the same way the pages decide.40+ let mut lines = Vec::new();
41+ for asset in store.list_release_assets(release_id).await? {
42+ lines.push(format!("asset {asset:?}"));
43+ }
44+ Ok(lines)
45+}
41 46
42 /// What the release list shows: the latest release and every release the viewer may see, with47 /// What the release list shows: the latest release and every release the viewer may see, with
43 /// their assets (names, sizes, download counts).48 /// their assets (names, sizes, download counts).
@@ -52,9 +57,7 @@ pub async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool) -> Res
52 continue;57 continue;
53 }58 }
54 lines.push(format!("{release:?}"));59 lines.push(format!("{release:?}"));
55- for asset in store.list_release_assets(&release.id).await? {60+ lines.extend(asset_lines(store, &release.id).await?);
56- lines.push(format!("asset {asset:?}"));
57- }
58 }61 }
59 Ok(lines.join("\n"))62 Ok(lines.join("\n"))
60 }63 }
@@ -74,9 +77,7 @@ pub async fn release_fingerprint(
74 return Ok("gone".to_owned());77 return Ok("gone".to_owned());
75 }78 }
76 let mut lines = vec![format!("{release:?}")];79 let mut lines = vec![format!("{release:?}")];
77- for asset in store.list_release_assets(&release.id).await? {80+ lines.extend(asset_lines(store, &release.id).await?);
78- lines.push(format!("asset {asset:?}"));
79- }
80 Ok(lines.join("\n"))81 Ok(lines.join("\n"))
81 }82 }
82 83
@@ -106,16 +107,12 @@ async fn release_events(cx: &Cx) -> Result<Response> {
106 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;107 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
107 let state = context::<AppState>(cx);108 let state = context::<AppState>(cx);
108 let writer = can_write(&ctx);109 let writer = can_write(&ctx);
109- let visible = match state.store.release_by_tag(&ctx.repo.id, &tag).await? {110+ let store = state.store.clone();
110- Some(release) => writer || !release.draft,111+ let repo_id = ctx.repo.id.clone();
111- None => false,112+ if release_fingerprint(&store, &repo_id, &tag, writer).await? == "gone" {
112- };
113- if !visible {
114 return Err(not_found().into());113 return Err(not_found().into());
115 }114 }
116 let topic = Topic::RepoReleases(ctx.repo.id.clone());115 let topic = Topic::RepoReleases(ctx.repo.id.clone());
117- let store = state.store.clone();
118- let repo_id = ctx.repo.id.clone();
119 stream_changes(cx, &state.live, &[topic], move || {116 stream_changes(cx, &state.live, &[topic], move || {
120 let store = store.clone();117 let store = store.clone();
121 let repo_id = repo_id.clone();118 let repo_id = repo_id.clone();
crates/forge-web-pages/src/pages/repo.rsmodified+1 -1
@@ -397,7 +397,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
397 facts = Some(tree_facts(state, repo, &ctx.path, commit, &names).await?);397 facts = Some(tree_facts(state, repo, &ctx.path, commit, &names).await?);
398 let (last, latest) = tokio::join!(398 let (last, latest) = tokio::join!(
399 last_commits(state, &ctx.path, commit, "", &names),399 last_commits(state, &ctx.path, commit, "", &names),
400- latest_bar(state, repo, &ctx.path, commit, "", lang, ctx.viewer_tz()),400+ latest_bar(state, repo, &ctx.path, commit, lang, ctx.viewer_tz()),
401 );401 );
402 bar = latest;402 bar = latest;
403 readme = load_readme(state, repo, &ctx.path, &branch, commit, "", &entries).await?;403 readme = load_readme(state, repo, &ctx.path, &branch, commit, "", &entries).await?;
crates/forge-web-pages/src/pages/repo_ctx.rsmodified+29 -49
@@ -121,6 +121,10 @@ pub struct WatchButton {
121 }121 }
122 122
123 impl RepoCtx {123 impl RepoCtx {
124+ pub fn title(&self) -> String {
125+ format!("{}/{}", self.repo.owner_name, self.repo.name)
126+ }
127+
124 /// Whether the viewer may delete this repo: its owner or an instance admin only.128 /// Whether the viewer may delete this repo: its owner or an instance admin only.
125 pub fn can_delete(&self) -> bool {129 pub fn can_delete(&self) -> bool {
126 let actor = self.viewer.as_ref().map(|(user, _)| user);130 let actor = self.viewer.as_ref().map(|(user, _)| user);
@@ -138,8 +142,7 @@ impl RepoCtx {
138 /// Write role or higher, an org role that grants it, or the owner. Archived repos stay read-only.142 /// Write role or higher, an org role that grants it, or the owner. Archived repos stay read-only.
139 pub fn can_write(&self) -> bool {143 pub fn can_write(&self) -> bool {
140 let actor = self.viewer.as_ref().map(|(user, _)| user);144 let actor = self.viewer.as_ref().map(|(user, _)| user);
141- !self.repo.archived145+ authorize(actor, &self.repo, self.role, self.org_role, Action::Write).is_ok()
142- && authorize(actor, &self.repo, self.role, self.org_role, Action::Write).is_ok()
143 }146 }
144 147
145 /// Open issue count for the Issues tab: one indexed COUNT query.148 /// Open issue count for the Issues tab: one indexed COUNT query.
@@ -155,17 +158,8 @@ impl RepoCtx {
155 let Some(source) = state.store.repo_by_id(source_id).await? else {158 let Some(source) = state.store.repo_by_id(source_id).await? else {
156 return Ok(None);159 return Ok(None);
157 };160 };
158- let (role, org_role) = match &self.viewer {
159- Some((user, _)) => (
160- state.store.collaborator_role(&source.id, &user.id).await?,
161- state
162- .store
163- .org_repo_role(&source.owner_id, &user.id, &source.id)
164- .await?,
165- ),
166- None => (None, None),
167- };
168 let actor = self.viewer.as_ref().map(|(user, _)| user);161 let actor = self.viewer.as_ref().map(|(user, _)| user);
162+ let (role, org_role) = access(&state.store, actor, &source).await?;
169 if authorize(actor, &source, role, org_role, Action::Read).is_err() {163 if authorize(actor, &source, role, org_role, Action::Read).is_err() {
170 return Ok(None);164 return Ok(None);
171 }165 }
@@ -200,8 +194,7 @@ impl RepoCtx {
200 let forks = fork_count(state, &self.repo.id).await?;194 let forks = fork_count(state, &self.repo.id).await?;
201 let discussions = state.store.discussions_enabled(&self.repo.id).await?;195 let discussions = state.store.discussions_enabled(&self.repo.id).await?;
202 let wiki = state.store.wiki_enabled(&self.repo.id).await?;196 let wiki = state.store.wiki_enabled(&self.repo.id).await?;
203- let security =197+ let security = state.config.advisories.enabled && self.can_write();
204- state.config.advisories.enabled && crate::pages::repo_security::can_write(self);
205 let mirror = state198 let mirror = state
206 .store199 .store
207 .pull_mirror(&self.repo.id)200 .pull_mirror(&self.repo.id)
@@ -264,12 +257,29 @@ impl RepoCtx {
264 }257 }
265 }258 }
266 259
267-/// Load `owner/name` for the current viewer, or 404.
268 /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`).260 /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`).
269 pub async fn fork_count(state: &AppState, repo_id: &str) -> Result<u64> {261 pub async fn fork_count(state: &AppState, repo_id: &str) -> Result<u64> {
270 Ok(state.store.public_fork_count(repo_id).await?)262 Ok(state.store.public_fork_count(repo_id).await?)
271 }263 }
272 264
265+/// The viewer's collaborator role and organization role on `repo`; both `None` for anonymous viewers.
266+pub async fn access(
267+ store: &Store,
268+ viewer: Option<&User>,
269+ repo: &Repo,
270+) -> Result<(Option<Role>, Option<Role>)> {
271+ match viewer {
272+ Some(user) => Ok((
273+ store.collaborator_role(&repo.id, &user.id).await?,
274+ store
275+ .org_repo_role(&repo.owner_id, &user.id, &repo.id)
276+ .await?,
277+ )),
278+ None => Ok((None, None)),
279+ }
280+}
281+
282+/// Load `owner/name` for the current viewer, or 404.
273 pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {283 pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {
274 let state = context::<AppState>(cx);284 let state = context::<AppState>(cx);
275 let viewer = current_user(cx).await?;285 let viewer = current_user(cx).await?;
@@ -280,17 +290,8 @@ pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {
280 }290 }
281 return Err(not_found().into());291 return Err(not_found().into());
282 };292 };
283- let (role, org_role) = match &viewer {
284- Some((user, _)) => (
285- state.store.collaborator_role(&repo.id, &user.id).await?,
286- state
287- .store
288- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
289- .await?,
290- ),
291- None => (None, None),
292- };
293 let actor = viewer.as_ref().map(|(user, _)| user);293 let actor = viewer.as_ref().map(|(user, _)| user);
294+ let (role, org_role) = access(&state.store, actor, &repo).await?;
294 if authorize(actor, &repo, role, org_role, Action::Read).is_err() {295 if authorize(actor, &repo, role, org_role, Action::Read).is_err() {
295 return Err(not_found().into());296 return Err(not_found().into());
296 }297 }
@@ -313,20 +314,8 @@ pub async fn still_readable(store: &Store, viewer: Option<&User>, repo_id: &str)
313 let Ok(Some(repo)) = store.repo_by_id(repo_id).await else {314 let Ok(Some(repo)) = store.repo_by_id(repo_id).await else {
314 return false;315 return false;
315 };316 };
316- let (role, org_role) = match viewer {317+ let Ok((role, org_role)) = access(store, viewer, &repo).await else {
317- Some(user) => {318+ return false;
318- let Ok(role) = store.collaborator_role(&repo.id, &user.id).await else {
319- return false;
320- };
321- let Ok(org_role) = store
322- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
323- .await
324- else {
325- return false;
326- };
327- (role, org_role)
328- }
329- None => (None, None),
330 };319 };
331 authorize(viewer, &repo, role, org_role, Action::Read).is_ok()320 authorize(viewer, &repo, role, org_role, Action::Read).is_ok()
332 }321 }
@@ -357,17 +346,8 @@ async fn moved_location(
357 None => return Ok(None),346 None => return Ok(None),
358 },347 },
359 };348 };
360- let (role, org_role) = match viewer {
361- Some((user, _)) => (
362- state.store.collaborator_role(&target.id, &user.id).await?,
363- state
364- .store
365- .org_repo_role(&target.owner_id, &user.id, &target.id)
366- .await?,
367- ),
368- None => (None, None),
369- };
370 let actor = viewer.map(|(user, _)| user);349 let actor = viewer.map(|(user, _)| user);
350+ let (role, org_role) = access(&state.store, actor, &target).await?;
371 if authorize(actor, &target, role, org_role, Action::Read).is_err() {351 if authorize(actor, &target, role, org_role, Action::Read).is_err() {
372 return Ok(None);352 return Ok(None);
373 }353 }
crates/forge-web-pages/src/pages/repo_mirrors.rsmodified+44 -37
@@ -262,12 +262,34 @@ fn interval_text(lang: Lang, minutes: u32) -> String {
262 }262 }
263 }263 }
264 264
265-/// The last sync, as the list and the header show it: ok, failed (with the error) or not run yet.265+#[derive(Clone, Copy)]
266-fn status_of(lang: Lang, mirror: &Mirror) -> (&'static str, &'static str) {266+enum SyncStatus {
267+ Ok,
268+ Failed,
269+ NotRun,
270+}
271+
272+fn sync_status(mirror: &Mirror) -> SyncStatus {
267 match mirror.last_ok {273 match mirror.last_ok {
268- Some(true) => ("ok", g::t(lang, K::StatusOk)),274+ Some(true) => SyncStatus::Ok,
269- Some(false) => ("failed", g::t(lang, K::StatusFailed)),275+ Some(false) => SyncStatus::Failed,
270- None => ("none", g::t(lang, K::StatusNotRun)),276+ None => SyncStatus::NotRun,
277+ }
278+}
279+
280+fn status_label(lang: Lang, status: SyncStatus) -> &'static str {
281+ match status {
282+ SyncStatus::Ok => g::t(lang, K::StatusOk),
283+ SyncStatus::Failed => g::t(lang, K::StatusFailed),
284+ SyncStatus::NotRun => g::t(lang, K::StatusNotRun),
285+ }
286+}
287+
288+fn dot_class(enabled: bool, status: SyncStatus) -> &'static str {
289+ match (enabled, status) {
290+ (true, SyncStatus::Ok) => "runner-dot is-online",
291+ (true, SyncStatus::Failed) => "runner-dot is-failed",
292+ _ => "runner-dot",
271 }293 }
272 }294 }
273 295
@@ -338,12 +360,7 @@ struct MirrorRow {
338 }360 }
339 361
340 fn mirror_row(lang: Lang, mirror: &Mirror, title: &str, tz: &str) -> MirrorRow {362 fn mirror_row(lang: Lang, mirror: &Mirror, title: &str, tz: &str) -> MirrorRow {
341- let (status_class, status_text) = status_of(lang, mirror);363+ let status = sync_status(mirror);
342- let dot_class = match (mirror.enabled, status_class) {
343- (true, "ok") => "runner-dot is-online",
344- (true, "failed") => "runner-dot is-failed",
345- _ => "runner-dot",
346- };
347 let (sync_prefix, sync_suffix) = match lang {364 let (sync_prefix, sync_suffix) = match lang {
348 Lang::En => ("synced ", ""),365 Lang::En => ("synced ", ""),
349 Lang::Tr => ("", " eşitlendi"),366 Lang::Tr => ("", " eşitlendi"),
@@ -370,8 +387,8 @@ fn mirror_row(lang: Lang, mirror: &Mirror, title: &str, tz: &str) -> MirrorRow {
370 last_sync_rel,387 last_sync_rel,
371 sync_prefix,388 sync_prefix,
372 sync_suffix,389 sync_suffix,
373- dot_class,390+ dot_class: dot_class(mirror.enabled, status),
374- status_text,391+ status_text: status_label(lang, status),
375 error: mirror.last_error.clone().unwrap_or_default(),392 error: mirror.last_error.clone().unwrap_or_default(),
376 }393 }
377 }394 }
@@ -697,12 +714,7 @@ async fn mirror_create(cx: &Cx, Form(form): Form<PushForm>) -> Result<impl View>
697 let name = repo(cx);714 let name = repo(cx);
698 let ctx = load_repo(cx, owner, name).await?;715 let ctx = load_repo(cx, owner, name).await?;
699 let (user, session) = require_csrf(cx, &form.csrf).await?;716 let (user, session) = require_csrf(cx, &form.csrf).await?;
700- if !ctx.can_admin() {717+ require_mirror_admin(&ctx)?;
701- return Err(not_found().into());
702- }
703- if ctx.repo.archived {
704- return Err(forbidden().into());
705- }
706 let state = context::<AppState>(cx);718 let state = context::<AppState>(cx);
707 let lang = lang_of(cx, &ctx);719 let lang = lang_of(cx, &ctx);
708 let pull = form.direction == "pull";720 let pull = form.direction == "pull";
@@ -760,6 +772,16 @@ async fn mirror_create(cx: &Cx, Form(form): Form<PushForm>) -> Result<impl View>
760 Err(back_to_list(&title_of(&ctx), notice).into())772 Err(back_to_list(&title_of(&ctx), notice).into())
761 }773 }
762 774
775+fn require_mirror_admin(ctx: &RepoCtx) -> Result<()> {
776+ if !ctx.can_admin() {
777+ return Err(not_found().into());
778+ }
779+ if ctx.repo.archived {
780+ return Err(forbidden().into());
781+ }
782+ Ok(())
783+}
784+
763 /// The mirror in the path, when it belongs to this repo. Any other mirror answers 404.785 /// The mirror in the path, when it belongs to this repo. Any other mirror answers 404.
764 async fn repo_mirror(state: &AppState, ctx: &RepoCtx, id: &str) -> Result<Mirror> {786 async fn repo_mirror(state: &AppState, ctx: &RepoCtx, id: &str) -> Result<Mirror> {
765 match state.store.mirror(id).await? {787 match state.store.mirror(id).await? {
@@ -881,12 +903,7 @@ async fn mirror_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View>
881 let id = mirror_id(cx);903 let id = mirror_id(cx);
882 let ctx = load_repo(cx, owner, name).await?;904 let ctx = load_repo(cx, owner, name).await?;
883 let (user, session) = require_csrf(cx, &form.csrf).await?;905 let (user, session) = require_csrf(cx, &form.csrf).await?;
884- if !ctx.can_admin() {906+ require_mirror_admin(&ctx)?;
885- return Err(not_found().into());
886- }
887- if ctx.repo.archived {
888- return Err(forbidden().into());
889- }
890 let state = context::<AppState>(cx);907 let state = context::<AppState>(cx);
891 let mirror = repo_mirror(state, &ctx, id).await?;908 let mirror = repo_mirror(state, &ctx, id).await?;
892 let url = if form.url.trim().is_empty() {909 let url = if form.url.trim().is_empty() {
@@ -975,12 +992,7 @@ async fn mirror_sync(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
975 let id = mirror_id(cx);992 let id = mirror_id(cx);
976 let ctx = load_repo(cx, owner, name).await?;993 let ctx = load_repo(cx, owner, name).await?;
977 require_csrf(cx, &form.csrf).await?;994 require_csrf(cx, &form.csrf).await?;
978- if !ctx.can_admin() {995+ require_mirror_admin(&ctx)?;
979- return Err(not_found().into());
980- }
981- if ctx.repo.archived {
982- return Err(forbidden().into());
983- }
984 let state = context::<AppState>(cx);996 let state = context::<AppState>(cx);
985 let mirror = repo_mirror(state, &ctx, id).await?;997 let mirror = repo_mirror(state, &ctx, id).await?;
986 state998 state
@@ -999,12 +1011,7 @@ async fn mirror_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther
999 let id = mirror_id(cx);1011 let id = mirror_id(cx);
1000 let ctx = load_repo(cx, owner, name).await?;1012 let ctx = load_repo(cx, owner, name).await?;
1001 let (user, _) = require_csrf(cx, &form.csrf).await?;1013 let (user, _) = require_csrf(cx, &form.csrf).await?;
1002- if !ctx.can_admin() {1014+ require_mirror_admin(&ctx)?;
1003- return Err(not_found().into());
1004- }
1005- if ctx.repo.archived {
1006- return Err(forbidden().into());
1007- }
1008 let state = context::<AppState>(cx);1015 let state = context::<AppState>(cx);
1009 let mirror = repo_mirror(state, &ctx, id).await?;1016 let mirror = repo_mirror(state, &ctx, id).await?;
1010 let title = title_of(&ctx);1017 let title = title_of(&ctx);
crates/forge-web-pages/src/pages/repo_settings.rsmodified+24 -140
@@ -1,11 +1,3 @@
1-//! Page: repo settings (`/{owner}/{repo}/settings`). The owner, an instance admin and collaborators
2-//! with the Admin role get the page. It shows one section at a time, chosen by `?section=`: General
3-//! (description, default branch, and the Features switches: discussions and wiki; the default), branch
4-//! protection rules (Admin), and the danger zone (rename, then transfer, visibility, archive and
5-//! delete). Transfer and delete need Delete: owner or instance admin only. Deleting moves the bare repo
6-//! into `data_dir/trash` and removes its database rows in one transaction. The repo is never erased
7-//! from disk, so an admin can recover it from the trash.
8-
9 use std::path::Path;1 use std::path::Path;
10 2
11 use forge_core::protection::{3 use forge_core::protection::{
@@ -49,14 +41,11 @@ use crate::views::{alert, enc, shell};
49 path_param!(owner);41 path_param!(owner);
50 path_param!(repo);42 path_param!(repo);
51 43
52-/// The `?section=` query of the settings page. Unknown values show General.
53 #[query_params(error = bad_request)]44 #[query_params(error = bad_request)]
54 pub struct SectionQuery {45 pub struct SectionQuery {
55 section: Option<String>,46 section: Option<String>,
56 }47 }
57 48
58-/// The section to show: `branches`, or `danger` (the danger zone, for a viewer who may admin the
59-/// repo, which the page requires). Anything else, including the old `discussions`, is `general`.
60 fn pick_section(raw: Option<&str>) -> &'static str {49 fn pick_section(raw: Option<&str>) -> &'static str {
61 match raw {50 match raw {
62 Some("branches") => "branches",51 Some("branches") => "branches",
@@ -65,14 +54,10 @@ fn pick_section(raw: Option<&str>) -> &'static str {
65 }54 }
66 }55 }
67 56
68-/// Cookie that carries a one-shot notice (the deleted repo's `owner/name`) to the next profile page.
69 pub const NOTICE_COOKIE: &str = "forge_notice";57 pub const NOTICE_COOKIE: &str = "forge_notice";
70 58
71-/// Cookie that carries a one-shot settings notice to the next settings page. Its value is one of
72-/// the fixed words in `SETTINGS_NOTICES`, never user text.
73 const SETTINGS_NOTICE_COOKIE: &str = "forge_settings_notice";59 const SETTINGS_NOTICE_COOKIE: &str = "forge_settings_notice";
74 60
75-/// Notice words, the text each one shows, and whether it is an error (shown as an alert).
76 const SETTINGS_NOTICES: [(&str, K, bool); 13] = [61 const SETTINGS_NOTICES: [(&str, K, bool); 13] = [
77 ("saved", K::BranchRuleSaved, false),62 ("saved", K::BranchRuleSaved, false),
78 ("removed", K::BranchRuleRemoved, false),63 ("removed", K::BranchRuleRemoved, false),
@@ -89,7 +74,6 @@ const SETTINGS_NOTICES: [(&str, K, bool); 13] = [
89 ("bad_form", K::BadForm, true),74 ("bad_form", K::BadForm, true),
90 ];75 ];
91 76
92-/// Longest accepted `owner/name` in the notice cookie.
93 const MAX_NOTICE_CHARS: usize = 256;77 const MAX_NOTICE_CHARS: usize = 256;
94 78
95 #[derive(Deserialize)]79 #[derive(Deserialize)]
@@ -100,19 +84,16 @@ struct DeleteForm {
100 confirm: String,84 confirm: String,
101 }85 }
102 86
103-/// The General form: description and default branch, saved together.
104 #[derive(Deserialize)]87 #[derive(Deserialize)]
105 struct GeneralForm {88 struct GeneralForm {
106 #[serde(default)]89 #[serde(default)]
107 csrf: String,90 csrf: String,
108 #[serde(default)]91 #[serde(default)]
109 description: String,92 description: String,
110- /// Empty when the repo has no branches yet; the current default branch is then kept.
111 #[serde(default)]93 #[serde(default)]
112 default_branch: String,94 default_branch: String,
113 }95 }
114 96
115-/// The visibility form. `understand` is the confirm popup's hidden field; a request without it is refused.
116 #[derive(Deserialize)]97 #[derive(Deserialize)]
117 struct VisibilityForm {98 struct VisibilityForm {
118 #[serde(default)]99 #[serde(default)]
@@ -127,12 +108,10 @@ struct VisibilityForm {
127 struct ArchiveForm {108 struct ArchiveForm {
128 #[serde(default)]109 #[serde(default)]
129 csrf: String,110 csrf: String,
130- /// `1` archives the repo, `0` unarchives it.
131 #[serde(default)]111 #[serde(default)]
132 archived: String,112 archived: String,
133 }113 }
134 114
135-/// The add/update rule form. An unchecked box is absent from the body, so `Option` is `None`.
136 #[derive(Deserialize)]115 #[derive(Deserialize)]
137 struct BranchForm {116 struct BranchForm {
138 #[serde(default)]117 #[serde(default)]
@@ -143,7 +122,6 @@ struct BranchForm {
143 allow_force_push: Option<String>,122 allow_force_push: Option<String>,
144 #[serde(default)]123 #[serde(default)]
145 allow_deletion: Option<String>,124 allow_deletion: Option<String>,
146- /// Text from the number field; blank means 0.
147 #[serde(default)]125 #[serde(default)]
148 required_approvals: String,126 required_approvals: String,
149 #[serde(default)]127 #[serde(default)]
@@ -154,11 +132,8 @@ struct BranchForm {
154 restrict_push: Option<String>,132 restrict_push: Option<String>,
155 #[serde(default)]133 #[serde(default)]
156 require_merge_queue: Option<String>,134 require_merge_queue: Option<String>,
157- /// Required check contexts, separated by commas or new lines.
158 #[serde(default)]135 #[serde(default)]
159 required_checks: String,136 required_checks: String,
160- /// Set by an existing rule's form, whose pattern is fixed. Without it the form adds a rule, and
161- /// a pattern that already has one is refused rather than overwriting it.
162 #[serde(default)]137 #[serde(default)]
163 existing: Option<String>,138 existing: Option<String>,
164 }139 }
@@ -171,10 +146,9 @@ struct BranchDeleteForm {
171 rule_id: String,146 rule_id: String,
172 }147 }
173 148
174-/// Sets the notice shown on the next profile page view.149+fn set_cookie(cx: &Cx, name: &'static str, value: String) {
175-pub fn set_notice(cx: &Cx, title: &str) {
176 cookies(cx).add(150 cookies(cx).add(
177- Cookie::build((NOTICE_COOKIE, title.to_owned()))151+ Cookie::build((name, value))
178 .path("/")152 .path("/")
179 .http_only(true)153 .http_only(true)
180 .same_site(SameSite::Lax)154 .same_site(SameSite::Lax)
@@ -182,11 +156,19 @@ pub fn set_notice(cx: &Cx, title: &str) {
182 );156 );
183 }157 }
184 158
185-/// Reads and clears the notice cookie. Anything that is not a plain `owner/name` is ignored.159+fn take_cookie(cx: &Cx, name: &'static str) -> Option<String> {
186-pub fn take_notice(cx: &Cx) -> Option<String> {
187 let jar = cookies(cx);160 let jar = cookies(cx);
188- let value = jar.get(NOTICE_COOKIE)?.value().to_owned();161+ let value = jar.get(name)?.value().to_owned();
189- jar.remove(Cookie::build((NOTICE_COOKIE, "")).path("/"));162+ jar.remove(Cookie::build((name, "")).path("/"));
163+ Some(value)
164+}
165+
166+pub fn set_notice(cx: &Cx, title: &str) {
167+ set_cookie(cx, NOTICE_COOKIE, title.to_owned());
168+}
169+
170+pub fn take_notice(cx: &Cx) -> Option<String> {
171+ let value = take_cookie(cx, NOTICE_COOKIE)?;
190 let plain = !value.is_empty()172 let plain = !value.is_empty()
191 && value.chars().count() <= MAX_NOTICE_CHARS173 && value.chars().count() <= MAX_NOTICE_CHARS
192 && value174 && value
@@ -195,40 +177,26 @@ pub fn take_notice(cx: &Cx) -> Option<String> {
195 plain.then_some(value)177 plain.then_some(value)
196 }178 }
197 179
198-/// Sets the one-line notice shown on the next settings page view.
199 pub fn set_settings_notice(cx: &Cx, word: &'static str) {180 pub fn set_settings_notice(cx: &Cx, word: &'static str) {
200- cookies(cx).add(181+ set_cookie(cx, SETTINGS_NOTICE_COOKIE, word.to_owned());
201- Cookie::build((SETTINGS_NOTICE_COOKIE, word))
202- .path("/")
203- .http_only(true)
204- .same_site(SameSite::Lax)
205- .build(),
206- );
207 }182 }
208 183
209-/// Reads and clears the settings notice cookie. Only the fixed words are shown. The flag says
210-/// whether the notice is an error.
211 fn take_settings_notice(cx: &Cx) -> Option<(K, bool)> {184 fn take_settings_notice(cx: &Cx) -> Option<(K, bool)> {
212- let jar = cookies(cx);185+ let value = take_cookie(cx, SETTINGS_NOTICE_COOKIE)?;
213- let value = jar.get(SETTINGS_NOTICE_COOKIE)?.value().to_owned();
214- jar.remove(Cookie::build((SETTINGS_NOTICE_COOKIE, "")).path("/"));
215 SETTINGS_NOTICES186 SETTINGS_NOTICES
216 .iter()187 .iter()
217 .find(|(word, _, _)| *word == value)188 .find(|(word, _, _)| *word == value)
218 .map(|(_, key, is_error)| (*key, *is_error))189 .map(|(_, key, is_error)| (*key, *is_error))
219 }190 }
220 191
221-/// Redirect back to the General section, which shows the notice set just before.
222 fn back_to_settings(title: &str) -> SeeOther {192 fn back_to_settings(title: &str) -> SeeOther {
223 see_other(format!("/{title}/settings"))193 see_other(format!("/{title}/settings"))
224 }194 }
225 195
226-/// Redirect back to one section of the settings page (its `?section=` value).
227 fn back_to_section(title: &str, section: &str) -> SeeOther {196 fn back_to_section(title: &str, section: &str) -> SeeOther {
228 see_other(format!("/{title}/settings?section={section}"))197 see_other(format!("/{title}/settings?section={section}"))
229 }198 }
230 199
231-/// Drops control characters (so the text is one line) and surrounding spaces.
232 fn clean_description(raw: &str) -> String {200 fn clean_description(raw: &str) -> String {
233 raw.chars()201 raw.chars()
234 .filter(|c| !c.is_control())202 .filter(|c| !c.is_control())
@@ -237,8 +205,6 @@ fn clean_description(raw: &str) -> String {
237 .to_owned()205 .to_owned()
238 }206 }
239 207
240-/// Points git HEAD of the bare repo at `branch`. The caller has checked that the branch exists.
241-/// The `refs/heads/` prefix means the value can never be read as an option.
242 async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git::Result<()> {208 async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git::Result<()> {
243 GitCommand::new(env, "symbolic-ref")209 GitCommand::new(env, "symbolic-ref")
244 .git_dir(repo_path)210 .git_dir(repo_path)
@@ -248,7 +214,6 @@ async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git::
248 .await214 .await
249 }215 }
250 216
251-/// Branch names of the repo. Empty for an empty repo.
252 async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> {217 async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> {
253 let refs = load_refs(ctx.path.clone()).await?;218 let refs = load_refs(ctx.path.clone()).await?;
254 Ok(refs219 Ok(refs
@@ -258,7 +223,6 @@ async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> {
258 .collect())223 .collect())
259 }224 }
260 225
261-/// The one-line notice on the profile page after a delete.
262 #[component]226 #[component]
263 pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Result<impl View> {227 pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Result<impl View> {
264 Ok(view! {228 Ok(view! {
@@ -270,8 +234,6 @@ pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Re
270 })234 })
271 }235 }
272 236
273-/// What the danger zone's forms show when one came back with an error: the drafts the viewer typed and
274-/// the error each form got. A fresh page has the repo's own name in the rename form and nothing else.
275 pub struct DangerForms {237 pub struct DangerForms {
276 pub rename_name: String,238 pub rename_name: String,
277 pub rename_error: Option<String>,239 pub rename_error: Option<String>,
@@ -292,7 +254,6 @@ impl DangerForms {
292 }254 }
293 }255 }
294 256
295-/// The Visibility topic: the current value as a line, and the other side behind a confirm.
296 #[component]257 #[component]
297 async fn visibility_section(258 async fn visibility_section(
298 cx: &Cx,259 cx: &Cx,
@@ -331,7 +292,6 @@ async fn visibility_section(
331 })292 })
332 }293 }
333 294
334-/// The Archive topic: what archiving does, and the one action for the repo's state.
335 #[component]295 #[component]
336 async fn archive_section(296 async fn archive_section(
337 cx: &Cx,297 cx: &Cx,
@@ -359,9 +319,6 @@ async fn archive_section(
359 })319 })
360 }320 }
361 321
362-/// The danger zone, in order: Rename; Transfer, Visibility, Archive and Delete for a viewer who may
363-/// delete the repo (Transfer and Delete are hidden from the rest). Every topic is a `.sec` whose own
364-/// action is a small pill that opens its form or confirm in place.
365 #[component]322 #[component]
366 async fn danger_section(323 async fn danger_section(
367 cx: &Cx,324 cx: &Cx,
@@ -395,7 +352,6 @@ async fn danger_section(
395 })352 })
396 }353 }
397 354
398-/// The Delete topic: what deleting does, and the confirmation form, which opens in place.
399 #[component]355 #[component]
400 async fn delete_section(356 async fn delete_section(
401 cx: &Cx,357 cx: &Cx,
@@ -434,10 +390,6 @@ async fn delete_section(
434 })390 })
435 }391 }
436 392
437-/// The settings frame: the rail of settings pages beside the sheet holding the page's own content
438-/// (its children). Every settings page shows the same rail, one list of every page. `current` names
439-/// the page shown (`general`, `branches`, `webhooks`, ...) and marks its rail item. Every settings
440-/// page is for a repo admin, so the Danger zone is always listed.
441 #[component]393 #[component]
442 pub async fn settings_frame(394 pub async fn settings_frame(
443 cx: &Cx,395 cx: &Cx,
@@ -499,9 +451,6 @@ pub async fn settings_frame(
499 })451 })
500 }452 }
501 453
502-/// The General section: description and default branch in one form, under no heading (the page's
503-/// head names it), then the Features topic with one switch per feature. Each form carries its own
504-/// CSRF token. An empty repo shows "No branches yet" and no selector.
505 #[component]454 #[component]
506 async fn general_section(455 async fn general_section(
507 cx: &Cx,456 cx: &Cx,
@@ -554,8 +503,6 @@ async fn general_section(
554 })503 })
555 }504 }
556 505
557-/// Reads the rule settings from the form. Any problem is the message to show next to the form.
558-/// The message is for a `required_approvals` value outside 0..=20 or not a whole number.
559 fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFlags, String> {506 fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFlags, String> {
560 let approvals_msg = || g::t(lang, K::ApprovalsRange).to_owned();507 let approvals_msg = || g::t(lang, K::ApprovalsRange).to_owned();
561 let raw = form.required_approvals.trim();508 let raw = form.required_approvals.trim();
@@ -583,13 +530,11 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFl
583 })530 })
584 }531 }
585 532
586-/// One pill in a rule card's summary: its text and its classes.
587 struct RulePill {533 struct RulePill {
588 text: String,534 text: String,
589 class: &'static str,535 class: &'static str,
590 }536 }
591 537
592-/// The pills that describe a rule in its card summary. A rule that sets nothing gets one muted pill.
593 fn rule_pills(lang: Lang, rule: &BranchRule) -> Vec<RulePill> {538 fn rule_pills(lang: Lang, rule: &BranchRule) -> Vec<RulePill> {
594 let warn = "warn";539 let warn = "warn";
595 let plain = "";540 let plain = "";
@@ -634,7 +579,6 @@ fn pill(text: &str, class: &'static str) -> RulePill {
634 }579 }
635 }580 }
636 581
637-/// A rule as the settings page shows it: its id, its summary pills, and the form it opens with.
638 struct RuleCard {582 struct RuleCard {
639 id: String,583 id: String,
640 pills: Vec<RulePill>,584 pills: Vec<RulePill>,
@@ -642,11 +586,6 @@ struct RuleCard {
642 draft: RuleDraft,586 draft: RuleDraft,
643 }587 }
644 588
645-/// The rule list: a line per rule with its summary and an Edit word. The last line is the add line:
646-/// when no rule covers the default branch it also names that branch as protected by default, and
647-/// the add line opens the add form, prefilled with the default branch. A rule opens in place with its
648-/// rule's values, and the rule whose draft has an error opens with the draft instead. The add line
649-/// opens with the draft when no rule takes it. The rows share one `name`, so opening one closes the rest.
650 #[component]589 #[component]
651 async fn branch_rule_cards(590 async fn branch_rule_cards(
652 cx: &Cx,591 cx: &Cx,
@@ -699,11 +638,6 @@ async fn branch_rule_cards(
699 })638 })
700 }639 }
701 640
702-/// The rule form: the pattern (a new rule only), two groups of toggles, and the approvals and checks,
703-/// with the actions in one row under the form. The Pull requests group hides while Only through
704-/// pull requests is off, unless the rule already keeps a pull request setting, so a saved setting is
705-/// never hidden. The actions sit outside the form and submit it by its id, because forms cannot nest;
706-/// an existing rule's Remove action is a confirm_act beside them, on the same row.
707 #[component]641 #[component]
708 async fn branch_rule_form(642 async fn branch_rule_form(
709 cx: &Cx,643 cx: &Cx,
@@ -728,7 +662,6 @@ async fn branch_rule_form(
728 error,662 error,
729 is_new: _,663 is_new: _,
730 } = draft;664 } = draft;
731- // A pull request setting that is not the default keeps its group in view while the switch is off.
732 let pr_saved = !matches!(required_approvals.trim(), "" | "0")665 let pr_saved = !matches!(required_approvals.trim(), "" | "0")
733 || block_on_changes_requested666 || block_on_changes_requested
734 || require_up_to_date667 || require_up_to_date
@@ -739,7 +672,6 @@ async fn branch_rule_form(
739 } else {672 } else {
740 "rule-pr"673 "rule-pr"
741 };674 };
742- // Field ids are per rule, so two open rule forms never share an id.
743 let prefix = match &rule_id {675 let prefix = match &rule_id {
744 Some(id) => format!("rule-{id}"),676 Some(id) => format!("rule-{id}"),
745 None => "rule-new".to_owned(),677 None => "rule-new".to_owned(),
@@ -755,8 +687,6 @@ async fn branch_rule_form(
755 alert(message: message.as_str())687 alert(message: message.as_str())
756 }688 }
757 <input type="hidden" name="csrf" value=(csrf.as_str())>689 <input type="hidden" name="csrf" value=(csrf.as_str())>
758- // An existing rule's pattern is fixed: this form only changes what the rule does. A
759- // different pattern is a new rule, added from the Add rule line.
760 if rule_id.is_some() {690 if rule_id.is_some() {
761 <input type="hidden" name="pattern" value=(pattern.as_str())>691 <input type="hidden" name="pattern" value=(pattern.as_str())>
762 <input type="hidden" name="existing" value="1">692 <input type="hidden" name="existing" value="1">
@@ -837,7 +767,6 @@ async fn branch_rule_form(
837 })767 })
838 }768 }
839 769
840-/// The form values to show: the pattern and checkboxes, plus any validation error.
841 #[derive(Clone)]770 #[derive(Clone)]
842 struct RuleDraft {771 struct RuleDraft {
843 pattern: String,772 pattern: String,
@@ -850,12 +779,10 @@ struct RuleDraft {
850 require_merge_queue: bool,779 require_merge_queue: bool,
851 required_checks: String,780 required_checks: String,
852 error: Option<String>,781 error: Option<String>,
853- /// True for the New rule form's draft, so a refused new rule never opens an existing rule's card.
854 is_new: bool,782 is_new: bool,
855 }783 }
856 784
857 impl RuleDraft {785 impl RuleDraft {
858- /// The values a saved rule opens with.
859 fn from_rule(rule: &BranchRule) -> Self {786 fn from_rule(rule: &BranchRule) -> Self {
860 Self {787 Self {
861 pattern: rule.pattern.clone(),788 pattern: rule.pattern.clone(),
@@ -872,7 +799,6 @@ impl RuleDraft {
872 }799 }
873 }800 }
874 801
875- /// The default values for the add form, with the default branch as the pattern.
876 fn for_default_branch(default_branch: &str) -> Self {802 fn for_default_branch(default_branch: &str) -> Self {
877 Self {803 Self {
878 pattern: default_branch.to_owned(),804 pattern: default_branch.to_owned(),
@@ -890,21 +816,16 @@ impl RuleDraft {
890 }816 }
891 }817 }
892 818
893-/// Everything the settings page shows besides the repo header.
894 struct SettingsView {819 struct SettingsView {
895 rules: Vec<BranchRule>,820 rules: Vec<BranchRule>,
896- /// A settings notice: its text and whether it is an error.
897 notice: Option<(K, bool)>,821 notice: Option<(K, bool)>,
898 draft: RuleDraft,822 draft: RuleDraft,
899 danger: DangerForms,823 danger: DangerForms,
900 transfer: TransferStatus,824 transfer: TransferStatus,
901 wiki_on: bool,825 wiki_on: bool,
902- /// Recently reported status contexts, offered as required-check suggestions.
903 contexts: Vec<String>,826 contexts: Vec<String>,
904 }827 }
905 828
906-/// What a settings page shows: its section, a notice, a rule draft and the danger zone's forms. A
907-/// page drawn again after a refused POST passes what the viewer had typed.
908 pub struct Shown {829 pub struct Shown {
909 section: &'static str,830 section: &'static str,
910 notice: Option<(K, bool)>,831 notice: Option<(K, bool)>,
@@ -913,7 +834,6 @@ pub struct Shown {
913 }834 }
914 835
915 impl Shown {836 impl Shown {
916- /// The danger zone, with its forms as they came back.
917 pub fn danger(danger: DangerForms) -> Self {837 pub fn danger(danger: DangerForms) -> Self {
918 Self {838 Self {
919 section: "danger",839 section: "danger",
@@ -924,8 +844,6 @@ impl Shown {
924 }844 }
925 }845 }
926 846
927-/// Draws the settings page at `shown.section`. The page and every POST that is refused draw through
928-/// here, so a refused form comes back as the same page with its message.
929 pub async fn render_settings(847 pub async fn render_settings(
930 cx: &Cx,848 cx: &Cx,
931 ctx: RepoCtx,849 ctx: RepoCtx,
@@ -965,8 +883,6 @@ pub async fn render_settings(
965 })883 })
966 }884 }
967 885
968-/// The settings body: the repo header with Settings active, then the rail and one section (`section`:
969-/// general, branches or danger) in the sheet.
970 #[component]886 #[component]
971 async fn settings_body(887 async fn settings_body(
972 cx: &Cx,888 cx: &Cx,
@@ -996,8 +912,6 @@ async fn settings_body(
996 wiki_on,912 wiki_on,
997 contexts,913 contexts,
998 } = page;914 } = page;
999- // A card takes the draft when the draft has an error and the pattern is its rule's pattern.
1000- // Every other card opens with its saved values. A draft no card takes goes to the New rule card.
1001 let mut draft = Some(draft);915 let mut draft = Some(draft);
1002 let mut cards = Vec::with_capacity(rules.len());916 let mut cards = Vec::with_capacity(rules.len());
1003 for rule in rules {917 for rule in rules {
@@ -1016,9 +930,7 @@ async fn settings_body(
1016 });930 });
1017 }931 }
1018 let new_draft = draft.unwrap_or_else(|| RuleDraft::for_default_branch(&default_branch));932 let new_draft = draft.unwrap_or_else(|| RuleDraft::for_default_branch(&default_branch));
1019- // The New rule form stays collapsed unless its draft was rejected with an error.
1020 let mut new_open = new_draft.error.is_some();933 let mut new_open = new_draft.error.is_some();
1021- // The editor pane is never blank on arrival: the first rule, or the new rule if there is none.
1022 if !new_open && !cards.iter().any(|card| card.open) {934 if !new_open && !cards.iter().any(|card| card.open) {
1023 match cards.first_mut() {935 match cards.first_mut() {
1024 Some(first) => first.open = true,936 Some(first) => first.open = true,
@@ -1033,7 +945,6 @@ async fn settings_body(
1033 "danger" => g::t(lang, K::DangerZone),945 "danger" => g::t(lang, K::DangerZone),
1034 _ => g::t(lang, K::General),946 _ => g::t(lang, K::General),
1035 };947 };
1036- // Only one section is rendered.
1037 Ok(view! {948 Ok(view! {
1038 repo_head(head: head, title: Some(section_name.to_owned()))949 repo_head(head: head, title: Some(section_name.to_owned()))
1039 settings_frame(lang: lang, title: title.clone(), current: section,950 settings_frame(lang: lang, title: title.clone(), current: section,
@@ -1065,7 +976,6 @@ async fn settings_body(
1065 })976 })
1066 }977 }
1067 978
1068-/// The repo fields the settings page shows, read once from the repo context.
1069 struct SettingsFrame {979 struct SettingsFrame {
1070 page_title: String,980 page_title: String,
1071 default_branch: String,981 default_branch: String,
@@ -1077,7 +987,7 @@ struct SettingsFrame {
1077 987
1078 impl SettingsFrame {988 impl SettingsFrame {
1079 async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> {989 async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> {
1080- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);990+ let title = ctx.title();
1081 Ok(Self {991 Ok(Self {
1082 page_title: g::settings_page_title(lang, &title),992 page_title: g::settings_page_title(lang, &title),
1083 default_branch: ctx.repo.default_branch.clone(),993 default_branch: ctx.repo.default_branch.clone(),
@@ -1089,8 +999,6 @@ impl SettingsFrame {
1089 }999 }
1090 }1000 }
1091 1001
1092-/// Gets the settings page. Hidden repos are 404 (checked in `load_repo`), anonymous viewers of
1093-/// visible repos go to login, and signed-in viewers who may not manage the repo get 403.
1094 #[page("/{owner}/{repo}/settings")]1002 #[page("/{owner}/{repo}/settings")]
1095 async fn settings_page(cx: &Cx) -> Result<impl View> {1003 async fn settings_page(cx: &Cx) -> Result<impl View> {
1096 let owner = owner(cx);1004 let owner = owner(cx);
@@ -1111,9 +1019,6 @@ async fn settings_page(cx: &Cx) -> Result<impl View> {
1111 render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await1019 render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await
1112 }1020 }
1113 1021
1114-/// Saves the description and the default branch together. The form is checked for CSRF and
1115-/// `Action::Admin` first. The branch must be an existing branch: git HEAD is pointed at it first,
1116-/// and the database changes only when that succeeds. A failed database write puts HEAD back.
1117 #[route(POST "/{owner}/{repo}/settings/general")]1022 #[route(POST "/{owner}/{repo}/settings/general")]
1118 async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result<SeeOther> {1023 async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result<SeeOther> {
1119 let owner = owner(cx);1024 let owner = owner(cx);
@@ -1123,7 +1028,7 @@ async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result
1123 if !ctx.can_admin() {1028 if !ctx.can_admin() {
1124 return Err(forbidden().into());1029 return Err(forbidden().into());
1125 }1030 }
1126- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);1031+ let title = ctx.title();
1127 let state = context::<AppState>(cx);1032 let state = context::<AppState>(cx);
1128 1033
1129 let description = clean_description(&form.description);1034 let description = clean_description(&form.description);
@@ -1181,8 +1086,6 @@ async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result
1181 Ok(back_to_settings(&title))1086 Ok(back_to_settings(&title))
1182 }1087 }
1183 1088
1184-/// Changes the visibility. Changing it needs `understand`, which only the confirm popup sends. Picking the current value
1185-/// changes nothing.
1186 #[route(POST "/{owner}/{repo}/settings/visibility")]1089 #[route(POST "/{owner}/{repo}/settings/visibility")]
1187 async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) -> Result<SeeOther> {1090 async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) -> Result<SeeOther> {
1188 let owner = owner(cx);1091 let owner = owner(cx);
@@ -1192,7 +1095,7 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) ->
1192 if !ctx.can_admin() {1095 if !ctx.can_admin() {
1193 return Err(forbidden().into());1096 return Err(forbidden().into());
1194 }1097 }
1195- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);1098+ let title = ctx.title();
1196 let Ok(target) = form.visibility.parse::<Visibility>() else {1099 let Ok(target) = form.visibility.parse::<Visibility>() else {
1197 set_settings_notice(cx, "bad_form");1100 set_settings_notice(cx, "bad_form");
1198 return Ok(back_to_section(&title, "danger"));1101 return Ok(back_to_section(&title, "danger"));
@@ -1233,8 +1136,6 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) ->
1233 Ok(back_to_section(&title, "danger"))1136 Ok(back_to_section(&title, "danger"))
1234 }1137 }
1235 1138
1236-/// Archives (`archived=1`) or unarchives (`archived=0`) the repo. Archiving is an Admin action, and
1237-/// the archived flag does not block Admin.
1238 #[route(POST "/{owner}/{repo}/settings/archive")]1139 #[route(POST "/{owner}/{repo}/settings/archive")]
1239 async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result<SeeOther> {1140 async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result<SeeOther> {
1240 let owner = owner(cx);1141 let owner = owner(cx);
@@ -1244,7 +1145,7 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result
1244 if !ctx.can_admin() {1145 if !ctx.can_admin() {
1245 return Err(forbidden().into());1146 return Err(forbidden().into());
1246 }1147 }
1247- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);1148+ let title = ctx.title();
1248 let archived = match form.archived.as_str() {1149 let archived = match form.archived.as_str() {
1249 "1" => true,1150 "1" => true,
1250 "0" => false,1151 "0" => false,
@@ -1288,10 +1189,6 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result
1288 Ok(back_to_section(&title, "danger"))1189 Ok(back_to_section(&title, "danger"))
1289 }1190 }
1290 1191
1291-/// Deletes the repo when the viewer may delete it, the CSRF token is valid and the confirmation
1292-/// is exactly `owner/name`. On success the repo is moved to trash, its rows are deleted, and the
1293-/// viewer is redirected to the owner's repositories tab with a notice. If the database delete fails the directory goes back.
1294-/// A wrong confirmation re-renders the page with an error and changes nothing.
1295 #[page(POST "/{owner}/{repo}/settings/delete")]1192 #[page(POST "/{owner}/{repo}/settings/delete")]
1296 async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View> {1193 async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View> {
1297 let owner = owner(cx);1194 let owner = owner(cx);
@@ -1302,7 +1199,7 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1302 return Err(forbidden().into());1199 return Err(forbidden().into());
1303 }1200 }
1304 let lang = i18n::lang(cx, Some(&user));1201 let lang = i18n::lang(cx, Some(&user));
1305- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);1202+ let title = ctx.title();
1306 let error = if form.confirm.trim() == title {1203 let error = if form.confirm.trim() == title {
1307 None1204 None
1308 } else {1205 } else {
@@ -1313,8 +1210,7 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1313 let state = context::<AppState>(cx);1210 let state = context::<AppState>(cx);
1314 let repo: &RepoRow = &ctx.repo;1211 let repo: &RepoRow = &ctx.repo;
1315 let data_dir = &state.config.data_dir;1212 let data_dir = &state.config.data_dir;
1316- // A missing directory (already removed by hand) has nothing to trash, so only the rows go.1213+ let release_assets = state.store.repo_release_asset_ids(&repo.id).await?;
1317- // Any other failure to inspect or move the directory aborts before the database is touched.
1318 let trash_path = if repo_dir_missing(data_dir, &repo.id).map_err(forge_core::Error::from)? {1214 let trash_path = if repo_dir_missing(data_dir, &repo.id).map_err(forge_core::Error::from)? {
1319 tracing::warn!(repo_id = %repo.id, "repo dir missing, deleting DB rows only");1215 tracing::warn!(repo_id = %repo.id, "repo dir missing, deleting DB rows only");
1320 None1216 None
@@ -1325,7 +1221,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1325 .map_err(forge_core::Error::from)?,1221 .map_err(forge_core::Error::from)?,
1326 )1222 )
1327 };1223 };
1328- // The wiki goes to the trash with the repo. A failure here puts the repo back first.
1329 let wiki_trash = match move_wiki_to_trash(data_dir, &repo.id).await {1224 let wiki_trash = match move_wiki_to_trash(data_dir, &repo.id).await {
1330 Ok(path) => path,1225 Ok(path) => path,
1331 Err(e) => {1226 Err(e) => {
@@ -1338,8 +1233,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1338 return Err(forge_core::Error::from(e).into());1233 return Err(forge_core::Error::from(e).into());
1339 }1234 }
1340 };1235 };
1341- // Release assets: their rows go with the repo, so their blob ids are read first.
1342- let release_assets = state.store.repo_release_asset_ids(&repo.id).await?;
1343 let deleted = state.store.delete_repo(&repo.id).await;1236 let deleted = state.store.delete_repo(&repo.id).await;
1344 state.live.bump_repo(&repo.owner_id, &repo.id);1237 state.live.bump_repo(&repo.owner_id, &repo.id);
1345 if let Err(e) = deleted {1238 if let Err(e) = deleted {
@@ -1393,11 +1286,9 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1393 )1286 )
1394 .await;1287 .await;
1395 set_notice(cx, &title);1288 set_notice(cx, &title);
1396- // The owner's profile repository list shows the notice (the profile reads the cookie).
1397 return Err(see_other(format!("/{}?tab=repositories", enc(&ctx.repo.owner_name))).into());1289 return Err(see_other(format!("/{}?tab=repositories", enc(&ctx.repo.owner_name))).into());
1398 }1290 }
1399 1291
1400- // The delete form lives in the danger zone, so a failed confirmation draws that section again.
1401 let shown = Shown {1292 let shown = Shown {
1402 section: "danger",1293 section: "danger",
1403 notice: None,1294 notice: None,
@@ -1410,8 +1301,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
1410 render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await1301 render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await
1411 }1302 }
1412 1303
1413-/// Adds a branch rule or updates the one with the same pattern. The form is checked for CSRF and
1414-/// `Action::Admin` first. An invalid pattern re-renders the page with the error next to the form.
1415 #[page(POST "/{owner}/{repo}/settings/branches")]1304 #[page(POST "/{owner}/{repo}/settings/branches")]
1416 async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<impl View> {1305 async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<impl View> {
1417 let owner = owner(cx);1306 let owner = owner(cx);
@@ -1423,7 +1312,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
1423 }1312 }
1424 let lang = i18n::lang(cx, Some(&user));1313 let lang = i18n::lang(cx, Some(&user));
1425 let pattern = form.pattern.trim().to_owned();1314 let pattern = form.pattern.trim().to_owned();
1426- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);1315+ let title = ctx.title();
1427 1316
1428 let is_new = form.existing.is_none();1317 let is_new = form.existing.is_none();
1429 let taken = is_new1318 let taken = is_new
@@ -1491,7 +1380,6 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
1491 Err(back_to_section(&title, "branches").into())1380 Err(back_to_section(&title, "branches").into())
1492 }1381 }
1493 1382
1494-/// Removes a branch rule by id, scoped to this repo. Same checks as the save form.
1495 #[route(POST "/{owner}/{repo}/settings/branches/delete")]1383 #[route(POST "/{owner}/{repo}/settings/branches/delete")]
1496 async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) -> Result<SeeOther> {1384 async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) -> Result<SeeOther> {
1497 let owner = owner(cx);1385 let owner = owner(cx);
@@ -1520,7 +1408,7 @@ async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) ->
1520 )1408 )
1521 .await;1409 .await;
1522 set_settings_notice(cx, "removed");1410 set_settings_notice(cx, "removed");
1523- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);1411+ let title = ctx.title();
1524 Ok(back_to_section(&title, "branches"))1412 Ok(back_to_section(&title, "branches"))
1525 }1413 }
1526 1414
@@ -1536,7 +1424,6 @@ mod tests {
1536 1424
1537 const CSRF: &str = "settings-test-csrf";1425 const CSRF: &str = "settings-test-csrf";
1538 1426
1539- /// Posts the branch form as `tahinli` and returns the status and body.
1540 async fn post_rule(app: &Router, cookie: &str, fields: &[(&str, &str)]) -> (u16, String) {1427 async fn post_rule(app: &Router, cookie: &str, fields: &[(&str, &str)]) -> (u16, String) {
1541 let mut form = form_urlencoded::Serializer::new(String::new());1428 let mut form = form_urlencoded::Serializer::new(String::new());
1542 form.append_pair("csrf", CSRF);1429 form.append_pair("csrf", CSRF);
@@ -1600,7 +1487,6 @@ mod tests {
1600 assert!(rule.restrict_push);1487 assert!(rule.restrict_push);
1601 assert!(!rule.allow_force_push && !rule.allow_deletion);1488 assert!(!rule.allow_force_push && !rule.allow_deletion);
1602 1489
1603- // A blank count means 0 and unchecked boxes are off.
1604 let (status, _) = post_rule(1490 let (status, _) = post_rule(
1605 &app,1491 &app,
1606 &cookie,1492 &cookie,
@@ -1618,7 +1504,6 @@ mod tests {
1618 !rule.block_on_changes_requested && !rule.require_up_to_date && !rule.restrict_push1504 !rule.block_on_changes_requested && !rule.require_up_to_date && !rule.restrict_push
1619 );1505 );
1620 1506
1621- // Out of range re-renders the form with the error and saves nothing.
1622 let (status, body) = post_rule(1507 let (status, body) = post_rule(
1623 &app,1508 &app,
1624 &cookie,1509 &cookie,
@@ -1639,7 +1524,6 @@ mod tests {
1639 assert_eq!(rule.required_approvals, 0);1524 assert_eq!(rule.required_approvals, 0);
1640 assert!(!rule.restrict_push);1525 assert!(!rule.restrict_push);
1641 1526
1642- // Not a number is refused the same way.
1643 let (status, body) = post_rule(1527 let (status, body) = post_rule(
1644 &app,1528 &app,
1645 &cookie,1529 &cookie,
crates/forge-web-pages/src/pages/tree.rsmodified+3 -6
@@ -125,21 +125,18 @@ pub struct LatestBar {
125 pub author: String,125 pub author: String,
126 }126 }
127 127
128-/// Latest commit bar for `dir` at `commit` (`""` is the root). Errors and timeouts leave the bar128+/// Latest commit bar at `commit`. Errors and timeouts leave the bar out.
129-/// out.
130 pub async fn latest_bar(129 pub async fn latest_bar(
131 state: &AppState,130 state: &AppState,
132 repo: &RepoRow,131 repo: &RepoRow,
133 path: &Path,132 path: &Path,
134 commit: &str,133 commit: &str,
135- dir: &str,
136 lang: Lang,134 lang: Lang,
137 tz: &str,135 tz: &str,
138 ) -> Option<LatestBar> {136 ) -> Option<LatestBar> {
139- let filter = (!dir.is_empty()).then_some(dir);
140 let log = tokio::time::timeout(137 let log = tokio::time::timeout(
141 LAST_COMMIT_TIMEOUT,138 LAST_COMMIT_TIMEOUT,
142- history::log(&state.git, path, commit, filter, 0, 1),139+ history::log(&state.git, path, commit, None, 0, 1),
143 )140 )
144 .await;141 .await;
145 let info = match log {142 let info = match log {
@@ -476,7 +473,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
476 };473 };
477 let (last, bar, strip, runs) = tokio::join!(474 let (last, bar, strip, runs) = tokio::join!(
478 last_commits(state, &ctx.path, &commit, &dir, &names),475 last_commits(state, &ctx.path, &commit, &dir, &names),
479- latest_bar(state, repo, &ctx.path, &commit, "", lang, ctx.viewer_tz()),476+ latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()),
480 commit_strip(state, repo, &ctx.path, &commit),477 commit_strip(state, repo, &ctx.path, &commit),
481 run_rows(state, lang, repo),478 run_rows(state, lang, repo),
482 );479 );
crates/forge-web-pages/src/pages/wiki.rsmodified+7 -14
@@ -364,16 +364,6 @@ async fn wiki_edit_body(
364 })364 })
365 }365 }
366 366
367-/// Reads the page `name` and the wiki head in one blocking call.
368-async fn load_page(dir: PathBuf, name: String) -> Result<(Option<String>, Option<String>)> {
369- blocking(move || {
370- let head = wiki::head_commit(&dir)?;
371- let text = wiki::read_page(&dir, &name)?;
372- Ok((head, text))
373- })
374- .await
375-}
376-
377 #[page("/{owner}/{repo}/wiki")]367 #[page("/{owner}/{repo}/wiki")]
378 async fn wiki_home(cx: &Cx) -> Result<impl View> {368 async fn wiki_home(cx: &Cx) -> Result<impl View> {
379 let owner = owner(cx);369 let owner = owner(cx);
@@ -383,7 +373,7 @@ async fn wiki_home(cx: &Cx) -> Result<impl View> {
383 ensure_enabled(state, &ctx).await?;373 ensure_enabled(state, &ctx).await?;
384 let dir = wiki_dir(state, &ctx)?;374 let dir = wiki_dir(state, &ctx)?;
385 let names = page_names(dir.clone()).await?;375 let names = page_names(dir.clone()).await?;
386- let (_, home) = load_page(dir, "Home".to_owned()).await?;376+ let home = blocking(move || wiki::read_page(&dir, "Home")).await?;
387 let can_write = ctx.can_write();377 let can_write = ctx.can_write();
388 let owner_name = ctx.repo.owner_name.clone();378 let owner_name = ctx.repo.owner_name.clone();
389 let repo_name = ctx.repo.name.clone();379 let repo_name = ctx.repo.name.clone();
@@ -469,7 +459,8 @@ async fn wiki_page_view(cx: &Cx) -> Result<impl View> {
469 }459 }
470 let dir = wiki_dir(state, &ctx)?;460 let dir = wiki_dir(state, &ctx)?;
471 let names = page_names(dir.clone()).await?;461 let names = page_names(dir.clone()).await?;
472- let (_, text) = load_page(dir, page_name.clone()).await?;462+ let name = page_name.clone();
463+ let text = blocking(move || wiki::read_page(&dir, &name)).await?;
473 let Some(text) = text else {464 let Some(text) = text else {
474 return Err(not_found().into());465 return Err(not_found().into());
475 };466 };
@@ -646,7 +637,8 @@ async fn wiki_edit_page(cx: &Cx) -> Result<impl View> {
646 return Err(not_found().into());637 return Err(not_found().into());
647 }638 }
648 let dir = wiki_dir(state, &ctx)?;639 let dir = wiki_dir(state, &ctx)?;
649- let (_, text) = load_page(dir, page_name.clone()).await?;640+ let name = page_name.clone();
641+ let text = blocking(move || wiki::read_page(&dir, &name)).await?;
650 edit_screen(cx, ctx, page_name, false, text.unwrap_or_default(), None).await642 edit_screen(cx, ctx, page_name, false, text.unwrap_or_default(), None).await
651 }643 }
652 644
@@ -667,7 +659,8 @@ async fn wiki_new_post(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View>
667 Some(g::t(lang, K::PageNameRules).to_owned())659 Some(g::t(lang, K::PageNameRules).to_owned())
668 } else {660 } else {
669 let dir = wiki_dir(state, &ctx)?;661 let dir = wiki_dir(state, &ctx)?;
670- let (_, existing) = load_page(dir, name.clone()).await?;662+ let check = name.clone();
663+ let existing = blocking(move || wiki::read_page(&dir, &check)).await?;
671 if existing.is_some() {664 if existing.is_some() {
672 Some(g::t(lang, K::PageExists).to_owned())665 Some(g::t(lang, K::PageExists).to_owned())
673 } else {666 } else {
crates/forge-web-repo/src/pages/authoring.rsmodified+7 -43
@@ -29,7 +29,7 @@ use crate::api;
29 use crate::auth::{current_user, require_csrf};29 use crate::auth::{current_user, require_csrf};
30 use crate::blobs::attachment_key;30 use crate::blobs::attachment_key;
31 use crate::pages::issue_parts::{ItemKind, comment_for, item_for, may_change, parse_number};31 use crate::pages::issue_parts::{ItemKind, comment_for, item_for, may_change, parse_number};
32-use crate::pages::repo_ctx::load_repo;32+use crate::pages::repo_ctx::{access, load_repo};
33 use crate::render::markdown::{set_task, task_progress};33 use crate::render::markdown::{set_task, task_progress};
34 use crate::state::AppState;34 use crate::state::AppState;
35 35
@@ -86,33 +86,6 @@ pub fn clean_name(raw: &str) -> String {
86 out86 out
87 }87 }
88 88
89-/// Decodes `%XX` escapes and `+` in a query value; invalid escapes are kept as typed.
90-fn percent_decode(input: &str) -> String {
91- let bytes = input.as_bytes();
92- let mut out = Vec::with_capacity(bytes.len());
93- let mut i = 0;
94- while i < bytes.len() {
95- match bytes[i] {
96- b'+' => out.push(b' '),
97- b'%' if i + 2 < bytes.len() => {
98- let hex = std::str::from_utf8(&bytes[i + 1..i + 3])
99- .ok()
100- .and_then(|h| u8::from_str_radix(h, 16).ok());
101- match hex {
102- Some(b) => {
103- out.push(b);
104- i += 2;
105- }
106- None => out.push(b'%'),
107- }
108- }
109- b => out.push(b),
110- }
111- i += 1;
112- }
113- String::from_utf8_lossy(&out).into_owned()
114-}
115-
116 fn fail(status: StatusCode, message: &str) -> Response {89 fn fail(status: StatusCode, message: &str) -> Response {
117 api::error(status, message)90 api::error(status, message)
118 }91 }
@@ -239,17 +212,8 @@ async fn download(cx: &Cx) -> Result<Response> {
239 return Err(not_found().into());212 return Err(not_found().into());
240 };213 };
241 let viewer = current_user(cx).await?;214 let viewer = current_user(cx).await?;
242- let (role, org_role) = match &viewer {
243- Some((user, _)) => (
244- state.store.collaborator_role(&repo.id, &user.id).await?,
245- state
246- .store
247- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
248- .await?,
249- ),
250- None => (None, None),
251- };
252 let actor = viewer.as_ref().map(|(user, _)| user);215 let actor = viewer.as_ref().map(|(user, _)| user);
216+ let (role, org_role) = access(&state.store, actor, &repo).await?;
253 if authorize(actor, &repo, role, org_role, Action::Read).is_err() {217 if authorize(actor, &repo, role, org_role, Action::Read).is_err() {
254 return Err(not_found().into());218 return Err(not_found().into());
255 }219 }
@@ -296,11 +260,11 @@ async fn suggest(cx: &Cx) -> Result<Response> {
296 }260 }
297 let mut kind = "";261 let mut kind = "";
298 let mut q = String::new();262 let mut q = String::new();
299- for pair in uri(cx).query().unwrap_or_default().split('&') {263+ for (key, value) in form_urlencoded::parse(uri(cx).query().unwrap_or_default().as_bytes()) {
300- if let Some(v) = pair.strip_prefix("kind=") {264+ match &*key {
301- kind = if v == "issue" { "issue" } else { "user" };265+ "kind" => kind = if value == "issue" { "issue" } else { "user" },
302- } else if let Some(v) = pair.strip_prefix("q=") {266+ "q" => q = value.into_owned(),
303- q = percent_decode(v);267+ _ => {}
304 }268 }
305 }269 }
306 let q: String = q.chars().take(60).collect();270 let q: String = q.chars().take(60).collect();
crates/forge-web-repo/src/pages/blame.rsmodified+4 -21
@@ -16,7 +16,7 @@ use crate::i18n::browse as b;
16 use crate::i18n::code::{self as g, K};16 use crate::i18n::code::{self as g, K};
17 use crate::i18n::s;17 use crate::i18n::s;
18 use crate::i18n::{self, Lang};18 use crate::i18n::{self, Lang};
19-use crate::pages::blob::{Line, text_lines};19+use crate::pages::blob::{Line, file_href, is_markdown, text_lines};
20 use crate::pages::ref_live;20 use crate::pages::ref_live;
21 use crate::pages::repo::repo_head;21 use crate::pages::repo::repo_head;
22 use crate::pages::repo_ctx::load_repo;22 use crate::pages::repo_ctx::load_repo;
@@ -191,31 +191,14 @@ async fn blame_page(cx: &Cx) -> Result<impl View> {
191 }191 }
192 }192 }
193 193
194- let blob_href = repo_href(194+ let blob_href = file_href(&repo.owner_name, &repo.name, "blob", &ref_name, &file);
195- &repo.owner_name,
196- &repo.name,
197- "blob",
198- &format!("{ref_name}/{file}"),
199- );
200 // Blame sits beside the file's source: a markdown file's plain view, any other file's own page.195 // Blame sits beside the file's source: a markdown file's plain view, any other file's own page.
201- let markdown = matches!(196+ let source_href = if is_markdown(&file_name) {
202- file_name
203- .rsplit_once('.')
204- .map(|(_, ext)| ext.to_ascii_lowercase())
205- .as_deref(),
206- Some("md" | "markdown")
207- );
208- let source_href = if markdown {
209 format!("{blob_href}?plain=1")197 format!("{blob_href}?plain=1")
210 } else {198 } else {
211 blob_href.clone()199 blob_href.clone()
212 };200 };
213- let history = repo_href(201+ let history = file_href(&repo.owner_name, &repo.name, "commits", &ref_name, &file);
214- &repo.owner_name,
215- &repo.name,
216- "commits",
217- &format!("{ref_name}/{file}"),
218- );
219 let title = format!(202 let title = format!(
220 "{}/{} \u{b7} {} \u{b7} {file}",203 "{}/{} \u{b7} {} \u{b7} {file}",
221 repo.owner_name,204 repo.owner_name,
crates/forge-web-repo/src/pages/blob.rsmodified+49 -81
@@ -45,21 +45,25 @@ struct BlobQuery {
45 }45 }
46 46
47 /// One line of a text file. `highlighted` is true when `code` is trusted highlighter output.47 /// One line of a text file. `highlighted` is true when `code` is trusted highlighter output.
48+#[derive(Clone)]
48 pub struct Line {49 pub struct Line {
49 pub num: String,50 pub num: String,
50 pub code: String,51 pub code: String,
51 pub highlighted: bool,52 pub highlighted: bool,
52 }53 }
53 54
54-/// What the page shows for the file. `kind` is one of: image, submodule, symlink, binary,55+enum ViewerKind {
55-/// markdown, text.56+ Submodule(String),
57+ Symlink(String),
58+ Lfs(String),
59+ Image,
60+ Binary(String),
61+ Markdown(String),
62+ Text(Vec<Line>),
63+}
64+
56 struct Viewer {65 struct Viewer {
57- kind: &'static str,66+ kind: ViewerKind,
58- /// Notice text: the symlink target, the submodule commit, or the binary size.
59- note: String,
60- /// Rendered markdown (trusted output of `render_markdown`).
61- html: String,
62- lines: Vec<Line>,
63 truncated: bool,67 truncated: bool,
64 }68 }
65 69
@@ -69,6 +73,14 @@ fn extension(name: &str) -> String {
69 .unwrap_or_default()73 .unwrap_or_default()
70 }74 }
71 75
76+pub fn is_markdown(name: &str) -> bool {
77+ MARKDOWN_EXTS.contains(&extension(name).as_str())
78+}
79+
80+pub fn file_href(owner: &str, name: &str, verb: &str, ref_name: &str, file: &str) -> String {
81+ repo_href(owner, name, verb, &format!("{ref_name}/{file}"))
82+}
83+
72 pub fn text_lines(text: &str, file_name: &str) -> Vec<Line> {84 pub fn text_lines(text: &str, file_name: &str) -> Vec<Line> {
73 let plain: Vec<&str> = text.lines().collect();85 let plain: Vec<&str> = text.lines().collect();
74 let highlighted = highlight_lines(file_name, text).filter(|h| h.len() == plain.len());86 let highlighted = highlight_lines(file_name, text).filter(|h| h.len() == plain.len());
@@ -140,7 +152,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
140 .unwrap_or("")152 .unwrap_or("")
141 .to_owned();153 .to_owned();
142 let ext = extension(&file_name);154 let ext = extension(&file_name);
143- let is_markdown = MARKDOWN_EXTS.contains(&ext.as_str());155+ let is_markdown = is_markdown(&file_name);
144 156
145 // A Git LFS pointer is a small text blob that names an object the forge stores.157 // A Git LFS pointer is a small text blob that names an object the forge stores.
146 let pointer = match blob.kind {158 let pointer = match blob.kind {
@@ -158,7 +170,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
158 Ok(None) => (Some(g::lfs_missing(lang, &size)), None),170 Ok(None) => (Some(g::lfs_missing(lang, &size)), None),
159 Err(e) => {171 Err(e) => {
160 tracing::warn!(error = %e, "blob: LFS object link lookup failed");172 tracing::warn!(error = %e, "blob: LFS object link lookup failed");
161- (Some(g::lfs_stored(lang, &size)), None)173+ (None, None)
162 }174 }
163 }175 }
164 }176 }
@@ -167,38 +179,23 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
167 179
168 let viewer = match blob.kind {180 let viewer = match blob.kind {
169 EntryKind::Submodule => Viewer {181 EntryKind::Submodule => Viewer {
170- kind: "submodule",182+ kind: ViewerKind::Submodule(blob.oid.clone()),
171- note: blob.oid.clone(),
172- html: String::new(),
173- lines: Vec::new(),
174 truncated: false,183 truncated: false,
175 },184 },
176 EntryKind::Symlink => Viewer {185 EntryKind::Symlink => Viewer {
177- kind: "symlink",186+ kind: ViewerKind::Symlink(String::from_utf8_lossy(&blob.data).into_owned()),
178- note: String::from_utf8_lossy(&blob.data).into_owned(),
179- html: String::new(),
180- lines: Vec::new(),
181 truncated: false,187 truncated: false,
182 },188 },
183 _ if lfs_note.is_some() => Viewer {189 _ if lfs_note.is_some() => Viewer {
184- kind: "lfs",190+ kind: ViewerKind::Lfs(lfs_note.clone().unwrap_or_default()),
185- note: lfs_note.clone().unwrap_or_default(),
186- html: String::new(),
187- lines: Vec::new(),
188 truncated: false,191 truncated: false,
189 },192 },
190 _ if IMAGE_EXTS.contains(&ext.as_str()) => Viewer {193 _ if IMAGE_EXTS.contains(&ext.as_str()) => Viewer {
191- kind: "image",194+ kind: ViewerKind::Image,
192- note: String::new(),
193- html: String::new(),
194- lines: Vec::new(),
195 truncated: blob.truncated,195 truncated: blob.truncated,
196 },196 },
197 _ if blob.is_binary => Viewer {197 _ if blob.is_binary => Viewer {
198- kind: "binary",198+ kind: ViewerKind::Binary(g::binary_note(lang, blob.size)),
199- note: g::binary_note(lang, blob.size),
200- html: String::new(),
201- lines: Vec::new(),
202 truncated: false,199 truncated: false,
203 },200 },
204 _ => {201 _ => {
@@ -206,18 +203,12 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
206 if is_markdown && !plain {203 if is_markdown && !plain {
207 let link_ctx = link_context(state, repo, &ref_name, &dir);204 let link_ctx = link_context(state, repo, &ref_name, &dir);
208 Viewer {205 Viewer {
209- kind: "markdown",206+ kind: ViewerKind::Markdown(render_markdown(&text, Some(&link_ctx))),
210- note: String::new(),
211- html: render_markdown(&text, Some(&link_ctx)),
212- lines: Vec::new(),
213 truncated: blob.truncated,207 truncated: blob.truncated,
214 }208 }
215 } else {209 } else {
216 Viewer {210 Viewer {
217- kind: "text",211+ kind: ViewerKind::Text(text_lines(&text, &file_name)),
218- note: String::new(),
219- html: String::new(),
220- lines: text_lines(&text, &file_name),
221 truncated: blob.truncated,212 truncated: blob.truncated,
222 }213 }
223 }214 }
@@ -225,38 +216,17 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
225 };216 };
226 217
227 let raw = raw_url(state, repo, &ref_name, &file);218 let raw = raw_url(state, repo, &ref_name, &file);
228- let base = repo_href(219+ let base = file_href(&repo.owner_name, &repo.name, "blob", &ref_name, &file);
229- &repo.owner_name,220+ let history = file_href(&repo.owner_name, &repo.name, "commits", &ref_name, &file);
230- &repo.name,221+ let blame = file_href(&repo.owner_name, &repo.name, "blame", &ref_name, &file);
231- "blob",
232- &format!("{ref_name}/{file}"),
233- );
234- let history = repo_href(
235- &repo.owner_name,
236- &repo.name,
237- "commits",
238- &format!("{ref_name}/{file}"),
239- );
240- let blame = repo_href(
241- &repo.owner_name,
242- &repo.name,
243- "blame",
244- &format!("{ref_name}/{file}"),
245- );
246 // The same file pinned to this exact commit, for sharing and for the `y` shortcut.222 // The same file pinned to this exact commit, for sharing and for the `y` shortcut.
247- let permalink = repo_href(223+ let permalink = file_href(&repo.owner_name, &repo.name, "blob", &commit, &file);
248- &repo.owner_name,
249- &repo.name,
250- "blob",
251- &format!("{commit}/{file}"),
252- );
253 let finder_owner = repo.owner_name.clone();224 let finder_owner = repo.owner_name.clone();
254 let finder_repo = repo.name.clone();225 let finder_repo = repo.name.clone();
255 let finder_ref = ref_name.clone();226 let finder_ref = ref_name.clone();
256 let title = format!("{}/{} \u{b7} {file}", repo.owner_name, repo.name);227 let title = format!("{}/{} \u{b7} {file}", repo.owner_name, repo.name);
257 228
258- let kind = viewer.kind;229+ let is_text = matches!(viewer.kind, ViewerKind::Text(_));
259- let is_text = kind == "text";
260 // The ways to read the file, one switch with the current one marked, the same on every view of230 // The ways to read the file, one switch with the current one marked, the same on every view of
261 // it: Rendered and Source for markdown, Source alone otherwise, and Blame for any text.231 // it: Rendered and Source for markdown, Source alone otherwise, and Blame for any text.
262 let mut views: Vec<(&'static str, String, bool)> = Vec::new();232 let mut views: Vec<(&'static str, String, bool)> = Vec::new();
@@ -274,9 +244,6 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
274 if can_blame {244 if can_blame {
275 views.push((b::t(lang, b::K::BlameLink), blame.clone(), false));245 views.push((b::t(lang, b::K::BlameLink), blame.clone(), false));
276 }246 }
277- let note = viewer.note;
278- let html = viewer.html;
279- let lines = viewer.lines;
280 let truncated = viewer.truncated;247 let truncated = viewer.truncated;
281 let image_alt = file_name.clone();248 let image_alt = file_name.clone();
282 let download_name = file_name.clone();249 let download_name = file_name.clone();
@@ -301,7 +268,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
301 };268 };
302 let (last, bar, strip, runs) = tokio::join!(269 let (last, bar, strip, runs) = tokio::join!(
303 last_commits(state, &ctx.path, &commit, &dir, &names),270 last_commits(state, &ctx.path, &commit, &dir, &names),
304- latest_bar(state, repo, &ctx.path, &commit, "", lang, ctx.viewer_tz()),271+ latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()),
305 commit_strip(state, repo, &ctx.path, &commit),272 commit_strip(state, repo, &ctx.path, &commit),
306 run_rows(state, lang, repo),273 run_rows(state, lang, repo),
307 );274 );
@@ -325,10 +292,11 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
325 let mut header = ctx.head(state, "code").await?;292 let mut header = ctx.head(state, "code").await?;
326 header.live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name);293 header.live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name);
327 let size = human_size(lang, blob.size);294 let size = human_size(lang, blob.size);
328- let size_line = if is_text {295+ let size_line = match &viewer.kind {
329- format!("{} {}, {size}", lines.len(), s(lang, "lines", "satır"))296+ ViewerKind::Text(lines) => {
330- } else {297+ format!("{} {}, {size}", lines.len(), s(lang, "lines", "satır"))
331- size298+ }
299+ _ => size,
332 };300 };
333 Ok(view! {301 Ok(view! {
334 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),302 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
@@ -363,27 +331,27 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
363 }331 }
364 </div>332 </div>
365 <section class="file" data-lines="" data-permalink=(permalink.as_str())>333 <section class="file" data-lines="" data-permalink=(permalink.as_str())>
366- if kind == "image" {334+ if let ViewerKind::Image = &viewer.kind {
367 <div class="file-image">335 <div class="file-image">
368 <img src=(raw.clone()) alt=(image_alt)>336 <img src=(raw.clone()) alt=(image_alt)>
369 </div>337 </div>
370 }338 }
371- if kind == "markdown" {339+ if let ViewerKind::Markdown(html) = &viewer.kind {
372- <div class="markdown-body">(Unescaped::new_unchecked(html))</div>340+ <div class="markdown-body">(Unescaped::new_unchecked(html.clone()))</div>
373 }341 }
374- if kind == "text" {342+ if let ViewerKind::Text(lines) = &viewer.kind {
375- file_table(lines: lines)343+ file_table(lines: lines.clone())
376 }344 }
377- if kind == "lfs" {345+ if let ViewerKind::Lfs(note) = &viewer.kind {
378 <p class="state">(note.clone())</p>346 <p class="state">(note.clone())</p>
379 }347 }
380- if kind == "binary" {348+ if let ViewerKind::Binary(note) = &viewer.kind {
381 <p class="state">(note.clone())</p>349 <p class="state">(note.clone())</p>
382 }350 }
383- if kind == "symlink" {351+ if let ViewerKind::Symlink(note) = &viewer.kind {
384 <p class="state">(g::t(lang, K::SymlinkPrefix)) <code>(note.clone())</code></p>352 <p class="state">(g::t(lang, K::SymlinkPrefix)) <code>(note.clone())</code></p>
385 }353 }
386- if kind == "submodule" {354+ if let ViewerKind::Submodule(note) = &viewer.kind {
387 <p class="state">(g::t(lang, K::SubmodulePrefix)) <code>(note.clone())</code> (g::t(lang, K::SubmoduleSuffix))</p>355 <p class="state">(g::t(lang, K::SubmodulePrefix)) <code>(note.clone())</code> (g::t(lang, K::SubmoduleSuffix))</p>
388 }356 }
389 if truncated {357 if truncated {
crates/forge-web-repo/src/pages/browse_tests.rsmodified+20 -43
@@ -1,6 +1,3 @@
1-//! Page tests for the code-browsing upgrades: diff toolbar, whitespace and split views, patch and
2-//! diff downloads, the file list endpoint, the branches page and the default-branch setting.
3-
4 use forge_core::Visibility;1 use forge_core::Visibility;
5 use forge_core::protection::RuleFlags;2 use forge_core::protection::RuleFlags;
6 use topcoat::router::request::Request;3 use topcoat::router::request::Request;
@@ -49,7 +46,6 @@ async fn send(
49 )46 )
50 }47 }
51 48
52-/// A commit whose changes are a whitespace-only edit of `a.txt` and a real edit of `ws.txt`.
53 fn whitespace_commit(fx: &Fixture) -> String {49 fn whitespace_commit(fx: &Fixture) -> String {
54 std::fs::write(fx.work.join("ws.txt"), "x\ny\n").unwrap();50 std::fs::write(fx.work.join("ws.txt"), "x\ny\n").unwrap();
55 git(&fx.work, &["add", "-A"]);51 git(&fx.work, &["add", "-A"]);
@@ -71,7 +67,6 @@ fn whitespace_commit(fx: &Fixture) -> String {
71 oid67 oid
72 }68 }
73 69
74-/// The commit toolbar, and the whitespace toggle that hides whitespace-only files.
75 async fn scenario_whitespace_toolbar(fx: &Fixture) {70 async fn scenario_whitespace_toolbar(fx: &Fixture) {
76 let oid = whitespace_commit(fx);71 let oid = whitespace_commit(fx);
77 let base = format!("/{OWNER}/{REPO}/commit/{oid}");72 let base = format!("/{OWNER}/{REPO}/commit/{oid}");
@@ -84,7 +79,6 @@ async fn scenario_whitespace_toolbar(fx: &Fixture) {
84 assert!(html.contains(&format!("{base}.diff")));79 assert!(html.contains(&format!("{base}.diff")));
85 assert!(html.contains("a.txt"));80 assert!(html.contains("a.txt"));
86 assert!(html.contains("ws.txt"));81 assert!(html.contains("ws.txt"));
87- // The toggle links to the same page with w=1.
88 assert!(html.contains("w=1"));82 assert!(html.contains("w=1"));
89 83
90 let (_, _, body) = get(&fx.router, &format!("{base}?w=1")).await;84 let (_, _, body) = get(&fx.router, &format!("{base}?w=1")).await;
@@ -98,7 +92,6 @@ async fn scenario_whitespace_toolbar(fx: &Fixture) {
98 assert!(main.contains("aria-pressed=\"true\""));92 assert!(main.contains("aria-pressed=\"true\""));
99 }93 }
100 94
101-/// The split view renders two sides and is remembered in a cookie.
102 async fn scenario_split_view(fx: &Fixture) {95 async fn scenario_split_view(fx: &Fixture) {
103 let uri = format!("/{OWNER}/{REPO}/commit/{}?view=split", fx.modified);96 let uri = format!("/{OWNER}/{REPO}/commit/{}?view=split", fx.modified);
104 97
@@ -107,7 +100,6 @@ async fn scenario_split_view(fx: &Fixture) {
107 let html = String::from_utf8(body).unwrap();100 let html = String::from_utf8(body).unwrap();
108 assert!(html.contains("diff-split"));101 assert!(html.contains("diff-split"));
109 assert!(html.contains("diff-split-row"));102 assert!(html.contains("diff-split-row"));
110- // The deleted "two" and the added "TWO" sit in one row.
111 let row = html103 let row = html
112 .split("diff-split-row")104 .split("diff-split-row")
113 .find(|r| r.contains("-two") && r.contains("+TWO"))105 .find(|r| r.contains("-two") && r.contains("+TWO"))
@@ -121,7 +113,6 @@ async fn scenario_split_view(fx: &Fixture) {
121 .expect("view cookie");113 .expect("view cookie");
122 assert!(cookie.starts_with("forge_diff=split"));114 assert!(cookie.starts_with("forge_diff=split"));
123 115
124- // With the cookie and no query, the page is split; ?view=unified switches back.
125 let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);116 let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);
126 let req = Request::builder()117 let req = Request::builder()
127 .method("GET")118 .method("GET")
@@ -136,7 +127,6 @@ async fn scenario_split_view(fx: &Fixture) {
136 assert!(!String::from_utf8(body).unwrap().contains("diff-split-row"));127 assert!(!String::from_utf8(body).unwrap().contains("diff-split-row"));
137 }128 }
138 129
139-/// Patch and diff downloads for a commit and a root commit, and 404s for bad or private ones.
140 async fn scenario_patch_and_diff(fx: &Fixture) {130 async fn scenario_patch_and_diff(fx: &Fixture) {
141 let base = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);131 let base = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);
142 132
@@ -159,7 +149,6 @@ async fn scenario_patch_and_diff(fx: &Fixture) {
159 assert!(text.starts_with("diff --git a/a.txt b/a.txt"));149 assert!(text.starts_with("diff --git a/a.txt b/a.txt"));
160 assert!(!text.contains("Subject:"));150 assert!(!text.contains("Subject:"));
161 151
162- // Root commits work.
163 let (status, _, _) = get(152 let (status, _, _) = get(
164 &fx.router,153 &fx.router,
165 &format!("/{OWNER}/{REPO}/commit/{}.patch", fx.root),154 &format!("/{OWNER}/{REPO}/commit/{}.patch", fx.root),
@@ -170,7 +159,6 @@ async fn scenario_patch_and_diff(fx: &Fixture) {
170 assert_eq!(status, 404);159 assert_eq!(status, 404);
171 }160 }
172 161
173-/// Compare lists the commits on the head side, as a patch and as a diff.
174 async fn scenario_compare(fx: &Fixture) {162 async fn scenario_compare(fx: &Fixture) {
175 git(&fx.work, &["checkout", "-q", "-b", "topic", &fx.root]);163 git(&fx.work, &["checkout", "-q", "-b", "topic", &fx.root]);
176 std::fs::write(fx.work.join("topic.txt"), "topic\n").unwrap();164 std::fs::write(fx.work.join("topic.txt"), "topic\n").unwrap();
@@ -204,14 +192,12 @@ async fn scenario_compare(fx: &Fixture) {
204 assert!(text.contains("+++ b/topic.txt"));192 assert!(text.contains("+++ b/topic.txt"));
205 }193 }
206 194
207-/// The blob page offers blame, a commit-pinned permalink and the finder.
208 async fn scenario_blob_page(fx: &Fixture) {195 async fn scenario_blob_page(fx: &Fixture) {
209 let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blob/main/a.txt")).await;196 let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blob/main/a.txt")).await;
210 assert_eq!(status, 200);197 assert_eq!(status, 200);
211 let html = String::from_utf8(body).unwrap();198 let html = String::from_utf8(body).unwrap();
212 assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/main/a.txt")));199 assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/main/a.txt")));
213 assert!(html.contains("data-copy-permalink"));200 assert!(html.contains("data-copy-permalink"));
214- // The permalink is pinned to a full commit oid, not the branch.
215 let permalink = html201 let permalink = html
216 .split("data-permalink=\"")202 .split("data-permalink=\"")
217 .nth(1)203 .nth(1)
@@ -226,12 +212,10 @@ async fn scenario_blob_page(fx: &Fixture) {
226 assert!(html.contains("data-finder"));212 assert!(html.contains("data-finder"));
227 assert!(html.contains(&format!("/{OWNER}/{REPO}/paths/main")));213 assert!(html.contains(&format!("/{OWNER}/{REPO}/paths/main")));
228 214
229- // The tree page has the finder too.
230 let (_, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/tree/main")).await;215 let (_, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/tree/main")).await;
231 assert!(String::from_utf8(body).unwrap().contains("data-finder"));216 assert!(String::from_utf8(body).unwrap().contains("data-finder"));
232 }217 }
233 218
234-/// The paths endpoint lists every file on the ref, and refuses unknown refs and subpaths.
235 async fn scenario_paths(fx: &Fixture) {219 async fn scenario_paths(fx: &Fixture) {
236 let (status, headers, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/main")).await;220 let (status, headers, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/main")).await;
237 assert_eq!(status, 200);221 assert_eq!(status, 200);
@@ -258,7 +242,6 @@ async fn scenario_paths(fx: &Fixture) {
258 assert_eq!(status, 404);242 assert_eq!(status, 404);
259 }243 }
260 244
261-/// The branches page shows counts, creates and deletes branches, and refuses bad input.
262 async fn scenario_branches(fx: &Fixture, cookie: &str) {245 async fn scenario_branches(fx: &Fixture, cookie: &str) {
263 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);246 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
264 std::fs::write(fx.work.join("f.txt"), "f\n").unwrap();247 std::fs::write(fx.work.join("f.txt"), "f\n").unwrap();
@@ -277,18 +260,15 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
277 260
278 let (status, _, html) = send(&fx.router, "GET", &page, Some(cookie), &[]).await;261 let (status, _, html) = send(&fx.router, "GET", &page, Some(cookie), &[]).await;
279 assert_eq!(status, 200);262 assert_eq!(status, 200);
280- // feature is 1 ahead of and 54 behind main (the root is its base, main has 54 more commits).
281 assert!(html.contains("1 ahead, 54 behind"), "{html}");263 assert!(html.contains("1 ahead, 54 behind"), "{html}");
282 assert!(html.contains(&format!("/{OWNER}/{REPO}/compare/main...feature")));264 assert!(html.contains(&format!("/{OWNER}/{REPO}/compare/main...feature")));
283 assert!(html.contains("tahinli"));265 assert!(html.contains("tahinli"));
284 let delete_form = format!("action=\"/{OWNER}/{REPO}/branches/delete\"");266 let delete_form = format!("action=\"/{OWNER}/{REPO}/branches/delete\"");
285 assert!(html.contains(&delete_form), "{html}");267 assert!(html.contains(&delete_form), "{html}");
286- // Anonymous viewers get no create or delete controls.
287 let (_, _, anon) = send(&fx.router, "GET", &page, None, &[]).await;268 let (_, _, anon) = send(&fx.router, "GET", &page, None, &[]).await;
288 assert!(!anon.contains(&delete_form));269 assert!(!anon.contains(&delete_form));
289 assert!(!anon.contains("new-branch"));270 assert!(!anon.contains("new-branch"));
290 271
291- // Create from a ref.
292 let (status, headers, _) = send(272 let (status, headers, _) = send(
293 &fx.router,273 &fx.router,
294 "POST",274 "POST",
@@ -305,11 +285,25 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
305 feature_tip285 feature_tip
306 );286 );
307 287
308- // Existing name, bad name and missing source change nothing and report why.288+ for (name, from, word, message) in [
309- for (name, from, word) in [289+ (
310- ("topic/one", "feature", "exists"),290+ "topic/one",
311- ("bad..name", "feature", "invalid"),291+ "feature",
312- ("other", "no-such-ref", "source"),292+ "exists",
293+ "A branch with that name already exists.",
294+ ),
295+ (
296+ "bad..name",
297+ "feature",
298+ "invalid",
299+ "That is not a valid branch name.",
300+ ),
301+ (
302+ "other",
303+ "no-such-ref",
304+ "source",
305+ "The source branch, tag or commit was not found.",
306+ ),
313 ] {307 ] {
314 let (status, _, _) = send(308 let (status, _, _) = send(
315 &fx.router,309 &fx.router,
@@ -328,13 +322,9 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
328 &[],322 &[],
329 )323 )
330 .await;324 .await;
331- assert!(325+ assert!(html.contains(message), "{word}");
332- html.contains("role=\"alert\"") || html.contains("alert"),
333- "{word}"
334- );
335 }326 }
336 327
337- // A bad CSRF token is refused.
338 let (status, _, _) = send(328 let (status, _, _) = send(
339 &fx.router,329 &fx.router,
340 "POST",330 "POST",
@@ -345,7 +335,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
345 .await;335 .await;
346 assert_eq!(status, 403);336 assert_eq!(status, 403);
347 337
348- // Delete: a moved branch is left alone, the right oid deletes it.
349 let delete = format!("{page}/delete");338 let delete = format!("{page}/delete");
350 let (status, _, _) = send(339 let (status, _, _) = send(
351 &fx.router,340 &fx.router,
@@ -369,7 +358,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
369 let listing = git(&fx.bare, &["branch", "--list", "topic/one"]);358 let listing = git(&fx.bare, &["branch", "--list", "topic/one"]);
370 assert!(listing.is_empty(), "branch should be gone: {listing}");359 assert!(listing.is_empty(), "branch should be gone: {listing}");
371 360
372- // The default branch can never be deleted.
373 let main_tip = git(&fx.bare, &["rev-parse", "refs/heads/main"]);361 let main_tip = git(&fx.bare, &["rev-parse", "refs/heads/main"]);
374 send(362 send(
375 &fx.router,363 &fx.router,
@@ -382,7 +370,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
382 git(&fx.bare, &["rev-parse", "--verify", "refs/heads/main"]);370 git(&fx.bare, &["rev-parse", "--verify", "refs/heads/main"]);
383 }371 }
384 372
385-/// A branch rule blocks deleting the branches it matches.
386 async fn scenario_protection(fx: &Fixture, cookie: &str) {373 async fn scenario_protection(fx: &Fixture, cookie: &str) {
387 git(&fx.bare, &["branch", "release/1", "main"]);374 git(&fx.bare, &["branch", "release/1", "main"]);
388 git(&fx.bare, &["branch", "scratch", "main"]);375 git(&fx.bare, &["branch", "scratch", "main"]);
@@ -420,7 +407,6 @@ async fn scenario_protection(fx: &Fixture, cookie: &str) {
420 assert!(git(&fx.bare, &["branch", "--list", "scratch"]).is_empty());407 assert!(git(&fx.bare, &["branch", "--list", "scratch"]).is_empty());
421 }408 }
422 409
423-/// Changing the default branch moves HEAD and the record; a missing branch changes nothing.
424 async fn scenario_default_branch(fx: &Fixture, cookie: &str) {410 async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
425 git(&fx.bare, &["branch", "trunk", "main"]);411 git(&fx.bare, &["branch", "trunk", "main"]);
426 let settings = format!("/{OWNER}/{REPO}/settings/general");412 let settings = format!("/{OWNER}/{REPO}/settings/general");
@@ -448,7 +434,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
448 assert_eq!(repo.default_branch, "trunk");434 assert_eq!(repo.default_branch, "trunk");
449 assert_eq!(repo.description, "demo");435 assert_eq!(repo.description, "demo");
450 436
451- // A branch that does not exist changes nothing.
452 send(437 send(
453 &fx.router,438 &fx.router,
454 "POST",439 "POST",
@@ -470,7 +455,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
470 .unwrap();455 .unwrap();
471 assert_eq!(repo.default_branch, "trunk");456 assert_eq!(repo.default_branch, "trunk");
472 457
473- // The settings page offers the branches and marks the current one.
474 let (_, _, html) = send(458 let (_, _, html) = send(
475 &fx.router,459 &fx.router,
476 "GET",460 "GET",
@@ -482,8 +466,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
482 assert!(html.contains("name=\"default_branch\""));466 assert!(html.contains("name=\"default_branch\""));
483 }467 }
484 468
485-/// Paths, patch and diff, split view and blob page, on one public repo. These pin the file set
486-/// and the commit count, so they run before any commit is added.
487 #[tokio::test]469 #[tokio::test]
488 async fn public_repo_pages_and_downloads() {470 async fn public_repo_pages_and_downloads() {
489 let fx = Fixture::new(Visibility::Public).await;471 let fx = Fixture::new(Visibility::Public).await;
@@ -493,8 +475,6 @@ async fn public_repo_pages_and_downloads() {
493 scenario_blob_page(&fx).await;475 scenario_blob_page(&fx).await;
494 }476 }
495 477
496-/// The commit toolbar, then compare. The whitespace scenario adds commits to main, and compare
497-/// moves the working checkout to a topic branch, so compare runs last.
498 #[tokio::test]478 #[tokio::test]
499 async fn public_repo_commit_views_and_compare() {479 async fn public_repo_commit_views_and_compare() {
500 let fx = Fixture::new(Visibility::Public).await;480 let fx = Fixture::new(Visibility::Public).await;
@@ -502,8 +482,6 @@ async fn public_repo_commit_views_and_compare() {
502 scenario_compare(&fx).await;482 scenario_compare(&fx).await;
503 }483 }
504 484
505-/// Branches, branch rules and the default branch on one fixture. The branch counts assume main
506-/// has not moved, and the default-branch change runs last.
507 #[tokio::test]485 #[tokio::test]
508 async fn public_repo_branches_rules_and_default_branch() {486 async fn public_repo_branches_rules_and_default_branch() {
509 let fx = Fixture::new(Visibility::Public).await;487 let fx = Fixture::new(Visibility::Public).await;
@@ -513,7 +491,6 @@ async fn public_repo_branches_rules_and_default_branch() {
513 scenario_default_branch(&fx, &cookie).await;491 scenario_default_branch(&fx, &cookie).await;
514 }492 }
515 493
516-/// A private repo hides its patch download and its file list from anonymous viewers.
517 #[tokio::test]494 #[tokio::test]
518 async fn private_repo_hides_downloads_and_paths() {495 async fn private_repo_hides_downloads_and_paths() {
519 let private = Fixture::new(Visibility::Private).await;496 let private = Fixture::new(Visibility::Private).await;
crates/forge-web-repo/src/pages/ci_badge.rsmodified+5 -5
@@ -37,7 +37,7 @@ const GREY: &str = "#9f9f9f";
37 37
38 /// What the right-hand half of the badge says.38 /// What the right-hand half of the badge says.
39 #[derive(Clone, Copy, Debug, PartialEq, Eq)]39 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
40-pub enum BadgeStatus {40+enum BadgeStatus {
41 Passing,41 Passing,
42 Failing,42 Failing,
43 Error,43 Error,
@@ -76,7 +76,7 @@ impl BadgeStatus {
76 }76 }
77 77
78 /// The badge status of a run. Waiting for approval shows as pending.78 /// The badge status of a run. Waiting for approval shows as pending.
79-pub fn status_of_run(state: RunState) -> BadgeStatus {79+fn status_of_run(state: RunState) -> BadgeStatus {
80 match state {80 match state {
81 RunState::Success => BadgeStatus::Passing,81 RunState::Success => BadgeStatus::Passing,
82 RunState::Failure => BadgeStatus::Failing,82 RunState::Failure => BadgeStatus::Failing,
@@ -88,7 +88,7 @@ pub fn status_of_run(state: RunState) -> BadgeStatus {
88 }88 }
89 89
90 /// The badge status of one job.90 /// The badge status of one job.
91-pub fn status_of_job(state: JobState) -> BadgeStatus {91+fn status_of_job(state: JobState) -> BadgeStatus {
92 match state {92 match state {
93 JobState::Success => BadgeStatus::Passing,93 JobState::Success => BadgeStatus::Passing,
94 JobState::Failure => BadgeStatus::Failing,94 JobState::Failure => BadgeStatus::Failing,
@@ -101,7 +101,7 @@ pub fn status_of_job(state: JobState) -> BadgeStatus {
101 101
102 /// Escapes text for XML element content and attribute values. Control characters, which XML102 /// Escapes text for XML element content and attribute values. Control characters, which XML
103 /// does not allow, become spaces.103 /// does not allow, become spaces.
104-pub fn escape_xml(text: &str) -> String {104+fn escape_xml(text: &str) -> String {
105 let mut out = String::with_capacity(text.len());105 let mut out = String::with_capacity(text.len());
106 for c in text.chars() {106 for c in text.chars() {
107 match c {107 match c {
@@ -124,7 +124,7 @@ fn text_box(text: &str) -> u32 {
124 }124 }
125 125
126 /// Renders the flat badge: a grey label half and a coloured status half.126 /// Renders the flat badge: a grey label half and a coloured status half.
127-pub fn render_badge(label: &str, status: BadgeStatus) -> String {127+fn render_badge(label: &str, status: BadgeStatus) -> String {
128 let label: String = label.chars().take(MAX_LABEL_CHARS).collect();128 let label: String = label.chars().take(MAX_LABEL_CHARS).collect();
129 let status_text = status.text();129 let status_text = status.text();
130 let label_w = text_box(&label);130 let label_w = text_box(&label);
crates/forge-web-repo/src/pages/ci_tests.rsmodified+9 -78
@@ -1,6 +1,3 @@
1-//! Route tests for the CI run and job pages. The fixture: tahinli owns the private repo `proj`, bob
2-//! has Write, dave has Read, and carol is outside the repo.
3-
4 use std::io::Write;1 use std::io::Write;
5 use std::path::{Path, PathBuf};2 use std::path::{Path, PathBuf};
6 use std::sync::Arc;3 use std::sync::Arc;
@@ -18,7 +15,6 @@ use crate::ci::{CiLive, artifact_key, log_path};
18 use crate::test_support::{app_router, create_session, test_state};15 use crate::test_support::{app_router, create_session, test_state};
19 16
20 const CSRF: &str = "ci-test-csrf";17 const CSRF: &str = "ci-test-csrf";
21-/// A hash no ref reaches, standing in for a commit that was overwritten.
22 const SHA: &str = "0123456789abcdef0123456789abcdef01234567";18 const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
23 const SPEC: &str = r#"{"runs_on":[]}"#;19 const SPEC: &str = r#"{"runs_on":[]}"#;
24 const RUN_BASE: &str = "/tahinli/proj/ci";20 const RUN_BASE: &str = "/tahinli/proj/ci";
@@ -29,7 +25,6 @@ struct Fixture {
29 live: Arc<CiLive>,25 live: Arc<CiLive>,
30 repo: forge_core::Repo,26 repo: forge_core::Repo,
31 tahinli: String,27 tahinli: String,
32- /// The commit `main` points at in `proj`.
33 head: String,28 head: String,
34 data_dir: PathBuf,29 data_dir: PathBuf,
35 blobs: BlobStore,30 blobs: BlobStore,
@@ -90,7 +85,6 @@ async fn fixture(dir: &Path) -> Fixture {
90 }85 }
91 }86 }
92 87
93-/// Puts one empty commit on `main` and returns its hash.
94 fn commit_main(bare: &Path) -> String {88 fn commit_main(bare: &Path) -> String {
95 let git = |args: &[&str]| {89 let git = |args: &[&str]| {
96 let out = std::process::Command::new("git")90 let out = std::process::Command::new("git")
@@ -113,7 +107,6 @@ fn cookie_for(token: &str) -> String {
113 format!("__Host-{SESSION_COOKIE}={token}")107 format!("__Host-{SESSION_COOKIE}={token}")
114 }108 }
115 109
116-/// A response: status, headers and the whole body.
117 struct Reply {110 struct Reply {
118 status: u16,111 status: u16,
119 headers: HeaderMap,112 headers: HeaderMap,
@@ -150,7 +143,6 @@ async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply {
150 collect(app.handle(req).await).await143 collect(app.handle(req).await).await
151 }144 }
152 145
153-/// A POST with the CSRF token and the given form fields.
154 async fn post(app: &Router, uri: &str, cookie: &str, fields: &[(&str, &str)]) -> Reply {146 async fn post(app: &Router, uri: &str, cookie: &str, fields: &[(&str, &str)]) -> Reply {
155 let mut form = form_urlencoded::Serializer::new(String::new());147 let mut form = form_urlencoded::Serializer::new(String::new());
156 form.append_pair("csrf", CSRF);148 form.append_pair("csrf", CSRF);
@@ -178,7 +170,6 @@ async fn collect(res: topcoat::router::response::Response) -> Reply {
178 }170 }
179 }171 }
180 172
181-/// Creates a run on `main` with one job per name. Jobs wait for approval when `needs_approval`.
182 async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {173 async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {
183 let needs: &[String] = &[];174 let needs: &[String] = &[];
184 let specs: Vec<NewJob<'_>> = jobs175 let specs: Vec<NewJob<'_>> = jobs
@@ -207,7 +198,6 @@ async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {
207 .expect("run")198 .expect("run")
208 }199 }
209 200
210-/// Claims the one queued job with a fresh runner and finishes it as a success.
211 async fn finish_job(fx: &Fixture) -> CiJob {201 async fn finish_job(fx: &Fixture) -> CiJob {
212 let token = fx202 let token = fx
213 .store203 .store
@@ -232,6 +222,10 @@ async fn finish_job(fx: &Fixture) -> CiJob {
232 job222 job
233 }223 }
234 224
225+async fn run_now(fx: &Fixture, id: &str) -> CiRun {
226+ fx.store.run_by_id(id).await.expect("run").expect("run")
227+}
228+
235 async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob {229 async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob {
236 fx.store230 fx.store
237 .jobs_for_run(&run.id)231 .jobs_for_run(&run.id)
@@ -242,7 +236,6 @@ async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob {
242 .expect("a job")236 .expect("a job")
243 }237 }
244 238
245-/// Access follows the repo's role on every route: anonymous and outsider requests are 404, readers see the pages and streams, and only writers see or use the controls. Each scenario makes its own run.
246 #[tokio::test]239 #[tokio::test]
247 async fn access_follows_the_repo_role_on_every_route() {240 async fn access_follows_the_repo_role_on_every_route() {
248 let dir = tempfile::tempdir().expect("tempdir");241 let dir = tempfile::tempdir().expect("tempdir");
@@ -298,12 +291,7 @@ async fn access_follows_the_repo_role_on_every_route() {
298 )291 )
299 .await;292 .await;
300 assert_eq!(refused.status, 403, "reader cannot cancel");293 assert_eq!(refused.status, 403, "reader cannot cancel");
301- let still = fx294+ let still = run_now(&fx, &run.id).await;
302- .store
303- .run_by_id(&run.id)
304- .await
305- .expect("run")
306- .expect("run");
307 assert_eq!(still.state, RunState::Queued);295 assert_eq!(still.state, RunState::Queued);
308 }296 }
309 297
@@ -326,7 +314,6 @@ async fn access_follows_the_repo_role_on_every_route() {
326 }314 }
327 }315 }
328 316
329-/// The run list pages 25 at a time and is live on page 1 only. Thirty runs make two pages; page 2 is a fixed slice, so it carries no live marker.
330 #[tokio::test]317 #[tokio::test]
331 async fn run_list_pages_and_its_live_marker() {318 async fn run_list_pages_and_its_live_marker() {
332 let dir = tempfile::tempdir().expect("tempdir");319 let dir = tempfile::tempdir().expect("tempdir");
@@ -337,7 +324,6 @@ async fn run_list_pages_and_its_live_marker() {
337 }324 }
338 let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await;325 let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await;
339 let text = first.text();326 let text = first.text();
340- // The topbar's live strip links the viewer's own running runs too; only the list counts.
341 let list = text327 let list = text
342 .split_once("</header>")328 .split_once("</header>")
343 .map_or(text.as_str(), |(_, rest)| rest);329 .map_or(text.as_str(), |(_, rest)| rest);
@@ -395,7 +381,6 @@ async fn run_list_pages_and_its_live_marker() {
395 }381 }
396 }382 }
397 383
398-/// Opens an event stream without reading it. The response head carries the status.
399 async fn open(384 async fn open(
400 app: &Router,385 app: &Router,
401 uri: &str,386 uri: &str,
@@ -409,7 +394,6 @@ async fn open(
409 .await394 .await
410 }395 }
411 396
412-/// The next frame of an event stream, or None once the stream has ended. Fails after five seconds.
413 async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>>397 async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>>
414 where398 where
415 S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,399 S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
@@ -430,7 +414,6 @@ where
430 {414 {
431 use futures_util::StreamExt;415 use futures_util::StreamExt;
432 416
433- // Every stream opens with its `retry` field (one frame): skip it, the tests want the events.
434 loop {417 loop {
435 let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())418 let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
436 .await419 .await
@@ -442,7 +425,6 @@ where
442 }425 }
443 }426 }
444 427
445-/// The pages no longer reload themselves, and a job's live streams end with the job. Each scenario finishes its own job first, since `finish_job` claims the oldest queued job.
446 #[tokio::test]428 #[tokio::test]
447 async fn live_pages_and_streams_follow_a_job_to_its_end() {429 async fn live_pages_and_streams_follow_a_job_to_its_end() {
448 let dir = tempfile::tempdir().expect("tempdir");430 let dir = tempfile::tempdir().expect("tempdir");
@@ -455,7 +437,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
455 let url = format!("/tahinli/proj/ci/jobs/{}", job.id);437 let url = format!("/tahinli/proj/ci/jobs/{}", job.id);
456 let run_url = format!("{RUN_BASE}/runs/{}", run.number);438 let run_url = format!("{RUN_BASE}/runs/{}", run.number);
457 let job_marker = format!("data-live=\"{url}/events\"");439 let job_marker = format!("data-live=\"{url}/events\"");
458- // The split view is live on page 1 through the repo stream, whatever the run's state.
459 let run_marker = format!("data-live=\"{RUN_BASE}/events\"");440 let run_marker = format!("data-live=\"{RUN_BASE}/events\"");
460 441
461 let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;442 let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;
@@ -474,7 +455,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
474 455
475 finish_job(&fx).await;456 finish_job(&fx).await;
476 let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;457 let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await;
477- // A finished job stays live: a retention purge can still take its artifacts and log.
478 assert!(458 assert!(
479 done.text().contains(&job_marker),459 done.text().contains(&job_marker),
480 "job still live when finished"460 "job still live when finished"
@@ -518,26 +498,18 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
518 format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes()498 format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes()
519 );499 );
520 500
521- // A bump with no new log bytes and no status change sends nothing.
522 fx.live.bump_job(&job.id);501 fx.live.bump_job(&job.id);
523 let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await;502 let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await;
524 assert!(quiet.is_err(), "a log append sends no status event");503 assert!(quiet.is_err(), "a log append sends no status event");
525 504
526- // The run stream sends its status on every bump of the run.
527 fx.live.bump_run(&run.id);505 fx.live.bump_run(&run.id);
528 let bumped = next_event(&mut run_frames).await.expect("the run status");506 let bumped = next_event(&mut run_frames).await.expect("the run status");
529- let now = fx507+ let now = run_now(&fx, &run.id).await;
530- .store
531- .run_by_id(&run.id)
532- .await
533- .expect("run")
534- .expect("run");
535 assert_eq!(508 assert_eq!(
536 bumped,509 bumped,
537 format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes()510 format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes()
538 );511 );
539 512
540- // The job finishes: its final status is sent, then the stream ends.
541 finish_job(&fx).await;513 finish_job(&fx).await;
542 fx.live.close_job(&job.id);514 fx.live.close_job(&job.id);
543 let last = next_event(&mut job_frames).await.expect("the final status");515 let last = next_event(&mut job_frames).await.expect("the final status");
@@ -553,7 +525,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
553 }525 }
554 }526 }
555 527
556-/// The href of the list row marked as current, from the markup of the runs page.
557 fn current_href(html: &str) -> Option<&str> {528 fn current_href(html: &str) -> Option<&str> {
558 let mark = html.find("aria-current=\"true\"")?;529 let mark = html.find("aria-current=\"true\"")?;
559 let start = html[..mark].rfind("<a ")?;530 let start = html[..mark].rfind("<a ")?;
@@ -562,8 +533,6 @@ fn current_href(html: &str) -> Option<&str> {
562 link[at..].split('"').next()533 link[at..].split('"').next()
563 }534 }
564 535
565-/// `/ci` is the run list alone, each row opening its run; `/ci/runs/n` draws run n. A run that is not
566-/// on the list page is still drawn, and no row of the list is marked for it.
567 #[tokio::test]536 #[tokio::test]
568 async fn split_view_draws_the_newest_run_or_the_one_named() {537 async fn split_view_draws_the_newest_run_or_the_one_named() {
569 let dir = tempfile::tempdir().expect("tempdir");538 let dir = tempfile::tempdir().expect("tempdir");
@@ -585,8 +554,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
585 .await554 .await
586 .text();555 .text();
587 assert!(named.contains(&format!("data-run=\"{}\"", first.number)));556 assert!(named.contains(&format!("data-run=\"{}\"", first.number)));
588- // The run page is the run alone: the All runs link goes back to the list, and a one-job run has
589- // no job list to mark.
590 assert!(557 assert!(
591 named.contains(&format!("href=\"{RUN_BASE}\"")),558 named.contains(&format!("href=\"{RUN_BASE}\"")),
592 "All runs link"559 "All runs link"
@@ -594,7 +561,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
594 assert!(!named.contains("ci-run-list"));561 assert!(!named.contains("ci-run-list"));
595 assert_eq!(named.matches("aria-current=\"true\"").count(), 0);562 assert_eq!(named.matches("aria-current=\"true\"").count(), 0);
596 563
597- // Thirty runs make two pages. Run 1 is on page 2, so page 1 marks no row and draws run 1.
598 for _ in 0..28 {564 for _ in 0..28 {
599 run_with(&fx, &["build"], false).await;565 run_with(&fx, &["build"], false).await;
600 }566 }
@@ -606,7 +572,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
606 .await572 .await
607 .text();573 .text();
608 assert!(off_page.contains(&format!("data-run=\"{}\"", first.number)));574 assert!(off_page.contains(&format!("data-run=\"{}\"", first.number)));
609- // A run off the list's first page opens all the same.
610 assert!(off_page.contains(&format!("data-live=\"{RUN_BASE}/events\"")));575 assert!(off_page.contains(&format!("data-live=\"{RUN_BASE}/events\"")));
611 let rows = get(&fx.app, &format!("{RUN_BASE}?page=2"), tahinli.as_deref())576 let rows = get(&fx.app, &format!("{RUN_BASE}?page=2"), tahinli.as_deref())
612 .await577 .await
@@ -617,7 +582,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
617 );582 );
618 }583 }
619 584
620-/// The list stream sends nothing on connect, then one `changed` event per change of the repo.
621 #[tokio::test]585 #[tokio::test]
622 async fn run_list_events_follow_repo_changes() {586 async fn run_list_events_follow_repo_changes() {
623 use futures_util::StreamExt;587 use futures_util::StreamExt;
@@ -633,7 +597,6 @@ async fn run_list_events_follow_repo_changes() {
633 .into_body()597 .into_body()
634 .into_data_stream();598 .into_data_stream();
635 599
636- // The retry field comes first; after it nothing is sent until a change.
637 let retry = next_frame(&mut frames).await.expect("the retry field");600 let retry = next_frame(&mut frames).await.expect("the retry field");
638 assert!(retry.starts_with(b"retry: "), "{retry:?}");601 assert!(retry.starts_with(b"retry: "), "{retry:?}");
639 let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;602 let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;
@@ -645,7 +608,6 @@ async fn run_list_events_follow_repo_changes() {
645 assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec());608 assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec());
646 }609 }
647 610
648-/// The job's log stream: each append is a `log` event with its bytes, the id is the offset past them, bytes before `?from=` are not sent again, a long append is split into 64 KiB events, and a reconnect resumes after `Last-Event-ID`.
649 #[tokio::test]611 #[tokio::test]
650 async fn job_log_events() {612 async fn job_log_events() {
651 let dir = tempfile::tempdir().expect("tempdir");613 let dir = tempfile::tempdir().expect("tempdir");
@@ -750,7 +712,6 @@ async fn job_log_events() {
750 }712 }
751 }713 }
752 714
753-/// The job page's log tail says where its text ends, tails the last 512 KiB, and a cut log starts at its own line number.
754 #[tokio::test]715 #[tokio::test]
755 async fn job_page_log_tail() {716 async fn job_page_log_tail() {
756 let dir = tempfile::tempdir().expect("tempdir");717 let dir = tempfile::tempdir().expect("tempdir");
@@ -814,7 +775,6 @@ async fn job_page_log_tail() {
814 let path = log_path(&fx.data_dir, &job.id);775 let path = log_path(&fx.data_dir, &job.id);
815 std::fs::create_dir_all(path.parent().unwrap()).unwrap();776 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
816 let mut file = std::fs::File::create(&path).unwrap();777 let mut file = std::fs::File::create(&path).unwrap();
817- // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000.
818 for n in 0..11_000 {778 for n in 0..11_000 {
819 writeln!(file, "{n:0>98}").unwrap();779 writeln!(file, "{n:0>98}").unwrap();
820 }780 }
@@ -840,7 +800,6 @@ async fn job_page_log_tail() {
840 }800 }
841 }801 }
842 802
843-/// The next chunk a follower sends. Fails the test when none comes within five seconds.
844 async fn next_chunk(803 async fn next_chunk(
845 chunks: &mut tokio::sync::mpsc::UnboundedReceiver<bytes::Bytes>,804 chunks: &mut tokio::sync::mpsc::UnboundedReceiver<bytes::Bytes>,
846 ) -> Option<bytes::Bytes> {805 ) -> Option<bytes::Bytes> {
@@ -849,7 +808,6 @@ async fn next_chunk(
849 .expect("a chunk within five seconds")808 .expect("a chunk within five seconds")
850 }809 }
851 810
852-/// `log.txt` is the full file of a finished job, and a log follower is woken by bumps and ends once the job is terminal.
853 #[tokio::test]811 #[tokio::test]
854 async fn log_txt_and_log_follower() {812 async fn log_txt_and_log_follower() {
855 let dir = tempfile::tempdir().expect("tempdir");813 let dir = tempfile::tempdir().expect("tempdir");
@@ -933,7 +891,6 @@ async fn log_txt_and_log_follower() {
933 }891 }
934 }892 }
935 893
936-/// Artifact downloads send attachment headers, and a run's artifacts list and zip for readers only.
937 #[tokio::test]894 #[tokio::test]
938 async fn artifact_downloads_and_zip() {895 async fn artifact_downloads_and_zip() {
939 let dir = tempfile::tempdir().expect("tempdir");896 let dir = tempfile::tempdir().expect("tempdir");
@@ -1069,12 +1026,7 @@ async fn approve_only_works_while_waiting_for_approval() {
1069 )1026 )
1070 .await;1027 .await;
1071 assert_notice(&approved, "approved");1028 assert_notice(&approved, "approved");
1072- let now = fx1029+ let now = run_now(&fx, &run.id).await;
1073- .store
1074- .run_by_id(&run.id)
1075- .await
1076- .expect("run")
1077- .expect("run");
1078 assert_eq!(now.state, RunState::Queued);1030 assert_eq!(now.state, RunState::Queued);
1079 let page = get(&fx.app, &run_url, Some(&cookie_for("bob-token"))).await;1031 let page = get(&fx.app, &run_url, Some(&cookie_for("bob-token"))).await;
1080 assert!(1032 assert!(
@@ -1090,12 +1042,7 @@ async fn approve_only_works_while_waiting_for_approval() {
1090 )1042 )
1091 .await;1043 .await;
1092 assert_notice(&again, "not-waiting");1044 assert_notice(&again, "not-waiting");
1093- let still = fx1045+ let still = run_now(&fx, &run.id).await;
1094- .store
1095- .run_by_id(&run.id)
1096- .await
1097- .expect("run")
1098- .expect("run");
1099 assert_eq!(still.state, RunState::Queued);1046 assert_eq!(still.state, RunState::Queued);
1100 }1047 }
1101 1048
@@ -1113,12 +1060,7 @@ async fn cancel_and_rerun_post_and_redirect() {
1113 )1060 )
1114 .await;1061 .await;
1115 assert_notice(&cancelled, "cancelled");1062 assert_notice(&cancelled, "cancelled");
1116- let now = fx1063+ let now = run_now(&fx, &run.id).await;
1117- .store
1118- .run_by_id(&run.id)
1119- .await
1120- .expect("run")
1121- .expect("run");
1122 assert_eq!(now.state, RunState::Cancelled);1064 assert_eq!(now.state, RunState::Cancelled);
1123 let finished = post(1065 let finished = post(
1124 &fx.app,1066 &fx.app,
@@ -1171,7 +1113,6 @@ async fn manual_run_refuses_an_unknown_branch() {
1171 assert_eq!(reader.status, 403, "reader cannot start a manual run");1113 assert_eq!(reader.status, 403, "reader cannot start a manual run");
1172 }1114 }
1173 1115
1174-/// The badge follows read access, and a repo with no run answers 200 with "no status". It runs before any run exists on the private repo.
1175 #[tokio::test]1116 #[tokio::test]
1176 async fn badge_follows_read_access_and_has_no_run_before_one_exists() {1117 async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
1177 let dir = tempfile::tempdir().expect("tempdir");1118 let dir = tempfile::tempdir().expect("tempdir");
@@ -1202,7 +1143,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
1202 .expect("public repo");1143 .expect("public repo");
1203 let svg_path = "/tahinli/proj/badge.svg";1144 let svg_path = "/tahinli/proj/badge.svg";
1204 1145
1205- // The private repo: a run exists, but only readers see its badge.
1206 run_with(&fx, &["build"], false).await;1146 run_with(&fx, &["build"], false).await;
1207 finish_job(&fx).await;1147 finish_job(&fx).await;
1208 assert_eq!(get(&fx.app, svg_path, None).await.status, 404, "anonymous");1148 assert_eq!(get(&fx.app, svg_path, None).await.status, 404, "anonymous");
@@ -1226,7 +1166,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
1226 Some("no-cache, max-age=0")1166 Some("no-cache, max-age=0")
1227 );1167 );
1228 1168
1229- // The public repo: anyone sees the badge. Unknown branches and jobs have no status.
1230 let needs: &[String] = &[];1169 let needs: &[String] = &[];
1231 let specs = [NewJob {1170 let specs = [NewJob {
1232 name: "build",1171 name: "build",
@@ -1266,7 +1205,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
1266 }1205 }
1267 }1206 }
1268 1207
1269-/// Writes `.forge/ci.toml` with `text` into a new commit of the bare repo and returns its id.
1270 fn commit_ci_toml(bare: &Path, text: &str) -> String {1208 fn commit_ci_toml(bare: &Path, text: &str) -> String {
1271 fn git(bare: &Path, args: &[&str], stdin: &str) -> String {1209 fn git(bare: &Path, args: &[&str], stdin: &str) -> String {
1272 let mut child = std::process::Command::new("git")1210 let mut child = std::process::Command::new("git")
@@ -1305,7 +1243,6 @@ fn commit_ci_toml(bare: &Path, text: &str) -> String {
1305 git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], "")1243 git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], "")
1306 }1244 }
1307 1245
1308-/// Creates a queued run of one job `build` at `commit` on `main`.
1309 async fn run_at(fx: &Fixture, commit: &str) {1246 async fn run_at(fx: &Fixture, commit: &str) {
1310 let needs: &[String] = &[];1247 let needs: &[String] = &[];
1311 let specs = [NewJob {1248 let specs = [NewJob {
@@ -1331,7 +1268,6 @@ async fn run_at(fx: &Fixture, commit: &str) {
1331 .expect("run");1268 .expect("run");
1332 }1269 }
1333 1270
1334-/// The badge label comes from `?label=`, the job or the workflow name, trimmed and escaped, with "build" as the fallback. Each scenario finishes its own run, so the latest run is the one it made.
1335 #[tokio::test]1271 #[tokio::test]
1336 async fn badge_label_comes_from_the_query_job_or_name() {1272 async fn badge_label_comes_from_the_query_job_or_name() {
1337 let dir = tempfile::tempdir().expect("tempdir");1273 let dir = tempfile::tempdir().expect("tempdir");
@@ -1414,7 +1350,6 @@ async fn badge_label_comes_from_the_query_job_or_name() {
1414 1350
1415 {1351 {
1416 let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path");1352 let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path");
1417- // A run whose config has an empty name: the name is ignored.
1418 let commit = commit_ci_toml(1353 let commit = commit_ci_toml(
1419 &bare,1354 &bare,
1420 "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n",1355 "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n",
@@ -1429,7 +1364,6 @@ async fn badge_label_comes_from_the_query_job_or_name() {
1429 }1364 }
1430 }1365 }
1431 1366
1432-/// The pages say whether a run is counting. A running run carries the start of each counting duration, and the run page previews each job's last log line and opens a failed job.
1433 #[tokio::test]1367 #[tokio::test]
1434 async fn running_runs_and_run_page_previews() {1368 async fn running_runs_and_run_page_previews() {
1435 let dir = tempfile::tempdir().expect("tempdir");1369 let dir = tempfile::tempdir().expect("tempdir");
@@ -1474,7 +1408,6 @@ async fn running_runs_and_run_page_previews() {
1474 html.contains("data-tick=\"rest\""),1408 html.contains("data-tick=\"rest\""),
1475 "the hatched remainder follows the clock"1409 "the hatched remainder follows the clock"
1476 );1410 );
1477- // The timeline is on the run's own page.
1478 let html = get(&fx.app, &format!("{RUN_BASE}/runs/1"), Some(&cookie))1411 let html = get(&fx.app, &format!("{RUN_BASE}/runs/1"), Some(&cookie))
1479 .await1412 .await
1480 .text()1413 .text()
@@ -1570,7 +1503,6 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() {
1570 let run_url = format!("{RUN_BASE}/runs/{}", run.number);1503 let run_url = format!("{RUN_BASE}/runs/{}", run.number);
1571 let writer = cookie_for("bob-token");1504 let writer = cookie_for("bob-token");
1572 1505
1573- // A live run offers neither control and refuses the request.
1574 let page = get(&fx.app, &run_url, Some(&writer)).await.text();1506 let page = get(&fx.app, &run_url, Some(&writer)).await.text();
1575 assert!(!page.contains("Re-run failed jobs"));1507 assert!(!page.contains("Re-run failed jobs"));
1576 let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;1508 let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await;
@@ -1604,7 +1536,6 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() {
1604 .unwrap();1536 .unwrap();
1605 assert_eq!(fx.store.jobs_for_run(&second.id).await.unwrap().len(), 2);1537 assert_eq!(fx.store.jobs_for_run(&second.id).await.unwrap().len(), 2);
1606 1538
1607- // One job: it must have finished, and the request needs Write.
1608 let job = job_of(&fx, &run).await;1539 let job = job_of(&fx, &run).await;
1609 let single = post(1540 let single = post(
1610 &fx.app,1541 &fx.app,
crates/forge-web-repo/src/pages/commit.rsmodified+24 -24
@@ -8,12 +8,12 @@ use topcoat::Result;
8 use topcoat::context::{Cx, context};8 use topcoat::context::{Cx, context};
9 use topcoat::router::error::{content_too_large, not_found};9 use topcoat::router::error::{content_too_large, not_found};
10 use topcoat::router::{page, path_param, route};10 use topcoat::router::{page, path_param, route};
11-use topcoat::view::{View, view};11+use topcoat::view::{View, component, view};
12 12
13 use crate::i18n::code::{self as g, K};13 use crate::i18n::code::{self as g, K};
14 use crate::i18n::{self};14 use crate::i18n::{self};
15 use crate::layers::RawDownload;15 use crate::layers::RawDownload;
16-use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid};16+use crate::pages::commits::{SigBadgeView, blocking};
17 use crate::pages::ref_live;17 use crate::pages::ref_live;
18 use crate::pages::repo::repo_head;18 use crate::pages::repo::repo_head;
19 use crate::pages::repo_ctx::load_repo;19 use crate::pages::repo_ctx::load_repo;
@@ -24,7 +24,9 @@ use crate::state::AppState;
24 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary};24 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary};
25 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};25 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
26 use crate::views::shell;26 use crate::views::shell;
27-use crate::views::{avatar_url, display_name, relative_time, user_href};27+use crate::views::{
28+ avatar_url, display_name, iso_time, now_unix, relative_time, short_oid, user_href,
29+};
28 30
29 path_param!(owner);31 path_param!(owner);
30 path_param!(repo);32 path_param!(repo);
@@ -54,6 +56,22 @@ struct CoAuthorView {
54 sep: bool,56 sep: bool,
55 }57 }
56 58
59+#[component]
60+async fn coauthor_link(cx: &Cx, c: &CoAuthorView) -> Result<impl View> {
61+ Ok(view! {
62+ if let Some(href) = c.href.as_ref() {
63+ <a class="coauthor" href=(href.as_str())>
64+ if let Some(src) = c.avatar.as_ref() {
65+ <img class="avatar coauthor-avatar" src=(src.as_str()) alt="" width="16" height="16">
66+ }
67+ (c.name.as_str())
68+ </a>
69+ } else {
70+ <span class="coauthor" title=(c.email.as_str())>(c.name.as_str())</span>
71+ }
72+ })
73+}
74+
57 fn is_hex_prefix(s: &str) -> bool {75 fn is_hex_prefix(s: &str) -> bool {
58 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())76 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
59 }77 }
@@ -146,7 +164,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> {
146 let tz = ctx.viewer_tz().to_owned();164 let tz = ctx.viewer_tz().to_owned();
147 let parent = info.parents.first().cloned();165 let parent = info.parents.first().cloned();
148 166
149- let now = now_secs();167+ let now = now_unix();
150 let author = Person {168 let author = Person {
151 name: info.author_name.clone(),169 name: info.author_name.clone(),
152 email: info.author_email.clone(),170 email: info.author_email.clone(),
@@ -277,16 +295,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> {
277 (g::t(lang, K::CoAuthorAnd))295 (g::t(lang, K::CoAuthorAnd))
278 for c in coauthors.iter() {296 for c in coauthors.iter() {
279 if c.sep { ", " }297 if c.sep { ", " }
280- if let Some(href) = c.href.as_ref() {298+ coauthor_link(c: c)
281- <a class="coauthor" href=(href.as_str())>
282- if let Some(src) = c.avatar.as_ref() {
283- <img class="avatar coauthor-avatar" src=(src.as_str()) alt="" width="16" height="16">
284- }
285- (c.name.as_str())
286- </a>
287- } else {
288- <span class="coauthor" title=(c.email.as_str())>(c.name.as_str())</span>
289- }
290 }299 }
291 if folded {300 if folded {
292 ", "301 ", "
@@ -295,16 +304,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> {
295 <ul class="coauthors-list" aria-label=(coauthors_label)>304 <ul class="coauthors-list" aria-label=(coauthors_label)>
296 for c in rest.iter() {305 for c in rest.iter() {
297 <li>306 <li>
298- if let Some(href) = c.href.as_ref() {307+ coauthor_link(c: c)
299- <a class="coauthor" href=(href.as_str())>
300- if let Some(src) = c.avatar.as_ref() {
301- <img class="avatar coauthor-avatar" src=(src.as_str()) alt="" width="16" height="16">
302- }
303- (c.name.as_str())
304- </a>
305- } else {
306- <span class="coauthor" title=(c.email.as_str())>(c.name.as_str())</span>
307- }
308 </li>308 </li>
309 }309 }
310 </ul>310 </ul>
crates/forge-web-repo/src/pages/commits.rsmodified+2 -47
@@ -1,8 +1,6 @@
1 //! Page: commit history for a ref and optional path, at `/{owner}/{repo}/commits/{*rest}`.1 //! Page: commit history for a ref and optional path, at `/{owner}/{repo}/commits/{*rest}`.
2 //! Also home of the helpers shared by the commit and archive pages.2 //! Also home of the helpers shared by the commit and archive pages.
3 3
4-use std::time::{SystemTime, UNIX_EPOCH};
5-
6 use std::collections::HashMap;4 use std::collections::HashMap;
7 5
8 use forge_core::store::commit_status::CommitStatus;6 use forge_core::store::commit_status::CommitStatus;
@@ -28,7 +26,7 @@ use crate::signatures::{self, SigBadge};
28 use crate::state::AppState;26 use crate::state::AppState;
29 use crate::views::commit_line::commit_line;27 use crate::views::commit_line::commit_line;
30 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};28 use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list};
31-use crate::views::{enc, shell};29+use crate::views::{enc, iso_time, now_unix, shell, short_oid};
32 30
33 path_param!(owner);31 path_param!(owner);
34 path_param!(repo);32 path_param!(repo);
@@ -53,46 +51,6 @@ where
53 Ok(tokio::task::spawn_blocking(f).await??)51 Ok(tokio::task::spawn_blocking(f).await??)
54 }52 }
55 53
56-/// Current Unix time in seconds.
57-pub(crate) fn now_secs() -> i64 {
58- SystemTime::now()
59- .duration_since(UNIX_EPOCH)
60- .ok()
61- .and_then(|d| i64::try_from(d.as_secs()).ok())
62- .unwrap_or(0)
63-}
64-
65-/// Days since the Unix epoch to a proleptic Gregorian `(year, month, day)`.
66-fn civil_from_days(days: i64) -> (i64, u32, u32) {
67- let z = days + 719_468;
68- let era = z.div_euclid(146_097);
69- let doe = z - era * 146_097;
70- let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
71- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
72- let mp = (5 * doy + 2) / 153;
73- let day = doy - (153 * mp + 2) / 5 + 1;
74- let month = if mp < 10 { mp + 3 } else { mp - 9 };
75- let year = yoe + era * 400 + i64::from(month <= 2);
76- (year, month as u32, day as u32)
77-}
78-
79-/// RFC 3339 UTC stamp for the `datetime` attribute.
80-pub(crate) fn iso_time(at: i64) -> String {
81- let (y, m, d) = civil_from_days(at.div_euclid(86_400));
82- let secs = at.rem_euclid(86_400);
83- format!(
84- "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
85- secs / 3600,
86- secs % 3600 / 60,
87- secs % 60
88- )
89-}
90-
91-/// Seven-character abbreviation, as shown in lists.
92-pub(crate) fn short_oid(oid: &str) -> &str {
93- oid.get(..7).unwrap_or(oid)
94-}
95-
96 /// One commit as shown in the history list.54 /// One commit as shown in the history list.
97 pub(crate) struct CommitRow {55 pub(crate) struct CommitRow {
98 /// The full oid: the row's `data-arrive` value.56 /// The full oid: the row's `data-arrive` value.
@@ -279,7 +237,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
279 let older_href = href_for(page_no + 1);237 let older_href = href_for(page_no + 1);
280 let has_newer = page_no > 1;238 let has_newer = page_no > 1;
281 239
282- let now = now_secs();240+ let now = now_unix();
283 let tz = ctx.viewer_tz().to_owned();241 let tz = ctx.viewer_tz().to_owned();
284 let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect();242 let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect();
285 let statuses = state243 let statuses = state
@@ -403,7 +361,6 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
403 mod tests {361 mod tests {
404 use forge_core::Visibility;362 use forge_core::Visibility;
405 363
406- use super::iso_time;
407 use crate::i18n::Lang;364 use crate::i18n::Lang;
408 use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};365 use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};
409 use crate::views::relative_time;366 use crate::views::relative_time;
@@ -411,8 +368,6 @@ mod tests {
411 368
412 #[test]369 #[test]
413 fn dates_and_relative_units_format() {370 fn dates_and_relative_units_format() {
414- assert_eq!(iso_time(0), "1970-01-01T00:00:00Z");
415- assert_eq!(iso_time(1_700_000_000), "2023-11-14T22:13:20Z");
416 assert_eq!(relative_time(Lang::En, 990, 1000), "just now");371 assert_eq!(relative_time(Lang::En, 990, 1000), "just now");
417 assert_eq!(372 assert_eq!(
418 relative_time(Lang::En, 10_000 - 3 * 86_400, 10_000),373 relative_time(Lang::En, 10_000 - 3 * 86_400, 10_000),
crates/forge-web-repo/src/pages/compare.rsmodified+8 -30
@@ -11,7 +11,7 @@
11 11
12 use std::path::PathBuf;12 use std::path::PathBuf;
13 13
14-use forge_core::{Action, Repo as RepoRecord, Session, authorize, validate_body, validate_title};14+use forge_core::{Action, Repo as RepoRecord, authorize, validate_body, validate_title};
15 use forge_git::browse::{self, CommitInfo, RefKind};15 use forge_git::browse::{self, CommitInfo, RefKind};
16 use forge_git::command::ObjectSource;16 use forge_git::command::ObjectSource;
17 use forge_git::history;17 use forge_git::history;
@@ -21,16 +21,18 @@ use serde::Deserialize;
21 use topcoat::Result;21 use topcoat::Result;
22 use topcoat::context::{Cx, context};22 use topcoat::context::{Cx, context};
23 use topcoat::router::content::Form;23 use topcoat::router::content::Form;
24-use topcoat::router::error::{bad_request, forbidden, not_found, see_other};24+use topcoat::router::error::{bad_request, not_found, see_other};
25 use topcoat::router::{page, path_param, query_params};25 use topcoat::router::{page, path_param, query_params};
26 use topcoat::view::{View, view};26 use topcoat::view::{View, view};
27 27
28-use crate::auth::{check_csrf, require_user};28+use crate::auth::require_user;
29 use crate::i18n;29 use crate::i18n;
30 use crate::i18n::pulls::{self as g, K};30 use crate::i18n::pulls::{self as g, K};
31 use crate::notify::{self, Activity};31 use crate::notify::{self, Activity};
32 use crate::pages::commit::Download;32 use crate::pages::commit::Download;
33-use crate::pages::commits::{CommitRow, blocking, now_secs, short_oid};33+use crate::pages::commits::{CommitRow, blocking};
34+use crate::pages::issue_parts::{check_write, csrf_of};
35+use crate::pages::pull_flow::pull_href;
34 use crate::pages::ref_live;36 use crate::pages::ref_live;
35 use crate::pages::repo::repo_head;37 use crate::pages::repo::repo_head;
36 use crate::pages::repo_ctx::{RepoCtx, load_repo};38 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -39,7 +41,7 @@ use crate::templates;
39 use crate::views::commit_line::commit_line;41 use crate::views::commit_line::commit_line;
40 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};42 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
41 use crate::views::parts::reveal;43 use crate::views::parts::reveal;
42-use crate::views::{alert, enc, repo_href, shell, user_facing_message};44+use crate::views::{alert, enc, now_unix, repo_href, shell, short_oid, user_facing_message};
43 use crate::webhooks::emit::{Sender, emit_pull};45 use crate::webhooks::emit::{Sender, emit_pull};
44 46
45 path_param!(owner);47 path_param!(owner);
@@ -195,30 +197,6 @@ async fn resolve_comparison(
195 }))197 }))
196 }198 }
197 199
198-fn csrf_of(ctx: &RepoCtx) -> String {
199- ctx.viewer
200- .as_ref()
201- .map(|(_, session)| session.csrf_token.clone())
202- .unwrap_or_default()
203-}
204-
205-/// Write requests need an unarchived repo and a matching CSRF token.
206-fn check_write(ctx: &RepoCtx, session: &Session, csrf: &str) -> Result<()> {
207- if ctx.repo.archived || !check_csrf(session, csrf) {
208- return Err(forbidden().into());
209- }
210- Ok(())
211-}
212-
213-fn pull_href(ctx: &RepoCtx, number: i64) -> String {
214- repo_href(
215- &ctx.repo.owner_name,
216- &ctx.repo.name,
217- "pulls",
218- &number.to_string(),
219- )
220-}
221-
222 /// The body the pull request form starts with: the default branch's pull request template, or200 /// The body the pull request form starts with: the default branch's pull request template, or
223 /// empty when there is none.201 /// empty when there is none.
224 async fn pull_template_body(ctx: &RepoCtx) -> Result<String> {202 async fn pull_template_body(ctx: &RepoCtx) -> Result<String> {
@@ -241,7 +219,7 @@ async fn compare_view(
241 let owner = ctx.repo.owner_name.clone();219 let owner = ctx.repo.owner_name.clone();
242 let name = ctx.repo.name.clone();220 let name = ctx.repo.name.clone();
243 let tz = ctx.viewer_tz().to_owned();221 let tz = ctx.viewer_tz().to_owned();
244- let now = now_secs();222+ let now = now_unix();
245 let title = format!("{owner}/{name}");223 let title = format!("{owner}/{name}");
246 let base = cmp.base.clone();224 let base = cmp.base.clone();
247 let head = head_value(&ctx, &cmp.head);225 let head = head_value(&ctx, &cmp.head);
crates/forge-web-repo/src/pages/discussion_live.rsmodified+0 -2
@@ -54,5 +54,3 @@ async fn discussion_live(cx: &Cx) -> Result<Response> {
54 let discussion = discussion_by_number(state, &ctx, number(cx)).await?;54 let discussion = discussion_by_number(state, &ctx, number(cx)).await?;
55 stream_wakes(cx, &state.live, &[Topic::Discussion(discussion.id.clone())])55 stream_wakes(cx, &state.live, &[Topic::Discussion(discussion.id.clone())])
56 }56 }
57-
58-// The write layer
crates/forge-web-repo/src/pages/fork.rsmodified+31 -4
@@ -48,8 +48,7 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
48 }48 }
49 49
50 // One fork per viewer and source: an existing one is reused.50 // One fork per viewer and source: an existing one is reused.
51- let forks = state.store.list_forks(&source_repo.id).await?;51+ if let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? {
52- if let Some(existing) = forks.iter().find(|fork| fork.owner_id == viewer.id) {
53 return Ok(see_other(repo_href(52 return Ok(see_other(repo_href(
54 &existing.owner_name,53 &existing.owner_name,
55 &existing.name,54 &existing.name,
@@ -59,10 +58,25 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
59 }58 }
60 59
61 let fork_name = free_name(state, &viewer.username, &source_repo.name).await?;60 let fork_name = free_name(state, &viewer.username, &source_repo.name).await?;
62- let fork = state61+ let fork = match state
63 .store62 .store
64 .create_fork(source_repo, &viewer.id, &fork_name)63 .create_fork(source_repo, &viewer.id, &fork_name)
65- .await?;64+ .await
65+ {
66+ Ok(fork) => fork,
67+ Err(e @ forge_core::Error::Conflict(_)) => {
68+ let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? else {
69+ return Err(e.into());
70+ };
71+ return Ok(see_other(repo_href(
72+ &existing.owner_name,
73+ &existing.name,
74+ "",
75+ "",
76+ )));
77+ }
78+ Err(e) => return Err(e.into()),
79+ };
66 let dst = repo_path(&state.config.data_dir, &fork.id)?;80 let dst = repo_path(&state.config.data_dir, &fork.id)?;
67 if let Err(e) = fork_bare(&state.git, &source.path, &dst).await {81 if let Err(e) = fork_bare(&state.git, &source.path, &dst).await {
68 // Without the directory the row would point at nothing, so drop it again.82 // Without the directory the row would point at nothing, so drop it again.
@@ -107,6 +121,19 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
107 Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", "")))121 Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", "")))
108 }122 }
109 123
124+async fn viewer_fork(
125+ state: &AppState,
126+ source_id: &str,
127+ viewer_id: &str,
128+) -> Result<Option<forge_core::Repo>> {
129+ Ok(state
130+ .store
131+ .list_forks(source_id)
132+ .await?
133+ .into_iter()
134+ .find(|fork| fork.owner_id == viewer_id))
135+}
136+
110 /// `base` when `owner` has no repo of that name, else the first of `base-1`, `base-2`, ... that is137 /// `base` when `owner` has no repo of that name, else the first of `base-1`, `base-2`, ... that is
111 /// free.138 /// free.
112 async fn free_name(state: &AppState, owner: &str, base: &str) -> Result<String> {139 async fn free_name(state: &AppState, owner: &str, base: &str) -> Result<String> {
crates/forge-web-repo/src/pages/labels_css.rsmodified+2 -6
@@ -32,12 +32,8 @@ fn parse_hex(color: &str) -> Option<(u8, u8, u8)> {
32 if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {32 if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
33 return None;33 return None;
34 }34 }
35- let value = u32::from_str_radix(hex, 16).ok()?;35+ let [_, r, g, b] = u32::from_str_radix(hex, 16).ok()?.to_be_bytes();
36- Some((36+ Some((r, g, b))
37- u8::try_from(value >> 16).ok()?,
38- u8::try_from((value >> 8) & 0xff).ok()?,
39- u8::try_from(value & 0xff).ok()?,
40- ))
41 }37 }
42 38
43 /// Label ids go into a CSS class name, so only plain identifier characters are kept.39 /// Label ids go into a CSS class name, so only plain identifier characters are kept.
crates/forge-web-repo/src/pages/labels_page.rsmodified+14 -61
@@ -8,18 +8,15 @@ use serde::Deserialize;
8 use topcoat::Result;8 use topcoat::Result;
9 use topcoat::context::{Cx, context};9 use topcoat::context::{Cx, context};
10 use topcoat::router::content::Form;10 use topcoat::router::content::Form;
11-use topcoat::router::error::see_other;
12 use topcoat::router::{page, path_param, query_params};11 use topcoat::router::{page, path_param, query_params};
13 use topcoat::view::{View, component, view};12 use topcoat::view::{View, component, view};
14 13
15 use crate::i18n::issues::{self as g, K};14 use crate::i18n::issues::{self as g, K};
16 use crate::i18n::{self, Lang};15 use crate::i18n::{self, Lang};
17-use crate::pages::issue_meta::{16+use crate::pages::issue_meta::{RepoFrame, finish_write, issue_subnav, triage_guard};
18- RepoFrame, action_error_at, issue_subnav, refusal_message, triage_guard,
19-};
20 use crate::pages::issues_live::list_live_url;17 use crate::pages::issues_live::list_live_url;
21 use crate::pages::repo::repo_head;18 use crate::pages::repo::repo_head;
22-use crate::pages::repo_ctx::load_repo;19+use crate::pages::repo_ctx::{RepoCtx, load_repo};
23 use crate::state::AppState;20 use crate::state::AppState;
24 use crate::views::parts::{confirm_act, post_act, reveal};21 use crate::views::parts::{confirm_act, post_act, reveal};
25 use crate::views::repo_list::{PageLink, pager, pager_links};22 use crate::views::repo_list::{PageLink, pager, pager_links};
@@ -77,6 +74,10 @@ fn labels_href(title: &str) -> String {
77 format!("/{title}/labels")74 format!("/{title}/labels")
78 }75 }
79 76
77+fn labels_back(ctx: &RepoCtx) -> String {
78+ labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name))
79+}
80+
80 /// The header, the label list and, for triage holders, the forms.81 /// The header, the label list and, for triage holders, the forms.
81 #[component]82 #[component]
82 async fn labels_body(83 async fn labels_body(
@@ -249,24 +250,12 @@ async fn label_create(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View>
249 let ctx = load_repo(cx, owner, name).await?;250 let ctx = load_repo(cx, owner, name).await?;
250 triage_guard(cx, &ctx, &form.csrf).await?;251 triage_guard(cx, &ctx, &form.csrf).await?;
251 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));252 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));
252- let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name));253+ let back = labels_back(&ctx);
253 let result = context::<AppState>(cx)254 let result = context::<AppState>(cx)
254 .store255 .store
255 .create_label(&ctx.repo.id, &form.name, &form.color, &form.description)256 .create_label(&ctx.repo.id, &form.name, &form.color, &form.description)
256 .await;257 .await;
257- match result {258+ finish_write(cx, ctx, lang, back, result).await
258- Ok(_) => {
259- context::<AppState>(cx).live.bump_repo_issues(&ctx.repo.id);
260- Err(see_other(back).into())
261- }
262- Err(e) => {
263- let message = refusal_message(e)?;
264- Ok(view! {
265- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
266- action_error_at(lang: lang, message: message, back: back))
267- })
268- }
269- }
270 }259 }
271 260
272 /// Updates a label's name, color and description.261 /// Updates a label's name, color and description.
@@ -278,24 +267,12 @@ async fn label_update(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View>
278 let ctx = load_repo(cx, owner, name).await?;267 let ctx = load_repo(cx, owner, name).await?;
279 triage_guard(cx, &ctx, &form.csrf).await?;268 triage_guard(cx, &ctx, &form.csrf).await?;
280 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));269 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));
281- let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name));270+ let back = labels_back(&ctx);
282 let result = context::<AppState>(cx)271 let result = context::<AppState>(cx)
283 .store272 .store
284 .update_label(&ctx.repo.id, id, &form.name, &form.color, &form.description)273 .update_label(&ctx.repo.id, id, &form.name, &form.color, &form.description)
285 .await;274 .await;
286- match result {275+ finish_write(cx, ctx, lang, back, result).await
287- Ok(()) => {
288- context::<AppState>(cx).live.bump_repo_issues(&ctx.repo.id);
289- Err(see_other(back).into())
290- }
291- Err(e) => {
292- let message = refusal_message(e)?;
293- Ok(view! {
294- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
295- action_error_at(lang: lang, message: message, back: back))
296- })
297- }
298- }
299 }276 }
300 277
301 /// Adds the default labels to a repo that has none. Triage holders only; labels that already278 /// Adds the default labels to a repo that has none. Triage holders only; labels that already
@@ -307,24 +284,12 @@ async fn label_defaults(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View
307 let ctx = load_repo(cx, owner, name).await?;284 let ctx = load_repo(cx, owner, name).await?;
308 triage_guard(cx, &ctx, &form.csrf).await?;285 triage_guard(cx, &ctx, &form.csrf).await?;
309 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));286 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));
310- let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name));287+ let back = labels_back(&ctx);
311 let result = context::<AppState>(cx)288 let result = context::<AppState>(cx)
312 .store289 .store
313 .create_default_labels(&ctx.repo.id)290 .create_default_labels(&ctx.repo.id)
314 .await;291 .await;
315- match result {292+ finish_write(cx, ctx, lang, back, result).await
316- Ok(_) => {
317- context::<AppState>(cx).live.bump_repo_issues(&ctx.repo.id);
318- Err(see_other(back).into())
319- }
320- Err(e) => {
321- let message = refusal_message(e)?;
322- Ok(view! {
323- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
324- action_error_at(lang: lang, message: message, back: back))
325- })
326- }
327- }
328 }293 }
329 294
330 /// Deletes a label and its links to issues.295 /// Deletes a label and its links to issues.
@@ -336,24 +301,12 @@ async fn label_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View>
336 let ctx = load_repo(cx, owner, name).await?;301 let ctx = load_repo(cx, owner, name).await?;
337 triage_guard(cx, &ctx, &form.csrf).await?;302 triage_guard(cx, &ctx, &form.csrf).await?;
338 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));303 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));
339- let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name));304+ let back = labels_back(&ctx);
340 let result = context::<AppState>(cx)305 let result = context::<AppState>(cx)
341 .store306 .store
342 .delete_label(&ctx.repo.id, id)307 .delete_label(&ctx.repo.id, id)
343 .await;308 .await;
344- match result {309+ finish_write(cx, ctx, lang, back, result).await
345- Ok(()) => {
346- context::<AppState>(cx).live.bump_repo_issues(&ctx.repo.id);
347- Err(see_other(back).into())
348- }
349- Err(e) => {
350- let message = refusal_message(e)?;
351- Ok(view! {
352- shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(),
353- action_error_at(lang: lang, message: message, back: back))
354- })
355- }
356- }
357 }310 }
358 311
359 #[cfg(test)]312 #[cfg(test)]
crates/forge-web-repo/src/pages/merge_queue.rsmodified+28 -66
@@ -13,13 +13,10 @@ use std::collections::HashMap;
13 13
14 use forge_core::merge_queue::{QueueEntry, QueueState};14 use forge_core::merge_queue::{QueueEntry, QueueState};
15 use forge_core::{Action, MergeStyle, PullRequest, authorize};15 use forge_core::{Action, MergeStyle, PullRequest, authorize};
16-use futures_util::{Stream, stream};
17 use serde::Deserialize;16 use serde::Deserialize;
18-use tokio::sync::watch;
19 use topcoat::Result;17 use topcoat::Result;
20 use topcoat::context::{Cx, context};18 use topcoat::context::{Cx, context};
21 use topcoat::router::content::Form;19 use topcoat::router::content::Form;
22-use topcoat::router::content::sse::Event;
23 use topcoat::router::error::{bad_request, forbidden, not_found, see_other};20 use topcoat::router::error::{bad_request, forbidden, not_found, see_other};
24 use topcoat::router::response::Response;21 use topcoat::router::response::Response;
25 use topcoat::router::{page, path_param, query_params, route};22 use topcoat::router::{page, path_param, query_params, route};
@@ -28,10 +25,11 @@ use topcoat::view::{View, component, view};
28 use crate::auth::require_csrf;25 use crate::auth::require_csrf;
29 use crate::i18n::merge_queue::{self as g, K};26 use crate::i18n::merge_queue::{self as g, K};
30 use crate::i18n::{self, Lang};27 use crate::i18n::{self, Lang};
31-use crate::live::{changed_event, events_response};28+use crate::live::{events_response, wake_stream};
32 use crate::merge::ERR_NOT_OPEN;29 use crate::merge::ERR_NOT_OPEN;
33 use crate::merge_queue as queue;30 use crate::merge_queue as queue;
34 use crate::pages::issue_parts::parse_number;31 use crate::pages::issue_parts::parse_number;
32+use crate::pages::pull_flow::pull_href;
35 use crate::pages::repo::repo_head;33 use crate::pages::repo::repo_head;
36 use crate::pages::repo_ctx::{RepoCtx, load_repo};34 use crate::pages::repo_ctx::{RepoCtx, load_repo};
37 use crate::state::AppState;35 use crate::state::AppState;
@@ -55,15 +53,6 @@ struct QueueQuery {
55 show: Option<String>,53 show: Option<String>,
56 }54 }
57 55
58-fn pull_href(ctx: &RepoCtx, number: i64) -> String {
59- repo_href(
60- &ctx.repo.owner_name,
61- &ctx.repo.name,
62- "pulls",
63- &number.to_string(),
64- )
65-}
66-
67 fn queue_href(ctx: &RepoCtx) -> String {56 fn queue_href(ctx: &RepoCtx) -> String {
68 repo_href(&ctx.repo.owner_name, &ctx.repo.name, "merge-queue", "")57 repo_href(&ctx.repo.owner_name, &ctx.repo.name, "merge-queue", "")
69 }58 }
@@ -323,6 +312,8 @@ fn reason_label(lang: Lang, reason: &str) -> String {
323 "permission" => K::ReasonPermission,312 "permission" => K::ReasonPermission,
324 "blocked" => K::ReasonBlocked,313 "blocked" => K::ReasonBlocked,
325 "no_branch" => K::ReasonNoBranch,314 "no_branch" => K::ReasonNoBranch,
315+ "draft" => K::ReasonDraft,
316+ "head_missing" => K::ReasonHeadMissing,
326 _ => return reason.to_owned(),317 _ => return reason.to_owned(),
327 };318 };
328 g::t(lang, key).to_owned()319 g::t(lang, key).to_owned()
@@ -335,14 +326,7 @@ async fn queue_events(cx: &Cx) -> Result<Response> {
335 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;326 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
336 let state = context::<AppState>(cx);327 let state = context::<AppState>(cx);
337 let wake = state.ci_live.subscribe_queue(&ctx.repo.id);328 let wake = state.ci_live.subscribe_queue(&ctx.repo.id);
338- events_response(cx, queue_changes(wake))329+ events_response(cx, wake_stream(wake, "queue"))
339-}
340-
341-fn queue_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static {
342- stream::unfold(wake, |mut wake| async move {
343- wake.changed().await.ok()?;
344- Some((changed_event("queue".to_owned()), wake))
345- })
346 }330 }
347 331
348 #[component]332 #[component]
@@ -378,52 +362,30 @@ async fn queue_body(
378 }362 }
379 } else {363 } else {
380 for row in rows.iter() {364 for row in rows.iter() {
381- if row.remove {365+ <div class="line" data-kb-row="">
382- <div class="line" data-kb-row="">366+ <span class="name"><a href=(row.pull_href.as_str())>"#"(row.pull_number)" "(row.pull_title.as_str())</a></span>
383- <span class="name"><a href=(row.pull_href.as_str())>"#"(row.pull_number)" "(row.pull_title.as_str())</a></span>367+ <span class="val">
384- <span class="val">368+ if !row.position.is_empty() {
385- if !row.position.is_empty() {369+ (g::t(lang, K::QueueColPosition)) " " (row.position.as_str()) " · "
386- (g::t(lang, K::QueueColPosition)) " " (row.position.as_str()) " · "370+ }
387- }371+ <span class=(row.state_class)>(row.state)</span>
388- <span class=(row.state_class)>(row.state)</span>372+ " · " <code>(row.branch.as_str())</code>
389- " · " <code>(row.branch.as_str())</code>373+ " · " (row.by.as_str())
390- " · " (row.by.as_str())374+ " · " rel_time(lang: lang, stamp: row.queued_at.as_str())
391- " · " rel_time(lang: lang, stamp: row.queued_at.as_str())375+ " · "
392- " · "376+ if let Some(href) = row.run_href.as_ref() {
393- if let Some(href) = row.run_href.as_ref() {377+ <a href=(href.as_str())>(row.run_label.as_str())</a>
394- <a href=(href.as_str())>(row.run_label.as_str())</a>378+ } else {
395- } else {379+ <span>(row.run_label.as_str())</span>
396- <span>(row.run_label.as_str())</span>380+ }
397- }381+ if !row.reason.is_empty() {
398- if !row.reason.is_empty() {382+ " · " (row.reason.as_str())
399- " · " (row.reason.as_str())383+ }
400- }384+ </span>
401- </span>385+ if row.remove {
402 confirm_act(lang: lang, label: remove_label, action: row.remove_action.as_str(), csrf: csrf.as_str(), note: Some(remove_note.clone()))386 confirm_act(lang: lang, label: remove_label, action: row.remove_action.as_str(), csrf: csrf.as_str(), note: Some(remove_note.clone()))
403- </div>387+ }
404- } else {388+ </div>
405- <div class="line" data-kb-row="">
406- <span class="name"><a href=(row.pull_href.as_str())>"#"(row.pull_number)" "(row.pull_title.as_str())</a></span>
407- <span class="val">
408- if !row.position.is_empty() {
409- (g::t(lang, K::QueueColPosition)) " " (row.position.as_str()) " · "
410- }
411- <span class=(row.state_class)>(row.state)</span>
412- " · " <code>(row.branch.as_str())</code>
413- " · " (row.by.as_str())
414- " · " rel_time(lang: lang, stamp: row.queued_at.as_str())
415- " · "
416- if let Some(href) = row.run_href.as_ref() {
417- <a href=(href.as_str())>(row.run_label.as_str())</a>
418- } else {
419- <span>(row.run_label.as_str())</span>
420- }
421- if !row.reason.is_empty() {
422- " · " (row.reason.as_str())
423- }
424- </span>
425- </div>
426- }
427 }389 }
428 }390 }
429 </div>391 </div>
crates/forge-web-repo/src/pages/pull_branch.rsmodified+33 -21
@@ -100,13 +100,7 @@ async fn branch_post(cx: &Cx, csrf: &str, op: Op) -> Result<Response> {
100 let head = head_repo(state, &pr).await?;100 let head = head_repo(state, &pr).await?;
101 match &head {101 match &head {
102 Some(head) => {102 Some(head) => {
103- let role = state.store.collaborator_role(&head.id, &user.id).await?;103+ if !head_writable(state, head, &user).await? {
104- let org_role = state
105- .store
106- .org_repo_role(&head.owner_id, &user.id, &head.id)
107- .await?;
108- if head.archived || authorize(Some(&user), head, role, org_role, Action::Write).is_err()
109- {
110 return Err(forbidden().into());104 return Err(forbidden().into());
111 }105 }
112 }106 }
@@ -149,6 +143,29 @@ fn finished(pr: &PullRequest) -> bool {
149 pr.merged_at.is_some() || pr.issue.state != IssueState::Open143 pr.merged_at.is_some() || pr.issue.state != IssueState::Open
150 }144 }
151 145
146+async fn head_writable(
147+ state: &AppState,
148+ head: &forge_core::Repo,
149+ user: &User,
150+) -> forge_core::Result<bool> {
151+ let role = state.store.collaborator_role(&head.id, &user.id).await?;
152+ let org_role = state
153+ .store
154+ .org_repo_role(&head.owner_id, &user.id, &head.id)
155+ .await?;
156+ Ok(!head.archived && authorize(Some(user), head, role, org_role, Action::Write).is_ok())
157+}
158+
159+fn cas_refusal(
160+ result: forge_git::error::Result<()>,
161+) -> forge_core::Result<Option<&'static str>> {
162+ match result {
163+ Ok(()) => Ok(None),
164+ Err(forge_git::error::Error::RefMoved(_)) => Ok(Some(ERR_MOVED)),
165+ Err(e) => Err(e.into()),
166+ }
167+}
168+
152 /// The head repo of `pr` when it still exists.169 /// The head repo of `pr` when it still exists.
153 async fn head_repo(170 async fn head_repo(
154 state: &AppState,171 state: &AppState,
@@ -177,10 +194,10 @@ async fn delete_branch(
177 Some(tip) if tip != pr.head_oid => return Ok(Some(ERR_MOVED)),194 Some(tip) if tip != pr.head_oid => return Ok(Some(ERR_MOVED)),
178 Some(_) => {}195 Some(_) => {}
179 }196 }
180- match delete_ref_cas(&state.git, &path, &refname, &pr.head_oid).await {197+ if let Some(code) =
181- Ok(()) => {}198+ cas_refusal(delete_ref_cas(&state.git, &path, &refname, &pr.head_oid).await)?
182- Err(forge_git::error::Error::RefMoved(_)) => return Ok(Some(ERR_MOVED)),199+ {
183- Err(e) => return Err(e.into()),200+ return Ok(Some(code));
184 }201 }
185 record_ref_change(state, head, user, &refname, &pr.head_oid, ZERO_OID).await;202 record_ref_change(state, head, user, &refname, &pr.head_oid, ZERO_OID).await;
186 state203 state
@@ -214,10 +231,10 @@ async fn restore_branch(
214 if read_commit(&path, &pr.head_oid)?.is_none() {231 if read_commit(&path, &pr.head_oid)?.is_none() {
215 return Ok(Some(ERR_MISSING));232 return Ok(Some(ERR_MISSING));
216 }233 }
217- match update_ref_cas(&state.git, &path, &refname, &pr.head_oid, ZERO_OID).await {234+ if let Some(code) = cas_refusal(
218- Ok(()) => {}235+ update_ref_cas(&state.git, &path, &refname, &pr.head_oid, ZERO_OID).await,
219- Err(forge_git::error::Error::RefMoved(_)) => return Ok(Some(ERR_MOVED)),236+ )? {
220- Err(e) => return Err(e.into()),237+ return Ok(Some(code));
221 }238 }
222 record_ref_change(state, head, user, &refname, ZERO_OID, &pr.head_oid).await;239 record_ref_change(state, head, user, &refname, ZERO_OID, &pr.head_oid).await;
223 state240 state
@@ -304,12 +321,7 @@ pub(crate) async fn branch_action(
304 let Some(head) = head_repo(state, pr).await? else {321 let Some(head) = head_repo(state, pr).await? else {
305 return Ok(None);322 return Ok(None);
306 };323 };
307- let role = state.store.collaborator_role(&head.id, &user.id).await?;324+ if !head_writable(state, &head, user).await? {
308- let org_role = state
309- .store
310- .org_repo_role(&head.owner_id, &user.id, &head.id)
311- .await?;
312- if head.archived || authorize(Some(user), &head, role, org_role, Action::Write).is_err() {
313 return Ok(None);325 return Ok(None);
314 }326 }
315 let path = repo_path(&state.git.data_dir, &head.id)?;327 let path = repo_path(&state.git.data_dir, &head.id)?;
crates/forge-web-repo/src/pages/pull_files.rsmodified+12 -108
@@ -1,9 +1,3 @@
1-//! The Files changed tab of a pull request, `/{owner}/{repo}/pulls/{n}/files`. Each diff line has
2-//! an anchor and a "+" link (`?comment=<file>:<old|new>:<line>`), which opens an inline comment
3-//! form under that line. Existing review threads render under their lines. Signed-in viewers see
4-//! the decision pill under the diff. The header and tabs come from `pull_view`. The review POST
5-//! routes are in `pull_reviews`.
6-
7 use std::collections::{HashMap, HashSet};1 use std::collections::{HashMap, HashSet};
8 use std::sync::Arc;2 use std::sync::Arc;
9 3
@@ -27,7 +21,7 @@ use crate::i18n::pulls::{self as g, K};
27 use crate::i18n::{self, Lang};21 use crate::i18n::{self, Lang};
28 use crate::pages::edit_history::thread_edit_counts;22 use crate::pages::edit_history::thread_edit_counts;
29 use crate::pages::issue_parts::{check_write, csrf_of, may_converse, parse_number, triage, viewer};23 use crate::pages::issue_parts::{check_write, csrf_of, may_converse, parse_number, triage, viewer};
30-use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states};24+use crate::pages::pull_reviews::{error_from, pull_diff, suggest_states};
31 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header};25 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header};
32 use crate::pages::repo_ctx::{RepoCtx, load_repo};26 use crate::pages::repo_ctx::{RepoCtx, load_repo};
33 use crate::pages::tree::link_context;27 use crate::pages::tree::link_context;
@@ -41,7 +35,6 @@ path_param!(owner);
41 path_param!(repo);35 path_param!(repo);
42 path_param!(number);36 path_param!(number);
43 37
44-/// Parses a non-empty run of ASCII digits. `str::parse` alone would also accept a leading `+`.
45 fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> {38 fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> {
46 if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {39 if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
47 return None;40 return None;
@@ -49,7 +42,6 @@ fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> {
49 raw.parse().ok()42 raw.parse().ok()
50 }43 }
51 44
52-/// The `comment=<file>:<old|new>:<line>` target of an inline form. Anything else is ignored.
53 fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> {45 fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> {
54 let request = uri(cx);46 let request = uri(cx);
55 let query = request.query()?;47 let query = request.query()?;
@@ -61,24 +53,12 @@ fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> {
61 parts.next().is_none().then_some((index, side, line))53 parts.next().is_none().then_some((index, side, line))
62 }54 }
63 55
64-/// The message for the `review_error` query value of the request, when it is a known code. The
65-/// codes and their messages are shared with the review routes (`pull_reviews::error_text`).
66-fn review_error_from(lang: Lang, cx: &Cx) -> Option<String> {
67- let request = uri(cx);
68- let query = request.query()?;
69- let (_, code) =
70- form_urlencoded::parse(query.as_bytes()).find(|(key, _)| *key == "review_error")?;
71- error_text_in(lang, &code).map(str::to_owned)
72-}
73-
74-/// Index of the diff file a thread's path names, matched on either side of a rename.
75 fn file_index(diff: &CommitDiff, path: &str) -> Option<usize> {56 fn file_index(diff: &CommitDiff, path: &str) -> Option<usize> {
76 diff.files57 diff.files
77 .iter()58 .iter()
78 .position(|f| f.new_path.as_deref() == Some(path) || f.old_path.as_deref() == Some(path))59 .position(|f| f.new_path.as_deref() == Some(path) || f.old_path.as_deref() == Some(path))
79 }60 }
80 61
81-/// The path a file's Viewed mark is kept under: its new path, or the old one when it was deleted.
82 fn mark_path(file: &FileDiff) -> Option<&str> {62 fn mark_path(file: &FileDiff) -> Option<&str> {
83 if file.status == DiffStatus::Deleted {63 if file.status == DiffStatus::Deleted {
84 file.old_path.as_deref()64 file.old_path.as_deref()
@@ -87,7 +67,6 @@ fn mark_path(file: &FileDiff) -> Option<&str> {
87 }67 }
88 }68 }
89 69
90-/// The file's heading in the diff, as `diff_section` writes it: `old → new` for a rename.
91 fn file_label(file: &FileDiff) -> String {70 fn file_label(file: &FileDiff) -> String {
92 match (&file.old_path, &file.new_path) {71 match (&file.old_path, &file.new_path) {
93 (Some(old), Some(new)) if old != new => format!("{old} → {new}"),72 (Some(old), Some(new)) if old != new => format!("{old} → {new}"),
@@ -97,12 +76,9 @@ fn file_label(file: &FileDiff) -> String {
97 }76 }
98 }77 }
99 78
100-/// Where a file's mark stands for the viewer.
101 #[derive(Clone, Copy, PartialEq, Eq)]79 #[derive(Clone, Copy, PartialEq, Eq)]
102 enum MarkState {80 enum MarkState {
103- /// Marked at the file's current blob.
104 Viewed,81 Viewed,
105- /// Marked at an older blob: the file changed since.
106 Changed,82 Changed,
107 Unviewed,83 Unviewed,
108 }84 }
@@ -117,29 +93,16 @@ impl MarkState {
117 }93 }
118 }94 }
119 95
120-/// One file of the full diff, as the Files pane lists it.
121 struct FileRow {96 struct FileRow {
122 path: String,97 path: String,
123- /// The heading `diff_section` gives the file, to find its section on the page.
124 label: String,98 label: String,
125 state: MarkState,99 state: MarkState,
126 additions: u32,100 additions: u32,
127 deletions: u32,101 deletions: u32,
128- /// The file's index in the diff the page shows, when that diff lists it.
129 index: Option<usize>,102 index: Option<usize>,
130- /// A thread on this file is still open.
131 commented: bool,103 commented: bool,
132 }104 }
133 105
134-/// Where the viewed checkboxes post, for a signed-in viewer.
135-struct ViewedControls {
136- pr_href: String,
137- csrf: String,
138-}
139-
140-/// One row per file of the full diff. A mark counts only while its blob is the file's blob at the
141-/// head, so a file a later push changed shows as changed. `marks` is `None` for a signed-out
142-/// viewer, whose rows carry no marks and so no blob reads.
143 async fn file_rows(106 async fn file_rows(
144 state: &AppState,107 state: &AppState,
145 ctx: &RepoCtx,108 ctx: &RepoCtx,
@@ -179,14 +142,12 @@ async fn file_rows(
179 Ok(rows)142 Ok(rows)
180 }143 }
181 144
182-/// One segment of the strip above the diff: one file, its size among the files, and its state.
183 struct SegView {145 struct SegView {
184 class: String,146 class: String,
185 href: String,147 href: String,
186 label: String,148 label: String,
187 }149 }
188 150
189-/// One row of the Files rail, with its tick and counts worked out.
190 struct RailFile {151 struct RailFile {
191 class: String,152 class: String,
192 tick: String,153 tick: String,
@@ -198,9 +159,6 @@ struct RailFile {
198 counts: String,159 counts: String,
199 }160 }
200 161
201-/// The Files rail: one row per file of the full diff, with its viewed tick, its name and its
202-/// counts. A row links to its file in the diff. For a signed-in viewer the tick is the Viewed
203-/// toggle, and a changed file says so.
204 #[component]162 #[component]
205 async fn files_rail(163 async fn files_rail(
206 cx: &Cx,164 cx: &Cx,
@@ -248,7 +206,6 @@ async fn files_rail(
248 })206 })
249 }207 }
250 208
251-/// The diff pane's top row: Unified or Split, and whitespace. Its links are the toolbar's own.
252 #[component]209 #[component]
253 async fn diff_top(210 async fn diff_top(
254 cx: &Cx,211 cx: &Cx,
@@ -271,7 +228,6 @@ async fn diff_top(
271 })228 })
272 }229 }
273 230
274-/// The Viewed form body: `viewed` is `1` to mark the file, anything else clears the mark.
275 #[derive(Deserialize)]231 #[derive(Deserialize)]
276 struct ViewedForm {232 struct ViewedForm {
277 csrf: String,233 csrf: String,
@@ -279,10 +235,6 @@ struct ViewedForm {
279 viewed: String,235 viewed: String,
280 }236 }
281 237
282-/// Marks or clears the viewer's Viewed mark on one file. The blob is read from the head here, never
283-/// taken from the form, so a mark always names the file as it is now. A path that is not a file of
284-/// the pull request changes nothing. The repo and pull lookups match the Files page, so an
285-/// unreadable repo answers with the same not-found.
286 #[route(POST "/{owner}/{repo}/pulls/{number}/viewed")]238 #[route(POST "/{owner}/{repo}/pulls/{number}/viewed")]
287 async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther> {239 async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther> {
288 let number = parse_number(number(cx))?;240 let number = parse_number(number(cx))?;
@@ -328,9 +280,6 @@ async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther>
328 Ok(see_other(files))280 Ok(see_other(files))
329 }281 }
330 282
331-/// The decision pill under the diff: the viewed count, the open threads, the next unviewed file and
332-/// Finish review. Finish review opens the review form in a panel above the pill. Approve and
333-/// Request changes in the pull's head submit the same form.
334 #[component]283 #[component]
335 async fn review_bar(284 async fn review_bar(
336 cx: &Cx,285 cx: &Cx,
@@ -381,7 +330,6 @@ async fn review_bar(
381 <label for="review-body">(summary)</label>330 <label for="review-body">(summary)</label>
382 <textarea id="review-body" name="body" rows="3"></textarea>331 <textarea id="review-body" name="body" rows="3"></textarea>
383 </div>332 </div>
384- // An author cannot approve or block their own pull, so they only comment.
385 if !is_author {333 if !is_author {
386 <label class="opt"><input type="radio" name="state" value="approve"><span>(approve)</span></label>334 <label class="opt"><input type="radio" name="state" value="approve"><span>(approve)</span></label>
387 <label class="opt"><input type="radio" name="state" value="request_changes"><span>(changes)</span></label>335 <label class="opt"><input type="radio" name="state" value="request_changes"><span>(changes)</span></label>
@@ -403,7 +351,6 @@ async fn review_bar(
403 })351 })
404 }352 }
405 353
406-/// The `file=<index>` param: the diff file the Files pane marks as current.
407 fn file_param(cx: &Cx) -> Option<usize> {354 fn file_param(cx: &Cx) -> Option<usize> {
408 let request = uri(cx);355 let request = uri(cx);
409 let query = request.query()?;356 let query = request.query()?;
@@ -411,6 +358,10 @@ fn file_param(cx: &Cx) -> Option<usize> {
411 digits::<usize>(&raw)358 digits::<usize>(&raw)
412 }359 }
413 360
361+fn file_href(i: usize) -> String {
362+ format!("?file={i}#file-{}", i + 1)
363+}
364+
414 #[page("/{owner}/{repo}/pulls/{number}/files")]365 #[page("/{owner}/{repo}/pulls/{number}/files")]
415 async fn pull_files(cx: &Cx) -> Result<impl View> {366 async fn pull_files(cx: &Cx) -> Result<impl View> {
416 let number = parse_number(number(cx))?;367 let number = parse_number(number(cx))?;
@@ -429,8 +380,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
429 (add + file.additions, del + file.deletions)380 (add + file.additions, del + file.deletions)
430 }));381 }));
431 let opts = DiffOpts::from_cx(cx, None).await?;382 let opts = DiffOpts::from_cx(cx, None).await?;
432- // The Files pane lists the full diff. Its marks are read here, and its rows are built once the
433- // shown diff is known, since a whitespace-ignoring view may list fewer files.
434 let viewer_user = viewer(&ctx);383 let viewer_user = viewer(&ctx);
435 let marks = match &viewer_user {384 let marks = match &viewer_user {
436 Some(user) => Some(385 Some(user) => Some(
@@ -441,12 +390,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
441 ),390 ),
442 None => None,391 None => None,
443 };392 };
444- let controls = viewer_user.as_ref().map(|_| ViewedControls {
445- pr_href: frame.href.clone(),
446- csrf: csrf_of(&ctx),
447- });
448- // With whitespace ignored the file list can shrink, so file indexes differ from the comment
449- // routes' view. Existing threads still show; new inline comments wait for the full diff.
450 let shown_ws = if opts.ignore_ws {393 let shown_ws = if opts.ignore_ws {
451 Some(394 Some(
452 range_diff_files_ws(395 range_diff_files_ws(
@@ -484,14 +427,11 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
484 Action::Write,427 Action::Write,
485 )428 )
486 .is_ok();429 .is_ok();
487- // Comments and replies stay open on a closed pull request; new reviews do not.
488 let can_review = can_comment && open;430 let can_review = can_comment && open;
489- // Approve and request changes are offered to every viewer who may review but did not open it.
490 let href = frame.href.clone();431 let href = frame.href.clone();
491 let csrf = csrf_of(&ctx);432 let csrf = csrf_of(&ctx);
433+ let panel = signed_in.then(|| (format!("{href}/viewed"), csrf.clone()));
492 434
493- // The viewer's own pending comments are included by `review_threads`. Outdated threads are
494- // left out of the Files tab; they still show in the Conversation.
495 let threads = state435 let threads = state
496 .store436 .store
497 .review_threads(&pr.issue.id, viewer_id.as_deref())437 .review_threads(&pr.issue.id, viewer_id.as_deref())
@@ -521,7 +461,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
521 }461 }
522 }462 }
523 463
524- // The view owns the diff it shows, so the shown diff moves here once every borrow of it is done.
525 let diff = shown_ws.unwrap_or(full_diff);464 let diff = shown_ws.unwrap_or(full_diff);
526 465
527 let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, "");466 let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, "");
@@ -547,7 +486,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
547 ctx: thread_ctx,486 ctx: thread_ctx,
548 };487 };
549 488
550- // The diff pane has its own top row, so the section's toolbar is left off.
551 let mut section_opts = opts.clone();489 let mut section_opts = opts.clone();
552 section_opts.enabled = false;490 section_opts.enabled = false;
553 section_opts.only = selected;491 section_opts.only = selected;
@@ -557,21 +495,13 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
557 let split_on = opts.split;495 let split_on = opts.split;
558 let ws_on = opts.ignore_ws;496 let ws_on = opts.ignore_ws;
559 497
560- let error = review_error_from(lang, cx);498+ let error = error_from(lang, cx);
561- // The page follows the pull request's event stream: a change re-renders it.
562 let live = format!("{href}/events");499 let live = format!("{href}/events");
563 let owner = ctx.repo.owner_name.clone();500 let owner = ctx.repo.owner_name.clone();
564 let name = ctx.repo.name.clone();501 let name = ctx.repo.name.clone();
565 let parent = pr.merge_base.clone();502 let parent = pr.merge_base.clone();
566 let page_title = frame.page_title.clone();503 let page_title = frame.page_title.clone();
567- let panel_action = controls504+ let (panel_action, panel_csrf) = panel.unwrap_or_default();
568- .as_ref()
569- .map(|c| format!("{}/viewed", c.pr_href))
570- .unwrap_or_default();
571- let panel_csrf = controls
572- .as_ref()
573- .map(|c| c.csrf.clone())
574- .unwrap_or_default();
575 505
576 let done = rows506 let done = rows
577 .iter()507 .iter()
@@ -596,7 +526,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
596 let current_path = current.map(|row| row.path.clone()).unwrap_or_default();526 let current_path = current.map(|row| row.path.clone()).unwrap_or_default();
597 let current_viewed = current.is_some_and(|row| row.state == MarkState::Viewed);527 let current_viewed = current.is_some_and(|row| row.state == MarkState::Viewed);
598 let mark_shown = signed_in && !archived && current.is_some();528 let mark_shown = signed_in && !archived && current.is_some();
599- // The next file after the current one that is not viewed, wrapping round.
600 let next = {529 let next = {
601 let start = rows530 let start = rows
602 .iter()531 .iter()
@@ -610,9 +539,8 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
610 row.index.is_some() && row.index != selected && row.state != MarkState::Viewed539 row.index.is_some() && row.index != selected && row.state != MarkState::Viewed
611 })540 })
612 .and_then(|row| row.index)541 .and_then(|row| row.index)
613- .map(|i| format!("?file={i}#file-{}", i + 1))542+ .map(file_href)
614 };543 };
615- // The strip above the diff: one segment per file, sized by its changed lines.
616 let segs: Vec<SegView> = rows544 let segs: Vec<SegView> = rows
617 .iter()545 .iter()
618 .map(|row| {546 .map(|row| {
@@ -630,9 +558,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
630 };558 };
631 SegView {559 SegView {
632 class: format!("seg {fr} {state}").trim_end().to_owned(),560 class: format!("seg {fr} {state}").trim_end().to_owned(),
633- href: row561+ href: row.index.map_or_else(|| "#".to_owned(), file_href),
634- .index
635- .map_or_else(|| "#".to_owned(), |i| format!("?file={i}#file-{}", i + 1)),
636 label: row.path.clone(),562 label: row.path.clone(),
637 }563 }
638 })564 })
@@ -656,7 +582,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
656 }582 }
657 .to_owned(),583 .to_owned(),
658 tick,584 tick,
659- href: row.index.map(|i| format!("?file={i}#file-{}", i + 1)),585+ href: row.index.map(file_href),
660 path: row.path,586 path: row.path,
661 label: row.label,587 label: row.label,
662 state: row.state,588 state: row.state,
@@ -675,7 +601,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
675 }601 }
676 </div>602 </div>
677 if let Some(message) = error {603 if let Some(message) = error {
678- alert(message: message.as_str())604+ alert(message: message)
679 }605 }
680 <div class="work" data-live=(live.as_str()) data-viewed-panel="" data-action=(panel_action.as_str()) data-csrf=(panel_csrf.as_str())>606 <div class="work" data-live=(live.as_str()) data-viewed-panel="" data-action=(panel_action.as_str()) data-csrf=(panel_csrf.as_str())>
681 files_rail(lang: lang, rows: rail, done_text: viewed_text.clone(), signed_in: signed_in, archived: archived)607 files_rail(lang: lang, rows: rail, done_text: viewed_text.clone(), signed_in: signed_in, archived: archived)
@@ -719,8 +645,6 @@ mod tests {
719 format!("__Host-{SESSION_COOKIE}={token}")645 format!("__Host-{SESSION_COOKIE}={token}")
720 }646 }
721 647
722- /// The page's own `<main>` element. The shell's header echoes the request URL (theme
723- /// form `back` field), so the body checks are scoped to `<main>`.
724 fn page_main(body: &str) -> &str {648 fn page_main(body: &str) -> &str {
725 body.split_once("<main tabindex=\"-1\"")649 body.split_once("<main tabindex=\"-1\"")
726 .and_then(|(_, rest)| rest.split_once('>'))650 .and_then(|(_, rest)| rest.split_once('>'))
@@ -729,7 +653,6 @@ mod tests {
729 .expect("page has a <main> element")653 .expect("page has a <main> element")
730 }654 }
731 655
732- /// Sends one GET through the router and returns `(status, body)`.
733 async fn get(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {656 async fn get(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
734 let mut req = Request::builder().method("GET").uri(uri);657 let mut req = Request::builder().method("GET").uri(uri);
735 if let Some(token) = token {658 if let Some(token) = token {
@@ -741,7 +664,6 @@ mod tests {
741 (status, String::from_utf8_lossy(&bytes).into_owned())664 (status, String::from_utf8_lossy(&bytes).into_owned())
742 }665 }
743 666
744- /// A user with a session whose CSRF token is `{token}-csrf`.
745 async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {667 async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
746 let user = fx668 let user = fx
747 .store669 .store
@@ -753,14 +675,11 @@ mod tests {
753 user675 user
754 }676 }
755 677
756- /// The repo owner, signed in with token `tahinli`.
757 async fn owner_session(fx: &Fixture) {678 async fn owner_session(fx: &Fixture) {
758 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();679 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
759 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;680 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
760 }681 }
761 682
762- /// Pushes a `feature` branch (one commit adding `feat.txt` with the line `feature`) and opens
763- /// a pull request for it against `main`. Returns the pull request number.
764 async fn open_pull(fx: &Fixture) -> i64 {683 async fn open_pull(fx: &Fixture) -> i64 {
765 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);684 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
766 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);685 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
@@ -810,7 +729,6 @@ mod tests {
810 pr.issue.number729 pr.issue.number
811 }730 }
812 731
813- /// The pull request's issue id and head commit.
814 async fn pull_ids(fx: &Fixture, number: i64) -> (String, String) {732 async fn pull_ids(fx: &Fixture, number: i64) -> (String, String) {
815 let repo = fx733 let repo = fx
816 .store734 .store
@@ -831,9 +749,6 @@ mod tests {
831 format!("/{OWNER}/{REPO}/pulls/{number}/files{query}")749 format!("/{OWNER}/{REPO}/pulls/{number}/files{query}")
832 }750 }
833 751
834- /// Every Files tab scenario for one open pull request. The pull is opened once. Each
835- /// scenario adds only what it needs, and the scenarios that add comments run last in an
836- /// order where no later scenario is confused by an earlier comment.
837 #[tokio::test]752 #[tokio::test]
838 async fn files_tab_scenarios_on_one_open_pull() {753 async fn files_tab_scenarios_on_one_open_pull() {
839 let fx = Fixture::new(Visibility::Public).await;754 let fx = Fixture::new(Visibility::Public).await;
@@ -844,7 +759,6 @@ mod tests {
844 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();759 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
845 let uri = files_uri(number, "");760 let uri = files_uri(number, "");
846 761
847- // Turkish viewers get the translated review bar.
848 let req = Request::builder()762 let req = Request::builder()
849 .method("GET")763 .method("GET")
850 .uri(uri.as_str())764 .uri(uri.as_str())
@@ -856,13 +770,11 @@ mod tests {
856 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();770 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
857 let body = String::from_utf8_lossy(&bytes).into_owned();771 let body = String::from_utf8_lossy(&bytes).into_owned();
858 assert!(body.contains("İncelemeyi tamamla"), "turkish bar: {body}");772 assert!(body.contains("İncelemeyi tamamla"), "turkish bar: {body}");
859- // With nothing pending there is nothing to discard.
860 assert!(773 assert!(
861 !body.contains("Bekleyen yorumları sil"),774 !body.contains("Bekleyen yorumları sil"),
862 "turkish bar: {body}"775 "turkish bar: {body}"
863 );776 );
864 777
865- // Signed-in viewer: line anchors and plus links.
866 let (status, body) = get(&fx.router, &uri, Some("tahinli")).await;778 let (status, body) = get(&fx.router, &uri, Some("tahinli")).await;
867 assert_eq!(status, 200, "anchors");779 assert_eq!(status, 200, "anchors");
868 assert!(body.contains("id=\"L-0-new-1\""), "anchors: {body}");780 assert!(body.contains("id=\"L-0-new-1\""), "anchors: {body}");
@@ -872,7 +784,6 @@ mod tests {
872 );784 );
873 assert!(body.contains("id=\"review-form\""), "review bar: {body}");785 assert!(body.contains("id=\"review-form\""), "review bar: {body}");
874 786
875- // A well-formed `comment` param opens the form under its line.
876 let (status, body) = get(787 let (status, body) = get(
877 &fx.router,788 &fx.router,
878 &files_uri(number, "?comment=0:new:1"),789 &files_uri(number, "?comment=0:new:1"),
@@ -896,7 +807,6 @@ mod tests {
896 let form = body.find("name=\"file_index\"").unwrap();807 let form = body.find("name=\"file_index\"").unwrap();
897 assert!(form > line, "the form sits after its line");808 assert!(form > line, "the form sits after its line");
898 809
899- // Malformed `comment` params are ignored.
900 for query in [810 for query in [
901 "?comment=abc",811 "?comment=abc",
902 "?comment=0:bogus:1",812 "?comment=0:bogus:1",
@@ -911,7 +821,6 @@ mod tests {
911 assert!(!body.contains("name=\"file_index\""), "garbage {query}");821 assert!(!body.contains("name=\"file_index\""), "garbage {query}");
912 }822 }
913 823
914- // The review bar hides approve from the pull's author only.
915 let (_, author) = get(&fx.router, &uri, Some("tahinli")).await;824 let (_, author) = get(&fx.router, &uri, Some("tahinli")).await;
916 assert!(author.contains("value=\"comment\""), "author bar: {author}");825 assert!(author.contains("value=\"comment\""), "author bar: {author}");
917 assert!(826 assert!(
@@ -929,7 +838,6 @@ mod tests {
929 "reader bar: {other}"838 "reader bar: {other}"
930 );839 );
931 840
932- // Anonymous viewers get no comment controls at all.
933 let (status, body) = get(&fx.router, &files_uri(number, "?comment=0:new:1"), None).await;841 let (status, body) = get(&fx.router, &files_uri(number, "?comment=0:new:1"), None).await;
934 assert_eq!(status, 200, "anonymous");842 assert_eq!(status, 200, "anonymous");
935 assert!(!page_main(&body).contains("?comment="), "anonymous: {body}");843 assert!(!page_main(&body).contains("?comment="), "anonymous: {body}");
@@ -938,7 +846,6 @@ mod tests {
938 assert!(!body.contains("id=\"review-form\""), "anonymous: {body}");846 assert!(!body.contains("id=\"review-form\""), "anonymous: {body}");
939 assert!(!body.contains("class=\"diff-plus\""), "anonymous: {body}");847 assert!(!body.contains("class=\"diff-plus\""), "anonymous: {body}");
940 848
941- // A known review error shows its message, an unknown code shows nothing.
942 let (_, known) = get(849 let (_, known) = get(
943 &fx.router,850 &fx.router,
944 &files_uri(number, "?review_error=own_pr"),851 &files_uri(number, "?review_error=own_pr"),
@@ -959,7 +866,6 @@ mod tests {
959 );866 );
960 assert!(!unknown.contains("<b>hi</b>"), "unknown error: {unknown}");867 assert!(!unknown.contains("<b>hi</b>"), "unknown error: {unknown}");
961 868
962- // An outdated thread is hidden. Only the outdated comment exists at this point.
963 let comment = fx869 let comment = fx
964 .store870 .store
965 .add_review_comment(871 .add_review_comment(
@@ -987,7 +893,6 @@ mod tests {
987 "outdated: {body}"893 "outdated: {body}"
988 );894 );
989 895
990- // A pending comment is visible only to its author.
991 fx.store896 fx.store
992 .add_review_comment(897 .add_review_comment(
993 &issue_id,898 &issue_id,
@@ -1014,7 +919,6 @@ mod tests {
1014 "pending author: {author}"919 "pending author: {author}"
1015 );920 );
1016 921
1017- // A submitted thread renders under its line.
1018 fx.store922 fx.store
1019 .add_review_comment(923 .add_review_comment(
1020 &issue_id,924 &issue_id,
crates/forge-web-repo/src/pages/pull_flow.rsmodified+5 -9
@@ -10,7 +10,7 @@
10 //! or approvals that can still arrive. All of them answer with a redirect back to the pull10 //! or approvals that can still arrive. All of them answer with a redirect back to the pull
11 //! request (the soft-nav script follows it without a reload).11 //! request (the soft-nav script follows it without a reload).
12 12
13-use forge_core::{Action, IssueState, MergeStyle, PullRequest, authorize};13+use forge_core::{IssueState, MergeStyle, PullRequest};
14 use serde::Deserialize;14 use serde::Deserialize;
15 use topcoat::Result;15 use topcoat::Result;
16 use topcoat::context::{Cx, context};16 use topcoat::context::{Cx, context};
@@ -40,7 +40,7 @@ struct FlowForm {
40 style: String,40 style: String,
41 }41 }
42 42
43-fn pull_href(ctx: &RepoCtx, number: i64) -> String {43+pub(crate) fn pull_href(ctx: &RepoCtx, number: i64) -> String {
44 repo_href(44 repo_href(
45 &ctx.repo.owner_name,45 &ctx.repo.owner_name,
46 &ctx.repo.name,46 &ctx.repo.name,
@@ -49,10 +49,6 @@ fn pull_href(ctx: &RepoCtx, number: i64) -> String {
49 )49 )
50 }50 }
51 51
52-fn can_write(ctx: &RepoCtx, user: &forge_core::User) -> bool {
53- authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok()
54-}
55-
56 async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> {52 async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> {
57 let state = context::<AppState>(cx);53 let state = context::<AppState>(cx);
58 match state.store.pull_by_number(&ctx.repo.id, number).await? {54 match state.store.pull_by_number(&ctx.repo.id, number).await? {
@@ -77,7 +73,7 @@ async fn set_draft(cx: &Cx, csrf: &str, draft: bool) -> Result<Response> {
77 let (user, _) = require_csrf(cx, csrf).await?;73 let (user, _) = require_csrf(cx, csrf).await?;
78 let state = context::<AppState>(cx);74 let state = context::<AppState>(cx);
79 let pr = load(cx, &ctx, number).await?;75 let pr = load(cx, &ctx, number).await?;
80- if ctx.repo.archived || !(can_write(&ctx, &user) || user.id == pr.issue.author_id) {76+ if ctx.repo.archived || !(ctx.can_write() || user.id == pr.issue.author_id) {
81 return Err(forbidden().into());77 return Err(forbidden().into());
82 }78 }
83 let href = pull_href(&ctx, number);79 let href = pull_href(&ctx, number);
@@ -121,7 +117,7 @@ async fn auto_merge_enable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Respon
121 let number = parse_number(number(cx))?;117 let number = parse_number(number(cx))?;
122 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;118 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
123 let (user, _) = require_csrf(cx, &form.csrf).await?;119 let (user, _) = require_csrf(cx, &form.csrf).await?;
124- if ctx.repo.archived || !can_write(&ctx, &user) {120+ if !ctx.can_write() {
125 return Err(forbidden().into());121 return Err(forbidden().into());
126 }122 }
127 let state = context::<AppState>(cx);123 let state = context::<AppState>(cx);
@@ -152,7 +148,7 @@ async fn auto_merge_disable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Respo
152 let number = parse_number(number(cx))?;148 let number = parse_number(number(cx))?;
153 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;149 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
154 let (user, _) = require_csrf(cx, &form.csrf).await?;150 let (user, _) = require_csrf(cx, &form.csrf).await?;
155- if ctx.repo.archived || !can_write(&ctx, &user) {151+ if !ctx.can_write() {
156 return Err(forbidden().into());152 return Err(forbidden().into());
157 }153 }
158 let state = context::<AppState>(cx);154 let state = context::<AppState>(cx);
crates/forge-web-repo/src/pages/pull_view.rsmodified+29 -38
@@ -29,7 +29,7 @@ use crate::merge::{
29 ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE,29 ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE,
30 merge_gate,30 merge_gate,
31 };31 };
32-use crate::pages::commits::{CommitRow, now_secs};32+use crate::pages::commits::CommitRow;
33 use crate::pages::issue_meta::item_href;33 use crate::pages::issue_meta::item_href;
34 use crate::pages::issue_parts::{34 use crate::pages::issue_parts::{
35 CommentForm, ItemKind, Posted, check_write, comment_form, csrf_of, discussion_timeline,35 CommentForm, ItemKind, Posted, check_write, comment_form, csrf_of, discussion_timeline,
@@ -38,7 +38,7 @@ use crate::pages::issue_parts::{
38 };38 };
39 use crate::pages::notifications::notify_box_for;39 use crate::pages::notifications::notify_box_for;
40 use crate::pages::pull_branch::{self, branch_box, branch_error_from};40 use crate::pages::pull_branch::{self, branch_box, branch_error_from};
41-use crate::pages::pull_reviews::error_text_in;41+use crate::pages::pull_reviews::error_from;
42 use crate::pages::repo_ctx::{RepoCtx, load_repo};42 use crate::pages::repo_ctx::{RepoCtx, load_repo};
43 use crate::pages::review_requests::{load_reviewers, reviewers_box};43 use crate::pages::review_requests::{load_reviewers, reviewers_box};
44 use crate::state::AppState;44 use crate::state::AppState;
@@ -315,6 +315,20 @@ struct FlowView {
315 queue_add: Option<String>,315 queue_add: Option<String>,
316 }316 }
317 317
318+#[component]
319+async fn style_select(cx: &Cx, id: &str, lang: Lang) -> Result<impl View> {
320+ let merge = g::t(lang, K::StyleMergeCommit).trim();
321+ let squash = g::t(lang, K::StyleSquash).trim();
322+ let rebase = g::t(lang, K::StyleRebase).trim();
323+ Ok(view! {
324+ <select id=(id) name="style">
325+ <option value="merge">(merge)</option>
326+ <option value="squash">(squash)</option>
327+ <option value="rebase">(rebase)</option>
328+ </select>
329+ })
330+}
331+
318 /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of332 /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of
319 /// `ok`, `bad` or `muted` and picks the box colors.333 /// `ok`, `bad` or `muted` and picks the box colors.
320 #[component]334 #[component]
@@ -335,8 +349,6 @@ async fn merge_box(
335 let class = format!("sec merge-{tone}");349 let class = format!("sec merge-{tone}");
336 let required_heading = g::t(lang, K::RequiredChecksHeading);350 let required_heading = g::t(lang, K::RequiredChecksHeading);
337 let style_rebase = g::t(lang, K::StyleRebase);351 let style_rebase = g::t(lang, K::StyleRebase);
338- let style_merge_option = g::t(lang, K::StyleMergeCommit);
339- let style_squash_option = g::t(lang, K::StyleSquash);
340 let enable_auto = g::t(lang, K::EnableAutoMerge);352 let enable_auto = g::t(lang, K::EnableAutoMerge);
341 let disable_auto = g::t(lang, K::DisableAutoMerge);353 let disable_auto = g::t(lang, K::DisableAutoMerge);
342 let FlowView {354 let FlowView {
@@ -425,11 +437,7 @@ async fn merge_box(
425 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>437 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
426 <div class="field">438 <div class="field">
427 <label for="queue-style">(queue_add_label)</label>439 <label for="queue-style">(queue_add_label)</label>
428- <select id="queue-style" name="style">440+ style_select(id: "queue-style", lang: lang)
429- <option value="merge">(style_merge_option.trim())</option>
430- <option value="squash">(style_squash_option.trim())</option>
431- <option value="rebase">(style_rebase.trim())</option>
432- </select>
433 </div>441 </div>
434 <button type="submit" class="primary">(queue_add_label)</button>442 <button type="submit" class="primary">(queue_add_label)</button>
435 </form>443 </form>
@@ -445,11 +453,7 @@ async fn merge_box(
445 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>453 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
446 <div class="field">454 <div class="field">
447 <label for="auto-style">(enable_auto)</label>455 <label for="auto-style">(enable_auto)</label>
448- <select id="auto-style" name="style">456+ style_select(id: "auto-style", lang: lang)
449- <option value="merge">(style_merge_option.trim())</option>
450- <option value="squash">(style_squash_option.trim())</option>
451- <option value="rebase">(style_rebase.trim())</option>
452- </select>
453 </div>457 </div>
454 <button type="submit" class="primary">(enable_auto)</button>458 <button type="submit" class="primary">(enable_auto)</button>
455 </form>459 </form>
@@ -693,19 +697,15 @@ async fn pull_conversation(
693 // outdated head does not block it.697 // outdated head does not block it.
694 let queue_required =698 let queue_required =
695 crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await?;699 crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await?;
696- let queue_blocker = gate.as_ref().and_then(|gate| {700+ let blocked = gate
697- gate.blockers()701+ .as_ref()
698- .into_iter()702+ .and_then(|gate| {
699- .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE))703+ gate.blockers()
700- });704+ .into_iter()
701- let blocked = if queue_required {705+ .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE))
702- queue_blocker.and_then(|code| merge_error_text(lang, code))706+ })
703- } else {707+ .and_then(|code| merge_error_text(lang, code))
704- gate.as_ref()708+ .map(str::to_owned);
705- .and_then(|gate| gate.blocked())
706- .and_then(|code| merge_error_text(lang, code))
707- }
708- .map(str::to_owned);
709 let approvals = gate709 let approvals = gate
710 .as_ref()710 .as_ref()
711 .filter(|gate| gate.rule.required_approvals > 0)711 .filter(|gate| gate.rule.required_approvals > 0)
@@ -857,7 +857,7 @@ async fn pull_conversation(
857 .then(|| format!("/{owner}/{name}/commit/{oid}")),857 .then(|| format!("/{owner}/{name}/commit/{oid}")),
858 };858 };
859 859
860- let review_error = review_error_from(lang, cx);860+ let review_error = error_from(lang, cx);
861 let summary = state.store.review_summary(&pr.issue.id).await?;861 let summary = state.store.review_summary(&pr.issue.id).await?;
862 // Approvals of an earlier head no longer count for the merge rules (see `merge_gate`), so862 // Approvals of an earlier head no longer count for the merge rules (see `merge_gate`), so
863 // they are listed apart from the current ones.863 // they are listed apart from the current ones.
@@ -990,15 +990,6 @@ fn merge_error_from(lang: Lang, cx: &Cx) -> Option<String> {
990 merge_error_text(lang, &code).map(str::to_owned)990 merge_error_text(lang, &code).map(str::to_owned)
991 }991 }
992 992
993-/// The message for the `review_error` query value of the request, when it is a known code.
994-fn review_error_from(lang: Lang, cx: &Cx) -> Option<&'static str> {
995- let request = uri(cx);
996- let query = request.query()?;
997- let (_, code) =
998- form_urlencoded::parse(query.as_bytes()).find(|(key, _)| *key == "review_error")?;
999- error_text_in(lang, &code)
1000-}
1001-
1002 #[page("/{owner}/{repo}/pulls/{number}")]993 #[page("/{owner}/{repo}/pulls/{number}")]
1003 async fn pull_show(cx: &Cx) -> Result<impl View> {994 async fn pull_show(cx: &Cx) -> Result<impl View> {
1004 let (ctx, pr) = load_pull(cx).await?;995 let (ctx, pr) = load_pull(cx).await?;
@@ -1019,7 +1010,7 @@ async fn pull_commits(cx: &Cx) -> Result<impl View> {
1019 let owner = ctx.repo.owner_name.clone();1010 let owner = ctx.repo.owner_name.clone();
1020 let name = ctx.repo.name.clone();1011 let name = ctx.repo.name.clone();
1021 let tz = ctx.viewer_tz().to_owned();1012 let tz = ctx.viewer_tz().to_owned();
1022- let now = now_secs();1013+ let now = now_unix();
1023 let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect();1014 let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect();
1024 let statuses = state1015 let statuses = state
1025 .store1016 .store
crates/forge-web-repo/src/pages/pulls_list.rsmodified+3 -2
@@ -17,14 +17,15 @@ use crate::i18n::pulls::{self as g, K};
17 use crate::i18n::s;17 use crate::i18n::s;
18 use crate::i18n::{self, Lang};18 use crate::i18n::{self, Lang};
19 use crate::pages::issues_list::{19 use crate::pages::issues_list::{
20- AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href, stamp_unix,20+ AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href,
21 };21 };
22 use crate::pages::repo::repo_head;22 use crate::pages::repo::repo_head;
23 use crate::pages::repo_ctx::load_repo;23 use crate::pages::repo_ctx::load_repo;
24 use crate::state::AppState;24 use crate::state::AppState;
25 use crate::views::parts::{RailItem, SubPart, rail};25 use crate::views::parts::{RailItem, SubPart, rail};
26 use crate::views::{26 use crate::views::{
27- avatar_url_unknown, iso_time, now_unix, relative_time, repo_href, shell, user_link,27+ avatar_url_unknown, iso_time, now_unix, relative_time, repo_href, shell, stamp_unix,
28+ user_link,
28 };29 };
29 30
30 path_param!(owner);31 path_param!(owner);
crates/forge-web-repo/src/pages/reactions.rsmodified+1 -5
@@ -66,11 +66,7 @@ async fn react(cx: &Cx, kind: ItemKind, form: ReactionForm) -> Result<SeeOther>
66 if form.target_id != item.id {66 if form.target_id != item.id {
67 return Err(not_found().into());67 return Err(not_found().into());
68 }68 }
69- let prefix = match kind {69+ (ReactionTarget::Issue, kind.anchor(number))
70- ItemKind::Issue => "issue",
71- ItemKind::Pull => "pull",
72- };
73- (ReactionTarget::Issue, format!("{prefix}-{number}"))
74 }70 }
75 "comment" => {71 "comment" => {
76 let comment = comment_for(state, &item, &form.target_id).await?;72 let comment = comment_for(state, &item, &form.target_id).await?;
crates/forge-web-repo/src/pages/repo_collaborators.rsmodified+6 -15
@@ -31,7 +31,7 @@ use crate::pages::repo_settings::settings_frame;
31 use crate::pages::repo_settings_live::settings_head;31 use crate::pages::repo_settings_live::settings_head;
32 use crate::state::AppState;32 use crate::state::AppState;
33 use crate::views::parts::{PeopleList, PersonRow, people_list};33 use crate::views::parts::{PeopleList, PersonRow, people_list};
34-use crate::views::{alert, avatar_url, display_name, shell};34+use crate::views::{avatar_url, display_name, notice_line, shell};
35 35
36 path_param!(owner);36 path_param!(owner);
37 path_param!(repo);37 path_param!(repo);
@@ -128,11 +128,6 @@ async fn owns_repo_org(state: &AppState, ctx: &RepoCtx, actor: &User) -> Result<
128 ))128 ))
129 }129 }
130 130
131-/// `Owner/name` for redirects and form actions.
132-fn title_of(ctx: &RepoCtx) -> String {
133- format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)
134-}
135-
136 fn collaborators_redirect(title: &str) -> SeeOther {131 fn collaborators_redirect(title: &str) -> SeeOther {
137 see_other(format!("/{title}/settings/collaborators"))132 see_other(format!("/{title}/settings/collaborators"))
138 }133 }
@@ -146,7 +141,7 @@ struct FrameData {
146 141
147 impl FrameData {142 impl FrameData {
148 async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> {143 async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> {
149- let title = title_of(ctx);144+ let title = ctx.title();
150 Ok(Self {145 Ok(Self {
151 page_title: g::collaborators_page_title(lang, &title),146 page_title: g::collaborators_page_title(lang, &title),
152 title,147 title,
@@ -215,11 +210,7 @@ async fn collaborators_body(
215 repo_head(head: header, title: Some(section_name))210 repo_head(head: header, title: Some(section_name))
216 settings_frame(lang: lang, title: nav_title, current: "collaborators",211 settings_frame(lang: lang, title: nav_title, current: "collaborators",
217 if let Some((text, is_error)) = notice {212 if let Some((text, is_error)) = notice {
218- if is_error {213+ notice_line(text: text, is_error: is_error)
219- alert(message: text)
220- } else {
221- <p class="state" role="status">(text)</p>
222- }
223 }214 }
224 people_list(list: list)215 people_list(list: list)
225 )216 )
@@ -282,7 +273,7 @@ async fn collaborators_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOthe
282 if !ctx.can_admin() {273 if !ctx.can_admin() {
283 return Err(forbidden().into());274 return Err(forbidden().into());
284 }275 }
285- let title = title_of(&ctx);276+ let title = ctx.title();
286 let state = context::<AppState>(cx);277 let state = context::<AppState>(cx);
287 278
288 let Ok(role) = form.role.trim().parse::<Role>() else {279 let Ok(role) = form.role.trim().parse::<Role>() else {
@@ -368,7 +359,7 @@ async fn collaborators_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOt
368 if !ctx.can_admin() {359 if !ctx.can_admin() {
369 return Err(forbidden().into());360 return Err(forbidden().into());
370 }361 }
371- let title = title_of(&ctx);362+ let title = ctx.title();
372 let state = context::<AppState>(cx);363 let state = context::<AppState>(cx);
373 364
374 let Ok(role) = form.role.trim().parse::<Role>() else {365 let Ok(role) = form.role.trim().parse::<Role>() else {
@@ -429,7 +420,7 @@ async fn collaborators_remove(cx: &Cx, Form(form): Form<RemoveForm>) -> Result<S
429 if !ctx.can_admin() {420 if !ctx.can_admin() {
430 return Err(forbidden().into());421 return Err(forbidden().into());
431 }422 }
432- let title = title_of(&ctx);423+ let title = ctx.title();
433 let state = context::<AppState>(cx);424 let state = context::<AppState>(cx);
434 let target_id = form.user_id.trim();425 let target_id = form.user_id.trim();
435 let self_removal = target_id == actor.id;426 let self_removal = target_id == actor.id;
crates/forge-web-repo/src/pages/repo_secrets.rsmodified+8 -27
@@ -30,7 +30,7 @@ path_param!(owner);
30 path_param!(repo);30 path_param!(repo);
31 31
32 /// Longest secret value accepted, in bytes.32 /// Longest secret value accepted, in bytes.
33-pub const MAX_VALUE_BYTES: usize = 48 * 1024;33+const MAX_VALUE_BYTES: usize = 48 * 1024;
34 /// Longest secret name accepted, in characters.34 /// Longest secret name accepted, in characters.
35 const MAX_NAME_CHARS: usize = 64;35 const MAX_NAME_CHARS: usize = 64;
36 36
@@ -60,7 +60,7 @@ struct DeleteForm {
60 }60 }
61 61
62 /// `^[A-Z_][A-Z0-9_]{0,63}$`, checked by hand so no regex engine is needed.62 /// `^[A-Z_][A-Z0-9_]{0,63}$`, checked by hand so no regex engine is needed.
63-pub fn valid_name(name: &str) -> bool {63+fn valid_name(name: &str) -> bool {
64 let bytes = name.as_bytes();64 let bytes = name.as_bytes();
65 let Some((first, rest)) = bytes.split_first() else {65 let Some((first, rest)) = bytes.split_first() else {
66 return false;66 return false;
@@ -231,19 +231,14 @@ async fn secrets_body(
231 }231 }
232 <div>232 <div>
233 for row in rows.iter() {233 for row in rows.iter() {
234- if archived {234+ <div class="line">
235- <div class="line">235+ <span class="name"><code>(row.name.as_str())</code></span>
236- <span class="name"><code>(row.name.as_str())</code></span>236+ <span class="val">rel_time(lang: lang, stamp: row.updated_at.as_str())</span>
237- <span class="val">rel_time(lang: lang, stamp: row.updated_at.as_str())</span>237+ if !archived {
238- </div>
239- } else {
240- <div class="line">
241- <span class="name"><code>(row.name.as_str())</code></span>
242- <span class="val">rel_time(lang: lang, stamp: row.updated_at.as_str())</span>
243 confirm_act(lang: lang, label: g::t(lang, K::Delete), action: delete_action.as_str(), csrf: csrf.as_str(),238 confirm_act(lang: lang, label: g::t(lang, K::Delete), action: delete_action.as_str(), csrf: csrf.as_str(),
244 fields: vec![("name".to_owned(), row.name.clone())])239 fields: vec![("name".to_owned(), row.name.clone())])
245- </div>240+ }
246- }241+ </div>
247 }242 }
248 </div>243 </div>
249 </section>244 </section>
@@ -615,20 +610,6 @@ mod tests {
615 async fn bad_name_and_bad_value_are_rejected() {610 async fn bad_name_and_bad_value_are_rejected() {
616 let dir = tempfile::tempdir().expect("tempdir");611 let dir = tempfile::tempdir().expect("tempdir");
617 let (store, app, repo) = fixture(dir.path()).await;612 let (store, app, repo) = fixture(dir.path()).await;
618- let too_long = format!("A{}", "1".repeat(64));
619- for name in ["", "lower", "1NUM", "A-B", too_long.as_str()] {
620- let (status, _, body) = send(
621- &app,
622- "POST",
623- PAGE,
624- Some("tahinli-token"),
625- &[("name", name), ("value", "v")],
626- None,
627- )
628- .await;
629- assert_eq!(status, 200, "{name:?} re-renders the form");
630- assert!(body.contains("Names are 1 to 64 characters"), "{name:?}");
631- }
632 let (_, _, body) = send(613 let (_, _, body) = send(
633 &app,614 &app,
634 "POST",615 "POST",
crates/forge-web-repo/src/pages/repo_webhooks.rsmodified+25 -58
@@ -4,6 +4,8 @@
4 //! and response. A hook's secret is sealed with the instance key and is never shown again: a blank4 //! and response. A hook's secret is sealed with the instance key and is never shown again: a blank
5 //! secret on edit keeps the stored one. Archived repos show everything but change nothing.5 //! secret on edit keeps the stored one. Archived repos show everything but change nothing.
6 6
7+use std::collections::HashMap;
8+
7 use forge_core::AuditAction;9 use forge_core::AuditAction;
8 use forge_core::secret;10 use forge_core::secret;
9 use forge_core::tz::format_in_tz;11 use forge_core::tz::format_in_tz;
@@ -69,7 +71,6 @@ const EVENT_CHOICES: [(WebhookEvent, K); 8] = [
69 (WebhookEvent::Release, K::EvRelease),71 (WebhookEvent::Release, K::EvRelease),
70 ];72 ];
71 73
72-/// The hook form. Unticked boxes are absent from the body, so each event has an `Option`.
73 #[derive(Deserialize)]74 #[derive(Deserialize)]
74 struct HookForm {75 struct HookForm {
75 #[serde(default)]76 #[serde(default)]
@@ -81,44 +82,18 @@ struct HookForm {
81 secret: String,82 secret: String,
82 #[serde(default)]83 #[serde(default)]
83 active: Option<String>,84 active: Option<String>,
84- #[serde(default)]85+ #[serde(flatten)]
85- ev_push: Option<String>,86+ boxes: HashMap<String, String>,
86- #[serde(default)]
87- ev_pull_request: Option<String>,
88- #[serde(default)]
89- ev_issues: Option<String>,
90- #[serde(default)]
91- ev_issue_comment: Option<String>,
92- #[serde(default)]
93- ev_pull_request_review: Option<String>,
94- #[serde(default)]
95- ev_create: Option<String>,
96- #[serde(default)]
97- ev_delete: Option<String>,
98- #[serde(default)]
99- ev_release: Option<String>,
100 }87 }
101 88
102 impl HookForm {89 impl HookForm {
103 /// The ticked events, in the form's order.90 /// The ticked events, in the form's order.
104 fn events(&self) -> Vec<WebhookEvent> {91 fn events(&self) -> Vec<WebhookEvent> {
105- [92+ EVENT_CHOICES
106- (WebhookEvent::Push, &self.ev_push),93+ .iter()
107- (WebhookEvent::PullRequest, &self.ev_pull_request),94+ .map(|(event, _)| *event)
108- (WebhookEvent::Issues, &self.ev_issues),95+ .filter(|event| self.boxes.contains_key(&format!("ev_{}", event.as_str())))
109- (WebhookEvent::IssueComment, &self.ev_issue_comment),96+ .collect()
110- (
111- WebhookEvent::PullRequestReview,
112- &self.ev_pull_request_review,
113- ),
114- (WebhookEvent::Create, &self.ev_create),
115- (WebhookEvent::Delete, &self.ev_delete),
116- (WebhookEvent::Release, &self.ev_release),
117- ]
118- .into_iter()
119- .filter(|(_, ticked)| ticked.is_some())
120- .map(|(event, _)| event)
121- .collect()
122 }97 }
123 }98 }
124 99
@@ -339,15 +314,17 @@ fn hook_row(
339 tz: &str,314 tz: &str,
340 title: &str,315 title: &str,
341 hook: Webhook,316 hook: Webhook,
342- last: Option<(&'static str, &'static str)>,317+ last: Option<DeliveryState>,
343 last_stamp: &str,318 last_stamp: &str,
344 ) -> HookRow {319 ) -> HookRow {
345- let (dot_class, dot_text) = match last {320+ let dot_class = match last {
346- Some(("ok", text)) if hook.active => ("runner-dot is-online", text),321+ Some(DeliveryState::Ok) if hook.active => "runner-dot is-online",
347- Some(("failed" | "gave_up", text)) if hook.active => ("runner-dot is-failed", text),322+ Some(DeliveryState::Failed | DeliveryState::GaveUp) if hook.active => {
348- Some((_, text)) => ("runner-dot", text),323+ "runner-dot is-failed"
349- None => ("runner-dot", g::t(lang, K::NoneYet)),324+ }
325+ _ => "runner-dot",
350 };326 };
327+ let dot_text = last.map_or(g::t(lang, K::NoneYet), |state| state_label(lang, state).1);
351 let (last_text, last_rel) = match (last, last_stamp) {328 let (last_text, last_rel) = match (last, last_stamp) {
352 (Some(_), stamp) if !stamp.is_empty() => {329 (Some(_), stamp) if !stamp.is_empty() => {
353 let rel = OffsetDateTime::parse(stamp, &Rfc3339)330 let rel = OffsetDateTime::parse(stamp, &Rfc3339)
@@ -381,8 +358,8 @@ fn hook_row(
381 last_full: local_stamp(last_stamp, tz),358 last_full: local_stamp(last_stamp, tz),
382 last_rel,359 last_rel,
383 problem: match last {360 problem: match last {
384- Some(("ok", _)) | None => "",361+ None | Some(DeliveryState::Ok) => "",
385- Some((_, text)) => text,362+ Some(state) => state_label(lang, state).1,
386 },363 },
387 inactive_text: match lang {364 inactive_text: match lang {
388 Lang::En => "inactive",365 Lang::En => "inactive",
@@ -750,19 +727,7 @@ async fn hooks_list_page(cx: &Cx) -> Result<impl View> {
750 let tz = ctx.viewer_tz();727 let tz = ctx.viewer_tz();
751 let mut rows: Vec<HookRow> = Vec::with_capacity(hooks.len());728 let mut rows: Vec<HookRow> = Vec::with_capacity(hooks.len());
752 for (hook, last) in hooks {729 for (hook, last) in hooks {
753- // The list shows when the newest delivery happened, so it reads the one latest delivery per hook.730+ let (last, last_stamp) = last.map_or((None, String::new()), |(s, at)| (Some(s), at));
754- let last_stamp = if last.is_some() {
755- state
756- .store
757- .list_deliveries(&hook.id, 1)
758- .await?
759- .first()
760- .map(|d| d.created_at.clone())
761- .unwrap_or_default()
762- } else {
763- String::new()
764- };
765- let last = last.map(|last| state_label(lang, last));
766 rows.push(hook_row(lang, tz, &frame.title, hook, last, &last_stamp));731 rows.push(hook_row(lang, tz, &frame.title, hook, last, &last_stamp));
767 }732 }
768 let notice = notice_from_query(cx, lang);733 let notice = notice_from_query(cx, lang);
@@ -816,9 +781,11 @@ async fn hook_new_body(
816 <a class="act quiet" href=(back.as_str())>(g::t(lang, K::BackToWebhooks))</a>781 <a class="act quiet" href=(back.as_str())>(g::t(lang, K::BackToWebhooks))</a>
817 </div>782 </div>
818 </section>783 </section>
819- hook_form(action: action, csrf: csrf, url: draft.url, events: events,784+ if !archived {
820- active: draft.active, secret_hint: String::new(),785+ hook_form(action: action, csrf: csrf, url: draft.url, events: events,
821- error: draft.error, submit: g::t(lang, K::CreateWebhook), lang: lang)786+ active: draft.active, secret_hint: String::new(),
787+ error: draft.error, submit: g::t(lang, K::CreateWebhook), lang: lang)
788+ }
822 )789 )
823 })790 })
824 }791 }
crates/forge-web-repo/src/pages/review_requests.rsmodified+33 -29
@@ -5,6 +5,7 @@
5 //! clears the reviewer's own request in the store.5 //! clears the reviewer's own request in the store.
6 6
7 use forge_core::authz::{Action, authorize};7 use forge_core::authz::{Action, authorize};
8+use forge_core::{Repo, User};
8 use serde::Deserialize;9 use serde::Deserialize;
9 use topcoat::Result;10 use topcoat::Result;
10 use topcoat::context::{Cx, context};11 use topcoat::context::{Cx, context};
@@ -99,16 +100,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt
99 if target.id == pull.author_id {100 if target.id == pull.author_id {
100 return Ok(refusal("author", &href));101 return Ok(refusal("author", &href));
101 }102 }
102- let role = state103+ if target.is_org() || !can_read_repo(state, &target, &ctx.repo).await? {
103- .store
104- .collaborator_role(&ctx.repo.id, &target.id)
105- .await?;
106- let org_role = state
107- .store
108- .org_repo_role(&ctx.repo.owner_id, &target.id, &ctx.repo.id)
109- .await?;
110- if target.is_org() || authorize(Some(&target), &ctx.repo, role, org_role, Action::Read).is_err()
111- {
112 return Ok(refusal("access", &href));104 return Ok(refusal("access", &href));
113 }105 }
114 if state106 if state
@@ -124,6 +116,15 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt
124 Ok(see_other(format!("{href}#reviewers")))116 Ok(see_other(format!("{href}#reviewers")))
125 }117 }
126 118
119+async fn can_read_repo(state: &AppState, viewer: &User, repo: &Repo) -> Result<bool> {
120+ let role = state.store.collaborator_role(&repo.id, &viewer.id).await?;
121+ let org_role = state
122+ .store
123+ .org_repo_role(&repo.owner_id, &viewer.id, &repo.id)
124+ .await?;
125+ Ok(authorize(Some(viewer), repo, role, org_role, Action::Read).is_ok())
126+}
127+
127 /// What the Reviewers box shows.128 /// What the Reviewers box shows.
128 pub(crate) struct ReviewersView {129 pub(crate) struct ReviewersView {
129 pub(crate) action: String,130 pub(crate) action: String,
@@ -227,6 +228,14 @@ pub(crate) async fn reviewers_box(
227 })228 })
228 }229 }
229 230
231+struct ReviewRow {
232+ repo_full: String,
233+ href: String,
234+ title: String,
235+ requested_by: String,
236+ created_at: String,
237+}
238+
230 /// The open pull requests waiting for the viewer's review, newest request first.239 /// The open pull requests waiting for the viewer's review, newest request first.
231 #[page("/review-requests")]240 #[page("/review-requests")]
232 async fn review_requests(cx: &Cx) -> Result<impl View> {241 async fn review_requests(cx: &Cx) -> Result<impl View> {
@@ -245,26 +254,21 @@ async fn review_requests(cx: &Cx) -> Result<impl View> {
245 else {254 else {
246 continue;255 continue;
247 };256 };
248- let role = state.store.collaborator_role(&repo.id, &user.id).await?;257+ if !can_read_repo(state, user, &repo).await? {
249- let org_role = state
250- .store
251- .org_repo_role(&repo.owner_id, &user.id, &repo.id)
252- .await?;
253- if authorize(Some(user), &repo, role, org_role, Action::Read).is_err() {
254 continue;258 continue;
255 }259 }
256- rows.push((260+ rows.push(ReviewRow {
257- format!("{}/{}", item.repo_owner, item.repo_name),261+ repo_full: format!("{}/{}", item.repo_owner, item.repo_name),
258- repo_href(262+ href: repo_href(
259 &item.repo_owner,263 &item.repo_owner,
260 &item.repo_name,264 &item.repo_name,
261- "pulls",265+ ItemKind::Pull.segment(),
262 &item.number.to_string(),266 &item.number.to_string(),
263 ),267 ),
264- format!("#{} {}", item.number, item.title),268+ title: format!("#{} {}", item.number, item.title),
265- ga::requested_by(lang, &item.requested_by),269+ requested_by: ga::requested_by(lang, &item.requested_by),
266- item.created_at.clone(),270+ created_at: item.created_at.clone(),
267- ));271+ });
268 }272 }
269 let heading = ga::t(lang, AK::ReviewRequests);273 let heading = ga::t(lang, AK::ReviewRequests);
270 let empty = rows.is_empty();274 let empty = rows.is_empty();
@@ -280,11 +284,11 @@ async fn review_requests(cx: &Cx) -> Result<impl View> {
280 <p class="state">(ga::t(lang, AK::NoReviewRequests))</p>284 <p class="state">(ga::t(lang, AK::NoReviewRequests))</p>
281 }285 }
282 for row in rows.iter() {286 for row in rows.iter() {
283- <a class="line" href=(row.1.as_str()) data-kb-row="">287+ <a class="line" href=(row.href.as_str()) data-kb-row="">
284- <span class="name">(row.2.as_str())</span>288+ <span class="name">(row.title.as_str())</span>
285- <span class="val">(row.0.as_str())</span>289+ <span class="val">(row.repo_full.as_str())</span>
286- <span class="val">(row.3.as_str())</span>290+ <span class="val">(row.requested_by.as_str())</span>
287- <span class="val">rel_time(lang: lang, stamp: row.4.as_str())</span>291+ <span class="val">rel_time(lang: lang, stamp: row.created_at.as_str())</span>
288 </a>292 </a>
289 }293 }
290 </div>294 </div>
crates/forge-web/src/admin_cli.rsmodified+3 -7
@@ -40,13 +40,13 @@ const TEMPORARY_PASSWORD_CHARS: usize = 20;
40 40
41 const MIN_PASSWORD_CHARS: usize = 12;41 const MIN_PASSWORD_CHARS: usize = 12;
42 42
43-/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty.
44 /// Refusal text for admin commands that would give a login to an organization.43 /// Refusal text for admin commands that would give a login to an organization.
45 const ORG_NO_LOGIN: &str =44 const ORG_NO_LOGIN: &str =
46 "an organization cannot sign in, so it has no password or login name here";45 "an organization cannot sign in, so it has no password or login name here";
47 /// Refusal text for `create-user` on a name that an organization already holds.46 /// Refusal text for `create-user` on a name that an organization already holds.
48 const ORG_NAME_TAKEN: &str = "that name belongs to an organization";47 const ORG_NAME_TAKEN: &str = "that name belongs to an organization";
49 48
49+/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty.
50 pub async fn create_user(50 pub async fn create_user(
51 config_path: &Path,51 config_path: &Path,
52 username: &str,52 username: &str,
@@ -74,8 +74,6 @@ pub async fn create_user(
74 }74 }
75 75
76 let hash = hash_password_async(pw).await?;76 let hash = hash_password_async(pw).await?;
77- // The first user is always an admin. The insert is atomic, so a concurrent creator falls
78- // through to the ordinary path instead of racing into a second admin.
79 let user = match store.create_first_admin(&username, None, &hash).await? {77 let user = match store.create_first_admin(&username, None, &hash).await? {
80 Some(user) => user,78 Some(user) => user,
81 None => {79 None => {
@@ -117,7 +115,6 @@ pub async fn create_user(
117 pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> {115 pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> {
118 let config = Config::load(config_path)?;116 let config = Config::load(config_path)?;
119 let store = Store::open(&config.database).await?;117 let store = Store::open(&config.database).await?;
120- // The id is gone once the account is deleted, so it is read first.
121 let user_id = store.user_by_username(username).await?.map(|u| u.id);118 let user_id = store.user_by_username(username).await?.map(|u| u.id);
122 let report = delete_user_in(&store, username, yes).await?;119 let report = delete_user_in(&store, username, yes).await?;
123 if let Some(id) = user_id {120 if let Some(id) = user_id {
@@ -134,7 +131,7 @@ pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge
134 /// The store-level part of [`delete_user`]. Returns the report of what was (or, with `yes`131 /// The store-level part of [`delete_user`]. Returns the report of what was (or, with `yes`
135 /// unset, would be) done. Without `yes` nothing is written and an error is returned, so the132 /// unset, would be) done. Without `yes` nothing is written and an error is returned, so the
136 /// command exits nonzero. The ghost account is not created by a dry run.133 /// command exits nonzero. The ghost account is not created by a dry run.
137-pub async fn delete_user_in(134+async fn delete_user_in(
138 store: &Store,135 store: &Store,
139 username: &str,136 username: &str,
140 yes: bool,137 yes: bool,
@@ -258,7 +255,7 @@ pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::R
258 }255 }
259 256
260 /// The store-level part of [`reset_password`]. Returns the new password and the display name.257 /// The store-level part of [`reset_password`]. Returns the new password and the display name.
261-pub async fn reset_password_in(258+async fn reset_password_in(
262 store: &Store,259 store: &Store,
263 username: &str,260 username: &str,
264 ) -> forge_core::Result<(String, String)> {261 ) -> forge_core::Result<(String, String)> {
@@ -574,7 +571,6 @@ pub async fn backup_verify(path: &Path) -> forge_core::Result<()> {
574 .parent()571 .parent()
575 .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?572 .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?
576 .to_path_buf();573 .to_path_buf();
577- // Git runs with the set's parent as its HOME, so no user gitconfig is read.
578 let git = GitEnv {574 let git = GitEnv {
579 git_bin: find_git(),575 git_bin: find_git(),
580 data_dir: parent,576 data_dir: parent,
crates/forge-web/src/boot.rsmodified+7 -0
@@ -47,6 +47,13 @@ pub async fn serve(
47 // The data dir holds the instance key and the internal socket. Keep it private to this user.47 // The data dir holds the instance key and the internal socket. Keep it private to this user.
48 std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?;48 std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?;
49 let data_dir = config.data_dir.canonicalize()?;49 let data_dir = config.data_dir.canonicalize()?;
50+ let data_lock = std::fs::File::create(data_dir.join("forge.lock"))?;
51+ data_lock.try_lock().map_err(|e| {
52+ forge_core::Error::Config(format!(
53+ "another forge server already uses {}: {e}",
54+ data_dir.display()
55+ ))
56+ })?;
50 57
51 let key = Arc::new(secret::load_or_create_key(&data_dir.join("forge.key"))?);58 let key = Arc::new(secret::load_or_create_key(&data_dir.join("forge.key"))?);
52 let store = Store::open(&config.database).await?;59 let store = Store::open(&config.database).await?;
crates/forge-web/src/importer_route_tests.rsmodified+22 -13
@@ -24,6 +24,14 @@ use crate::test_support::{app_router, create_session, test_state};
24 24
25 const TOKEN: &str = "ghp_supersecret_token_value";25 const TOKEN: &str = "ghp_supersecret_token_value";
26 26
27+fn all_issues() -> IssueFilter {
28+ IssueFilter {
29+ state: None,
30+ per_page: 100,
31+ ..IssueFilter::default()
32+ }
33+}
34+
27 #[derive(Default)]35 #[derive(Default)]
28 struct Fake {36 struct Fake {
29 labels: Vec<ExtLabel>,37 labels: Vec<ExtLabel>,
@@ -343,12 +351,10 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() {
343 let job = store.import_job(&job.id).await.unwrap().unwrap();351 let job = store.import_job(&job.id).await.unwrap().unwrap();
344 assert_eq!(job.state, ImportState::Done, "{:?}", job.error);352 assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
345 353
346- let all = IssueFilter {354+ let (items, total) = store
347- state: None,355+ .list_issues(&fx.repo.id, &all_issues())
348- per_page: 100,356+ .await
349- ..IssueFilter::default()357+ .unwrap();
350- };
351- let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();
352 assert_eq!(total, 2);358 assert_eq!(total, 2);
353 let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap();359 let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap();
354 assert_eq!(issue.issue.state, IssueState::Closed);360 assert_eq!(issue.issue.state, IssueState::Closed);
@@ -407,7 +413,10 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() {
407 .await;413 .await;
408 let again = store.import_job(&again.id).await.unwrap().unwrap();414 let again = store.import_job(&again.id).await.unwrap().unwrap();
409 assert_eq!(again.state, ImportState::Done, "{:?}", again.error);415 assert_eq!(again.state, ImportState::Done, "{:?}", again.error);
410- let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();416+ let (items, total) = store
417+ .list_issues(&fx.repo.id, &all_issues())
418+ .await
419+ .unwrap();
411 assert_eq!(total, 2);420 assert_eq!(total, 2);
412 let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap();421 let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap();
413 assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1);422 assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1);
@@ -456,12 +465,12 @@ async fn a_rate_limit_fails_the_job_clearly_and_a_retry_finishes_it() {
456 let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap();465 let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
457 assert_eq!(done.state, ImportState::Done, "{:?}", done.error);466 assert_eq!(done.state, ImportState::Done, "{:?}", done.error);
458 assert!(done.error.is_none());467 assert!(done.error.is_none());
459- let all = IssueFilter {468+ let (_, total) = fx
460- state: None,469+ .state
461- per_page: 100,470+ .store
462- ..IssueFilter::default()471+ .list_issues(&fx.repo.id, &all_issues())
463- };472+ .await
464- let (_, total) = fx.state.store.list_issues(&fx.repo.id, &all).await.unwrap();473+ .unwrap();
465 assert_eq!(total, 2);474 assert_eq!(total, 2);
466 }475 }
467 476
crates/forge-web/src/main.rsmodified+11 -25
@@ -94,25 +94,11 @@ fn parse_args(
94 /// the binary, never the unit, so the server sets it itself: `serve` re-runs itself once with the94 /// the binary, never the unit, so the server sets it itself: `serve` re-runs itself once with the
95 /// variable set (same PID, so systemd is unaffected). An explicit value is left alone, and95 /// variable set (same PID, so systemd is unaffected). An explicit value is left alone, and
96 /// short-lived commands such as `hook` skip the extra exec.96 /// short-lived commands such as `hook` skip the extra exec.
97-fn reexec_with_allocator_env(raw: &[std::ffi::OsString]) {97+fn reexec_with_allocator_env(raw: &[std::ffi::OsString], command: Option<&str>) {
98 const VAR: &str = "MIMALLOC_ALLOW_THP";98 const VAR: &str = "MIMALLOC_ALLOW_THP";
99 if std::env::var_os(VAR).is_some() {99 if std::env::var_os(VAR).is_some() {
100 return;100 return;
101 }101 }
102- let mut words = raw.iter();
103- let mut command = None;
104- while let Some(arg) = words.next() {
105- match arg.to_str() {
106- Some("--config") => {
107- words.next();
108- }
109- Some("--admin") => {}
110- _ => {
111- command = Some(arg);
112- break;
113- }
114- }
115- }
116 if command.is_some_and(|c| c != "serve") {102 if command.is_some_and(|c| c != "serve") {
117 return;103 return;
118 }104 }
@@ -157,7 +143,14 @@ fn main() -> ExitCode {
157 if let Err(e) = nix::sys::prctl::set_thp_disable(true) {143 if let Err(e) = nix::sys::prctl::set_thp_disable(true) {
158 eprintln!("forge: cannot disable transparent huge pages: {e}");144 eprintln!("forge: cannot disable transparent huge pages: {e}");
159 }145 }
160- reexec_with_allocator_env(&raw);146+ let (flag_config, admin, positional) = match parse_args(std::env::args().skip(1)) {
147+ Ok(parsed) => parsed,
148+ Err(e) => {
149+ eprintln!("forge: {e}\n{USAGE}");
150+ return ExitCode::from(2);
151+ }
152+ };
153+ reexec_with_allocator_env(&raw, positional.first().map(String::as_str));
161 let runtime = match tokio::runtime::Builder::new_multi_thread()154 let runtime = match tokio::runtime::Builder::new_multi_thread()
162 .enable_all()155 .enable_all()
163 .build()156 .build()
@@ -168,10 +161,10 @@ fn main() -> ExitCode {
168 return ExitCode::FAILURE;161 return ExitCode::FAILURE;
169 }162 }
170 };163 };
171- runtime.block_on(real_main())164+ runtime.block_on(real_main(flag_config, admin, positional))
172 }165 }
173 166
174-async fn real_main() -> ExitCode {167+async fn real_main(flag_config: Option<PathBuf>, admin: bool, positional: Vec<String>) -> ExitCode {
175 // Logs go to stderr: the hook stages write protocol output to stdout.168 // Logs go to stderr: the hook stages write protocol output to stdout.
176 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));169 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
177 tracing_subscriber::fmt()170 tracing_subscriber::fmt()
@@ -179,13 +172,6 @@ async fn real_main() -> ExitCode {
179 .with_writer(std::io::stderr)172 .with_writer(std::io::stderr)
180 .init();173 .init();
181 174
182- let (flag_config, admin, positional) = match parse_args(std::env::args().skip(1)) {
183- Ok(parsed) => parsed,
184- Err(e) => {
185- eprintln!("forge: {e}\n{USAGE}");
186- return ExitCode::from(2);
187- }
188- };
189 let config_path = flag_config175 let config_path = flag_config
190 .or_else(|| std::env::var_os("FORGE_CONFIG").map(PathBuf::from))176 .or_else(|| std::env::var_os("FORGE_CONFIG").map(PathBuf::from))
191 .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG));177 .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG));
crates/forge-web/src/page_route_tests/edit_history.rsmodified+0 -10
@@ -5,7 +5,6 @@ use topcoat::router::{Body, Router, to_bytes};
5 use crate::auth::SESSION_COOKIE;5 use crate::auth::SESSION_COOKIE;
6 use crate::test_support::fixture::{Fixture, OWNER, REPO};6 use crate::test_support::fixture::{Fixture, OWNER, REPO};
7 7
8-/// Sends one request and returns `(status, body)`.
9 async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {8 async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
10 let mut req = Request::builder().method("GET").uri(uri);9 let mut req = Request::builder().method("GET").uri(uri);
11 if let Some(token) = token {10 if let Some(token) = token {
@@ -17,7 +16,6 @@ async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String)
17 (status, String::from_utf8_lossy(&bytes).into_owned())16 (status, String::from_utf8_lossy(&bytes).into_owned())
18 }17 }
19 18
20-/// The repo owner with a session whose token is `tahinli`.
21 async fn tahinli(fx: &Fixture) -> forge_core::User {19 async fn tahinli(fx: &Fixture) -> forge_core::User {
22 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();20 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
23 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;21 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
@@ -37,15 +35,12 @@ fn hex_oid(c: char) -> String {
37 std::iter::repeat_n(c, 40).collect()35 std::iter::repeat_n(c, 40).collect()
38 }36 }
39 37
40-/// Every scenario on the public repo shares one fixture. Each makes its own issue or pull and
41-/// reads its numbers from the store, so no scenario depends on another's data.
42 #[tokio::test]38 #[tokio::test]
43 async fn public_histories_show_diffs_markers_and_refusals() {39 async fn public_histories_show_diffs_markers_and_refusals() {
44 let fx = Fixture::new(Visibility::Public).await;40 let fx = Fixture::new(Visibility::Public).await;
45 let owner = tahinli(&fx).await;41 let owner = tahinli(&fx).await;
46 let id = repo_id(&fx).await;42 let id = repo_id(&fx).await;
47 43
48- // A comment edited twice: a marker on the item page and two versions with diffs.
49 let issue = fx44 let issue = fx
50 .store45 .store
51 .create_issue(&id, &owner.id, "bug", "body")46 .create_issue(&id, &owner.id, "bug", "body")
@@ -97,7 +92,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
97 "edited comment: editor {history}"92 "edited comment: editor {history}"
98 );93 );
99 94
100- // A comment that was never edited has no marker.
101 let plain = fx95 let plain = fx
102 .store96 .store
103 .create_issue(&id, &owner.id, "plain", "body")97 .create_issue(&id, &owner.id, "plain", "body")
@@ -119,7 +113,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
119 "unedited comment: no marker {page}"113 "unedited comment: no marker {page}"
120 );114 );
121 115
122- // An issue body and title edit: the old title and the changed lines show.
123 let titled = fx116 let titled = fx
124 .store117 .store
125 .create_issue(&id, &owner.id, "old title", "a\nb\nc")118 .create_issue(&id, &owner.id, "old title", "a\nb\nc")
@@ -153,7 +146,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
153 assert!(history.contains("-b"), "body edit: -b {history}");146 assert!(history.contains("-b"), "body edit: -b {history}");
154 assert!(history.contains("+B"), "body edit: +B {history}");147 assert!(history.contains("+B"), "body edit: +B {history}");
155 148
156- // A comment on one issue is not found under another issue's URL.
157 let other = fx149 let other = fx
158 .store150 .store
159 .create_issue(&id, &owner.id, "second", "body")151 .create_issue(&id, &owner.id, "second", "body")
@@ -189,7 +181,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
189 .await;181 .await;
190 assert_eq!(status, 200, "right item: found");182 assert_eq!(status, 200, "right item: found");
191 183
192- // An unknown kind and a missing target are both not found.
193 let (status, _) = send(184 let (status, _) = send(
194 &fx.router,185 &fx.router,
195 &format!(186 &format!(
@@ -211,7 +202,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
211 .await;202 .await;
212 assert_eq!(status, 404, "missing target");203 assert_eq!(status, 404, "missing target");
213 204
214- // Review comment history on a pull request, and not under the issue URL of the same number.
215 let pr = fx205 let pr = fx
216 .store206 .store
217 .create_pull(207 .create_pull(
crates/forge-web/src/page_route_tests/notifications.rsmodified+0 -15
@@ -34,7 +34,6 @@ async fn site() -> Site {
34 }34 }
35 }35 }
36 36
37-/// Signs `user_id` in with `token` and returns the cookie header value.
38 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {37 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
39 crate::test_support::create_session(store, user_id, token, CSRF).await;38 crate::test_support::create_session(store, user_id, token, CSRF).await;
40 format!("__Host-{SESSION_COOKIE}={token}")39 format!("__Host-{SESSION_COOKIE}={token}")
@@ -91,7 +90,6 @@ async fn post(site: &Site, uri: &str, cookie: &str, extra: &str) -> Reply {
91 .await90 .await
92 }91 }
93 92
94-/// Tahinli owns `demo` with one issue (#1), and Bob has a notification row for it.
95 struct World {93 struct World {
96 tahinli: forge_core::User,94 tahinli: forge_core::User,
97 bob: forge_core::User,95 bob: forge_core::User,
@@ -185,8 +183,6 @@ async fn unread_inbox_lists_unread_rows_grouped_by_repo() {
185 assert!(page.body.contains("Mark all as read"));183 assert!(page.body.contains("Mark all as read"));
186 }184 }
187 185
188-/// Another user cannot open or mark read a row that is not theirs. The owner's open redirects
189-/// to the issue and marks the row read.
190 #[tokio::test]186 #[tokio::test]
191 async fn another_users_notification_is_404_and_the_owner_opens_it() {187 async fn another_users_notification_is_404_and_the_owner_opens_it() {
192 let site = site().await;188 let site = site().await;
@@ -215,7 +211,6 @@ async fn another_users_notification_is_404_and_the_owner_opens_it() {
215 assert_eq!(read.status, 303);211 assert_eq!(read.status, 303);
216 assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);212 assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
217 213
218- // Bob opens his own row: it redirects to the issue and marks the row read.
219 let res = get(214 let res = get(
220 &site,215 &site,
221 &format!("/notifications/{id}/open"),216 &format!("/notifications/{id}/open"),
@@ -261,13 +256,11 @@ async fn the_stream_sends_the_count_then_each_change() {
261 assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");256 assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");
262 257
263 let mut frames = res.into_body().into_data_stream();258 let mut frames = res.into_body().into_data_stream();
264- // The stream opens with its retry field, then the count.
265 let retry = frames.next().await.expect("a frame").expect("data");259 let retry = frames.next().await.expect("a frame").expect("data");
266 assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");260 assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
267 let first = frames.next().await.expect("a frame").expect("data");261 let first = frames.next().await.expect("a frame").expect("data");
268 assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");262 assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");
269 263
270- // Marking the row read pushes the new count to the open stream.
271 let read = post(&site, "/notifications/mark_all_read", &cookie, "").await;264 let read = post(&site, "/notifications/mark_all_read", &cookie, "").await;
272 assert_eq!(read.status, 303);265 assert_eq!(read.status, 303);
273 let next = frames.next().await.expect("a frame").expect("data");266 let next = frames.next().await.expect("a frame").expect("data");
@@ -328,7 +321,6 @@ async fn subscription_toggles_on_an_issue_and_unknown_pull_is_404() {
328 .expect("sub");321 .expect("sub");
329 assert_eq!(sub, Some((SubState::Ignored, Reason::Subscribed)));322 assert_eq!(sub, Some((SubState::Ignored, Reason::Subscribed)));
330 323
331- // A pull request number that does not exist is a 404 on the pulls subscription.
332 let res = post(324 let res = post(
333 &site,325 &site,
334 "/tahinli/demo/pulls/1/subscription",326 "/tahinli/demo/pulls/1/subscription",
@@ -355,7 +347,6 @@ async fn watch_form_sets_the_level() {
355 WatchLevel::Watching347 WatchLevel::Watching
356 );348 );
357 349
358- // The watch menu sits in the repo head on the code tab, which reads the repository.
359 let bare = forge_git::repo::repo_path(&site.git.data_dir, &w.repo.id).expect("repo path");350 let bare = forge_git::repo::repo_path(&site.git.data_dir, &w.repo.id).expect("repo path");
360 forge_git::repo::init_bare(&site.git, &bare, "main")351 forge_git::repo::init_bare(&site.git, &bare, "main")
361 .await352 .await
@@ -364,7 +355,6 @@ async fn watch_form_sets_the_level() {
364 assert!(header.body.contains("action=\"/tahinli/demo/watch\""));355 assert!(header.body.contains("action=\"/tahinli/demo/watch\""));
365 assert!(header.body.contains("<details class=\"menu watch-menu\">"));356 assert!(header.body.contains("<details class=\"menu watch-menu\">"));
366 assert!(!header.body.contains("<select"));357 assert!(!header.body.contains("<select"));
367- // One form per level, and only the watched level is marked current.
368 assert_eq!(header.body.matches("name=\"level\"").count(), 3);358 assert_eq!(header.body.matches("name=\"level\"").count(), 3);
369 assert_eq!(359 assert_eq!(
370 header360 header
@@ -417,7 +407,6 @@ async fn row_for_a_repo_the_viewer_lost_access_to_is_hidden() {
417 async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {407 async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
418 let site = site().await;408 let site = site().await;
419 let w = world(&site, Visibility::Public).await;409 let w = world(&site, Visibility::Public).await;
420- // The world's issue takes number 1, so the discussion is #2.
421 let discussion = site410 let discussion = site
422 .store411 .store
423 .create_discussion(412 .create_discussion(
@@ -446,7 +435,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
446 1435 1
447 );436 );
448 437
449- // Bob has no row for the discussion, so he cannot open it.
450 let other = get(&site, &open, Some(&bob)).await;438 let other = get(&site, &open, Some(&bob)).await;
451 assert_eq!(other.status, 404);439 assert_eq!(other.status, 404);
452 440
@@ -458,7 +446,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
458 0446 0
459 );447 );
460 448
461- // A second discussion, cleared by mark all read.
462 let discussion = site449 let discussion = site
463 .store450 .store
464 .create_discussion(451 .create_discussion(
@@ -491,7 +478,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
491 async fn advisory_alerts_show_for_managers_and_open_marks_read() {478 async fn advisory_alerts_show_for_managers_and_open_marks_read() {
492 let site = site().await;479 let site = site().await;
493 let w = world(&site, Visibility::Public).await;480 let w = world(&site, Visibility::Public).await;
494- // Tahinli owns the repo, so she manages its alerts. Bob is a reader with a stale row.
495 site.store481 site.store
496 .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2)482 .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2)
497 .await483 .await
@@ -514,7 +500,6 @@ async fn advisory_alerts_show_for_managers_and_open_marks_read() {
514 1500 1
515 );501 );
516 502
517- // Bob cannot manage the alerts: his row is hidden and marked read, as lost-access rows are.
518 let bob_page = get(&site, "/notifications", Some(&bob)).await;503 let bob_page = get(&site, "/notifications", Some(&bob)).await;
519 assert_eq!(bob_page.status, 200);504 assert_eq!(bob_page.status, 200);
520 assert!(!bob_page.body.contains(&open));505 assert!(!bob_page.body.contains(&open));
crates/forge-web/src/page_route_tests/pull_reviews.rsmodified+48 -95
@@ -11,7 +11,6 @@ fn cookie(token: &str) -> String {
11 format!("__Host-{SESSION_COOKIE}={token}")11 format!("__Host-{SESSION_COOKIE}={token}")
12 }12 }
13 13
14-/// Sends one request through the router and returns `(status, location, body)`.
15 async fn send(14 async fn send(
16 router: &Router,15 router: &Router,
17 method: &str,16 method: &str,
@@ -44,7 +43,6 @@ async fn send(
44 )43 )
45 }44 }
46 45
47-/// A user with a session whose CSRF token is `{token}-csrf`.
48 async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {46 async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
49 let user = fx47 let user = fx
50 .store48 .store
@@ -55,7 +53,6 @@ async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
55 user53 user
56 }54 }
57 55
58-/// The repo owner, signed in with token `tahinli` (CSRF `tahinli-csrf`).
59 async fn owner_session(fx: &Fixture) {56 async fn owner_session(fx: &Fixture) {
60 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();57 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
61 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;58 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
@@ -69,6 +66,22 @@ fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String {
69 form66 form
70 }67 }
71 68
69+async fn post_form(
70+ fx: &Fixture,
71+ uri: &str,
72+ token: &str,
73+ pairs: &[(&str, &str)],
74+) -> (u16, Option<String>, String) {
75+ send(
76+ &fx.router,
77+ "POST",
78+ uri,
79+ Some(token),
80+ Some(csrf_form(token, pairs)),
81+ )
82+ .await
83+}
84+
72 async fn pull(fx: &Fixture, number: i64) -> PullRequest {85 async fn pull(fx: &Fixture, number: i64) -> PullRequest {
73 let repo = fx86 let repo = fx
74 .store87 .store
@@ -83,8 +96,6 @@ async fn pull(fx: &Fixture, number: i64) -> PullRequest {
83 .unwrap()96 .unwrap()
84 }97 }
85 98
86-/// Pushes a `feature` branch from the root that changes `a.txt` (`two` becomes `changed`) and
87-/// opens a pull request for it against `main`. Returns the pull request number.
88 async fn open_pull(fx: &Fixture) -> i64 {99 async fn open_pull(fx: &Fixture) -> i64 {
89 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);100 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
90 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);101 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
@@ -126,12 +137,10 @@ async fn open_pull(fx: &Fixture) -> i64 {
126 pr.issue.number137 pr.issue.number
127 }138 }
128 139
129-/// The pull request's current head, for the `head_oid` field of a comment form.
130 async fn head_of(fx: &Fixture, number: i64) -> String {140 async fn head_of(fx: &Fixture, number: i64) -> String {
131 pull(fx, number).await.head_oid141 pull(fx, number).await.head_oid
132 }142 }
133 143
134-/// Posts a single line comment on line `line` of the new side of `a.txt` (file index 0).
135 async fn comment_on(144 async fn comment_on(
136 fx: &Fixture,145 fx: &Fixture,
137 number: i64,146 number: i64,
@@ -140,7 +149,9 @@ async fn comment_on(
140 body: &str,149 body: &str,
141 ) -> (u16, Option<String>) {150 ) -> (u16, Option<String>) {
142 let head = head_of(fx, number).await;151 let head = head_of(fx, number).await;
143- let form = csrf_form(152+ let (status, location, _) = post_form(
153+ fx,
154+ &format!("/tahinli/demo/pulls/{number}/review_comments"),
144 token,155 token,
145 &[156 &[
146 ("file_index", "0"),157 ("file_index", "0"),
@@ -150,19 +161,11 @@ async fn comment_on(
150 ("action", "single"),161 ("action", "single"),
151 ("body", body),162 ("body", body),
152 ],163 ],
153- );
154- let (status, location, _) = send(
155- &fx.router,
156- "POST",
157- &format!("/tahinli/demo/pulls/{number}/review_comments"),
158- Some(token),
159- Some(form),
160 )164 )
161 .await;165 .await;
162 (status, location)166 (status, location)
163 }167 }
164 168
165-/// The id of the thread at `index` (in creation order) on the pull request.
166 async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {169 async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {
167 let pr = pull(fx, number).await;170 let pr = pull(fx, number).await;
168 fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index]171 fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index]
@@ -171,26 +174,22 @@ async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {
171 .clone()174 .clone()
172 }175 }
173 176
174-/// The comment body that proposes replacing line 2 of `a.txt` with `text`.
175 fn suggestion(text: &str) -> String {177 fn suggestion(text: &str) -> String {
176 format!("Try this:\n```suggestion\n{text}\n```")178 format!("Try this:\n```suggestion\n{text}\n```")
177 }179 }
178 180
179-/// Posts the apply form for suggestion block 0 of comment `comment_id`.
180 async fn apply_as(181 async fn apply_as(
181 fx: &Fixture,182 fx: &Fixture,
182 number: i64,183 number: i64,
183 token: &str,184 token: &str,
184 comment_id: &str,185 comment_id: &str,
185 ) -> (u16, Option<String>) {186 ) -> (u16, Option<String>) {
186- let form = csrf_form(token, &[("block", "0"), ("return", "files")]);
187 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply");187 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply");
188- let (status, location, _) = send(&fx.router, "POST", &uri, Some(token), Some(form)).await;188+ let (status, location, _) =
189+ post_form(fx, &uri, token, &[("block", "0"), ("return", "files")]).await;
189 (status, location)190 (status, location)
190 }191 }
191 192
192-/// Comment posting rules and a pending review, on one open pull. Scenarios run in order:
193-/// the rejected posts first (no thread), then the first thread, then the pending review.
194 #[tokio::test]193 #[tokio::test]
195 async fn comment_rules_and_pending_review_on_one_pull() {194 async fn comment_rules_and_pending_review_on_one_pull() {
196 let fx = Fixture::new(Visibility::Public).await;195 let fx = Fixture::new(Visibility::Public).await;
@@ -198,7 +197,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
198 let number = open_pull(&fx).await;197 let number = open_pull(&fx).await;
199 let pr = pull(&fx, number).await;198 let pr = pull(&fx, number).await;
200 199
201- // A line outside the diff is rejected and leaves no thread.
202 let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await;200 let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await;
203 assert_eq!(status, 303, "outside diff");201 assert_eq!(status, 303, "outside diff");
204 assert!(202 assert!(
@@ -214,9 +212,10 @@ async fn comment_rules_and_pending_review_on_one_pull() {
214 "outside diff left a thread"212 "outside diff left a thread"
215 );213 );
216 214
217- // A head that is not the pull's current head is rejected.
218 let zero = "0".repeat(40);215 let zero = "0".repeat(40);
219- let form = csrf_form(216+ let (status, location, _) = post_form(
217+ &fx,
218+ &format!("/tahinli/demo/pulls/{number}/review_comments"),
220 "tahinli",219 "tahinli",
221 &[220 &[
222 ("file_index", "0"),221 ("file_index", "0"),
@@ -226,13 +225,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
226 ("action", "single"),225 ("action", "single"),
227 ("body", "Stale"),226 ("body", "Stale"),
228 ],227 ],
229- );
230- let (status, location, _) = send(
231- &fx.router,
232- "POST",
233- &format!("/tahinli/demo/pulls/{number}/review_comments"),
234- Some("tahinli"),
235- Some(form),
236 )228 )
237 .await;229 .await;
238 assert_eq!(status, 303, "stale head");230 assert_eq!(status, 303, "stale head");
@@ -250,7 +242,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
250 "stale head left a thread"242 "stale head left a thread"
251 );243 );
252 244
253- // A single comment on an added line creates a thread that carries its hunk.
254 let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await;245 let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await;
255 assert_eq!(status, 303, "single comment");246 assert_eq!(status, 303, "single comment");
256 assert_eq!(247 assert_eq!(
@@ -269,10 +260,11 @@ async fn comment_rules_and_pending_review_on_one_pull() {
269 assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment");260 assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment");
270 assert!(!root.pending, "single comment");261 assert!(!root.pending, "single comment");
271 262
272- // A pending review comment is hidden from everyone but its author until submitted.
273 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();263 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
274 let head = pr.head_oid.clone();264 let head = pr.head_oid.clone();
275- let form = csrf_form(265+ let (status, _, _) = post_form(
266+ &fx,
267+ &format!("/tahinli/demo/pulls/{number}/review_comments"),
276 "tahinli",268 "tahinli",
277 &[269 &[
278 ("file_index", "0"),270 ("file_index", "0"),
@@ -282,13 +274,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
282 ("action", "review"),274 ("action", "review"),
283 ("body", "Draft"),275 ("body", "Draft"),
284 ],276 ],
285- );
286- let (status, _, _) = send(
287- &fx.router,
288- "POST",
289- &format!("/tahinli/demo/pulls/{number}/review_comments"),
290- Some("tahinli"),
291- Some(form),
292 )277 )
293 .await;278 .await;
294 assert_eq!(status, 303, "pending start");279 assert_eq!(status, 303, "pending start");
@@ -326,7 +311,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
326 assert_eq!(threads.len(), 2, "submitted review is public");311 assert_eq!(threads.len(), 2, "submitted review is public");
327 assert!(threads.iter().all(|t| !t.root.pending), "submitted review");312 assert!(threads.iter().all(|t| !t.root.pending), "submitted review");
328 313
329- // Anonymous writes redirect to login, and a missing CSRF token is forbidden.
330 let uri = format!("/tahinli/demo/pulls/{number}/review_comments");314 let uri = format!("/tahinli/demo/pulls/{number}/review_comments");
331 let form = csrf_form(315 let form = csrf_form(
332 "tahinli",316 "tahinli",
@@ -347,8 +331,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
347 assert_eq!(status, 403, "missing csrf");331 assert_eq!(status, 403, "missing csrf");
348 }332 }
349 333
350-/// Reply, edit, resolve and delete on the threads of one pull. Each scenario acts on its
351-/// own thread (the first for reply, edit and resolve, the second for delete).
352 #[tokio::test]334 #[tokio::test]
353 async fn thread_reply_edit_resolve_and_delete() {335 async fn thread_reply_edit_resolve_and_delete() {
354 let fx = Fixture::new(Visibility::Public).await;336 let fx = Fixture::new(Visibility::Public).await;
@@ -359,14 +341,11 @@ async fn thread_reply_edit_resolve_and_delete() {
359 let pr = pull(&fx, number).await;341 let pr = pull(&fx, number).await;
360 let root = root_at(&fx, number, 0).await;342 let root = root_at(&fx, number, 0).await;
361 343
362- // A reader replies into the thread and is sent back to its root.344+ let (status, location, _) = post_form(
363- let form = csrf_form("bob", &[("body", "Reply")]);345+ &fx,
364- let (status, location, _) = send(
365- &fx.router,
366- "POST",
367 &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"),346 &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"),
368- Some("bob"),347+ "bob",
369- Some(form),348+ &[("body", "Reply")],
370 )349 )
371 .await;350 .await;
372 assert_eq!(status, 303, "reply");351 assert_eq!(status, 303, "reply");
@@ -379,18 +358,15 @@ async fn thread_reply_edit_resolve_and_delete() {
379 assert_eq!(threads[0].replies.len(), 1, "reply");358 assert_eq!(threads[0].replies.len(), 1, "reply");
380 assert_eq!(threads[0].replies[0].author_name, "bob", "reply");359 assert_eq!(threads[0].replies[0].author_name, "bob", "reply");
381 360
382- // Only the author may open the edit form, post an edit, or resolve.
383 let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit");361 let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit");
384 let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await;362 let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await;
385 assert_eq!(status, 200, "edit form");363 assert_eq!(status, 200, "edit form");
386 assert!(body.contains("Save comment"), "edit form");364 assert!(body.contains("Save comment"), "edit form");
387 let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await;365 let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await;
388 assert_eq!(status, 403, "edit form for a non-author");366 assert_eq!(status, 403, "edit form for a non-author");
389- let form = csrf_form("bob", &[("body", "Hijacked")]);367+ let (status, _, _) = post_form(&fx, &edit, "bob", &[("body", "Hijacked")]).await;
390- let (status, _, _) = send(&fx.router, "POST", &edit, Some("bob"), Some(form)).await;
391 assert_eq!(status, 403, "edit by a non-author");368 assert_eq!(status, 403, "edit by a non-author");
392- let form = csrf_form("tahinli", &[("body", "Edited")]);369+ let (status, location, _) = post_form(&fx, &edit, "tahinli", &[("body", "Edited")]).await;
393- let (status, location, _) = send(&fx.router, "POST", &edit, Some("tahinli"), Some(form)).await;
394 assert_eq!(status, 303, "edit");370 assert_eq!(status, 303, "edit");
395 assert_eq!(371 assert_eq!(
396 location.as_deref(),372 location.as_deref(),
@@ -401,32 +377,25 @@ async fn thread_reply_edit_resolve_and_delete() {
401 assert_eq!(threads[0].root.body, "Edited", "edit");377 assert_eq!(threads[0].root.body, "Edited", "edit");
402 378
403 let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve");379 let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve");
404- let form = csrf_form("bob", &[("resolved", "1")]);380+ let (status, _, _) = post_form(&fx, &resolve, "bob", &[("resolved", "1")]).await;
405- let (status, _, _) = send(&fx.router, "POST", &resolve, Some("bob"), Some(form)).await;
406 assert_eq!(status, 403, "resolve by a reader");381 assert_eq!(status, 403, "resolve by a reader");
407- let form = csrf_form("tahinli", &[("resolved", "1")]);382+ let (status, _, _) = post_form(&fx, &resolve, "tahinli", &[("resolved", "1")]).await;
408- let (status, _, _) = send(&fx.router, "POST", &resolve, Some("tahinli"), Some(form)).await;
409 assert_eq!(status, 303, "resolve");383 assert_eq!(status, 303, "resolve");
410 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();384 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
411 assert!(threads[0].root.resolved, "resolve");385 assert!(threads[0].root.resolved, "resolve");
412 386
413- // Delete removes only the second thread, and only for its author.
414 comment_on(&fx, number, "tahinli", "2", "Doomed").await;387 comment_on(&fx, number, "tahinli", "2", "Doomed").await;
415 let doomed = root_at(&fx, number, 1).await;388 let doomed = root_at(&fx, number, 1).await;
416 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete");389 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete");
417- let form = csrf_form("bob", &[]);390+ let (status, _, _) = post_form(&fx, &uri, "bob", &[]).await;
418- let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
419 assert_eq!(status, 403, "delete by a non-author");391 assert_eq!(status, 403, "delete by a non-author");
420- let form = csrf_form("tahinli", &[]);392+ let (status, _, _) = post_form(&fx, &uri, "tahinli", &[]).await;
421- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
422 assert_eq!(status, 303, "delete");393 assert_eq!(status, 303, "delete");
423 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();394 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
424 assert_eq!(threads.len(), 1, "delete");395 assert_eq!(threads.len(), 1, "delete");
425 assert_eq!(threads[0].root.id, root, "delete kept the other thread");396 assert_eq!(threads[0].root.id, root, "delete kept the other thread");
426 }397 }
427 398
428-/// Reviews on one pull: a reader approves, the author cannot approve their own pull, and
429-/// after the pull closes it takes comments but no reviews.
430 #[tokio::test]399 #[tokio::test]
431 async fn reviews_approve_then_close_the_pull() {400 async fn reviews_approve_then_close_the_pull() {
432 let fx = Fixture::new(Visibility::Public).await;401 let fx = Fixture::new(Visibility::Public).await;
@@ -436,18 +405,14 @@ async fn reviews_approve_then_close_the_pull() {
436 let pr = pull(&fx, number).await;405 let pr = pull(&fx, number).await;
437 let uri = format!("/tahinli/demo/pulls/{number}/reviews");406 let uri = format!("/tahinli/demo/pulls/{number}/reviews");
438 407
439- // A reader's approval is recorded.408+ let (status, location, _) = post_form(&fx, &uri, "bob", &[("state", "approve")]).await;
440- let form = csrf_form("bob", &[("state", "approve")]);
441- let (status, location, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
442 assert_eq!(status, 303, "reader approval");409 assert_eq!(status, 303, "reader approval");
443 assert!(location.unwrap().contains("#review-"), "reader approval");410 assert!(location.unwrap().contains("#review-"), "reader approval");
444 let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap();411 let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap();
445 assert_eq!(reviews.len(), 1, "reader approval");412 assert_eq!(reviews.len(), 1, "reader approval");
446 assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval");413 assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval");
447 414
448- // The author's approval is refused.415+ let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await;
449- let form = csrf_form("tahinli", &[("state", "approve")]);
450- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
451 assert_eq!(status, 303, "author approval");416 assert_eq!(status, 303, "author approval");
452 assert_eq!(417 assert_eq!(
453 location.as_deref(),418 location.as_deref(),
@@ -460,7 +425,6 @@ async fn reviews_approve_then_close_the_pull() {
460 "author approval"425 "author approval"
461 );426 );
462 427
463- // Once closed, comments still land but reviews are refused.
464 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();428 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
465 fx.store429 fx.store
466 .set_issue_state(430 .set_issue_state(
@@ -478,8 +442,7 @@ async fn reviews_approve_then_close_the_pull() {
478 location.unwrap().contains("#L-0-new-2"),442 location.unwrap().contains("#L-0-new-2"),
479 "comment on a closed pull"443 "comment on a closed pull"
480 );444 );
481- let form = csrf_form("tahinli", &[("state", "approve")]);445+ let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await;
482- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
483 assert_eq!(status, 303, "review on a closed pull");446 assert_eq!(status, 303, "review on a closed pull");
484 assert!(447 assert!(
485 location.unwrap().ends_with("?review_error=closed"),448 location.unwrap().ends_with("?review_error=closed"),
@@ -494,39 +457,33 @@ async fn dismiss_needs_write_and_a_reason() {
494 sign_in(&fx, "bob", "bob").await;457 sign_in(&fx, "bob", "bob").await;
495 let number = open_pull(&fx).await;458 let number = open_pull(&fx).await;
496 let pr = pull(&fx, number).await;459 let pr = pull(&fx, number).await;
497- let form = csrf_form("bob", &[("state", "request_changes")]);460+ let (status, _, _) = post_form(
498- send(461+ &fx,
499- &fx.router,
500- "POST",
501 &format!("/tahinli/demo/pulls/{number}/reviews"),462 &format!("/tahinli/demo/pulls/{number}/reviews"),
502- Some("bob"),463+ "bob",
503- Some(form),464+ &[("state", "request_changes")],
504 )465 )
505 .await;466 .await;
467+ assert_eq!(status, 303, "setup review");
506 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);468 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
507 let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id);469 let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id);
508 470
509- let form = csrf_form("bob", &[("reason", "mine")]);471+ let (status, _, _) = post_form(&fx, &uri, "bob", &[("reason", "mine")]).await;
510- let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
511 assert_eq!(status, 403, "dismiss by a reader");472 assert_eq!(status, 403, "dismiss by a reader");
512 473
513- let form = csrf_form("tahinli", &[("reason", " ")]);474+ let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("reason", " ")]).await;
514- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
515 assert_eq!(status, 303, "blank reason");475 assert_eq!(status, 303, "blank reason");
516 assert!(476 assert!(
517 location.unwrap().ends_with("?review_error=empty"),477 location.unwrap().ends_with("?review_error=empty"),
518 "blank reason"478 "blank reason"
519 );479 );
520 480
521- let form = csrf_form("tahinli", &[("reason", "Addressed")]);481+ let (status, _, _) = post_form(&fx, &uri, "tahinli", &[("reason", "Addressed")]).await;
522- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
523 assert_eq!(status, 303, "dismiss");482 assert_eq!(status, 303, "dismiss");
524 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);483 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
525 assert_eq!(review.state, ReviewState::Dismissed, "dismiss");484 assert_eq!(review.state, ReviewState::Dismissed, "dismiss");
526 }485 }
527 486
528-/// The apply-suggestion flow on one pull: a reader without push access sees no button, an
529-/// outdated suggestion is refused after the head moves, and a fresh suggestion applies.
530 #[tokio::test]487 #[tokio::test]
531 async fn suggestions_reader_outdated_and_apply() {488 async fn suggestions_reader_outdated_and_apply() {
532 let fx = Fixture::new(Visibility::Public).await;489 let fx = Fixture::new(Visibility::Public).await;
@@ -537,7 +494,6 @@ async fn suggestions_reader_outdated_and_apply() {
537 assert_eq!(status, 303, "first suggestion");494 assert_eq!(status, 303, "first suggestion");
538 let first = root_at(&fx, number, 0).await;495 let first = root_at(&fx, number, 0).await;
539 496
540- // A reader without push access sees the diff but no apply button, and is refused.
541 let page = get(&fx, number, "rita").await;497 let page = get(&fx, number, "rita").await;
542 assert!(page.contains("Suggested change"), "the diff still shows");498 assert!(page.contains("Suggested change"), "the diff still shows");
543 assert!(499 assert!(
@@ -551,7 +507,6 @@ async fn suggestions_reader_outdated_and_apply() {
551 "reader apply"507 "reader apply"
552 );508 );
553 509
554- // The head moves on: the first suggestion is outdated, shown without apply, and refused.
555 let pr = pull(&fx, number).await;510 let pr = pull(&fx, number).await;
556 std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();511 std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();
557 git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);512 git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);
@@ -596,7 +551,6 @@ async fn suggestions_reader_outdated_and_apply() {
596 "a refused apply leaves the thread open"551 "a refused apply leaves the thread open"
597 );552 );
598 553
599- // A fresh suggestion against the moved head applies as a commit by the commenter.
600 let before = pull(&fx, number).await.head_oid;554 let before = pull(&fx, number).await.head_oid;
601 assert_eq!(before, moved, "the head is the moved commit");555 assert_eq!(before, moved, "the head is the moved commit");
602 let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;556 let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
@@ -639,7 +593,6 @@ async fn suggestions_reader_outdated_and_apply() {
639 assert!(threads[1].root.resolved, "applying resolves the thread");593 assert!(threads[1].root.resolved, "applying resolves the thread");
640 }594 }
641 595
642-/// The Files tab of the pull request as `token` sees it.
643 async fn get(fx: &Fixture, number: i64, token: &str) -> String {596 async fn get(fx: &Fixture, number: i64, token: &str) -> String {
644 let uri = format!("/tahinli/demo/pulls/{number}/files");597 let uri = format!("/tahinli/demo/pulls/{number}/files");
645 let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await;598 let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await;
crates/forge-web/src/page_route_tests/repo.rsmodified+0 -15
@@ -31,7 +31,6 @@ fn git(dir: &Path, args: &[&str]) {
31 assert!(status.success(), "git {args:?} failed");31 assert!(status.success(), "git {args:?} failed");
32 }32 }
33 33
34-/// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).
35 async fn fixture(dir: &Path) -> (Router, AppState) {34 async fn fixture(dir: &Path) -> (Router, AppState) {
36 let state = crate::test_support::test_state(dir).await;35 let state = crate::test_support::test_state(dir).await;
37 let router = crate::test_support::app_router(state.clone());36 let router = crate::test_support::app_router(state.clone());
@@ -87,15 +86,11 @@ async fn fixture(dir: &Path) -> (Router, AppState) {
87 (router, state)86 (router, state)
88 }87 }
89 88
90-// The read-only tests below share one fixture: they only read the demo repo, so each scenario
91-// sees the same pristine contents.
92-
93 #[tokio::test]89 #[tokio::test]
94 async fn demo_pages_render_from_the_repo_contents() {90 async fn demo_pages_render_from_the_repo_contents() {
95 let dir = tempfile::tempdir().unwrap();91 let dir = tempfile::tempdir().unwrap();
96 let (router, _) = fixture(dir.path()).await;92 let (router, _) = fixture(dir.path()).await;
97 93
98- // Home renders the README, the tree, the clone popover and the archive links.
99 let (status, body) = get_as(&router, "/tahinli/demo", None).await;94 let (status, body) = get_as(&router, "/tahinli/demo", None).await;
100 assert_eq!(status, 200);95 assert_eq!(status, 200);
101 assert!(body.contains("Hello from the README"), "README rendered");96 assert!(body.contains("Hello from the README"), "README rendered");
@@ -117,7 +112,6 @@ async fn demo_pages_render_from_the_repo_contents() {
117 assert!(body.contains("/tahinli/demo/branches"));112 assert!(body.contains("/tahinli/demo/branches"));
118 assert!(body.contains("data-ref-filter"), "branch switcher rendered");113 assert!(body.contains("data-ref-filter"), "branch switcher rendered");
119 114
120- // Trees list their entries and link to subtrees and blobs.
121 let (status, body) = get_as(&router, "/tahinli/demo/tree/main/src", None).await;115 let (status, body) = get_as(&router, "/tahinli/demo/tree/main/src", None).await;
122 assert_eq!(status, 200);116 assert_eq!(status, 200);
123 assert!(body.contains("main.rs"));117 assert!(body.contains("main.rs"));
@@ -126,7 +120,6 @@ async fn demo_pages_render_from_the_repo_contents() {
126 assert_eq!(status, 200);120 assert_eq!(status, 200);
127 assert!(body.contains("/tahinli/demo/tree/main/docs"));121 assert!(body.contains("/tahinli/demo/tree/main/docs"));
128 122
129- // Rust source is highlighted with line anchors.
130 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/src/main.rs", None).await;123 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/src/main.rs", None).await;
131 assert_eq!(status, 200);124 assert_eq!(status, 200);
132 assert!(body.contains("id=\"L1\""));125 assert!(body.contains("id=\"L1\""));
@@ -134,7 +127,6 @@ async fn demo_pages_render_from_the_repo_contents() {
134 assert!(body.contains("<span class="), "syntax classes applied");127 assert!(body.contains("<span class="), "syntax classes applied");
135 assert!(body.contains("/assets/highlight.css?v="));128 assert!(body.contains("/assets/highlight.css?v="));
136 129
137- // Markdown renders unless the viewer asks for the plain source.
138 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/docs/guide.md", None).await;130 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/docs/guide.md", None).await;
139 assert_eq!(status, 200);131 assert_eq!(status, 200);
140 assert!(132 assert!(
@@ -146,12 +138,10 @@ async fn demo_pages_render_from_the_repo_contents() {
146 assert!(body.contains("file-table"), "source shown as lines");138 assert!(body.contains("file-table"), "source shown as lines");
147 assert!(!body.contains("markdown-body"), "not rendered");139 assert!(!body.contains("markdown-body"), "not rendered");
148 140
149- // Binary blobs show their size instead of content.
150 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/data.bin", None).await;141 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/data.bin", None).await;
151 assert_eq!(status, 200);142 assert_eq!(status, 200);
152 assert!(body.contains("Binary file, 3 bytes"));143 assert!(body.contains("Binary file, 3 bytes"));
153 144
154- // Fixed segment routes win over the repo catch-all.
155 let (status, body) = get_as(&router, "/tahinli/demo/branches", None).await;145 let (status, body) = get_as(&router, "/tahinli/demo/branches", None).await;
156 assert_eq!(status, 200);146 assert_eq!(status, 200);
157 assert!(body.contains("default"), "default branch marked");147 assert!(body.contains("default"), "default branch marked");
@@ -196,7 +186,6 @@ const ZERO_OID: &str = "0000000000000000000000000000000000000000";
196 const OID: &str = "1111111111111111111111111111111111111111";186 const OID: &str = "1111111111111111111111111111111111111111";
197 const BANNER: &str = "had recent pushes";187 const BANNER: &str = "had recent pushes";
198 188
199-/// Creates a session for `user_id` and returns the cookie header value.
200 async fn sign_in(state: &AppState, user_id: &str, token: &str) -> String {189 async fn sign_in(state: &AppState, user_id: &str, token: &str) -> String {
201 crate::test_support::create_session(&state.store, user_id, token, "csrf").await;190 crate::test_support::create_session(&state.store, user_id, token, "csrf").await;
202 format!("__Host-{SESSION_COOKIE}={token}")191 format!("__Host-{SESSION_COOKIE}={token}")
@@ -213,13 +202,11 @@ async fn get_as(router: &Router, uri: &str, cookie: Option<&str>) -> (u16, Strin
213 (status, String::from_utf8_lossy(&bytes).into_owned())202 (status, String::from_utf8_lossy(&bytes).into_owned())
214 }203 }
215 204
216-/// Points `branch` at the bare repo's `main`, so the branch exists.
217 fn make_branch(bare: &Path, branch: &str) {205 fn make_branch(bare: &Path, branch: &str) {
218 let full = format!("refs/heads/{branch}");206 let full = format!("refs/heads/{branch}");
219 git(bare, &["update-ref", &full, "refs/heads/main"]);207 git(bare, &["update-ref", &full, "refs/heads/main"]);
220 }208 }
221 209
222-/// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.
223 async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) {210 async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) {
224 let at = stamp_ago(age);211 let at = stamp_ago(age);
225 let full = format!("refs/heads/{branch}");212 let full = format!("refs/heads/{branch}");
@@ -439,12 +426,10 @@ async fn fork_push_links_to_parent_compare() {
439 .await;426 .await;
440 let cookie = sign_in(&state, &bob.id, "bob-token").await;427 let cookie = sign_in(&state, &bob.id, "bob-token").await;
441 428
442- // On the parent, the viewer's fork branch compares as owner:branch.
443 let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;429 let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
444 assert_eq!(status, 200);430 assert_eq!(status, 200);
445 assert!(body.contains("compare/main...bob%3Afeature"), "{body}");431 assert!(body.contains("compare/main...bob%3Afeature"), "{body}");
446 432
447- // On the fork itself, the link goes to the parent's compare page.
448 let (status, body) = get_as(&router, "/bob/demo", Some(&cookie)).await;433 let (status, body) = get_as(&router, "/bob/demo", Some(&cookie)).await;
449 assert_eq!(status, 200);434 assert_eq!(status, 200);
450 assert!(435 assert!(
crates/forge-web/src/route_list_tests.rsmodified+0 -4
@@ -1,7 +1,3 @@
1-//! Every route, page, layout and layer that `discover()` finds, against `routes.snap`. Moving code
2-//! between crates must not lose one: a crate the binary does not link drops all of its routes.
3-//! `FORGE_BLESS=1` rewrites the snapshot.
4-
5 use topcoat::internal::inventory;1 use topcoat::internal::inventory;
6 use topcoat::router::{Layer, Layout, Page, Route};2 use topcoat::router::{Layer, Layout, Page, Route};
7 3
crates/forge-web/src/shell_route_tests.rsmodified+0 -13
@@ -1,11 +1,8 @@
1-//! Shell tests that render pages, so they need the page routes linked in.
2-
3 use topcoat::router::request::Request;1 use topcoat::router::request::Request;
4 use topcoat::router::{Body, to_bytes};2 use topcoat::router::{Body, to_bytes};
5 3
6 use crate::views::NAV_SCRIPT_HREF;4 use crate::views::NAV_SCRIPT_HREF;
7 5
8-/// Every `<script` tag carries a `src`: an inline script could not run under the CSP.
9 fn assert_no_inline_scripts(html: &str) {6 fn assert_no_inline_scripts(html: &str) {
10 for (at, _) in html.match_indices("<script") {7 for (at, _) in html.match_indices("<script") {
11 let tag = &html[at..];8 let tag = &html[at..];
@@ -54,7 +51,6 @@ async fn shell_loads_the_deferred_nav_script_without_inline_scripts() {
54 assert!(html.contains("<main tabindex=\"-1\" data-width=\"col\">"));51 assert!(html.contains("<main tabindex=\"-1\" data-width=\"col\">"));
55 assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\""));52 assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\""));
56 53
57- // An anonymous page renders the default colours.
58 let tag = html_tag(&html);54 let tag = html_tag(&html);
59 assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");55 assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
60 assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");56 assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
@@ -62,15 +58,12 @@ async fn shell_loads_the_deferred_nav_script_without_inline_scripts() {
62 assert!(tag.contains("data-base-dark=\"ink\""), "{tag}");58 assert!(tag.contains("data-base-dark=\"ink\""), "{tag}");
63 }59 }
64 60
65-/// The `<html …>` start tag of a page.
66 fn html_tag(page: &str) -> &str {61 fn html_tag(page: &str) -> &str {
67 let at = page.find("<html").expect("the page has an html tag");62 let at = page.find("<html").expect("the page has an html tag");
68 let len = page[at..].find('>').expect("the html tag closes");63 let len = page[at..].find('>').expect("the html tag closes");
69 &page[at..at + len + 1]64 &page[at..at + len + 1]
70 }65 }
71 66
72-/// The `<html>` tag of `/settings/security` for a signed-in user whose stored colours are the
73-/// four ids given, in the order light accent, dark accent, light base, dark base.
74 async fn html_tag_for_colours(67 async fn html_tag_for_colours(
75 router: &topcoat::router::Router,68 router: &topcoat::router::Router,
76 store: &forge_core::Store,69 store: &forge_core::Store,
@@ -101,7 +94,6 @@ async fn html_tag_for_colours(
101 html_tag(&String::from_utf8_lossy(&bytes)).to_owned()94 html_tag(&String::from_utf8_lossy(&bytes)).to_owned()
102 }95 }
103 96
104-/// Every colour case shares one fixture; each has its own user and session.
105 #[tokio::test]97 #[tokio::test]
106 async fn the_html_tag_carries_the_viewers_colours() {98 async fn the_html_tag_carries_the_viewers_colours() {
107 let dir = tempfile::tempdir().expect("tempdir");99 let dir = tempfile::tempdir().expect("tempdir");
@@ -122,7 +114,6 @@ async fn the_html_tag_carries_the_viewers_colours() {
122 assert!(tag.contains("data-base-light=\"ink\""), "{tag}");114 assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
123 assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}");115 assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}");
124 assert!(!tag.contains("data-accent="), "{tag}");116 assert!(!tag.contains("data-accent="), "{tag}");
125- // Stored ids that are no longer offered fall back to the defaults, never to nothing.
126 let removed = html_tag_for_colours(117 let removed = html_tag_for_colours(
127 &router,118 &router,
128 &store,119 &store,
@@ -135,7 +126,6 @@ async fn the_html_tag_carries_the_viewers_colours() {
135 assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");126 assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");
136 assert!(removed.contains("data-base-light=\"ink\""), "{removed}");127 assert!(removed.contains("data-base-light=\"ink\""), "{removed}");
137 assert!(removed.contains("data-base-dark=\"ink\""), "{removed}");128 assert!(removed.contains("data-base-dark=\"ink\""), "{removed}");
138- // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself.
139 let retired = html_tag_for_colours(129 let retired = html_tag_for_colours(
140 &router,130 &router,
141 &store,131 &store,
@@ -162,7 +152,6 @@ async fn the_html_tag_carries_the_viewers_colours() {
162 assert!(hued.contains("data-base-dark=\"ink\""), "{hued}");152 assert!(hued.contains("data-base-dark=\"ink\""), "{hued}");
163 }153 }
164 154
165-/// Renders `/settings/security` (a page that uses the shell) for a freshly signed-in user.
166 async fn menu_html(155 async fn menu_html(
167 router: &topcoat::router::Router,156 router: &topcoat::router::Router,
168 store: &forge_core::Store,157 store: &forge_core::Store,
@@ -191,8 +180,6 @@ async fn menu_html(
191 String::from_utf8_lossy(&bytes).into_owned()180 String::from_utf8_lossy(&bytes).into_owned()
192 }181 }
193 182
194-/// A user sees no admin links and an admin sees the one Admin entry. Both render from one
195-/// fixture.
196 #[tokio::test]183 #[tokio::test]
197 async fn admin_links_follow_the_role() {184 async fn admin_links_follow_the_role() {
198 let dir = tempfile::tempdir().expect("tempdir");185 let dir = tempfile::tempdir().expect("tempdir");
crates/forge-web/src/templates_route_tests.rsmodified+0 -3
@@ -6,8 +6,6 @@ use forge_web_pages::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, s
6 const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n";6 const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n";
7 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";7 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";
8 8
9-/// A repo whose default branch gets `files` committed on top of the fixture's history.
10-/// Tahinli is signed in.
11 async fn setup(files: &[(&str, &str)]) -> Fixture {9 async fn setup(files: &[(&str, &str)]) -> Fixture {
12 let fx = Fixture::new(Visibility::Public).await;10 let fx = Fixture::new(Visibility::Public).await;
13 for (path, text) in files {11 for (path, text) in files {
@@ -35,7 +33,6 @@ fn new_issue_uri(query: &str) -> String {
35 format!("/{OWNER}/{REPO}/issues/new{query}")33 format!("/{OWNER}/{REPO}/issues/new{query}")
36 }34 }
37 35
38-/// The text of the tag that starts at `needle`, up to its closing `>`.
39 fn tag_at(html: &str, needle: &str) -> String {36 fn tag_at(html: &str, needle: &str) -> String {
40 let at = html.find(needle).expect("needle in page");37 let at = html.find(needle).expect("needle in page");
41 let end = html[at..].find('>').expect("tag end") + at;38 let end = html[at..].find('>').expect("tag end") + at;