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 {
253253 fetch_all(&conn, &sql, params, map_notice).await
254254 }
255255
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+
256267 /// Marks one of the user's alert rows read. Another user's row changes nothing.
257268 pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> {
258269 let conn = self.inner.conn.lock().await;
crates/forge-core/src/store/imports.rsmodified+16 -0
@@ -204,6 +204,22 @@ impl Store {
204204 Ok(())
205205 }
206206
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+
207223 /// Records the current stage and how far it is.
208224 pub async fn set_import_progress(
209225 &self,
crates/forge-core/src/store/mod.rsmodified+57 -0
@@ -837,6 +837,39 @@ impl Store {
837837 affected(n)
838838 }
839839
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+
840873 /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest.
841874 pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> {
842875 let conn = self.inner.conn.lock().await;
@@ -1583,6 +1616,30 @@ impl Store {
15831616 affected(n)
15841617 }
15851618
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+
15861643 /// Deletes every session of the user except `keep_session_id`. Returns how many were removed.
15871644 pub async fn delete_sessions_except(
15881645 &self,
crates/forge-core/src/store/webhooks.rsmodified+11 -5
@@ -308,25 +308,28 @@ impl Store {
308308 .await
309309 }
310310
311- /// The repo's hooks, oldest first, each with the state of its most recent delivery
311+ /// The repo's hooks, oldest first, each with the state and stamp of its most recent delivery
312312 /// (`None` when it has none yet).
313313 pub async fn list_webhooks(
314314 &self,
315315 repo_id: &str,
316- ) -> Result<Vec<(Webhook, Option<DeliveryState>)>> {
316+ ) -> Result<Vec<(Webhook, Option<(DeliveryState, String)>)>> {
317317 let sql = format!(
318318 "SELECT {WEBHOOK_COLS}, \
319319 (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 \
320322 ORDER BY d.created_at DESC, d.id DESC LIMIT 1) \
321323 FROM webhooks WHERE repo_id = ?1 ORDER BY created_at, id"
322324 );
323325 let conn = self.read_conn().await;
324326 fetch_all(&conn, &sql, (repo_id.to_string(),), |row| {
325327 let last = match col_opt_text(row, 7)? {
326- Some(s) => Some(
328+ Some(s) => Some((
327329 DeliveryState::parse(&s)
328330 .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?,
329- ),
331+ col_text(row, 8)?,
332+ )),
330333 None => None,
331334 };
332335 Ok((map_webhook(row)?, last))
@@ -922,7 +925,10 @@ mod tests {
922925 assert_eq!(failed.duration_ms, Some(12));
923926 assert!(failed.delivered_at.is_none());
924927 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),
926932 Some(DeliveryState::Failed)
927933 );
928934
crates/forge-web-account/Cargo.tomlmodified+0 -3
@@ -12,7 +12,6 @@ forge-web-pages.workspace = true
1212 forge-core.workspace = true
1313 forge-git.workspace = true
1414 forge-ci.workspace = true
15-forge-web-base.workspace = true
1615 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
1716 tokio.workspace = true
1817 futures-util.workspace = true
@@ -31,8 +30,6 @@ hex.workspace = true
3130 sha2.workspace = true
3231 time.workspace = true
3332 ulid.workspace = true
34-zip = { workspace = true }
35-tar.workspace = true
3633
3734
3835 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 {
4141 }
4242
4343 /// 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> {
4545 match state {
4646 RunState::Success => Some("passed"),
4747 RunState::Failure | RunState::Error => Some("failed"),
@@ -53,7 +53,7 @@ pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> {
5353 /// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts
5454 /// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting`
5555 /// 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> {
5757 let kinds = state.store.inbox_kind_counts(&user.id).await?;
5858 let runs = state.store.actor_runs(&user.id, RECENT_SECS).await?;
5959 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::{
2929 BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice,
3030 };
3131 use crate::pages::admin_users::admin_only;
32-use crate::pages::issues_list::stamp_unix;
3332 use crate::state::AppState;
3433 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};
3635
3736 /// Runs shown on the page.
3837 const RUN_LIMIT: u32 = 20;
@@ -59,21 +58,6 @@ struct RunRow {
5958 detail: String,
6059 }
6160
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-
7761 fn duration_text(run: &BackupRun) -> String {
7862 let start = stamp_unix(&run.started_at);
7963 let Some(end) = run.finished_at.as_deref().map(stamp_unix) else {
@@ -101,7 +85,7 @@ fn run_row(run: &BackupRun, lang: Lang) -> RunRow {
10185 trigger: g::trigger_name(lang, run.trigger).to_owned(),
10286 started: run.started_at.clone(),
10387 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(),
10589 status,
10690 detail,
10791 }
@@ -583,11 +567,4 @@ mod tests {
583567 );
584568 assert_eq!(fx.state.jobs.running(), None);
585569 }
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- }
593570 }
crates/forge-web-account/src/pages/admin_health.rsmodified+53 -52
@@ -1,6 +1,6 @@
11 //! Page: instance health for admins (`/admin/health`). A summary line, then one sheet with the alerts,
22 //! 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,
44 //! reads fresh values. The tree size of the repos (`du`) walks every repo, so a background task caches
55 //! it (see [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404.
66
@@ -80,10 +80,12 @@ struct Usage {
8080 path: String,
8181 /// Percent used, the bar's fill.
8282 pct: u8,
83- /// At least 90% used.
83+ /// At least [`DISK_BAD_PCT`] used.
8484 bad: bool,
8585 }
8686
87+const DISK_BAD_PCT: u8 = 90;
88+
8789 /// One fact in the storage topic: one row.
8890 struct Fact {
8991 label: &'static str,
@@ -102,6 +104,18 @@ struct Service {
102104 stamp: Option<String>,
103105 }
104106
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+
105119 /// Everything the page shows, and how many items need attention.
106120 struct Health {
107121 usage: Option<Usage>,
@@ -127,15 +141,6 @@ fn space(lang: Lang, total: u64, avail: u64) -> (u8, String) {
127141 (pct, text)
128142 }
129143
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-
139144 /// Kilobytes from `du -sk <path>` output, as bytes.
140145 fn parse_du(output: &str) -> Option<u64> {
141146 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
155160 }
156161
157162 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()
159168 }
160169
161170 async fn tree_size(path: &Path, limit: Duration) -> Option<u64> {
@@ -255,7 +264,7 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
255264 free_of_total,
256265 path: data_dir.to_string_lossy().into_owned(),
257266 pct,
258- bad: pct >= 90,
267+ bad: pct >= DISK_BAD_PCT,
259268 }
260269 });
261270
@@ -286,7 +295,11 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
286295 label: at(lang, A::BackupDirectory),
287296 value: text,
288297 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+ },
290303 }
291304 }
292305 None => Fact {
@@ -347,20 +360,16 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
347360 stamp: Some(run.started_at.clone()),
348361 }
349362 }
350- None if backup_on => Service {
351- label: at(lang, A::LastBackup),
352- dot: Dot::Neutral,
353- value: at(lang, A::Never).to_owned(),
354- detail: String::new(),
355- stamp: None,
356- },
357- None => Service {
358- label: at(lang, A::LastBackup),
359- dot: Dot::Off,
360- value: at(lang, A::NotConfigured).to_owned(),
361- detail: String::new(),
362- stamp: None,
363- },
363+ None if backup_on => Service::new(
364+ at(lang, A::LastBackup),
365+ Dot::Neutral,
366+ at(lang, A::Never).to_owned(),
367+ ),
368+ None => Service::new(
369+ at(lang, A::LastBackup),
370+ Dot::Off,
371+ at(lang, A::NotConfigured).to_owned(),
372+ ),
364373 });
365374
366375 let replicating = !live.replication.target.trim().is_empty();
@@ -390,22 +399,18 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
390399 stamp: status.last_ok_at.clone(),
391400 }
392401 }
393- None => Service {
394- label: at(lang, A::Replication),
395- dot: Dot::Neutral,
396- value: at(lang, A::Never).to_owned(),
397- detail: String::new(),
398- stamp: None,
399- },
402+ None => Service::new(
403+ at(lang, A::Replication),
404+ Dot::Neutral,
405+ at(lang, A::Never).to_owned(),
406+ ),
400407 }
401408 } else {
402- Service {
403- label: at(lang, A::Replication),
404- dot: Dot::Off,
405- value: at(lang, A::NotConfigured).to_owned(),
406- detail: String::new(),
407- stamp: None,
408- }
409+ Service::new(
410+ at(lang, A::Replication),
411+ Dot::Off,
412+ at(lang, A::NotConfigured).to_owned(),
413+ )
409414 });
410415
411416 let uptime = uptime_secs().map_or_else(
@@ -488,7 +493,6 @@ async fn health_view(
488493 nav: (Vec<PageLink>, Option<String>, Option<String>),
489494 ) -> Result<impl View> {
490495 // The heading counts every active alert; the sheet lists the current page of them.
491- let count = total;
492496 let (links, prev, next) = nav;
493497 let Health {
494498 usage,
@@ -498,7 +502,7 @@ async fn health_view(
498502 attention,
499503 } = health;
500504 // An active alert needs attention as much as a failing service does.
501- let attention = attention + count;
505+ let attention = attention + total;
502506 // The verdict leads the head's line, with its dot, so the page says how things are first.
503507 let summary = if attention > 0 {
504508 SubPart {
@@ -517,9 +521,9 @@ async fn health_view(
517521 Ok(view! {
518522 head(title: at(lang, A::Health), sub: sub, live: Some("/admin/health/events"))
519523 <div class="sheet health-sheet">
520- if count > 0 {
524+ if total > 0 {
521525 <section class="sec" role="alert">
522- <h2>(alert_text::banner_heading(lang, count))</h2>
526+ <h2>(alert_text::banner_heading(lang, total))</h2>
523527 for a in alerts.into_iter() {
524528 <div class="line" data-kb-row="">
525529 <span class="name">(a.title.as_str())</span>
@@ -612,8 +616,8 @@ async fn health_page(cx: &Cx) -> Result<impl View> {
612616
613617 /// What the health page shows that can change between renders, as one string: the alerts, the
614618 /// 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 size
616-/// of the repos is the cached value of the background walk, as the page displays it.
619+/// disk figures come from `statvfs`. The tree size of the repos is the cached value of the
620+/// background walk, as the page displays it.
617621 async fn health_fingerprint(state: &AppState) -> Result<String> {
618622 let counts = state.store.health_counts().await?;
619623 let mail = state
@@ -660,10 +664,7 @@ mod tests {
660664 use super::*;
661665
662666 #[test]
663- fn df_and_du_output_parse_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+ fn du_output_parses_to_bytes() {
667668 assert_eq!(parse_du("12\t/data/repos\n"), Some(12 * 1024), "du");
668669 assert_eq!(parse_du(""), None, "du empty");
669670 }
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-
101 use std::collections::HashMap;
112
123 use forge_core::mail::{
@@ -15,13 +6,10 @@ use forge_core::mail::{
156 use forge_core::server_settings::Group;
167 use forge_core::time::now_stamp;
178 use forge_core::{AuditAction, Error};
18-use futures_util::{Stream, stream};
199 use serde::Deserialize;
20-use tokio::sync::watch;
2110 use topcoat::Result;
2211 use topcoat::context::{Cx, context};
2312 use topcoat::router::content::Form;
24-use topcoat::router::content::sse::Event;
2513 use topcoat::router::error::{forbidden, see_other};
2614 use topcoat::router::response::Response;
2715 use topcoat::router::{page, query_params, route};
@@ -31,7 +19,7 @@ use crate::audit::{self, Actor, Target};
3119 use crate::auth::check_csrf;
3220 use crate::i18n::admin::{self as g, K};
3321 use crate::i18n::{self, Key, Lang};
34-use crate::live::{changed_event, events_response};
22+use crate::live::{events_response, wake_stream};
3523 use crate::mail::{enqueue, live, templates};
3624 use crate::pages::admin_server::{
3725 MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows,
@@ -41,7 +29,6 @@ use crate::state::AppState;
4129 use crate::views::parts::{confirm_act, head, post_act};
4230 use crate::views::{enc, rel_time, shell};
4331
44-/// Rows shown in the queue at most.
4532 const LIST_LIMIT: u32 = 100;
4633
4734 #[query_params(error = bad_request)]
@@ -51,14 +38,12 @@ pub(crate) struct NoticeQuery {
5138 state: Option<String>,
5239 }
5340
54-/// The two tabs of the page.
5541 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
5642 enum Tab {
5743 Settings,
5844 Queue,
5945 }
6046
61-/// One queue row, already formatted. There is no body field on purpose.
6247 struct QueueRow {
6348 id: String,
6449 to: String,
@@ -73,7 +58,6 @@ struct QueueRow {
7358 failed: bool,
7459 }
7560
76-/// One state filter: the link, its label and how many rows it covers.
7761 struct FilterChip {
7862 href: String,
7963 label: &'static str,
@@ -81,14 +65,12 @@ struct FilterChip {
8165 current: bool,
8266 }
8367
84-/// The queue tab: the filter chips, the rows and the state the filter is on, for the forms.
8568 struct QueueData {
8669 chips: Vec<FilterChip>,
8770 rows: Vec<QueueRow>,
8871 filter_param: String,
8972 }
9073
91-/// Everything the page shows. The password is never in here.
9274 struct PageData {
9375 host: String,
9476 port: String,
@@ -98,13 +80,11 @@ struct PageData {
9880 from_name: String,
9981 enabled: bool,
10082 has_password: bool,
101- /// The delivery setting (`mail.transport`), a settings row saved with the settings form.
10283 transport: Vec<Row>,
10384 tab: Tab,
10485 queue: Option<QueueData>,
10586 }
10687
107-/// The CSS class of a state pill. The pills reuse the CI state colours.
10888 fn state_class(state: MailState) -> &'static str {
10989 match state {
11090 MailState::Sent => "ci-state ci-success",
@@ -133,7 +113,6 @@ fn row_view(entry: &OutboxEntry, now: &str, lang: Lang) -> QueueRow {
133113 }
134114 }
135115
136-/// The queue tab's data. `filter` of `None` lists every state.
137116 async fn queue_data(
138117 state: &AppState,
139118 lang: Lang,
@@ -224,8 +203,6 @@ async fn mail_view(
224203 <a href="/admin/mail?tab=queue" aria-current=((!settings_on).then_some("page"))>(g::t(lang, K::MailTabQueue))</a>
225204 </nav>
226205 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.
229206 <div class="sheet" data-live="/admin/mail/events">
230207 <form method="post" action="/admin/mail" class="srv-form">
231208 <input type="hidden" name="csrf" value=(csrf.as_str())>
@@ -349,29 +326,17 @@ async fn mail_page(cx: &Cx) -> Result<impl View> {
349326 })
350327 }
351328
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.
362329 #[route(GET "/admin/mail/events")]
363330 async fn mail_events(cx: &Cx) -> Result<Response> {
364331 admin_only(cx).await?;
365- // Subscribed before the response is sent, so a change after this point is sent.
366332 let wake = live::subscribe();
367- events_response(cx, queue_changes(wake))
333+ events_response(cx, wake_stream(wake, "queue"))
368334 }
369335
370336 #[derive(Deserialize, Default)]
371337 struct SettingsForm {
372338 #[serde(default)]
373339 csrf: String,
374- /// The delivery setting, saved as an override like the server settings.
375340 #[serde(default, rename = "mail.transport")]
376341 transport: String,
377342 #[serde(default)]
@@ -424,8 +389,6 @@ async fn mail_save(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<Response>
424389 Err(see_other(&location).into())
425390 }
426391
427-/// Validates and stores the settings, wakes the worker, and audits the change. The password is
428-/// not part of the audit entry.
429392 async fn save_settings(
430393 cx: &Cx,
431394 state: &AppState,
@@ -499,8 +462,6 @@ async fn mail_test(cx: &Cx, Form(form): Form<TestForm>) -> Result<Response> {
499462 Err(see_other(&location).into())
500463 }
501464
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.
504465 async fn queue_test(
505466 cx: &Cx,
506467 state: &AppState,
@@ -555,7 +516,6 @@ struct QueueForm {
555516 csrf: String,
556517 #[serde(default)]
557518 id: String,
558- /// The filter the admin was on, so the redirect lands back on it.
559519 #[serde(default)]
560520 state: String,
561521 }
@@ -570,8 +530,6 @@ async fn queue_discard(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response>
570530 queue_action(cx, form, QueueAction::Discard).await
571531 }
572532
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.
575533 async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<Response> {
576534 let viewer = admin_only(cx).await?;
577535 if !check_csrf(&viewer.1, &form.csrf) {
@@ -626,7 +584,6 @@ mod tests {
626584 state: AppState,
627585 }
628586
629- /// An instance with an admin (who has an address) and a plain user.
630587 async fn fixture() -> Fixture {
631588 let dir = tempfile::tempdir().expect("tempdir");
632589 let data_dir = dir.path().join("data");
@@ -692,14 +649,10 @@ mod tests {
692649 .any(|e| e.action == action)
693650 }
694651
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.
698652 #[tokio::test]
699653 async fn settings_gates_saves_test_mail_and_turkish_page() {
700654 let fx = fixture().await;
701655
702- // Anonymous and non-admin users get 404 on the page and its posts.
703656 let (anon, _) = send(&fx.router, "GET", "/admin/mail", None, None).await;
704657 assert_eq!(anon, 404);
705658 let (user, _) = send(&fx.router, "GET", "/admin/mail", Some(USER_TOKEN), None).await;
@@ -731,7 +684,6 @@ mod tests {
731684 .has_password
732685 );
733686
734- // A missing CSRF token is refused.
735687 let (status, _) = send(
736688 &fx.router,
737689 "POST",
@@ -742,7 +694,6 @@ mod tests {
742694 .await;
743695 assert_eq!(status, 403, "a missing CSRF token is refused");
744696
745- // Test mail while mail is off queues nothing.
746697 let (status, _) = send(
747698 &fx.router,
748699 "POST",
@@ -762,7 +713,6 @@ mod tests {
762713 "nothing is queued while mail is off"
763714 );
764715
765- // A bad port is answered with a notice and changes nothing.
766716 let (status, _) = send(
767717 &fx.router,
768718 "POST",
@@ -777,7 +727,6 @@ mod tests {
777727 assert!(!saved.has_password);
778728 assert!(!audit_has(&fx.state.store, AuditAction::MailSettingsUpdated).await);
779729
780- // A good save stores the settings, audits them, and the page never shows the password.
781730 let (status, _) = send(
782731 &fx.router,
783732 "POST",
@@ -802,7 +751,6 @@ mod tests {
802751 "the stored password is never rendered"
803752 );
804753
805- // With mail on, a test mail is queued to the admin's address and audited.
806754 let (status, _) = send(
807755 &fx.router,
808756 "POST",
@@ -818,7 +766,6 @@ mod tests {
818766 assert!(rows[0].idem_key.starts_with("test:"));
819767 assert!(audit_has(&fx.state.store, AuditAction::MailTestQueued).await);
820768
821- // The page follows the viewer's language.
822769 let req = Request::builder()
823770 .method("GET")
824771 .uri("/admin/mail")
@@ -851,13 +798,10 @@ mod tests {
851798 }
852799 }
853800
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.
856801 #[tokio::test]
857802 async fn queue_tab_is_admin_only_live_filters_and_never_renders_a_body() {
858803 let fx = fixture().await;
859804
860- // Anonymous and plain users get 404 on the stream and on both queue actions.
861805 for (method, uri) in [
862806 ("GET", "/admin/mail/events"),
863807 ("POST", "/admin/mail/queue/retry"),
@@ -963,7 +907,6 @@ mod tests {
963907 "the queue is on its own tab"
964908 );
965909
966- // An admin gets the queue event stream.
967910 let request = Request::builder()
968911 .method("GET")
969912 .uri("/admin/mail/events")
@@ -1046,7 +989,6 @@ mod tests {
1046989 assert_eq!(discarded.len(), 1);
1047990 assert_eq!(discarded[0].id, ids[1]);
1048991
1049- // A queued message cannot be retried, and a bad token changes nothing.
1050992 let (status, _) = send(
1051993 &fx.router,
1052994 "POST",
crates/forge-web-account/src/pages/admin_replication.rsmodified+30 -57
@@ -57,7 +57,7 @@ pub(crate) struct NoticeQuery {
5757 const REPO_ROWS: usize = 10;
5858
5959 /// 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];
6161
6262 /// How a subject reads on the page.
6363 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -98,9 +98,7 @@ impl Health {
9898 }
9999
100100 fn from_key(key: &str) -> Option<Health> {
101- [Health::Ok, Health::Lagging, Health::Error, Health::Never]
102- .into_iter()
103- .find(|h| h.key() == key)
101+ HEALTH_MENU.into_iter().find(|h| h.key() == key)
104102 }
105103
106104 fn label(self, lang: Lang) -> &'static str {
@@ -127,29 +125,23 @@ fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health {
127125 }
128126 }
129127
130-/// One line of the repos table, already formatted.
128+/// One line of the repos table.
131129 struct RepoRow {
132130 name: String,
133131 kind: Health,
134- dot: &'static str,
135- tone: &'static str,
136- health: &'static str,
137132 /// The last good copy's stamp, shown as a live relative time.
138133 last_ok: Option<String>,
139134 error: String,
140135 }
141136
142-impl RepoRow {
143- fn copy(&self) -> RepoRow {
144- RepoRow {
145- name: self.name.clone(),
146- kind: self.kind,
147- dot: self.dot,
148- tone: self.tone,
149- health: self.health,
150- last_ok: self.last_ok.clone(),
151- error: self.error.clone(),
152- }
137+fn repo_row(name: String, status: Option<&ReplicationStatus>, cutoff: &str) -> RepoRow {
138+ RepoRow {
139+ name,
140+ kind: health(status, cutoff),
141+ last_ok: status.and_then(|s| s.last_ok_at.clone()),
142+ error: status
143+ .and_then(|s| s.last_error.clone())
144+ .unwrap_or_default(),
153145 }
154146 }
155147
@@ -187,39 +179,21 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData>
187179 Some(repo) => format!("{}/{}", repo.owner_name, repo.name),
188180 None => id.clone(),
189181 };
190- let h = health(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- });
182+ repos.push(repo_row(name, status, &repo_cutoff));
202183 }
203184 // Repos deleted since their last push: their standby copy is removed at the next reconcile.
204185 for status in statuses.values() {
205186 if status.subject != DB_SUBJECT && !ids.contains(&status.subject) {
206- let h = health(Some(status), &repo_cutoff);
207- repos.push(RepoRow {
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- });
187+ let name = g::deleted_repo_name(lang, &status.subject);
188+ repos.push(repo_row(name, Some(status), &repo_cutoff));
216189 }
217190 }
218191
192+ let db_health = health(db, &db_cutoff);
219193 Ok(PageData {
220194 enabled: config.enabled(),
221- db_dot: health(db, &db_cutoff).dot(),
222- db_health: health(db, &db_cutoff).label(lang),
195+ db_dot: db_health.dot(),
196+ db_health: db_health.label(lang),
223197 db_last_ok: db.and_then(|s| s.last_ok_at.clone()),
224198 db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()),
225199 db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(),
@@ -238,6 +212,7 @@ async fn replication_view(
238212 list: RepoList,
239213 ) -> Result<impl View> {
240214 let RepoList {
215+ has_repos,
241216 finder,
242217 health,
243218 rows,
@@ -245,7 +220,6 @@ async fn replication_view(
245220 pages,
246221 nav: (links, prev, next),
247222 } = list;
248- let has_repos = !data.repos.is_empty();
249223 let all_label = s(lang, "All", "Tümü");
250224 let health_label = s(lang, "Health", "Durum");
251225 let placeholder = s(lang, "Search repositories", "Depolarda ara");
@@ -306,10 +280,8 @@ async fn replication_view(
306280 (health_label) " "
307281 <select name="health" data-autosubmit="true">
308282 <option value="" selected=(health.is_none())>(all_label)</option>
309- for key in HEALTH_KEYS {
310- if let Some(h) = Health::from_key(key) {
311- <option value=(key) selected=(health == Some(h))>(h.label(lang))</option>
312- }
283+ for h in HEALTH_MENU {
284+ <option value=(h.key()) selected=(health == Some(h))>(h.label(lang))</option>
313285 }
314286 </select>
315287 </label>
@@ -320,7 +292,7 @@ async fn replication_view(
320292 for row in rows.into_iter() {
321293 <div class="line" data-kb-row="">
322294 <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>
324296 </div>
325297 if !row.error.is_empty() {
326298 alert(message: row.error.as_str())
@@ -341,7 +313,7 @@ async fn page_fingerprint(state: &AppState) -> Result<String> {
341313 let rows: Vec<_> = data
342314 .repos
343315 .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))
345317 .collect();
346318 Ok(format!(
347319 "{}|{}|{:?}|{:?}|{}|{:?}",
@@ -368,6 +340,7 @@ async fn replication_events(cx: &Cx) -> Result<Response> {
368340
369341 /// One page of the repo list, after the search and the health filter.
370342 struct RepoList {
343+ has_repos: bool,
371344 finder: Finder,
372345 health: Option<Health>,
373346 rows: Vec<RepoRow>,
@@ -376,20 +349,19 @@ struct RepoList {
376349 nav: (Vec<PageLink>, Option<String>, Option<String>),
377350 }
378351
379-/// Takes the repos that match the query out of `data`, a page of them.
380-fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList {
352+/// Filters the repos by the query and cuts out the page asked for.
353+fn repo_list(repos: Vec<RepoRow>, query: &NoticeQuery) -> RepoList {
381354 let finder = Finder::new(
382355 query.q.as_deref(),
383356 query.exact.as_deref(),
384357 query.case.as_deref(),
385358 );
386359 let health = query.health.as_deref().and_then(Health::from_key);
387- let matching: Vec<RepoRow> = data
388- .repos
389- .iter()
360+ let has_repos = !repos.is_empty();
361+ let matching: Vec<RepoRow> = repos
362+ .into_iter()
390363 .filter(|row| health.is_none_or(|h| row.kind == h))
391364 .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()]))
392- .map(RepoRow::copy)
393365 .collect();
394366 let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1);
395367 let page = query
@@ -412,6 +384,7 @@ fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList {
412384 list_href("/admin/replication", &params)
413385 });
414386 RepoList {
387+ has_repos,
415388 finder,
416389 health,
417390 rows,
@@ -428,7 +401,7 @@ async fn replication_page(cx: &Cx) -> Result<impl View> {
428401 let lang = i18n::lang(cx, Some(&viewer.0));
429402 let state = context::<AppState>(cx);
430403 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);
432405 let settings = setting_rows(state, lang, REPLICATION_KEYS).await?;
433406 let csrf = viewer.1.csrf_token.clone();
434407 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-
171 use std::collections::{BTreeMap, HashMap};
182
193 use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty};
@@ -45,32 +29,20 @@ use crate::views::{enc, shell};
4529 #[query_params(error = bad_request)]
4630 pub(crate) struct ServerQuery {
4731 notice: Option<String>,
48- /// The category shown: `general`, `limits`, `storage`, `backups`, `integrations` or `alerts`.
4932 cat: Option<String>,
50- /// The search text: when set, the page lists the matching settings from every category instead.
5133 q: Option<String>,
52- /// Set when the search asks for the text as typed, as one piece.
5334 exact: Option<String>,
54- /// Set when the search keeps upper and lower case apart.
5535 case: Option<String>,
56- /// The older name for `cat`, still read so an old link opens the same category.
5736 tab: Option<String>,
58- /// The boot id of the server that was asked to restart.
5937 restarting: Option<String>,
6038 }
6139
62-/// How long the restart waits after the request is answered, so the redirect that follows is
63-/// served by the old process.
6440 const RESTART_GRACE: std::time::Duration = std::time::Duration::from_millis(750);
6541
66-/// Where the page stands in a restart.
6742 #[derive(Clone, Copy, PartialEq, Eq)]
6843 enum Restart {
69- /// No restart was asked from this page.
7044 None,
71- /// Asked, and this process is still the old one or on its way down.
7245 Pending,
73- /// Asked, and a new process answered.
7446 Done,
7547 }
7648
@@ -88,12 +60,10 @@ struct OptionRow {
8860 selected: bool,
8961 }
9062
91-/// One field, already formatted for the template. A secret's value is never in here.
9263 pub(crate) struct Row {
9364 key: &'static str,
9465 label: &'static str,
9566 kind_label: &'static str,
96- /// What a line shows for the value: the text, the chosen option, On or Off, or the secret state.
9767 value_text: String,
9868 value: String,
9969 file_value: String,
@@ -112,9 +82,6 @@ pub(crate) struct Row {
11282 fixed: bool,
11383 }
11484
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.
11885 pub(crate) struct SrvPage {
11986 pub(crate) slug: &'static str,
12087 group: Group,
@@ -129,9 +96,6 @@ impl SrvPage {
12996 }
13097 }
13198
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`).
13599 pub(crate) const PAGES: &[SrvPage] = &[
136100 SrvPage {
137101 slug: "general",
@@ -238,7 +202,6 @@ pub(crate) const PAGES: &[SrvPage] = &[
238202 group: Group::Alerts,
239203 en: "Alerts",
240204 tr: "Uyarılar",
241- // Each threshold sits under the alert it tunes.
242205 keys: &[
243206 "alerts.enabled",
244207 "alerts.email",
@@ -255,7 +218,6 @@ pub(crate) const PAGES: &[SrvPage] = &[
255218 },
256219 ];
257220
258-/// The settings of the Backups page. Their group is `Group::Backups`.
259221 pub(crate) const BACKUP_KEYS: &[&str] = &[
260222 "backup.dir",
261223 "backup.interval_hours",
@@ -264,7 +226,6 @@ pub(crate) const BACKUP_KEYS: &[&str] = &[
264226 "backup.healthcheck_url",
265227 ];
266228
267-/// The settings of the Replication page. Their group is `Group::Backups`.
268229 pub(crate) const REPLICATION_KEYS: &[&str] = &[
269230 "replication.target",
270231 "replication.ssh_port",
@@ -275,16 +236,12 @@ pub(crate) const REPLICATION_KEYS: &[&str] = &[
275236 "replication.healthcheck_url",
276237 ];
277238
278-/// The settings of the Mail page. Their group is `Group::Integrations`.
279239 pub(crate) const MAIL_KEYS: &[&str] = &["mail.transport"];
280240
281-/// The page named by `slug`.
282241 pub(crate) fn page_by_slug(slug: &str) -> Option<&'static SrvPage> {
283242 PAGES.iter().find(|page| page.slug == slug)
284243 }
285244
286-/// Where the old slugs of moved pages went: `retention`, `s3`, `backups` and `replication`. `None`
287-/// for every slug that still names a page.
288245 fn moved_slug(slug: &str) -> Option<&'static str> {
289246 match slug {
290247 "retention" => Some("/admin/server?cat=limits"),
@@ -295,16 +252,12 @@ fn moved_slug(slug: &str) -> Option<&'static str> {
295252 }
296253 }
297254
298-/// Where a setting's row lives: the page's name and the link to the row.
299255 pub(crate) struct Home {
300- /// The page's name, with the area it belongs to when that is not obvious ("Backups").
301256 pub(crate) label: String,
302- /// True for a setting on the server settings page, so the area name is written before it.
303257 pub(crate) server: bool,
304258 pub(crate) href: String,
305259 }
306260
307-/// The page that holds the setting `key`, and the link to its row.
308261 pub(crate) fn page_of(lang: Lang, key: &str) -> Home {
309262 if BACKUP_KEYS.contains(&key) {
310263 return Home {
@@ -338,8 +291,6 @@ pub(crate) fn page_of(lang: Lang, key: &str) -> Home {
338291 }
339292 }
340293
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.
343294 fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> {
344295 let backend = views
345296 .iter()
@@ -360,7 +311,6 @@ fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> {
360311 .collect()
361312 }
362313
363-/// The words for a choice's stored value. Values that are names (smtp, s3, eu) read as they are.
364314 fn option_label(lang: Lang, option: &str) -> String {
365315 let (en, tr) = match option {
366316 "" => return g::t(lang, K::SrvEmpty).to_owned(),
@@ -379,7 +329,6 @@ fn option_label(lang: Lang, option: &str) -> String {
379329 fn row(lang: Lang, view: &FieldView) -> Row {
380330 let field: &Field = view.field;
381331 let kind_label = match field.kind {
382- // A live field needs no word: applying at once is what a field is expected to do.
383332 Kind::Live => "",
384333 Kind::Restart => g::t(lang, K::SrvKindRestart),
385334 Kind::ReadOnly => g::t(lang, K::SrvKindReadOnly),
@@ -456,7 +405,6 @@ fn row(lang: Lang, view: &FieldView) -> Row {
456405 }
457406 }
458407
459-/// The rows of the settings `keys`, in `keys` order.
460408 fn rows_of(lang: Lang, views: &[FieldView], keys: &[&str]) -> Vec<Row> {
461409 keys.iter()
462410 .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> {
464412 .collect()
465413 }
466414
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.
475415 pub(crate) async fn setting_rows(
476416 state: &AppState,
477417 lang: Lang,
@@ -482,9 +422,6 @@ pub(crate) async fn setting_rows(
482422 Ok(rows_of(lang, &views, keys))
483423 }
484424
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.
488425 pub(crate) async fn save_topic(
489426 cx: &Cx,
490427 state: &AppState,
@@ -510,7 +447,6 @@ pub(crate) async fn save_topic(
510447 save(cx, state, user, group, &submitted, lang).await
511448 }
512449
513-/// The notice a settings save shows: saved, nothing changed, or why it was refused.
514450 pub(crate) fn notice_of(lang: Lang, result: forge_core::Result<Option<()>>) -> String {
515451 match result {
516452 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
519455 }
520456 }
521457
522-/// The words for an error a page shows: the message itself for a refusal the user can fix.
523458 pub(crate) fn refusal(error: Error) -> String {
524459 match error {
525460 Error::Invalid(message) | Error::Config(message) => message,
@@ -527,8 +462,6 @@ pub(crate) fn refusal(error: Error) -> String {
527462 }
528463 }
529464
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.
532465 pub(crate) fn back_to(raw: &str) -> &str {
533466 if raw.starts_with("/admin/") && !raw.contains("//") && !raw.contains('\\') {
534467 raw
@@ -537,14 +470,11 @@ pub(crate) fn back_to(raw: &str) -> &str {
537470 }
538471 }
539472
540-/// `back` with a notice on its query string.
541473 pub(crate) fn with_notice(back: &str, notice: &str) -> String {
542474 let sep = if back.contains('?') { '&' } else { '?' };
543475 format!("{back}{sep}notice={}", enc(notice))
544476 }
545477
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.
548478 #[component]
549479 pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<impl View> {
550480 Ok(view! {
@@ -555,7 +485,6 @@ pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<im
555485 })
556486 }
557487
558-/// The rows of a settings topic, one line each. The caller's form holds them.
559488 #[component]
560489 pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result<impl View> {
561490 Ok(view! {
@@ -565,7 +494,6 @@ pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result
565494 })
566495 }
567496
568-/// The settings from every category whose key or label matches the search.
569497 async fn search_hits(
570498 state: &AppState,
571499 lang: Lang,
@@ -581,8 +509,6 @@ async fn search_hits(
581509 .collect())
582510 }
583511
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.
586512 #[component]
587513 async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {
588514 let id = format!("srv-{}", row.key);
@@ -617,7 +543,6 @@ async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {
617543 })
618544 }
619545
620-/// The facts after a setting's control: its kind, whether a restart is needed, and its override.
621546 #[component]
622547 async fn srv_hints(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> {
623548 Ok(view! {
@@ -657,8 +582,6 @@ async fn server_view(
657582 let tab = page.slug;
658583 let any_editable = rows.iter().any(|r| !r.fixed);
659584 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.
662585 let live = match restart {
663586 Restart::Pending => format!(
664587 "/admin/server/events?restarting={}",
@@ -752,7 +675,7 @@ async fn server_page(cx: &Cx) -> Result<impl View> {
752675 query.case.as_deref(),
753676 );
754677 let (rows, search) = if finder.is_empty() {
755- (rows_for(state, lang, page).await?, None)
678+ (setting_rows(state, lang, page.keys).await?, None)
756679 } else {
757680 (Vec::new(), Some(search_hits(state, lang, &finder).await?))
758681 };
@@ -787,8 +710,6 @@ async fn server_save(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> Resu
787710 .into())
788711 }
789712
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.
792713 async fn save(
793714 cx: &Cx,
794715 state: &AppState,
@@ -834,8 +755,6 @@ struct RestartForm {
834755 tab: String,
835756 }
836757
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.
839758 #[route(POST "/admin/server/restart")]
840759 async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Response> {
841760 let viewer = admin_only(cx).await?;
@@ -843,7 +762,7 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon
843762 return Err(forbidden().into());
844763 }
845764 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]);
847766 audit::record(
848767 &state.store,
849768 Some(cx),
@@ -864,16 +783,12 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon
864783 });
865784 Err(see_other(format!(
866785 "/admin/server?cat={}&restarting={}",
867- group.slug(),
786+ page.slug,
868787 enc(self_update::boot_id())
869788 ))
870789 .into())
871790 }
872791
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.
877792 #[route(GET "/admin/server/events")]
878793 async fn server_events(cx: &Cx) -> Result<Response> {
879794 admin_only(cx).await?;
@@ -898,7 +813,6 @@ struct ResetForm {
898813 csrf: String,
899814 #[serde(default)]
900815 key: String,
901- /// The page the reset came from: where the viewer goes back to.
902816 #[serde(default)]
903817 back: String,
904818 }
@@ -913,9 +827,7 @@ async fn server_reset(cx: &Cx, Form(form): Form<ResetForm>) -> Result<Response>
913827 let state = context::<AppState>(cx);
914828 let notice = match reset(cx, state, &viewer.0, &form.key).await {
915829 Ok(()) => g::t(lang, K::SrvResetDone).to_owned(),
916- Err(Error::Invalid(message)) => message,
917- Err(Error::Config(message)) => message,
918- Err(other) => other.to_string(),
830+ Err(other) => refusal(other),
919831 };
920832 Err(see_other(with_notice(back_to(&form.back), &notice)).into())
921833 }
@@ -1032,7 +944,6 @@ mod tests {
1032944 body
1033945 }
1034946
1035- /// Posts a tab and follows the redirect to read the notice it shows.
1036947 async fn save(fx: &Fixture, tab: &str, fields: &str) -> String {
1037948 let form = format!("csrf={CSRF}&tab={tab}&{fields}");
1038949 let (status, _, location) = send(
@@ -1047,7 +958,6 @@ mod tests {
1047958 admin_get(fx, &location).await
1048959 }
1049960
1050- /// Posts a settings topic of its own page (Backups, Replication) and reads the page it goes to.
1051961 async fn save_topic_at(fx: &Fixture, path: &str, fields: &str) -> String {
1052962 let form = format!("csrf={CSRF}&{fields}");
1053963 let (status, _, location) =
@@ -1056,8 +966,6 @@ mod tests {
1056966 admin_get(fx, &location).await
1057967 }
1058968
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.
1061969 #[tokio::test]
1062970 async fn gates_csrf_read_only_and_bad_values_change_nothing() {
1063971 let fx = fixture().await;
@@ -1086,7 +994,6 @@ mod tests {
1086994 }
1087995 assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
1088996
1089- // A bad CSRF token is refused for a settings save and for a restart.
1090997 let form = "csrf=wrong&tab=limits&ci.max_log_mb=99".to_owned();
1091998 let (status, _, _) = send(
1092999 &fx.router,
@@ -1108,14 +1015,12 @@ mod tests {
11081015 assert_eq!(status, 403, "bad csrf restart");
11091016 assert_eq!(fx.state.live().ci.max_log_mb, 16);
11101017
1111- // A read-only field is shown but cannot be posted.
11121018 let page = admin_get(&fx, "/admin/server?tab=addresses").await;
11131019 assert!(page.contains("127.0.0.1:7660"));
11141020 assert!(!page.contains("name=\"listen\""));
11151021 save(&fx, "addresses", "listen=0.0.0.0%3A1").await;
11161022 assert!(fx.state.store.server_overrides().await.unwrap().is_empty());
11171023
1118- // Out-of-range, wrong-kind and unknown-storage values are rejected, and nothing is stored.
11191024 for (tab, fields) in [
11201025 ("general", "registration=everyone"),
11211026 ("general", "trusted_proxies=not-an-ip"),
@@ -1133,8 +1038,6 @@ mod tests {
11331038 assert_eq!(fx.state.live().ci.max_log_mb, 16);
11341039 }
11351040
1136- // Scenario: a live override applies at once and reset goes back; registration follows the
1137- // saved general setting.
11381041 #[tokio::test]
11391042 async fn live_overrides_apply_reset_and_registration_follows() {
11401043 let fx = fixture().await;
@@ -1172,13 +1075,10 @@ mod tests {
11721075 assert_eq!(open, 200, "registration opens at once");
11731076 }
11741077
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.
11771078 #[tokio::test]
11781079 async fn restart_fields_secrets_and_audit_hold_their_rules() {
11791080 let fx = fixture().await;
11801081
1181- // A restart field is stored, the live value stays, and the page says so.
11821082 save(&fx, "addresses", "base_url=https%3A%2F%2Fnew.example").await;
11831083 assert_eq!(
11841084 fx.state
@@ -1195,7 +1095,6 @@ mod tests {
11951095 assert!(page.contains("restart needed"));
11961096 assert!(page.contains("https://new.example"));
11971097
1198- // A secret is saved, never shown on any tab, and a blank post keeps it.
11991098 let secret = "https://hc.example/ping/TOPSECRET-TOKEN";
12001099 let body = save_topic_at(
12011100 &fx,
@@ -1230,7 +1129,6 @@ mod tests {
12301129 .unwrap()
12311130 .contains_key("backup.healthcheck_url")
12321131 );
1233- // Reset removes the secret and leaves the restart field alone.
12341132 let form = format!("csrf={CSRF}&tab=backups&key=backup.healthcheck_url");
12351133 send(
12361134 &fx.router,
@@ -1244,7 +1142,6 @@ mod tests {
12441142 assert!(!stored.contains_key("backup.healthcheck_url"));
12451143 assert!(stored.contains_key("base_url"));
12461144
1247- // Saves are audited by key only: no value, secret or otherwise, reaches the log.
12481145 save(&fx, "limits", "ci.max_log_mb=77").await;
12491146 let entries = fx
12501147 .state
@@ -1268,12 +1165,10 @@ mod tests {
12681165 }
12691166 }
12701167
1271- // Scenario: restart is audited, and the page shows the restarting state until a new process runs.
12721168 #[tokio::test]
12731169 async fn restart_is_audited_and_the_page_shows_the_restarting_state() {
12741170 let fx = fixture().await;
12751171
1276- // The page offers the button with a confirm step.
12771172 let page = admin_get(&fx, "/admin/server").await;
12781173 assert!(page.contains("Restart server"));
12791174 assert!(page.contains("/admin/server/restart"));
@@ -1302,7 +1197,6 @@ mod tests {
13021197 .any(|e| e.action == AuditAction::ServerRestarted)
13031198 );
13041199
1305- // Same process: "Restarting" with the event stream. A new process: back to normal.
13061200 let page = admin_get(&fx, &location).await;
13071201 assert!(page.contains("Restarting..."));
13081202 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;
77 use forge_core::store::orgs::OrgMemberRole;
88 use forge_core::store::suspension::{AccountFacts, Suspension};
99 use forge_core::store::user_delete::GHOST_USERNAME;
10-use forge_core::{AuditAction, Store, User};
10+use forge_core::{AuditAction, Session, Store, User};
1111 use serde::Deserialize;
1212 use topcoat::Result;
1313 use topcoat::context::{Cx, context};
@@ -87,15 +87,20 @@ fn is_ghost(user: &User) -> bool {
8787 normalize_name(&user.username) == GHOST_USERNAME
8888 }
8989
90-async fn load(cx: &Cx) -> Result<Detail> {
91- let store = &context::<AppState>(cx).store;
92- let id = path_param_segment(cx, "user_id").to_owned();
93- let Some(target) = store.user_by_id(&id).await? else {
90+async fn visible_account(store: &Store, id: &str) -> Result<User> {
91+ let Some(user) = store.user_by_id(id).await? else {
9492 return Err(not_found().into());
9593 };
96- if target.is_org() || is_ghost(&target) {
94+ if user.is_org() || is_ghost(&user) {
9795 return Err(not_found().into());
9896 }
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?;
99104 let login_filter = forge_core::AuditFilter {
100105 actor_id: Some(target.id.clone()),
101106 action: Some(AuditAction::LoginSuccess),
@@ -537,12 +542,7 @@ async fn org_body(
537542
538543 /// What the page shows of one account, as one string. A missing or hidden account is a 404.
539544 async fn account_fingerprint(store: &Store, user_id: &str) -> Result<String> {
540- let Some(target) = store.user_by_id(user_id).await? else {
541- return Err(not_found().into());
542- };
543- if target.is_org() || is_ghost(&target) {
544- return Err(not_found().into());
545- }
545+ let target = visible_account(store, user_id).await?;
546546 let facts = store.account_facts(user_id).await?;
547547 let suspension = store.suspension(user_id).await?;
548548 let passkeys = store.passkey_count(user_id).await?;
@@ -621,8 +621,12 @@ enum Outcome {
621621 Refused(String),
622622 }
623623
624-async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, Detail)> {
625- let viewer = admin_only(cx).await?;
624+async fn perform(
625+ cx: &Cx,
626+ viewer: &(User, Session),
627+ form: &ActionForm,
628+ action: Action,
629+) -> Result<(Outcome, Detail)> {
626630 if !check_csrf(&viewer.1, &form.csrf) {
627631 return Err(forbidden().into());
628632 }
@@ -747,10 +751,8 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome,
747751
748752 /// Redirects to the detail page after a success, or renders it with a message.
749753 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?;
753754 let viewer = admin_only(cx).await?;
755+ let (outcome, detail) = perform(cx, &viewer, &form, action).await?;
754756 let lang = i18n::lang(cx, Some(&viewer.0));
755757 let notice = match outcome {
756758 Outcome::Done(key) => {
crates/forge-web-account/src/pages/assets.rsmodified+51 -123
@@ -6,7 +6,7 @@ use topcoat::Result;
66 use topcoat::context::Cx;
77 use topcoat::router::request::uri;
88 use topcoat::router::response::Response;
9-use topcoat::router::{HeaderMap, StatusCode, header, route};
9+use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, route};
1010
1111 use crate::accent;
1212 use crate::custom_colour;
@@ -15,15 +15,25 @@ use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href};
1515 /// Immutable only when the request names the current version (`href` is the URL the pages link).
1616 /// Any other `?v=` (a page from an older or newer build, or none) revalidates, so a mismatched
1717 /// 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 {
1919 let request = uri(cx);
2020 let current = href.split_once('?').map(|(_, query)| query);
21- let value = if request.query() == current {
21+ if request.query() == current {
2222 "public, max-age=31536000, immutable"
2323 } else {
2424 "no-cache"
25- };
26- topcoat::router::HeaderValue::from_static(value)
25+ }
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)
2737 }
2838
2939 const CSS: &str = forge_web_app::build_info::MAIN_CSS;
@@ -31,15 +41,7 @@ const CSS: &str = forge_web_app::build_info::MAIN_CSS;
3141 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.
3242 #[route(GET "/assets/main.css")]
3343 async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
34- let mut headers = HeaderMap::new();
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))
44+ Ok(respond("text/css; charset=utf-8", cache_for(cx, STYLESHEET_HREF), CSS))
4345 }
4446
4547 /// 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");
4951 /// Immutable like `main.css`: the URL carries a content hash.
5052 #[route(GET "/assets/nav.js")]
5153 async fn nav_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
52- let mut headers = HeaderMap::new();
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))
54+ Ok(respond("text/javascript; charset=utf-8", cache_for(cx, NAV_SCRIPT_HREF), NAV_JS))
6155 }
6256
6357 /// Immutable like `main.css`: the URL carries a content hash.
6458 #[route(GET "/assets/highlight.css")]
6559 async fn highlight_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
66- let mut headers = HeaderMap::new();
67- headers.insert(
68- header::CONTENT_TYPE,
69- "text/css; charset=utf-8"
70- .parse()
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()))
60+ Ok(respond(
61+ "text/css; charset=utf-8",
62+ cache_for(cx, highlight_href()),
63+ crate::views::highlight_css_text(),
64+ ))
7565 }
7666
7767 /// 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)> {
10191 .map(|(id, hue, vivid)| (id.as_str(), *hue, *vivid))
10292 });
10393 let css = custom_colour::stylesheet(accent_light, accent_dark, base_light, base_dark);
104- let mut headers = HeaderMap::new();
105- headers.insert(
106- header::CONTENT_TYPE,
107- "text/css; charset=utf-8"
108- .parse()
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))
94+ Ok(respond(
95+ "text/css; charset=utf-8",
96+ "public, max-age=31536000, immutable",
97+ css,
98+ ))
11899 }
119100
120101 // 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");
124105
125106 #[route(GET "/assets/offline.html")]
126107 async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
127- let mut headers = HeaderMap::new();
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))
108+ Ok(respond("text/html; charset=utf-8", "no-cache", OFFLINE_HTML))
139109 }
140110
141111 #[route(GET "/assets/offline.js")]
142112 async fn offline_js(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
143- let mut headers = HeaderMap::new();
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))
113+ Ok(respond("text/javascript; charset=utf-8", "no-cache", OFFLINE_JS))
155114 }
156115
157116 /// 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
186145 const PLEX_MONO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/IBMPlexMono-OFL.txt");
187146 const ARCHIVO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/Archivo-OFL.txt");
188147
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-
204148 const FONT_CACHE: &str = "public, max-age=31536000, immutable";
205149 const LICENSE_CACHE: &str = "public, max-age=86400";
206150
207151 #[route(GET "/assets/fonts/figtree-5.3.0-latin-wght.woff2")]
208-async fn figtree_latin(cx: &Cx) -> Result<Bytes> {
209- Ok(bytes_response(FIGTREE_LATIN, "font/woff2", FONT_CACHE))
152+async fn figtree_latin(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
153+ Ok(respond("font/woff2", FONT_CACHE, FIGTREE_LATIN))
210154 }
211155
212156 #[route(GET "/assets/fonts/figtree-5.3.0-latin-ext-wght.woff2")]
213-async fn figtree_latin_ext(cx: &Cx) -> Result<Bytes> {
214- Ok(bytes_response(FIGTREE_LATIN_EXT, "font/woff2", FONT_CACHE))
157+async fn figtree_latin_ext(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
158+ Ok(respond("font/woff2", FONT_CACHE, FIGTREE_LATIN_EXT))
215159 }
216160
217161 #[route(GET "/assets/fonts/archivo-5.3.0-latin-wdth.woff2")]
218-async fn archivo_latin(cx: &Cx) -> Result<Bytes> {
219- Ok(bytes_response(ARCHIVO_LATIN, "font/woff2", FONT_CACHE))
162+async fn archivo_latin(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
163+ Ok(respond("font/woff2", FONT_CACHE, ARCHIVO_LATIN))
220164 }
221165
222166 #[route(GET "/assets/fonts/archivo-5.3.0-latin-ext-wdth.woff2")]
223-async fn archivo_latin_ext(cx: &Cx) -> Result<Bytes> {
224- Ok(bytes_response(ARCHIVO_LATIN_EXT, "font/woff2", FONT_CACHE))
167+async fn archivo_latin_ext(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
168+ Ok(respond("font/woff2", FONT_CACHE, ARCHIVO_LATIN_EXT))
225169 }
226170
227171 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400.woff2")]
228-async fn plex_mono_400(cx: &Cx) -> Result<Bytes> {
229- Ok(bytes_response(PLEX_MONO_400, "font/woff2", FONT_CACHE))
172+async fn plex_mono_400(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
173+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_400))
230174 }
231175
232176 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-500.woff2")]
233-async fn plex_mono_500(cx: &Cx) -> Result<Bytes> {
234- Ok(bytes_response(PLEX_MONO_500, "font/woff2", FONT_CACHE))
177+async fn plex_mono_500(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
178+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_500))
235179 }
236180
237181 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-600.woff2")]
238-async fn plex_mono_600(cx: &Cx) -> Result<Bytes> {
239- Ok(bytes_response(PLEX_MONO_600, "font/woff2", FONT_CACHE))
182+async fn plex_mono_600(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
183+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_600))
240184 }
241185
242186 #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400-italic.woff2")]
243-async fn plex_mono_400_italic(cx: &Cx) -> Result<Bytes> {
244- Ok(bytes_response(
245- PLEX_MONO_400_ITALIC,
246- "font/woff2",
247- FONT_CACHE,
248- ))
187+async fn plex_mono_400_italic(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
188+ Ok(respond("font/woff2", FONT_CACHE, PLEX_MONO_400_ITALIC))
249189 }
250190
251191 #[route(GET "/assets/fonts/Figtree-OFL.txt")]
252-async fn figtree_license(cx: &Cx) -> Result<Bytes> {
253- Ok(bytes_response(
254- FIGTREE_LICENSE,
255- "text/plain; charset=utf-8",
256- LICENSE_CACHE,
257- ))
192+async fn figtree_license(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
193+ Ok(respond("text/plain; charset=utf-8", LICENSE_CACHE, FIGTREE_LICENSE))
258194 }
259195
260196 #[route(GET "/assets/fonts/Archivo-OFL.txt")]
261-async fn archivo_license(cx: &Cx) -> Result<Bytes> {
262- Ok(bytes_response(
263- ARCHIVO_LICENSE,
264- "text/plain; charset=utf-8",
265- LICENSE_CACHE,
266- ))
197+async fn archivo_license(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
198+ Ok(respond("text/plain; charset=utf-8", LICENSE_CACHE, ARCHIVO_LICENSE))
267199 }
268200
269201 #[route(GET "/assets/fonts/IBMPlexMono-OFL.txt")]
270-async fn plex_mono_license(cx: &Cx) -> Result<Bytes> {
271- Ok(bytes_response(
272- PLEX_MONO_LICENSE,
273- "text/plain; charset=utf-8",
274- LICENSE_CACHE,
275- ))
202+async fn plex_mono_license(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static [u8])> {
203+ Ok(respond("text/plain; charset=utf-8", LICENSE_CACHE, PLEX_MONO_LICENSE))
276204 }
277205
278206 #[cfg(test)]
crates/forge-web-account/src/pages/audit_log.rsmodified+15 -37
@@ -50,9 +50,6 @@ pub(crate) struct AuditQuery {
5050 to: Option<String>,
5151 exact: Option<String>,
5252 case: Option<String>,
53- /// Old cursor links. Still accepted so old bookmarks load, and ignored.
54- #[allow(dead_code)]
55- before: Option<String>,
5653 /// The 1-based page number. Anything unreadable is page 1.
5754 page: Option<String>,
5855 }
@@ -196,27 +193,12 @@ impl Group {
196193 &self.rows[0]
197194 }
198195
199- /// The target when every entry has the same one.
200- fn shared_target(&self) -> Option<&str> {
201- let first = self.first().target.as_str();
196+ /// The value of `field` when every entry has the same one.
197+ fn shared<'a>(&'a self, field: fn(&RowView) -> &str) -> Option<&'a str> {
198+ let first = field(self.first());
202199 self.rows
203200 .iter()
204- .all(|row| row.target == 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)
201+ .all(|row| field(row) == first)
220202 .then_some(first)
221203 }
222204 }
@@ -298,9 +280,10 @@ fn details_words(lang: Lang, data: &str) -> String {
298280 }
299281
300282 fn row_view(entry: &AuditEntry, lang: Lang) -> RowView {
301- let actor = match (entry.actor_name.as_str(), entry.actor_id.is_some()) {
302- ("", _) => g::t(lang, K::Anonymous).to_owned(),
303- (name, _) => name.to_owned(),
283+ let actor = if entry.actor_name.is_empty() {
284+ g::t(lang, K::Anonymous).to_owned()
285+ } else {
286+ entry.actor_name.clone()
304287 };
305288 let name = if entry.target_name.is_empty() {
306289 entry.target_id.as_str()
@@ -369,19 +352,14 @@ fn requested_page(query: &AuditQuery) -> u64 {
369352 }
370353
371354 /// 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) {
373356 let pages = (groups.len() as u64).div_ceil(PAGE_ROWS as u64).max(1);
374357 let page = page.clamp(1, pages);
375358 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();
377360 (shown, page, pages)
378361 }
379362
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-
385363 /// The numbered pager's entries and links for `page` of `pages`, under `base` with `params`.
386364 fn nav_for(
387365 page: u64,
@@ -523,13 +501,13 @@ async fn single_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) ->
523501 #[component]
524502 async fn group_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) -> Result<impl View> {
525503 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);
527505 let ip = group
528- .shared_ip()
506+ .shared(|row| &row.ip)
529507 .map(str::to_owned)
530508 .filter(|ip| !ip.is_empty());
531509 let details = group
532- .shared_details()
510+ .shared(|row| &row.details)
533511 .map(str::to_owned)
534512 .filter(|d| !d.is_empty());
535513 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> {
702680 let entries = if notice.is_some() {
703681 Vec::new()
704682 } else {
705- fetch_entries(store, &filter).await?
683+ store.list_audit_page(&filter, 0, SEARCH_CAP).await?
706684 };
707685 let groups = fold_groups(&entries, lang, &finder);
708686 let total = groups.iter().map(|group| group.rows.len()).sum();
@@ -778,7 +756,7 @@ async fn own_log_page(cx: &Cx) -> Result<impl View> {
778756 if let Some(known) = AuditAction::parse(&action) {
779757 filter.action = Some(known);
780758 }
781- let entries = fetch_entries(store, &filter).await?;
759+ let entries = store.list_audit_page(&filter, 0, SEARCH_CAP).await?;
782760 let groups = fold_groups(&entries, lang, &finder);
783761 let total = groups.iter().map(|group| group.rows.len()).sum();
784762 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 {
6565 }
6666
6767 /// 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)> {
6973 let mut all: Vec<User> = state
7074 .store
7175 .list_orgs()
@@ -80,12 +84,13 @@ async fn org_listing(state: &AppState, finder: &Finder, page: u64) -> Result<(Ve
8084 .collect();
8185 all.sort_by_key(|org| org.username.to_lowercase());
8286 let total = all.len() as u64;
87+ let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1));
8388 let shown = all
8489 .into_iter()
85- .skip(((page.max(1) - 1) * PER_PAGE) as usize)
90+ .skip(((page - 1) * PER_PAGE) as usize)
8691 .take(PER_PAGE as usize)
8792 .collect();
88- Ok((shown, total))
93+ Ok((shown, total, page))
8994 }
9095
9196 /// `/explore` with the given search, sort key and page. An empty search is left out.
@@ -129,7 +134,7 @@ async fn listing(
129134 finder: &Finder,
130135 sort: &'static str,
131136 page: u64,
132-) -> Result<(Vec<(Repo, u64, String)>, u64)> {
137+) -> Result<(Vec<(Repo, u64, String)>, u64, u64)> {
133138 let sort_kind = match sort {
134139 "stars" => RepoSort::MostStars,
135140 "name" => RepoSort::Name,
@@ -147,26 +152,30 @@ async fn listing(
147152 })
148153 .collect();
149154 let total = matching.len() as u64;
155+ let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1));
150156 let shown = matching
151157 .into_iter()
152- .skip(((page.max(1) - 1) * PER_PAGE) as usize)
158+ .skip(((page - 1) * PER_PAGE) as usize)
153159 .take(PER_PAGE as usize)
154160 .collect();
155- Ok((shown, total))
161+ Ok((shown, total, page))
156162 }
157163
158164 #[page("/explore")]
159165 async fn explore_page(cx: &Cx) -> Result<impl View> {
160166 let query = query_params::<ExploreQuery>(cx)?;
161167 let (finder, sort, page) = listing_args(query);
162- let live = explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1);
163168 let viewer = current_user(cx).await?;
164169 let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u));
165170 let state = context::<AppState>(cx);
166171 let on_orgs = orgs_tab(query);
167- let (listed, repo_total) = listing(state, &finder, sort, page).await?;
168- let (org_page, org_total) = org_listing(state, &finder, page).await?;
169- let total = if on_orgs { org_total } else { repo_total };
172+ let (listed, org_page, total, page) = if on_orgs {
173+ let (orgs, total, page) = org_listing(state, &finder, page).await?;
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+ };
170179 let (_, repos_all) = state
171180 .store
172181 .list_public_repos(None, RepoSort::RecentlyUpdated, 1, 1)
@@ -175,7 +184,7 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
175184 let live = if on_orgs {
176185 orgs_href(&finder, page).replacen("/explore?", "/explore/events?", 1)
177186 } else {
178- live
187+ explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1)
179188 };
180189
181190 let now = now_unix();
@@ -191,7 +200,6 @@ async fn explore_page(cx: &Cx) -> Result<impl View> {
191200 orgs.push((org.username, avatar));
192201 }
193202 let pages = total.div_ceil(PER_PAGE).max(1);
194- let page = page.min(pages);
195203 let sort_links: Vec<SortLink> = SORTS
196204 .iter()
197205 .map(|(key, label)| SortLink {
@@ -255,12 +263,12 @@ async fn explore_fingerprint(
255263 on_orgs: bool,
256264 ) -> Result<String> {
257265 if on_orgs {
258- let (orgs, total) = org_listing(state, finder, page).await?;
266+ let (orgs, total, _) = org_listing(state, finder, page).await?;
259267 let mut lines = vec![total.to_string()];
260268 lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username)));
261269 return Ok(lines.join("\n"));
262270 }
263- let (listed, total) = listing(state, finder, sort, page).await?;
271+ let (listed, total, _) = listing(state, finder, sort, page).await?;
264272 let mut lines = vec![total.to_string()];
265273 for (repo, stars, activity) in listed {
266274 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>
221221 Some(user_id) => {
222222 // The link is spent before the slow hash, so two redemptions cannot both pass.
223223 let hash = hash_password_async(form.password.clone()).await?;
224- state.store.set_password_hash(&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?;
224+ state.store.reset_password(&user_id, &hash).await?;
227225 if let Some(user) = state.store.user_by_id(&user_id).await? {
228226 audit::record(
229227 &state.store,
@@ -300,9 +298,9 @@ mod tests {
300298 assert_eq!(status, 200, "{address}");
301299 assert!(html.contains("a reset link is on its way"), "{address}");
302300 }
303- // Give the spawned lookups time to finish, then check that nothing was queued: Frank has
304- // no verified address, so his account gets no mail.
305- tokio::time::sleep(Duration::from_millis(200)).await;
301+ for address in ["nobody@example.com", "frank@example.com"] {
302+ send_reset_if_verified(state, address).await.unwrap();
303+ }
306304 let mail = state.store.recent_mail(20).await.unwrap();
307305 assert!(mail.iter().all(|m| !m.body.contains("/reset/")));
308306 }
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-
51 use std::collections::HashMap;
62
73 use forge_core::store::imports::{ImportJob, ImportState};
@@ -21,7 +17,7 @@ use crate::audit::{self, Actor, Target};
2117 use crate::auth::{require_csrf, require_user};
2218 use crate::i18n::migrate::{self as g, K};
2319 use crate::i18n::{self, Lang};
24-use crate::importer::api::{ApiError, RemoteApi};
20+use crate::importer::api::{ApiError, ExtRepo, RemoteApi};
2521 use crate::importer::{
2622 self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab,
2723 parse_remote, source_ref,
@@ -37,7 +33,6 @@ use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message};
3733
3834 path_param!(job_id);
3935
40-/// Most repositories one bulk submit starts.
4136 const MAX_BULK: usize = 50;
4237 const DEFAULT_BRANCH: &str = "main";
4338
@@ -99,7 +94,6 @@ struct BulkForm {
9994 opt_pulls: String,
10095 #[serde(default)]
10196 opt_releases: String,
102- /// The ticked repositories arrive as `sel_0`, `sel_1`, ... with the repository as the value.
10397 #[serde(flatten)]
10498 extra: HashMap<String, String>,
10599 }
@@ -112,9 +106,7 @@ struct SourceQuery {
112106
113107 #[query_params(error = bad_request)]
114108 struct JobsQuery {
115- /// The repositories a bulk import left out, with why, as one line.
116109 skipped: Option<String>,
117- /// The 1-based page of the history.
118110 page: Option<String>,
119111 }
120112
@@ -136,7 +128,6 @@ fn source_of(raw: Option<&str>) -> Source {
136128 raw.and_then(Source::parse).unwrap_or(Source::GitHub)
137129 }
138130
139-/// The instance a source form starts with.
140131 fn default_instance(source: Source) -> &'static str {
141132 match source {
142133 Source::Forgejo => "https://codeberg.org",
@@ -144,7 +135,6 @@ fn default_instance(source: Source) -> &'static str {
144135 }
145136 }
146137
147-/// Sources that are self-hostable and so take an instance address.
148138 fn has_instance(source: Source) -> bool {
149139 matches!(source, Source::GitLab | Source::Forgejo)
150140 }
@@ -162,8 +152,6 @@ fn token_of(raw: &str) -> Option<String> {
162152 (!t.is_empty()).then(|| t.to_owned())
163153 }
164154
165-// ---- shared pieces ----
166-
167155 #[component]
168156 pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<impl View> {
169157 let create = active == "create";
@@ -197,7 +185,6 @@ async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result<
197185 })
198186 }
199187
200-/// Public or private, as two switches with what each means under it. Shared with the create page.
201188 #[component]
202189 pub(crate) async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result<impl View> {
203190 Ok(view! {
@@ -226,8 +213,6 @@ async fn option_boxes(cx: &Cx, lang: Lang, opts: ImportOptions) -> Result<impl V
226213 })
227214 }
228215
229-// ---- single import ----
230-
231216 struct Draft {
232217 source: Source,
233218 remote: String,
@@ -260,7 +245,6 @@ impl Draft {
260245 }
261246 }
262247
263- /// The submitted values, never the token.
264248 fn from_form(form: &ImportForm, source: Source) -> Self {
265249 Draft {
266250 source,
@@ -325,7 +309,7 @@ async fn import_form(
325309 let opts = draft.opts;
326310 Ok(view! {
327311 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)
329313 newrepo_tabs(lang: lang, active: "import")
330314 <div class="sheet fit">
331315 <form method="post" action="/new/import" class="fields">
@@ -389,7 +373,6 @@ async fn import_form(
389373 })
390374 }
391375
392-/// The GET import page: the form. Past imports are on the Import history tab.
393376 #[component]
394377 async fn import_home(
395378 cx: &Cx,
@@ -404,7 +387,6 @@ async fn import_home(
404387 })
405388 }
406389
407-/// The import form again after a rejected submit.
408390 #[component]
409391 async fn import_error_body(
410392 cx: &Cx,
@@ -454,8 +436,6 @@ async fn import_submit(cx: &Cx, Form(form): Form<ImportForm>) -> Result<impl Vie
454436 }
455437 }
456438
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.
459439 async fn start_single(
460440 cx: &Cx,
461441 viewer: &User,
@@ -519,7 +499,6 @@ async fn start_single(
519499 .await
520500 }
521501
522-/// Creates the repo and the import job for `spec` and starts it. `Ok(Err(message))` is a rejection.
523502 async fn begin(
524503 cx: &Cx,
525504 actor: &User,
@@ -558,9 +537,10 @@ async fn begin(
558537 };
559538 let path = repo_path(&state.config.data_dir, &repo.id)?;
560539 if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await {
540+ state.store.delete_repo(&repo.id).await?;
561541 return Ok(Err(crate::i18n::misc::git_init_failed(lang, e)));
562542 }
563- let job = state
543+ let job = match state
564544 .store
565545 .create_import_job(
566546 &actor.id,
@@ -569,7 +549,14 @@ async fn begin(
569549 &source_ref(spec.source, &spec.remote, &spec.instance),
570550 &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()),
571551 )
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+ };
573560 let full_name = format!("{}/{}", repo.owner_name, repo.name);
574561 audit::record(
575562 &state.store,
@@ -588,8 +575,6 @@ async fn begin(
588575 Ok(Ok(job.id))
589576 }
590577
591-// ---- bulk import ----
592-
593578 #[component]
594579 async fn bulk_form(
595580 cx: &Cx,
@@ -609,11 +594,10 @@ async fn bulk_form(
609594 Source::Forgejo => g::t(lang, K::BulkOwnerForgejo),
610595 _ => g::t(lang, K::BulkOwnerGitHub),
611596 };
612- // A Forgejo token can list its own repositories, so the owner may stay empty.
613597 let owner_required = source != Source::Forgejo;
614598 Ok(view! {
615599 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)
617601 newrepo_tabs(lang: lang, active: "import")
618602 <div class="sheet fit">
619603 <form method="post" action="/new/import/bulk" class="fields">
@@ -645,15 +629,6 @@ async fn bulk_form(
645629 })
646630 }
647631
648-struct Listed {
649- name: String,
650- full_name: String,
651- description: String,
652- private: bool,
653- fork: bool,
654- archived: bool,
655-}
656-
657632 #[component]
658633 async fn bulk_select(
659634 cx: &Cx,
@@ -661,13 +636,11 @@ async fn bulk_select(
661636 username: String,
662637 csrf: &str,
663638 form: BulkFormEcho,
664- repos: Vec<Listed>,
639+ repos: Vec<ExtRepo>,
665640 owners: Vec<String>,
666641 ) -> Result<impl View> {
667642 let count = repos.len();
668643 let empty = repos.is_empty();
669- let private = form.private;
670- let opts = form.opts;
671644 let selected_owner = if form.owner.is_empty() {
672645 owners.first().cloned().unwrap_or_default()
673646 } else {
@@ -675,7 +648,7 @@ async fn bulk_select(
675648 };
676649 Ok(view! {
677650 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)
679652 newrepo_tabs(lang: lang, active: "import")
680653 <div class="sheet">
681654 <form method="post" action="/new/import/bulk" class="fields">
@@ -696,10 +669,8 @@ async fn bulk_select(
696669 }
697670 </select>
698671 </div>
699- visibility_pick(lang: lang, private: private)
700- if form.source != "git" {
701- option_boxes(lang: lang, opts: opts)
702- }
672+ visibility_pick(lang: lang, private: false)
673+ option_boxes(lang: lang, opts: ImportOptions { labels: true, issues: true, pulls: true, releases: true })
703674 <label class="line" data-kb-row="">
704675 <input type="checkbox" data-select-all=".import-pick-list">
705676 <span class="name">(g::t(lang, K::BulkSelectAll))</span>
@@ -732,16 +703,12 @@ async fn bulk_select(
732703 })
733704 }
734705
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).
737706 struct BulkFormEcho {
738707 source: String,
739708 instance: String,
740709 token: String,
741710 from: String,
742711 owner: String,
743- private: bool,
744- opts: ImportOptions,
745712 }
746713
747714 #[page("/new/import/bulk")]
@@ -761,20 +728,14 @@ async fn bulk_page(cx: &Cx) -> Result<impl View> {
761728 })
762729 }
763730
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.
770731 async fn list_remote(
771732 state: &AppState,
772733 source: Source,
773734 instance: &str,
774735 from: &str,
775736 token: Option<String>,
776-) -> std::result::Result<Vec<importer::api::ExtRepo>, String> {
777- let notice = notice_for(state);
737+) -> std::result::Result<Vec<ExtRepo>, String> {
738+ let notice: importer::api::Notice = std::sync::Arc::new(|_msg: String| {});
778739 let listed = match source {
779740 Source::GitLab => {
780741 make_gitlab(state, instance, token, notice)?
@@ -815,7 +776,6 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
815776
816777 let from = form.from.trim();
817778 let owner_max = if source == Source::GitLab { 20 } else { 1 };
818- // Forgejo lists the token's own repositories for an empty owner.
819779 let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some();
820780 let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max);
821781 let result = if bad_owner {
@@ -826,32 +786,14 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
826786 let (error, picker) = match result {
827787 Err(message) => (Some(message), None),
828788 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();
840789 let echo = BulkFormEcho {
841790 source: source.as_str().to_owned(),
842791 instance: instance.clone(),
843792 token: form.token.trim().to_owned(),
844793 from: from.to_owned(),
845794 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- },
853795 };
854- (None, Some((echo, repos)))
796+ (None, Some((echo, found)))
855797 }
856798 };
857799 Ok(view! {
@@ -860,7 +802,6 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> {
860802 })
861803 }
862804
863-/// The bulk page body: the picker once a listing exists, the lookup form otherwise.
864805 #[component]
865806 async fn bulk_stage(
866807 cx: &Cx,
@@ -871,7 +812,7 @@ async fn bulk_stage(
871812 instance: &str,
872813 owners: Vec<String>,
873814 error: Option<String>,
874- picker: Option<(BulkFormEcho, Vec<Listed>)>,
815+ picker: Option<(BulkFormEcho, Vec<ExtRepo>)>,
875816 ) -> Result<impl View> {
876817 Ok(view! {
877818 if let Some((echo, repos)) = picker {
@@ -882,7 +823,6 @@ async fn bulk_stage(
882823 })
883824 }
884825
885-/// Starts one job per ticked repository, then shows the imports list.
886826 async fn run_bulk(
887827 cx: &Cx,
888828 viewer: &User,
@@ -948,8 +888,6 @@ async fn run_bulk(
948888 options,
949889 };
950890 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.
953891 if let Some(repo) = state
954892 .store
955893 .repo_by_owner_and_name(&target.username, &name)
@@ -961,7 +899,6 @@ async fn run_bulk(
961899 retry_job(state, job.clone(), &form.token).await?;
962900 continue;
963901 }
964- // A name already taken, or any refusal, skips that one; the list page says which and why.
965902 if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? {
966903 tracing::info!(repo = %remote, %message, "bulk import: skipped a repository");
967904 skipped.push(format!("{name} ({message})"));
@@ -978,8 +915,6 @@ async fn run_bulk(
978915 Err(see_other(format!("/import?skipped={}", crate::views::enc(&list))).into())
979916 }
980917
981-// ---- jobs ----
982-
983918 fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) {
984919 match state {
985920 ImportState::Queued => ("badge", g::t(lang, K::JobQueued)),
@@ -1001,8 +936,6 @@ fn stage_name(lang: Lang, stage: &str) -> &'static str {
1001936 }
1002937 }
1003938
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.
1006939 async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Result<Option<Repo>> {
1007940 let Some(id) = &job.repo_id else {
1008941 return Ok(None);
@@ -1013,7 +946,6 @@ async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Res
1013946 Ok(state.store.repo_by_id(id).await?)
1014947 }
1015948
1016-/// The user's newest import jobs, each with its repository once it exists.
1017949 async fn load_job_rows(
1018950 state: &AppState,
1019951 user_id: &str,
@@ -1029,7 +961,6 @@ async fn load_job_rows(
1029961 Ok(rows)
1030962 }
1031963
1032-/// The import job rows, shared by the Import history page and the recent list on the Import tab.
1033964 #[component]
1034965 async fn job_rows(cx: &Cx, lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<impl View> {
1035966 Ok(view! {
@@ -1066,7 +997,7 @@ async fn jobs_list(
1066997 let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed);
1067998 Ok(view! {
1068999 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)
10701001 newrepo_tabs(lang: lang, active: "history")
10711002 <div class="sheet">
10721003 if retry {
@@ -1090,7 +1021,6 @@ async fn jobs_list(
10901021 })
10911022 }
10921023
1093-/// What the import list shows for `user_id`: each job's id, state, source and repo, in list order.
10941024 async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
10951025 let rows = load_job_rows(state, user_id, 50).await?;
10961026 Ok(rows
@@ -1110,8 +1040,6 @@ async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> {
11101040 .join("\n"))
11111041 }
11121042
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`]).
11151043 #[route(GET "/import/events")]
11161044 async fn jobs_events(cx: &Cx) -> Result<Response> {
11171045 let viewer = require_user(cx).await?;
@@ -1130,7 +1058,6 @@ async fn jobs_events(cx: &Cx) -> Result<Response> {
11301058 .await
11311059 }
11321060
1133-/// Imports per page of the history.
11341061 const HISTORY_ROWS: u64 = 10;
11351062
11361063 #[page("/import")]
@@ -1147,7 +1074,6 @@ async fn jobs_page(cx: &Cx) -> Result<impl View> {
11471074 .and_then(|p| p.parse::<u64>().ok())
11481075 .unwrap_or(1)
11491076 .clamp(1, pages);
1150- // Only the shown page's repos are looked up.
11511077 let user = state.store.user_by_id(&viewer.0.id).await?;
11521078 let mut rows = Vec::new();
11531079 for job in all
@@ -1206,7 +1132,7 @@ async fn job_view(
12061132 }];
12071133 Ok(view! {
12081134 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)
12101136 newrepo_tabs(lang: lang, active: "history")
12111137 <div class="sheet import-job" data-live-state=(state_word)>
12121138 <section class="sec">
@@ -1262,7 +1188,6 @@ async fn job_view(
12621188 })
12631189 }
12641190
1265-/// The job when the viewer owns it. Anyone else gets 404.
12661191 async fn owned_job(cx: &Cx, viewer: &User) -> Result<ImportJob> {
12671192 let id = job_id(cx).to_owned();
12681193 let state = context::<AppState>(cx);
@@ -1288,8 +1213,6 @@ async fn job_page(cx: &Cx) -> Result<impl View> {
12881213 })
12891214 }
12901215
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.
12931216 #[route(GET "/import/{job_id}/events")]
12941217 async fn job_events(cx: &Cx) -> Result<Response> {
12951218 let viewer = require_user(cx).await?;
@@ -1297,7 +1220,6 @@ async fn job_events(cx: &Cx) -> Result<Response> {
12971220 let query = query_params::<SeenQuery>(cx)?;
12981221 let state = context::<AppState>(cx);
12991222 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.
13011223 let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id));
13021224 let store = state.store.clone();
13031225 let id = job.id.clone();
@@ -1337,9 +1259,6 @@ struct RetryForm {
13371259 token: String,
13381260 }
13391261
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.
13431262 async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool> {
13441263 if job.state != ImportState::Failed {
13451264 return Ok(false);
@@ -1350,16 +1269,10 @@ async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool
13501269 let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else {
13511270 return Ok(false);
13521271 };
1353- if let Some(repo_id) = &job.repo_id
1354- && state.store.active_import_for_repo(repo_id).await?.is_some()
1355- {
1272+ let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default();
1273+ if !state.store.requeue_failed_import(&job.id).await? {
13561274 return Ok(false);
13571275 }
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?;
13631276 state
13641277 .store
13651278 .add_import_event(
@@ -1390,10 +1303,6 @@ async fn job_retry(cx: &Cx, Form(form): Form<RetryForm>) -> Result<SeeOther> {
13901303 Err(see_other(href).into())
13911304 }
13921305
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.
13971306 async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(ImportJob, Repo)>> {
13981307 let mut rows = Vec::new();
13991308 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
14161325 Ok(rows)
14171326 }
14181327
1419-/// The provider's name for a job's source, as the source tabs show it.
14201328 fn source_label(raw: &str) -> &'static str {
14211329 Source::parse(raw).map_or("", Source::label)
14221330 }
@@ -1433,7 +1341,7 @@ async fn retry_list(
14331341 let empty = rows.is_empty();
14341342 Ok(view! {
14351343 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)
14371345 newrepo_tabs(lang: lang, active: "history")
14381346 <div class="sheet">
14391347 <form method="post" action="/import/retry" class="fields">
@@ -1491,7 +1399,6 @@ struct RetrySelectedForm {
14911399 csrf: String,
14921400 #[serde(default)]
14931401 token: String,
1494- /// The ticked jobs arrive as `sel_0`, `sel_1`, ... with the job id as the value.
14951402 #[serde(flatten)]
14961403 extra: HashMap<String, String>,
14971404 }
@@ -1510,7 +1417,6 @@ async fn retry_submit(cx: &Cx, Form(form): Form<RetrySelectedForm>) -> Result<Se
15101417 return Err(see_other("/import/retry").into());
15111418 }
15121419 for (_, id) in picked {
1513- // Only the viewer's own jobs; anything else is skipped without a word.
15141420 let Some(job) = state.store.import_job(id).await? else {
15151421 continue;
15161422 };
crates/forge-web-account/src/pages/login.rsmodified+41 -56
@@ -2,7 +2,7 @@
22
33 use std::time::{Duration, Instant};
44
5-use forge_core::AuditAction;
5+use forge_core::{AuditAction, User};
66 use forge_core::names::normalize_name;
77 use http::header::{HeaderValue, RETRY_AFTER};
88 use serde::Deserialize;
@@ -224,17 +224,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View>
224224 set_pending_login(cx, &state.key, &user.id, &next)?;
225225 return Err(see_other("/login/2fa").into());
226226 }
227- login(cx, &user).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);
227+ finish_login(cx, state, &user, serde_json::Value::Null).await?;
238228 return Err(see_other(safe_next(Some(&form.next))).into());
239229 }
240230 _ => {
@@ -352,18 +342,8 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
352342 match user {
353343 Some(user) if verified => {
354344 state.throttle.clear(&key);
355- login(cx, &user).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;
345+ finish_login(cx, state, &user, json!({ "second_factor": true })).await?;
365346 clear_pending_login(cx);
366- clear_pre_csrf(cx);
367347 return Err(see_other(safe_next(Some(&pending.next))).into());
368348 }
369349 _ => {
@@ -395,6 +375,26 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i
395375 })
396376 }
397377
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+
398398 /// Whole seconds for a `Retry-After` header, at least 1.
399399 fn retry_after_secs(retry: Duration) -> u64 {
400400 retry.as_secs().max(1)
@@ -759,6 +759,14 @@ mod tests {
759759 shared.to_vec()
760760 }
761761
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+
762770 /// Cookie header for the pending login plus the pre-session CSRF cookie.
763771 fn both(pending: &str, precsrf_cookie: &str) -> String {
764772 format!("{pending}; {precsrf_cookie}")
@@ -832,22 +840,15 @@ mod tests {
832840 let (cookie, precsrf) = login_page(&router, from).await;
833841 let step = password_step(&router, from, (&cookie, &precsrf), "grace", PASSWORD).await;
834842 let pending = both(&pair(&step, "__Host-forge_2fa").unwrap(), &cookie);
835- let wrong = second_factor_step(&router, from, &pending, &precsrf, "000000").await;
836- // The chance that 000000 is the live code is about 1 in a million per window.
837- if wrong.status == 200 {
838- assert!(
839- wrong.body.contains("That code is not right"),
840- "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(),
843+ let wrong =
844+ second_factor_step(&router, from, &pending, &precsrf, &live_code(&shared, 2)).await;
845+ assert_eq!(wrong.status, 200, "wrong code: status");
846+ assert!(
847+ wrong.body.contains("That code is not right"),
848+ "wrong code: message"
849849 );
850- let code = totp::code_at(&shared, now_step);
850+
851+ let code = live_code(&shared, 0);
851852 let ok = second_factor_step(&router, from, &pending, &precsrf, &code).await;
852853 assert_eq!(ok.status, 303, "right code: body {}", ok.body);
853854 assert_eq!(
@@ -922,15 +923,7 @@ mod tests {
922923 let (cookie, precsrf) = login_page(&router, from).await;
923924 let stale = secret::seal(&state.key, format!("1|{}|/", user.id).as_bytes()).unwrap();
924925 let pending = format!("__Host-forge_2fa={stale}");
925- let code = totp::code_at(
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- );
926+ let code = live_code(&shared, 0);
934927 let reply =
935928 second_factor_step(&router, from, &both(&pending, &cookie), &precsrf, &code).await;
936929 assert_eq!(reply.status, 303, "expired: status");
@@ -954,15 +947,7 @@ mod tests {
954947 let reply = second_factor_step(&router, from, &pending, &precsrf, "111111").await;
955948 assert_eq!(reply.status, 200, "limit: wrong code");
956949 }
957- let code = totp::code_at(
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- );
950+ let code = live_code(&shared, 0);
966951 let blocked = second_factor_step(&router, from, &pending, &precsrf, &code).await;
967952 assert_eq!(blocked.status, 429, "limit: right code while locked");
968953 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-
31 use forge_core::mirrors::{DEFAULT_INTERVAL_MINUTES, MirrorDirection, NewMirror};
42 use forge_core::names::validate_name;
53 use forge_core::time::now_stamp;
@@ -10,7 +8,6 @@ use topcoat::Result;
108 use topcoat::context::{Cx, context};
119 use topcoat::router::content::Form;
1210 use topcoat::router::error::see_other;
13-// Named by the `#[query_params]` attribute below, which the unused-import lint does not see.
1411 #[allow(unused_imports)]
1512 use topcoat::router::error::bad_request;
1613 use topcoat::router::{page, query_params};
@@ -29,7 +26,6 @@ use crate::views::{alert, csrf_field, shell, user_facing_message};
2926 const MAX_DESCRIPTION_CHARS: usize = 350;
3027 const DEFAULT_BRANCH: &str = "main";
3128
32-/// The licenses the form offers, in menu order: SPDX id, menu label and the full SPDX text.
3329 const LICENSES: &[(&str, &str, &str)] = &[
3430 (
3531 "MIT",
@@ -93,8 +89,6 @@ const LICENSES: &[(&str, &str, &str)] = &[
9389 ),
9490 ];
9591
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.
9892 fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> {
9993 let (_, _, text) = LICENSES.iter().find(|(id, _, _)| *id == spdx)?;
10094 let text = match spdx {
@@ -109,7 +103,6 @@ fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> {
109103 Some(text)
110104 }
111105
112-/// The README of a new repo: the name as the heading, then the description when there is one.
113106 fn readme_text(name: &str, description: &str) -> String {
114107 let mut text = format!("# {name}\n");
115108 if !description.is_empty() {
@@ -132,16 +125,12 @@ struct NewRepoForm {
132125 visibility: String,
133126 #[serde(default)]
134127 default_branch: String,
135- /// The checkbox sends `on` when checked and nothing when unchecked.
136128 #[serde(default)]
137129 default_labels: String,
138- /// The "Add a README" checkbox. Present (`on`) when checked, absent otherwise.
139130 #[serde(default)]
140131 add_readme: Option<String>,
141- /// The SPDX id from the license select. Blank means no license.
142132 #[serde(default)]
143133 license: String,
144- /// The optional "Mirror an existing repository" section. A blank URL means no mirror.
145134 #[serde(default)]
146135 mirror_url: String,
147136 #[serde(default)]
@@ -150,13 +139,10 @@ struct NewRepoForm {
150139 mirror_secret: String,
151140 #[serde(default)]
152141 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.
155142 #[serde(default)]
156143 owner: String,
157144 }
158145
159-/// The form's values, echoed back when validation fails.
160146 struct Draft {
161147 owner: String,
162148 name: String,
@@ -188,7 +174,6 @@ impl Draft {
188174 }
189175 }
190176
191- /// The submitted values. The mirror password is never echoed back.
192177 fn from_form(form: &NewRepoForm) -> Self {
193178 Draft {
194179 owner: form.owner.trim().to_owned(),
@@ -230,14 +215,13 @@ async fn new_repo_form(
230215 let default_labels = draft.default_labels;
231216 let add_readme = draft.add_readme;
232217 let draft_license = draft.license;
233- // A mirror URL in the draft means the form was re-rendered after a validation error.
234218 let mirror_open = !draft.mirror_url.is_empty();
235219 let draft_mirror_url = draft.mirror_url;
236220 let draft_mirror_username = draft.mirror_username;
237221 let draft_mirror_interval = draft.mirror_interval;
238222 Ok(view! {
239223 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)
241225 crate::pages::import::newrepo_tabs(lang: lang, active: "create")
242226 <div class="sheet fit">
243227 <form method="post" action="/new" class="fields">
@@ -307,8 +291,6 @@ async fn new_repo_form(
307291 })
308292 }
309293
310-/// The accounts the viewer may create a repo under: themselves, then the orgs where
311-/// `may_create_repo_in` allows it.
312294 pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> {
313295 let mut names = vec![viewer.username.clone()];
314296 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
319301 Ok(names)
320302 }
321303
322-/// `/new?owner=acme` preselects that owner. An owner the viewer cannot pick is ignored.
323304 #[query_params(error = bad_request)]
324305 struct NewRepoQuery {
325306 owner: Option<String>,
@@ -361,8 +342,6 @@ async fn new_repo_submit(cx: &Cx, Form(form): Form<NewRepoForm>) -> Result<impl
361342 }
362343 }
363344
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.
366345 pub(crate) async fn repo_owner(
367346 state: &AppState,
368347 viewer: &User,
@@ -383,8 +362,6 @@ pub(crate) async fn repo_owner(
383362 Ok(Ok(org))
384363 }
385364
386-/// Validates the form and creates the repo. `Ok(Err(message))` is a user-facing rejection;
387-/// the outer `Err` is an internal failure.
388365 async fn create_repo(
389366 cx: &Cx,
390367 owner: &User,
@@ -423,7 +400,6 @@ async fn create_repo(
423400 Ok(target) => target,
424401 Err(message) => return Ok(Err(message)),
425402 };
426- // The mirror is checked before anything is created, so a refused URL leaves no repo behind.
427403 let mirror = if form.mirror_url.trim().is_empty() {
428404 None
429405 } else {
@@ -463,11 +439,10 @@ async fn create_repo(
463439
464440 let path = repo_path(&state.config.data_dir, &repo.id)?;
465441 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?;
467443 return Ok(Err(g::git_init_failed(lang, e)));
468444 }
469445 if want_files {
470- // The copyright holder is the account the repo belongs to; the author is the viewer.
471446 let year = jiff::Timestamp::now()
472447 .to_zoned_datetime(jiff::tz::TimeZone::UTC)
473448 .year()
@@ -494,7 +469,6 @@ async fn create_repo(
494469 .email
495470 .clone()
496471 .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.
498472 if let Err(e) = forge_git::seed::initial_commit(
499473 &state.git,
500474 &path,
@@ -509,8 +483,6 @@ async fn create_repo(
509483 tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not write the initial commit");
510484 }
511485 }
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.
514486 if add_default_labels && let Err(e) = state.store.create_default_labels(&repo.id).await {
515487 tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not add default labels");
516488 }
@@ -534,8 +506,6 @@ async fn create_repo(
534506 Ok(Ok(format!("/{}/{}", repo.owner_name, repo.name)))
535507 }
536508
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.
539509 async fn create_pull_mirror(
540510 cx: &Cx,
541511 state: &AppState,
@@ -592,8 +562,6 @@ mod tests {
592562
593563 const CSRF: &str = "new-repo-test-csrf";
594564
595- /// One store and router with `tahinli` signed in. Every scenario below uses its own repo name,
596- /// so they share this site.
597565 struct Site {
598566 store: Store,
599567 router: Router,
@@ -622,8 +590,6 @@ mod tests {
622590 }
623591 }
624592
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.
627593 async fn post_new(
628594 site: &Site,
629595 name: &str,
@@ -657,7 +623,6 @@ mod tests {
657623 (status, repo)
658624 }
659625
660- /// The default labels are added only when the box is checked.
661626 #[tokio::test]
662627 async fn default_labels_are_added_only_when_checked() {
663628 let site = site().await;
@@ -680,13 +645,10 @@ mod tests {
680645 }
681646 }
682647
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.
685648 #[tokio::test]
686649 async fn mirror_url_decides_whether_a_pull_mirror_is_made() {
687650 let site = site().await;
688651
689- // Case: a valid URL creates a pull mirror with the given settings.
690652 let (status, repo) = post_new(
691653 &site,
692654 "mirror-ok",
@@ -723,7 +685,6 @@ mod tests {
723685 "valid mirror: the first sync is due now"
724686 );
725687
726- // Case: a loopback URL shows the form again and creates nothing.
727688 let (status, repo) = post_new(
728689 &site,
729690 "mirror-loopback",
@@ -739,7 +700,6 @@ mod tests {
739700 "loopback: no repo is created for a refused mirror"
740701 );
741702
742- // Case: a blank URL creates the repo without a mirror.
743703 let (status, repo) = post_new(&site, "mirror-blank", &[("mirror_url", " ")]).await;
744704 assert_eq!(status, 303, "blank: status");
745705 let repo = repo.expect("blank: the repo is created");
@@ -753,7 +713,6 @@ mod tests {
753713 );
754714 }
755715
756- /// A README and a license make the first commit, and the README has the name and description.
757716 #[tokio::test]
758717 async fn readme_and_license_make_the_first_commit() {
759718 let site = site().await;
@@ -785,7 +744,6 @@ mod tests {
785744 assert!(!license.contains("<year>"), "{license}");
786745 }
787746
788- /// A viewer who chose Turkish gets the Turkish form.
789747 #[tokio::test]
790748 async fn the_form_is_in_turkish_for_a_turkish_viewer() {
791749 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};
1414 use crate::views::parts::{SubPart, head};
1515 use crate::views::shell;
1616
17-fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
18- match lang {
19- Lang::En => (
17+fn error_texts(lang: Lang, code: &'static str) -> (&'static str, &'static str, &'static str) {
18+ match (lang, code) {
19+ (Lang::En, "404") => (
2020 "Page not found",
2121 "This page does not exist, or you cannot see it. Check the address, or go back to the start.",
2222 "Back to the start",
2323 ),
24- Lang::Tr => (
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 => (
24+ (Lang::En, _) => (
4425 "Not allowed",
4526 "Your account cannot do this here. Ask an owner for access, or go back to the start.",
4627 "Back to the start",
4728 ),
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, _) => (
4935 "İzin yok",
5036 "Hesabınız burada bunu yapamaz. Bir sahibinden erişim isteyin ya da başa dönün.",
5137 "Başa dön",
@@ -54,10 +40,10 @@ fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) {
5440 }
5541
5642 #[component]
57-async fn forbidden_body(cx: &Cx, lang: Lang) -> Result<impl View> {
58- let (title, hint, back) = forbidden_texts(lang);
43+async fn error_body(cx: &Cx, lang: Lang, code: &'static str) -> Result<impl View> {
44+ let (title, hint, back) = error_texts(lang, code);
5945 Ok(view! {
60- head(title: title, sub: vec![SubPart::mono("403")])
46+ head(title: title, sub: vec![SubPart::mono(code)])
6147 <p class="state">(hint) " " <a class="act" href="/">(back)</a></p>
6248 })
6349 }
@@ -75,10 +61,10 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> {
7561 }
7662 }
7763 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;
7965 Ok(view! {
8066 (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"))
8268 })
8369 }
8470
@@ -86,9 +72,9 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> {
8672 async fn not_found_page(cx: &Cx) -> Result<impl View> {
8773 let viewer = current_user(cx).await?;
8874 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;
9076 Ok(view! {
9177 (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"))
9379 })
9480 }
crates/forge-web-account/src/pages/org_ctx.rsmodified+9 -23
@@ -24,7 +24,7 @@ use crate::views::{alert, profile_items};
2424 /// The query key that carries a notice on an org page. Its value is one of the fixed words in
2525 /// `NOTICES`, never user text. The notice lives in the URL, not in a cookie: a live refresh of the
2626 /// 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";
2828
2929 /// Notice words, the text key each one shows, and whether it is an error.
3030 pub const NOTICES: &[(&str, K, bool)] = &[
@@ -75,6 +75,9 @@ pub const TEAM_ROLES: [Role; 5] = [
7575 /// Default repo roles for the org settings select.
7676 pub const DEFAULT_ROLES: [&str; 3] = ["none", "read", "write"];
7777
78+/// Longest org description, in characters.
79+pub const MAX_DESCRIPTION_CHARS: usize = 2000;
80+
7881 /// The org a request is about, and what the viewer may do in it.
7982 pub struct OrgCtx {
8083 pub org: User,
@@ -155,16 +158,6 @@ pub async fn may_create_repo_in(state: &AppState, org_id: &str, user_id: &str) -
155158 }
156159 }
157160
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-
168161 /// The redirect target `back` with the notice `word` in its query, so the next view of the page
169162 /// shows it. `back` is an org path without a query.
170163 pub fn notice_href(back: &str, word: &'static str) -> String {
@@ -209,7 +202,7 @@ pub async fn org_tabs(
209202 repo_count: u64,
210203 package_count: usize,
211204 ) -> Result<impl View> {
212- let mut tabs: Vec<(String, String, bool, String, bool)> =
205+ let mut tabs: Vec<(String, String, bool, Option<String>)> =
213206 profile_items(lang, &name, true, false, true)
214207 .into_iter()
215208 .map(|item| {
@@ -218,13 +211,7 @@ pub async fn org_tabs(
218211 "packages" => Some(package_count.to_string()),
219212 _ => None,
220213 };
221- (
222- item.href,
223- item.label.to_owned(),
224- item.key == current,
225- count.clone().unwrap_or_default(),
226- count.is_some(),
227- )
214+ (item.href, item.label.to_owned(), item.key == current, count)
228215 })
229216 .collect();
230217 if owner {
@@ -232,16 +219,15 @@ pub async fn org_tabs(
232219 format!("/org/{name}/settings"),
233220 g::t(lang, K::Settings).to_owned(),
234221 current == "settings",
235- String::new(),
236- false,
222+ None,
237223 ));
238224 }
239225 Ok(view! {
240226 <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() {
242228 <a href=(href.as_str()) aria-current=(on.then_some("page"))>
243229 (label.as_str())
244- if has_count {
230+ if let Some(count) = count {
245231 " " <span class="tab-count">(count.as_str())</span>
246232 }
247233 </a>
crates/forge-web-account/src/pages/org_live.rsmodified+2 -2
@@ -20,7 +20,7 @@ use topcoat::router::response::Response;
2020 use topcoat::router::{path_param, route};
2121
2222 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};
2424 use crate::pages::org_teams::{team_of, visible_team_repos};
2525 use crate::state::AppState;
2626
@@ -43,7 +43,7 @@ async fn members_fingerprint(store: &Store, org_id: &str) -> Result<String> {
4343 "member {} {} {}",
4444 user.id,
4545 user.username,
46- member_role_word(role)
46+ role.as_str()
4747 ));
4848 }
4949 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};
1919 use crate::i18n::orgs::{self as g, K};
2020 use crate::i18n::{self, Lang};
2121 use crate::pages::org_ctx::{
22- load_org, member_role_word, notice_href, org_notice, org_tab_counts, org_tabs,
23- parse_member_role, require_form_csrf, require_member, require_owner, take_notice,
22+ load_org, notice_href, org_notice, org_tab_counts, org_tabs, require_form_csrf,
23+ require_member, require_owner, take_notice,
2424 };
2525 use crate::state::AppState;
2626 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>
171171 let state = context::<AppState>(cx);
172172 let back = ctx.href("/members");
173173
174- let Some(role) = parse_member_role(form.role.trim()) else {
174+ let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else {
175175 return Ok(see_other(notice_href(&back, "invalid_role")));
176176 };
177177 let username = form.username.trim();
@@ -207,7 +207,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther>
207207 id: &ctx.org.id,
208208 name: &ctx.org.username,
209209 },
210- serde_json::json!({ "user": target.username, "role": member_role_word(role) }),
210+ serde_json::json!({ "user": target.username, "role": role.as_str() }),
211211 )
212212 .await;
213213 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
222222 let state = context::<AppState>(cx);
223223 let back = ctx.href("/members");
224224
225- let Some(role) = parse_member_role(form.role.trim()) else {
225+ let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else {
226226 return Ok(see_other(notice_href(&back, "invalid_role")));
227227 };
228228 let user_id = form.user_id.trim();
@@ -255,7 +255,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe
255255 id: &ctx.org.id,
256256 name: &ctx.org.username,
257257 },
258- serde_json::json!({ "user": user_id, "role": member_role_word(role) }),
258+ serde_json::json!({ "user": user_id, "role": role.as_str() }),
259259 )
260260 .await;
261261 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};
1717 use crate::i18n::orgs::{self as g, K};
1818 use crate::i18n::{self, Lang};
1919 use crate::live::Topic;
20+use crate::pages::org_ctx::MAX_DESCRIPTION_CHARS;
2021 use crate::state::AppState;
2122 use crate::views::parts::head;
2223 use crate::views::{alert, csrf_field, shell, user_facing_message};
2324
24-const MAX_DESCRIPTION_CHARS: usize = 2000;
25-
2625 #[derive(Deserialize)]
2726 struct NewOrgForm {
2827 #[serde(default)]
@@ -53,7 +52,7 @@ async fn new_org_form(
5352 ) -> Result<impl View> {
5453 Ok(view! {
5554 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)
5756 <div class="sheet fit">
5857 if let Some(message) = error {
5958 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};
2222 use crate::i18n::{self, Key, Lang, t};
2323 use crate::live::Topic;
2424 use crate::pages::org_ctx::{
25- DEFAULT_ROLES, load_org, notice_href, org_notice, org_tab_counts, org_tabs, require_form_csrf,
26- require_owner, take_notice,
25+ DEFAULT_ROLES, MAX_DESCRIPTION_CHARS, load_org, notice_href, org_notice, org_tab_counts,
26+ org_tabs, require_form_csrf, require_owner, take_notice,
2727 };
2828 use crate::pages::settings_profile::store_avatar;
2929 use crate::state::AppState;
@@ -32,8 +32,6 @@ use crate::views::{avatar_url, shell, user_facing_message};
3232
3333 path_param!(org);
3434
35-const MAX_DESCRIPTION_CHARS: usize = 2000;
36-
3735 #[derive(Deserialize)]
3836 struct SettingsForm {
3937 #[serde(default)]
crates/forge-web-account/src/pages/org_teams.rsmodified+0 -12
@@ -782,18 +782,6 @@ mod tests {
782782 assert_eq!(parse_team_role(""), None);
783783 }
784784
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-
797785 #[test]
798786 fn duplicate_and_bad_names_get_their_own_notices() {
799787 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-
91 use forge_core::authz::{Action, authorize};
102 use forge_core::store::RepoSort;
113 use forge_core::store::orgs::OrgMemberRole;
@@ -47,47 +39,35 @@ use crate::views::{
4739
4840 path_param!(username);
4941
50-/// Repos per page on the repositories and stars tabs.
5142 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;
5344 struct PinsMenu {
5445 action: String,
5546 csrf: String,
5647 options: Vec<PinOption>,
5748 }
5849
59-/// Repos the overview shows when the owner has no visible pins.
6050 const POPULAR_COUNT: usize = 6;
61-/// Members an organization's overview lists; a longer list links to the members page.
6251 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;
6552
6653 #[query_params(error = bad_request)]
6754 struct ProfileQuery {
6855 tab: Option<String>,
6956 q: Option<String>,
70- /// Set when the filter asks for the text as typed, as one piece.
7157 exact: Option<String>,
72- /// Set when the filter keeps upper and lower case apart.
7358 case: Option<String>,
7459 sort: Option<String>,
7560 page: Option<String>,
76- /// A calendar day whose contributions to list under the calendar on the overview.
7761 day: Option<String>,
78- /// `too_many` after a save with more pins than the limit.
7962 pins: Option<String>,
8063 }
8164
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.
8465 const SORTS: [(&str, K); 3] = [
8566 ("updated", K::SortRecentlyUpdated),
8667 ("name", K::Name),
8768 ("stars", K::SortMostStars),
8869 ];
8970
90-/// Maps the `sort` query value to a key from `SORTS`; anything unknown means the default.
9171 fn sort_key(raw: Option<&str>) -> &'static str {
9272 SORTS
9373 .iter()
@@ -96,6 +76,40 @@ fn sort_key(raw: Option<&str>) -> &'static str {
9676 .unwrap_or(SORTS[0].0)
9777 }
9878
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+
99113 #[page("/{username}")]
100114 async fn profile_page(cx: &Cx) -> Result<impl View> {
101115 let name = username(cx);
@@ -117,15 +131,12 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
117131
118132 let actor = viewer.as_ref().map(|(u, _)| u);
119133 let lang = i18n::lang(cx, actor);
120- // Whether the viewer is this person. Only the person sees their Organizations tab and edit links.
121134 let own = !user.is_org() && actor.is_some_and(|u| u.id == user.id);
122- let tab = tab_key(query.tab.as_deref());
123- // An organization cannot be starred or keep snippets, so those tabs show the overview instead.
124- // The Organizations tab is the viewer's own, so anyone else gets the overview.
125- let tab = if (user.is_org() && matches!(tab, "stars" | "snippets"))
126- || (tab == "organizations" && !own)
135+ let tab = Tab::from_query(query.tab.as_deref());
136+ let tab = if (user.is_org() && matches!(tab, Tab::Stars | Tab::Snippets))
137+ || (tab == Tab::Organizations && !own)
127138 {
128- "overview"
139+ Tab::Overview
129140 } else {
130141 tab
131142 };
@@ -137,17 +148,14 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
137148 let page = page_number(query.page.as_deref());
138149 let sort = sort_key(query.sort.as_deref());
139150
140- // The tab labels count what the viewer may read, with no filter.
141151 let owned = RepoScope::OwnedBy(&user.id);
142152 let starred = RepoScope::StarredBy(&user.id);
143153 let repo_total = state.store.count_visible_repos(owned, actor).await?;
144154 let star_total = state.store.count_visible_repos(starred, actor).await?;
145155
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.
148156 let mut cards = Vec::new();
149157 let mut from_pins = true;
150- if tab == "overview" {
158+ if tab == Tab::Overview {
151159 let mut shown = readable(
152160 state,
153161 actor,
@@ -171,7 +179,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
171179 }
172180 }
173181
174- // The viewer's role in an organization, looked up once for the header, the tabs and the pins.
175182 let org_role = match actor {
176183 Some(u) if user.is_org() => state.store.org_member_role(&user.id, &u.id).await?,
177184 _ => None,
@@ -185,14 +192,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
185192 _ => false,
186193 };
187194
188- // An organization's pins are edited by its owners, a user's by the user.
189195 let can_edit_pins = match actor {
190196 Some(_) if user.is_org() => org_owner,
191197 Some(u) => u.id == user.id,
192198 None => false,
193199 };
194200 let mut pins_menu_data = None;
195- if can_edit_pins && tab == "overview" {
201+ if can_edit_pins && tab == Tab::Overview {
196202 let options = pin_options(&state.store, &user.id).await?;
197203 if let (false, Some((_, session))) = (options.is_empty(), viewer.as_ref()) {
198204 let action = if user.is_org() {
@@ -209,15 +215,12 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
209215 }
210216 let pins_error = can_edit_pins && query.pins.as_deref() == Some("too_many");
211217
212- // The contribution calendar on the overview, for a person only. Its counts and day links use
213- // public repos alone, so anyone may see it.
214- let heat = if tab == "overview" && !user.is_org() {
218+ let heat = if tab == Tab::Overview && !user.is_org() {
215219 Some(load_calendar(state, &user, query.day.as_deref()).await?)
216220 } else {
217221 None
218222 };
219223
220- // The Snippets tab lists the person's snippets the viewer may read. An organization keeps none.
221224 let snippets: Vec<ListRow> = if user.is_org() {
222225 Vec::new()
223226 } else {
@@ -229,18 +232,11 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
229232 .map(|summary| list_row(lang, summary))
230233 .collect()
231234 };
232- // Snippets page like the repo tabs, so the tab fits the screen however many there are.
233235 let snippet_total = snippets.len() as u64;
234236 let snippet_pages = snippet_total.div_ceil(PER_PAGE).max(1);
235237 let snippet_page = page.min(snippet_pages);
236238 let snippet_pager = pager_links(snippet_page, snippet_pages, |n| {
237- profile_href(
238- &user.username,
239- "snippets",
240- &Finder::default(),
241- SORTS[0].0,
242- n,
243- )
239+ profile_href(&user.username, Tab::Snippets.key(), &Finder::default(), SORTS[0].0, n)
244240 });
245241 let snippets: Vec<ListRow> = snippets
246242 .into_iter()
@@ -248,10 +244,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
248244 .take(PER_PAGE as usize)
249245 .collect();
250246
251- // The viewer's Organizations tab lists the organizations they belong to, and whether the
252- // instance lets them create one.
253247 let (orgs, org_create_allowed) = match actor {
254- Some(viewer_user) if tab == "organizations" => {
248+ Some(viewer_user) if tab == Tab::Organizations => {
255249 let mut cards = Vec::new();
256250 for (org, role) in state.store.orgs_for_user(&user.id).await? {
257251 let hash = state.store.avatar_hash(&org.id).await?;
@@ -276,8 +270,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
276270 };
277271
278272 let listing = match tab {
279- "repositories" | "stars" => {
280- let scope = if tab == "stars" { starred } else { owned };
273+ Tab::Repositories | Tab::Stars => {
274+ let scope = if tab == Tab::Stars { starred } else { owned };
281275 let sort_kind = match sort {
282276 "stars" => RepoSort::MostStars,
283277 "name" => RepoSort::Name,
@@ -289,12 +283,20 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
289283 .list_visible_repos(scope, actor, None, sort_kind, page, PER_PAGE)
290284 .await?
291285 } else {
292- // The search reads each repo's name and description, so it runs here over every
293- // repo in scope, then takes the one page asked for.
294- let (all, _) = state
295- .store
296- .list_visible_repos(scope, actor, None, sort_kind, 1, SEARCH_CAP)
297- .await?;
286+ let mut all = Vec::new();
287+ let mut batch_page = 1;
288+ loop {
289+ let (batch, in_scope) = state
290+ .store
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+ }
298300 let matching: Vec<_> = all
299301 .into_iter()
300302 .filter(|(repo, _, _)| {
@@ -302,6 +304,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
302304 })
303305 .collect();
304306 let total = matching.len() as u64;
307+ let page = page.min(total.div_ceil(PER_PAGE).max(1));
305308 let shown = matching
306309 .into_iter()
307310 .skip(((page - 1) * PER_PAGE) as usize)
@@ -313,10 +316,10 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
313316 let now = now_unix();
314317 let empty = match (tab, finder.is_empty()) {
315318 (_, false) => g::t(lang, K::NoReposMatch),
316- ("stars", true) => g::t(lang, K::NoVisibleStarred),
319+ (Tab::Stars, true) => g::t(lang, K::NoVisibleStarred),
317320 _ => g::t(lang, K::NoVisibleRepos),
318321 };
319- let count_text = if tab == "stars" {
322+ let count_text = if tab == Tab::Stars {
320323 g::starred_count(lang, total)
321324 } else {
322325 g::repo_count(lang, total)
@@ -331,13 +334,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
331334 page,
332335 pages,
333336 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)
335338 }),
336339 sort_links: SORTS
337340 .iter()
338341 .map(|(key, label)| SortLink {
339342 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),
341344 current: *key == sort,
342345 })
343346 .collect(),
@@ -348,8 +351,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
348351 _ => Listing::default(),
349352 };
350353
351- // An organization shows its members (the first few, with their avatars) and how many teams it
352- // has. Its `about` is its description.
353354 let org = if user.is_org() {
354355 let members = state.store.org_members(&user.id).await?;
355356 let teams = state.store.teams_for_org(&user.id).await?.len();
@@ -369,18 +370,16 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
369370 None
370371 };
371372
372- // The Packages tab lists the registry's packages the viewer may see.
373373 let package_rows = packages::package_rows(state, actor, &user).await?;
374- let packages_on = tab == "packages";
374+ let packages_on = tab == Tab::Packages;
375375
376- // A repo deleted just before this redirect here shows its one-line notice once.
377376 let notice = take_notice(cx);
378377 let title = user.username.clone();
379378 Ok(view! {
380379 shell(title: title.as_str(), viewer: viewer.as_ref(),
381380 notice_banner_for(lang: lang, title: notice)
382381 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,
384383 star_total: star_total, cards: cards, from_pins: from_pins,
385384 pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing,
386385 packages_on: packages_on, package_rows: package_rows,
@@ -391,9 +390,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
391390 })
392391 }
393392
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.
397393 #[route(GET "/users/{username}/events")]
398394 async fn profile_events(cx: &Cx) -> Result<Response> {
399395 let name = username(cx);
@@ -412,8 +408,6 @@ async fn profile_events(cx: &Cx) -> Result<Response> {
412408 .await
413409 }
414410
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.
417411 async fn profile_fingerprint(
418412 state: &AppState,
419413 user: &User,
@@ -433,7 +427,6 @@ async fn profile_fingerprint(
433427 .await?
434428 .to_string(),
435429 ];
436- // The header's about text and avatar, read fresh: the stream's `user` is a snapshot from connect.
437430 let about = state
438431 .store
439432 .user_by_id(&user.id)
@@ -445,13 +438,11 @@ async fn profile_fingerprint(
445438 "avatar {}",
446439 state.store.avatar_hash(&user.id).await?.unwrap_or_default()
447440 ));
448- // An organization's page shows its member and team counts.
449441 if user.is_org() {
450442 let members = state.store.org_members(&user.id).await?.len();
451443 let teams = state.store.teams_for_org(&user.id).await?.len();
452444 lines.push(format!("org {members} {teams}"));
453445 } else {
454- // The overview shows a person's calendar, so its total moves with each one.
455446 let total: u64 = state
456447 .store
457448 .contribution_counts(&user.id, &calendar_since(), &user.timezone)
@@ -485,38 +476,30 @@ async fn profile_fingerprint(
485476 Ok(lines.join("\n"))
486477 }
487478
488-/// What an organization's profile adds: its member count, the first members to list, and its team
489-/// count.
490479 struct OrgSummary {
491480 total: usize,
492481 members: Vec<OrgMember>,
493482 teams: usize,
494483 }
495484
496-/// A member on an organization's overview: the login name and the avatar URL.
497485 struct OrgMember {
498486 username: String,
499487 avatar: String,
500488 }
501489
502-/// A repo card on the overview: the repo and its star count.
503490 struct PinCard {
504491 repo: Repo,
505492 stars: u64,
506493 }
507494
508-/// One organization on the viewer's own Organizations tab, with its strings ready for the view.
509495 struct OrgCard {
510496 href: String,
511497 avatar: String,
512498 name: String,
513- /// Empty when the organization has no display name.
514499 display_name: String,
515500 role: &'static str,
516501 }
517502
518-/// One page of a repo tab: the rows, the pager, the sort chips, the match count text and the
519-/// empty-list text.
520503 #[derive(Default)]
521504 struct Listing {
522505 rows: Vec<RepoRow>,
@@ -528,25 +511,10 @@ struct Listing {
528511 empty: &'static str,
529512 }
530513
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.
544514 fn page_number(raw: Option<&str>) -> u64 {
545515 raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1)
546516 }
547517
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.
550518 fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String {
551519 let mut href = format!("/{}?tab={tab}", enc(name));
552520 if !finder.is_empty() {
@@ -567,9 +535,6 @@ fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -
567535 href
568536 }
569537
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.
573538 async fn may_read(state: &AppState, actor: Option<&User>, repo: &Repo) -> Result<bool> {
574539 let open = repo.visibility == Visibility::Public
575540 || 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
586551 Ok(authorize(actor, repo, role, org_role, Action::Read).is_ok())
587552 }
588553
589-/// The first `limit` repos of `repos` that the viewer may read, in their order.
590554 async fn readable(
591555 state: &AppState,
592556 actor: Option<&User>,
@@ -614,7 +578,7 @@ async fn profile_card(
614578 local_time: String,
615579 org: Option<OrgSummary>,
616580 lang: Lang,
617- tab: String,
581+ tab: Tab,
618582 finder: Finder,
619583 sort: &'static str,
620584 repo_total: u64,
@@ -640,16 +604,14 @@ async fn profile_card(
640604 ) -> Result<impl View> {
641605 let has_snippets = !snippets.is_empty();
642606 let (snippet_page, snippet_pages, (snippet_links, snippet_prev, snippet_next)) = snippet_paging;
643- let snippets_on = tab == "snippets";
644- let orgs_on = tab == "organizations";
607+ let snippets_on = tab == Tab::Snippets;
608+ let orgs_on = tab == Tab::Organizations;
645609 let has_orgs = !orgs.is_empty();
646610 let packages_events = packages::events_href(&user.username);
647611 let has_packages = !package_rows.is_empty();
648612 let src = avatar_url(&user.username, avatar.as_deref());
649613 let has_about = !about_html.is_empty();
650614 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.
653615 let avatar_px = if is_org { "96" } else { "256" };
654616 let avatar_class = if is_org {
655617 "profile-avatar org-avatar"
@@ -665,9 +627,9 @@ async fn profile_card(
665627 ("packages", package_rows.len().to_string()),
666628 ];
667629 let base = format!("/{}", enc(&user.username));
668- let overview_on = tab == "overview";
669- let repos_on = tab == "repositories";
670- let stars_on = tab == "stars";
630+ let overview_on = tab == Tab::Overview;
631+ let repos_on = tab == Tab::Repositories;
632+ let stars_on = tab == Tab::Stars;
671633 let list_on = repos_on || stars_on;
672634 let pinned_heading = if from_pins {
673635 g::t(lang, K::Pinned)
@@ -677,7 +639,6 @@ async fn profile_card(
677639 let has_cards = !cards.is_empty();
678640 let edit_label = mi::t(lang, MK::EditProfile);
679641 let org_edit_label = mi::t(lang, MK::EditOrganization);
680- // The display name is the heading when set; the username then moves under it.
681642 let has_name = user.display_name.is_some();
682643 let heading = user
683644 .display_name
@@ -700,8 +661,6 @@ async fn profile_card(
700661 let members_more = org
701662 .as_ref()
702663 .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.
705664 let mut sub = Vec::new();
706665 if has_name {
707666 sub.push(SubPart::text(user.username.as_str()));
@@ -734,7 +693,7 @@ async fn profile_card(
734693 <a class="button" href="/org/new">(g::t(lang, K::NewOrganization))</a>
735694 }
736695 )
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)
738697 <div class="sheet" data-live=(format!("/users/{}/events", user.username))>
739698 if has_about {
740699 <section class="sec profile-about markdown-body">(Unescaped::new_unchecked(about_html))</section>
@@ -806,7 +765,7 @@ async fn profile_card(
806765 <div class="sheet-tools">
807766 <strong>(count_text.as_str())</strong>
808767 <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())>
810769 <input type="hidden" name="sort" value=(sort)>
811770 finder_field(lang: lang, finder: finder, placeholder: filter_label, id: Some("profile-q"))
812771 </form>
@@ -879,14 +838,12 @@ async fn profile_card(
879838 })
880839 }
881840
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.
884841 #[component]
885842 pub async fn own_profile_tabs(
886843 cx: &Cx,
887844 lang: Lang,
888845 username: String,
889- current: String,
846+ current: Tab,
890847 ) -> Result<impl View> {
891848 let items = crate::views::profile_items(lang, &username, false, true, false);
892849 let mut counts = Vec::new();
@@ -920,53 +877,34 @@ pub async fn own_profile_tabs(
920877 })
921878 }
922879
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.
926880 #[component]
927881 pub async fn profile_tabs(
928882 cx: &Cx,
929883 username: String,
930884 items: Vec<NavItem>,
931- current: String,
885+ current: Tab,
932886 counts: Vec<(&'static str, String)>,
933887 ) -> Result<impl View> {
934- let rows: Vec<(String, String, bool, String, bool)> = items
888+ let rows: Vec<(String, String, bool, Option<String>)> = items
935889 .into_iter()
936890 .map(|item| {
937- let on = item.key == current;
891+ let on = item.key == current.key();
938892 let count = counts
939893 .iter()
940894 .find(|(key, _)| *key == item.key)
941895 .map(|(_, count)| count.clone());
942- let has_count = count.is_some();
943- (
944- item.href,
945- item.label.to_owned(),
946- on,
947- count.unwrap_or_default(),
948- has_count,
949- )
896+ (item.href, item.label.to_owned(), on, count)
950897 })
951898 .collect();
952899 Ok(view! {
953900 <nav class="tabs" aria-label=(username.as_str())>
954- for (href, label, on, count, has_count) in rows.into_iter() {
955- if on {
956- <a href=(href.as_str()) aria-current="page">
957- (label.as_str())
958- if has_count {
959- " " <span class="tab-count">(count.as_str())</span>
960- }
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- }
901+ for (href, label, on, count) in rows.into_iter() {
902+ <a href=(href.as_str()) aria-current=(on.then_some("page"))>
903+ (label.as_str())
904+ if let Some(count) = count {
905+ " " <span class="tab-count">(count.as_str())</span>
906+ }
907+ </a>
970908 }
971909 </nav>
972910 })
@@ -1003,7 +941,6 @@ mod tests {
1003941 }
1004942 }
1005943
1006- /// Creates a session for `user_id` and returns the cookie header value.
1007944 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
1008945 crate::test_support::create_session(store, user_id, token, CSRF).await;
1009946 format!("__Host-{SESSION_COOKIE}={token}")
@@ -1020,7 +957,6 @@ mod tests {
1020957 (status, String::from_utf8_lossy(&bytes).into_owned())
1021958 }
1022959
1023- /// Tahinli has a public repo, a private repo and a private repo that carol collaborates on.
1024960 async fn seeded() -> Site {
1025961 let site = site().await;
1026962 let tahinli = site
@@ -1061,14 +997,10 @@ mod tests {
1061997 site
1062998 }
1063999
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.
10671000 #[tokio::test]
10681001 async fn profile_visibility_routing_and_edit_button() {
10691002 let site = seeded().await;
10701003
1071- // About is rendered and sanitized.
10721004 let (status, anon) = get(&site.router, "/tahinli", None).await;
10731005 assert_eq!(status, 200, "about");
10741006 assert!(anon.contains("<h1"), "about: heading rendered: {anon}");
@@ -1080,7 +1012,6 @@ mod tests {
10801012 assert!(!anon.contains("<script>"), "about: script stripped: {anon}");
10811013 assert!(!anon.contains("alert(1)"), "about: script body stripped");
10821014
1083- // Anonymous visitors see only public repos and no edit button.
10841015 assert!(anon.contains("tahinli/open-repo"), "anonymous: public repo");
10851016 assert!(
10861017 !anon.contains("tahinli/secret-repo"),
@@ -1095,7 +1026,6 @@ mod tests {
10951026 "anonymous: edit button"
10961027 );
10971028
1098- // Another user sees the same public-only list and no edit button.
10991029 let bob = site
11001030 .store
11011031 .create_user("bob", None, "not-a-real-hash", false)
@@ -1120,7 +1050,6 @@ mod tests {
11201050 "other user: edit button"
11211051 );
11221052
1123- // The owner sees every repo and the edit button.
11241053 let tahinli = user_id(&site.store, "tahinli").await;
11251054 let cookie = sign_in(&site.store, &tahinli, "visibility-owner-token").await;
11261055 let (_, owner) = get(&site.router, "/tahinli", Some(&cookie)).await;
@@ -1131,7 +1060,6 @@ mod tests {
11311060 "owner: edit button"
11321061 );
11331062
1134- // A collaborator sees the repo they were added to, not the private one.
11351063 let carol = user_id(&site.store, "carol").await;
11361064 let cookie = sign_in(&site.store, &carol, "visibility-carol-token").await;
11371065 let (_, collab) = get(&site.router, "/tahinli", Some(&cookie)).await;
@@ -1144,14 +1072,12 @@ mod tests {
11441072 "collaborator: private repo"
11451073 );
11461074
1147- // Unknown users 404, and the lookup ignores case.
11481075 let (status, _) = get(&site.router, "/nobody-here", None).await;
11491076 assert_eq!(status, 404, "unknown user");
11501077 let (status, body) = get(&site.router, "/TAHINLI", None).await;
11511078 assert_eq!(status, 200, "case-insensitive lookup");
11521079 assert!(body.contains("tahinli"), "case-insensitive lookup");
11531080
1154- // Fixed routes are not shadowed by the profile.
11551081 for uri in [
11561082 "/new",
11571083 "/login",
@@ -1170,11 +1096,9 @@ mod tests {
11701096 "{uri} was served by the profile page"
11711097 );
11721098 }
1173- // The fixed login page still renders its form, not a profile.
11741099 let (status, body) = get(&site.router, "/login", None).await;
11751100 assert_eq!(status, 200, "fixed login page");
11761101 assert!(body.contains("<form"), "fixed login page renders its form");
1177- // Two-segment repo routes keep working and still 404 for a missing repo.
11781102 let (status, body) = get(&site.router, "/tahinli/missing", None).await;
11791103 assert_eq!(status, 404, "missing repo");
11801104 assert!(
@@ -1183,14 +1107,11 @@ mod tests {
11831107 );
11841108 }
11851109
1186- /// Stars, the org sidebar and org pins, on one seeded site. The org scenarios use their
1187- /// own org names and session tokens.
11881110 #[tokio::test]
11891111 async fn stars_org_sidebar_and_org_pins() {
11901112 let site = seeded().await;
11911113 let tahinli = user_id(&site.store, "tahinli").await;
11921114
1193- // The stars tab lists only starred repos the viewer may read.
11941115 let mira = site
11951116 .store
11961117 .create_user("mira", None, "not-a-real-hash", false)
@@ -1212,8 +1133,6 @@ mod tests {
12121133 "stars: private starred repo"
12131134 );
12141135
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.
12171136 let kaan = site
12181137 .store
12191138 .create_user("kaan", None, "not-a-real-hash", false)
@@ -1255,7 +1174,6 @@ mod tests {
12551174 !member_profile.contains("href=\"/org/forge-org/settings\""),
12561175 "org profile: member has no edit button"
12571176 );
1258- // Settings keeps a sidebar of its own pages, and its back link goes to the profile.
12591177 let (_, settings) = get(&site.router, "/org/forge-org/settings", Some(&owner_cookie)).await;
12601178 assert!(
12611179 !settings.contains("/org/forge-org/settings/pins"),
@@ -1270,7 +1188,6 @@ mod tests {
12701188 "org settings: Overview tab goes to the profile"
12711189 );
12721190
1273- // Org pins show on the org profile, with an edit link for owners only.
12741191 let acme = site.store.create_org("acme", &tahinli).await.unwrap();
12751192 let lib = site
12761193 .store
@@ -1306,8 +1223,6 @@ mod tests {
13061223 );
13071224 }
13081225
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.
13111226 #[tokio::test]
13121227 async fn pins_fallback_and_display_name() {
13131228 let site = seeded().await;
@@ -1317,7 +1232,6 @@ mod tests {
13171232 let open = id_of("open-repo");
13181233 let secret = id_of("secret-repo");
13191234
1320- // Pins: anonymous visitors see the public pin only; the owner sees both.
13211235 site.store
13221236 .set_profile_pins(&tahinli, &[open, secret.clone()])
13231237 .await
@@ -1359,7 +1273,6 @@ mod tests {
13591273 "pins: owner edits them on the profile"
13601274 );
13611275
1362- // Fallback: with no visible pin, the overview shows popular repos instead.
13631276 site.store
13641277 .set_profile_pins(&tahinli, &[secret])
13651278 .await
@@ -1372,7 +1285,6 @@ mod tests {
13721285 "fallback: private repo hidden"
13731286 );
13741287
1375- // Display name: the heading uses it with the username below; a blank name falls back.
13761288 site.store
13771289 .set_display_name(&tahinli, "Ahmet Kaan Gümüş")
13781290 .await
@@ -1400,7 +1312,6 @@ mod tests {
14001312 );
14011313 }
14021314
1403- /// The calendar sits on the overview. An old `?tab=contributions` link falls through to it.
14041315 #[tokio::test]
14051316 async fn overview_holds_the_calendar() {
14061317 let site = seeded().await;
@@ -1416,7 +1327,6 @@ mod tests {
14161327 assert!(day.contains("class=\"heat\""), "day link: calendar");
14171328 }
14181329
1419- /// The calendar's stream is the profile's own: an unknown name is 404.
14201330 #[tokio::test]
14211331 async fn profile_events_is_404_for_an_unknown_user() {
14221332 let site = seeded().await;
@@ -1428,7 +1338,6 @@ mod tests {
14281338 body.matches(needle).count()
14291339 }
14301340
1431- /// A user with 35 public repos, `bulk-00` to `bulk-34`.
14321341 async fn bulk_site() -> Site {
14331342 let site = site().await;
14341343 let tahinli = site
@@ -1455,12 +1364,10 @@ mod tests {
14551364 store.user_by_username(name).await.unwrap().unwrap().id
14561365 }
14571366
1458- /// Pagination and the name filter on one 35-repo site.
14591367 #[tokio::test]
14601368 async fn repositories_tab_paging_and_name_filter() {
14611369 let site = bulk_site().await;
14621370
1463- // Ten repos per page, the last five on page four.
14641371 let (status, first) = get(&site.router, "/tahinli?tab=repositories&sort=name", None).await;
14651372 assert_eq!(status, 200, "paging: first page");
14661373 assert_eq!(
@@ -1490,7 +1397,6 @@ mod tests {
14901397 "paging: first repo not on page two"
14911398 );
14921399
1493- // The name filter is a case-insensitive substring match.
14941400 let (_, body) = get(&site.router, "/tahinli?tab=repositories&q=BULK-1", None).await;
14951401 assert_eq!(
14961402 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 {
2020 forge_core::time::stamp_ago(Duration::from_secs((CALENDAR_DAYS + 1) * 86_400))
2121 }
2222
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+
2331 /// The day the `day` query asks for: a strict `YYYY-MM-DD` date from the calendar's first day to
2432 /// today. Anything else (malformed, a future day, or before the calendar) is ignored.
2533 pub(crate) fn selected_day(
@@ -33,12 +41,7 @@ pub(crate) fn selected_day(
3341 if date.to_string() != text {
3442 return None;
3543 }
36- let ymd = (
37- i64::from(date.year()),
38- i64::from(date.month()),
39- i64::from(date.day()),
40- );
41- (first..=today).contains(&ymd).then_some(date)
44+ (first..=today).contains(&ymd(date)).then_some(date)
4245 }
4346
4447 /// The contributions the user made on their local day `date`, newest first.
@@ -58,11 +61,7 @@ pub(crate) async fn day_detail(
5861 .contributions_between(&user.id, &from, &to)
5962 .await?;
6063 Ok(Some(DayDetail {
61- date: (
62- i64::from(date.year()),
63- i64::from(date.month()),
64- i64::from(date.day()),
65- ),
64+ date: ymd(date),
6665 items,
6766 }))
6867 }
@@ -74,11 +73,7 @@ pub(crate) async fn load_calendar(
7473 day: Option<&str>,
7574 ) -> Result<(Calendar, Option<DayDetail>)> {
7675 let local_now = forge_core::tz::local_datetime(Timestamp::now(), &user.timezone);
77- let today = (
78- i64::from(local_now.year()),
79- i64::from(local_now.month()),
80- i64::from(local_now.day()),
81- );
76+ let today = ymd(local_now.date());
8277 let counts = state
8378 .store
8479 .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(
215215 ) -> Result<std::result::Result<User, String>> {
216216 let username = match validate_username(&form.username) {
217217 Ok((name, _)) => name,
218- Err(e) => {
219- return Ok(Err(
220- user_facing_message(&e).unwrap_or_else(|| "invalid username".into())
221- ));
222- }
218+ Err(e) => match user_facing_message(&e) {
219+ Some(message) => return Ok(Err(message)),
220+ None => return Err(e.into()),
221+ },
223222 };
224223 if let Some(message) = check_new_password(lang, &form.password, &form.confirm) {
225224 return Ok(Err(message));
@@ -229,9 +228,10 @@ async fn create_account(
229228 None => {
230229 let address = form.email.trim().to_owned();
231230 if let Err(e) = validate_email(&address) {
232- return Ok(Err(
233- user_facing_message(&e).unwrap_or_else(|| "invalid email address".into())
234- ));
231+ match user_facing_message(&e) {
232+ Some(message) => return Ok(Err(message)),
233+ None => return Err(e.into()),
234+ }
235235 }
236236 address
237237 }
@@ -423,11 +423,13 @@ async fn verify_resend(cx: &Cx, Form(form): Form<ResendForm>) -> Result<SeeOther
423423 }
424424 if let Some(address) = viewer.0.email.clone()
425425 && !state.store.email_is_verified(&viewer.0.id).await?
426- && !account::send_verify(state, &viewer.0, &address).await?
427426 {
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"));
429431 }
430- Ok(see_other("/settings/security?saved=verify_sent"))
432+ Ok(see_other("/settings/security"))
431433 }
432434
433435 #[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-
41 use std::path::{Path, PathBuf};
52
63 use forge_core::releases::Release;
74 use forge_core::{Repo, Role, Store, User, Visibility};
85 use forge_git::repo::{init_bare, repo_path};
6+use futures_util::StreamExt;
97 use topcoat::router::request::Request;
8+use topcoat::router::response::Response;
109 use topcoat::router::{Body, HeaderMap, Router, to_bytes};
1110
1211 use crate::auth::SESSION_COOKIE;
@@ -15,6 +14,8 @@ use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
1514 use crate::test_support::{app_router, create_session, test_state};
1615
1716 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";
1819
1920 fn git(dir: &Path, args: &[&str]) -> String {
2021 let out = std::process::Command::new("git")
@@ -89,9 +90,6 @@ fn form(pairs: &[(&str, &str)]) -> Vec<u8> {
8990 .into_bytes()
9091 }
9192
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.
9593 fn upload_body(file_name: &str, data: &[u8]) -> (String, Vec<u8>) {
9694 crate::pages::settings_profile::tests::multipart(&[
9795 ("csrf", None, CSRF.as_bytes()),
@@ -111,8 +109,6 @@ struct Fixture {
111109 bob_cookie: String,
112110 }
113111
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.
116112 async fn fixture(max_mb: Option<u64>) -> Fixture {
117113 let tmp = tempfile::tempdir().expect("tempdir");
118114 let mut state = test_state(tmp.path()).await;
@@ -183,8 +179,7 @@ impl Fixture {
183179 .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
184180 }
185181
186- /// Creates a release row directly, bypassing the form.
187- async fn release(&self, tag: &str, draft: bool) -> forge_core::releases::Release {
182+ async fn release(&self, tag: &str, draft: bool) -> Release {
188183 self.store
189184 .create_release(&forge_core::releases::NewRelease {
190185 repo_id: &self.repo.id,
@@ -212,9 +207,20 @@ impl Fixture {
212207 )
213208 .await
214209 }
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+ }
215222 }
216223
217-/// The release's own fields, unchanged, with no tag change.
218224 fn keep(rel: &Release) -> EditRelease {
219225 EditRelease {
220226 title: rel.title.clone(),
@@ -226,7 +232,6 @@ fn keep(rel: &Release) -> EditRelease {
226232 }
227233 }
228234
229-/// Adds a commit on top of `main` and points branch `next` at it. Returns the new commit.
230235 fn second_commit(fx: &Fixture) -> String {
231236 let tree = git(&fx.bare, &["rev-parse", "refs/heads/main^{tree}"]);
232237 let next = git(
@@ -237,771 +242,656 @@ fn second_commit(fx: &Fixture) -> String {
237242 next
238243 }
239244
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-
244245 #[tokio::test]
245246 async fn drafts_and_permissions_share_one_repo() {
246247 let fx = fixture(None).await;
247248
248- // Drafts: readers see the published release only, owners see the draft too.
249- {
250- let published = fx.release("v1.0", false).await;
251- let draft = fx.release("v2.0", true).await;
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- )
249+ let published = fx.release("v1.0", false).await;
250+ let draft = fx.release("v2.0", true).await;
251+ let draft_asset = fx
252+ .upload(&draft.id, "secret.bin", b"x", &fx.tahinli_cookie)
382253 .await;
383- assert_ne!(delete.status, 303, "a reader cannot delete");
384- assert!(fx.store.release(&rel.id).await.expect("read").is_some());
385- }
254+ assert_eq!(draft_asset.status, 303, "writer uploads to a draft");
255+
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+ );
386271
387- // The repo home's head names the latest release and links to it and to the releases tab.
388- {
389- fx.release("v0.9-beta", false).await;
390- let home = send(&fx.app, "GET", "/tahinli/proj", None, None, Vec::new()).await;
391- assert_eq!(home.status, 200);
392- assert!(home.text().contains("/tahinli/proj/releases/tag/v0.9-beta"));
393- assert!(
394- home.text().contains("/tahinli/proj/releases"),
395- "the tabs link to releases"
396- );
397- }
398-}
272+ let anon_draft = send(
273+ &fx.app,
274+ "GET",
275+ "/tahinli/proj/releases/tag/v2.0",
276+ None,
277+ None,
278+ Vec::new(),
279+ )
280+ .await;
281+ assert_eq!(anon_draft.status, 404, "anonymous draft page");
282+ let anon_download = fx.download("v2.0/secret.bin").await;
283+ assert_eq!(
284+ anon_download.status, 404,
285+ "a draft asset is not downloadable by readers"
286+ );
399287
400-#[tokio::test]
401-async fn creating_a_release_takes_and_validates_its_tag_and_target() {
402- let fx = fixture(None).await;
288+ let writer_draft = send(
289+ &fx.app,
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+ );
403331
404- // A missing tag is created as a lightweight tag on the branch head.
405- {
406- let reply = send(
407- &fx.app,
408- "POST",
409- "/tahinli/proj/releases/new",
410- Some(&fx.tahinli_cookie),
411- Some(FORM_TYPE),
412- form(&[
413- ("csrf", CSRF),
414- ("tag", "v1.0"),
415- ("target", "main"),
416- ("title", "First"),
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")
332+ let edit = send(
333+ &fx.app,
334+ "POST",
335+ &format!("/tahinli/proj/releases/{}/edit", rel.id),
336+ Some(&fx.bob_cookie),
337+ Some(FORM_TYPE),
338+ form(&[("csrf", CSRF), ("title", "hacked"), ("body", "")]),
339+ )
340+ .await;
341+ assert_ne!(edit.status, 303, "a reader cannot edit");
342+ assert_eq!(
343+ fx.store
344+ .release(&rel.id)
431345 .await
432346 .expect("read")
433- .expect("release");
434- assert_eq!(release.target_oid, tip);
435- assert!(release.published_at.is_some());
436- }
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");
347+ .expect("row")
348+ .title,
349+ "Release v3.0"
350+ );
478351
479- let tip = fx.main_tip();
480- let made = release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input("v7", &tip))
352+ let upload = fx.upload(&rel.id, "a.bin", b"data", &fx.bob_cookie).await;
353+ assert_ne!(upload.status, 303, "a reader cannot upload");
354+ assert!(
355+ fx.store
356+ .list_release_assets(&rel.id)
481357 .await
482- .expect("a commit id works as a target");
483- assert_eq!(made.target_oid, tip, "commit id target");
484- assert_eq!(
485- fx.tag_target("v7").as_deref(),
486- Some(tip.as_str()),
487- "commit id target"
488- );
358+ .expect("assets")
359+ .is_empty()
360+ );
489361
490- let missing = release_ops::create(
491- &fx.state,
492- &fx.repo,
493- &fx.tahinli,
494- input("v8", "1111111111111111111111111111111111111111"),
495- )
496- .await;
497- assert!(
498- matches!(missing, Err(ReleaseError::Invalid(_))),
499- "missing target: {missing:?}"
500- );
501- assert!(fx.tag_target("v8").is_none(), "missing target");
502- }
362+ let delete = send(
363+ &fx.app,
364+ "POST",
365+ &format!("/tahinli/proj/releases/{}/delete", rel.id),
366+ Some(&fx.bob_cookie),
367+ Some(FORM_TYPE),
368+ form(&[("csrf", CSRF), ("confirm", "on")]),
369+ )
370+ .await;
371+ assert_ne!(delete.status, 303, "a reader cannot delete");
372+ assert!(fx.store.release(&rel.id).await.expect("read").is_some());
373+
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+ );
503382 }
504383
505384 #[tokio::test]
506-async fn retagging_rules_hold_for_published_and_draft_releases() {
385+async fn creating_and_retagging_releases_take_tags_and_targets() {
507386 let fx = fixture(None).await;
508387
509- // A published release moves to a new tag and keeps the old git tag.
510- {
511- git(&fx.bare, &["tag", "v1.0", "refs/heads/main"]);
512- let rel = fx.release("v1.0", false).await;
513- let edit = EditRelease {
514- tag: Some("v1.1".to_owned()),
515- ..keep(&rel)
516- };
517- let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)
518- .await
519- .expect("retag");
520- assert_eq!(moved.tag, "v1.1");
521- assert_eq!(moved.target_oid, fx.main_tip());
522- assert_eq!(
523- fx.tag_target("v1.1").as_deref(),
524- Some(fx.main_tip().as_str())
525- );
526- assert!(fx.tag_target("v1.0").is_some(), "the old git tag is kept");
527- assert!(
528- fx.store
529- .release_by_tag(&fx.repo.id, "v1.0")
530- .await
531- .expect("read")
532- .is_none(),
533- "the old tag no longer names a release"
534- );
535- }
388+ let reply = send(
389+ &fx.app,
390+ "POST",
391+ "/tahinli/proj/releases/new",
392+ Some(&fx.tahinli_cookie),
393+ Some(FORM_TYPE),
394+ form(&[
395+ ("csrf", CSRF),
396+ ("tag", "v1.0"),
397+ ("target", "main"),
398+ ("title", "First"),
399+ ("body", "hello"),
400+ ]),
401+ )
402+ .await;
403+ assert_eq!(reply.status, 303, "body: {}", reply.text());
404+ assert_eq!(
405+ reply.location.as_deref(),
406+ Some("/tahinli/proj/releases/tag/v1.0")
407+ );
408+ let tip = fx.main_tip();
409+ assert_eq!(fx.tag_target("v1.0").as_deref(), Some(tip.as_str()));
410+ let release = fx
411+ .store
412+ .release_by_tag(&fx.repo.id, "v1.0")
413+ .await
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");
536453
537- // A published tag cannot be moved in place, but a draft can.
538- {
539- git(&fx.bare, &["tag", "v2.0", "refs/heads/main"]);
540- let next = second_commit(&fx);
541- let published = fx.release("v2.0", false).await;
542- let move_published = EditRelease {
543- target: Some("next".to_owned()),
544- ..keep(&published)
545- };
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- );
454+ let made = release_ops::create(&fx.state, &fx.repo, &fx.tahinli, input("v7", &tip))
455+ .await
456+ .expect("a commit id works as a target");
457+ assert_eq!(made.target_oid, tip, "commit id target");
458+ assert_eq!(
459+ fx.tag_target("v7").as_deref(),
460+ Some(tip.as_str()),
461+ "commit id target"
462+ );
557463
558- let draft = fx
559- .store
560- .create_release(&forge_core::releases::NewRelease {
561- repo_id: &fx.repo.id,
562- tag: "v3.0",
563- target_oid: &fx.main_tip(),
564- title: "draft",
565- body: "",
566- draft: true,
567- prerelease: false,
568- author_id: &fx.tahinli.id,
569- })
570- .await
571- .expect("draft");
572- git(&fx.bare, &["tag", "v3.0", "refs/heads/main"]);
573- let move_draft = EditRelease {
574- target: Some("next".to_owned()),
575- ..keep(&draft)
576- };
577- let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, move_draft)
464+ let missing = release_ops::create(
465+ &fx.state,
466+ &fx.repo,
467+ &fx.tahinli,
468+ input("v8", "1111111111111111111111111111111111111111"),
469+ )
470+ .await;
471+ assert!(
472+ matches!(missing, Err(ReleaseError::Invalid(_))),
473+ "missing target: {missing:?}"
474+ );
475+ assert!(fx.tag_target("v8").is_none(), "missing target");
476+
477+ git(&fx.bare, &["tag", "r1.0", "refs/heads/main"]);
478+ let rel = fx.release("r1.0", false).await;
479+ let edit = EditRelease {
480+ tag: Some("r1.1".to_owned()),
481+ ..keep(&rel)
482+ };
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")
578496 .await
579- .expect("draft moves");
580- assert_eq!(moved.target_oid, next);
581- assert_eq!(fx.tag_target("v3.0"), Some(next));
582- }
497+ .expect("read")
498+ .is_none(),
499+ "the old tag no longer names a release"
500+ );
583501
584- // Retagging adopts an existing tag and refuses clashes and bad names.
585- {
586- git(&fx.bare, &["tag", "v0.9", "refs/heads/main"]);
587- let next = second_commit(&fx);
588- let draft = fx.release("v5", true).await;
589-
590- let clash_target = EditRelease {
591- tag: Some("v0.9".to_owned()),
592- target: Some("next".to_owned()),
593- ..keep(&draft)
594- };
595- let refused =
596- release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, clash_target).await;
597- assert!(
598- matches!(refused, Err(ReleaseError::Invalid(_))),
599- "{refused:?}"
600- );
502+ git(&fx.bare, &["tag", "r2.0", "refs/heads/main"]);
503+ let next = second_commit(&fx);
504+ let published = fx.release("r2.0", false).await;
505+ let move_published = EditRelease {
506+ target: Some("next".to_owned()),
507+ ..keep(&published)
508+ };
509+ let refused =
510+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &published, move_published).await;
511+ assert!(
512+ matches!(refused, Err(ReleaseError::Invalid(_))),
513+ "{refused:?}"
514+ );
515+ assert_eq!(
516+ fx.tag_target("r2.0").as_deref(),
517+ Some(fx.main_tip().as_str()),
518+ "published tag stays put"
519+ );
601520
602- let adopt = EditRelease {
603- tag: Some("v0.9".to_owned()),
604- ..keep(&draft)
605- };
606- let adopted = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, adopt)
607- .await
608- .expect("adopt");
609- assert_eq!(adopted.tag, "v0.9");
610- assert_eq!(adopted.target_oid, fx.main_tip());
611- assert_ne!(adopted.target_oid, next);
612-
613- let other = fx.release("v6", false).await;
614- let taken = EditRelease {
615- tag: Some("v0.9".to_owned()),
616- ..keep(&other)
617- };
618- let clash = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, taken).await;
619- assert!(matches!(clash, Err(ReleaseError::Conflict(_))), "{clash:?}");
620-
621- let bad_name = EditRelease {
622- tag: Some("a/b".to_owned()),
623- ..keep(&other)
624- };
625- let invalid = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &other, bad_name).await;
626- assert!(
627- matches!(invalid, Err(ReleaseError::Invalid(_))),
628- "{invalid:?}"
629- );
630- }
521+ git(&fx.bare, &["tag", "r3.0", "refs/heads/main"]);
522+ let draft = fx.release("r3.0", true).await;
523+ let move_draft = EditRelease {
524+ target: Some("next".to_owned()),
525+ ..keep(&draft)
526+ };
527+ let moved = release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, move_draft)
528+ .await
529+ .expect("draft moves");
530+ assert_eq!(moved.target_oid, next);
531+ assert_eq!(fx.tag_target("r3.0"), Some(next));
532+
533+ git(&fx.bare, &["tag", "r0.9", "refs/heads/main"]);
534+ let next = second_commit(&fx);
535+ let draft = fx.release("r5", true).await;
536+
537+ let clash_target = EditRelease {
538+ tag: Some("r0.9".to_owned()),
539+ target: Some("next".to_owned()),
540+ ..keep(&draft)
541+ };
542+ let refused =
543+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &draft, clash_target).await;
544+ assert!(
545+ matches!(refused, Err(ReleaseError::Invalid(_))),
546+ "{refused:?}"
547+ );
548+
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+ );
631577 }
632578
633579 #[tokio::test]
634580 async fn the_edit_page_and_its_form_follow_the_publish_state() {
635581 let fx = fixture(None).await;
636582
637- // The edit page shows tag and target controls, and hides the target once published.
638- {
639- let draft = fx.release("v1.0", true).await;
640- let published = fx.release("v2.0", false).await;
641-
642- let page = send(
643- &fx.app,
644- "GET",
645- &format!("/tahinli/proj/releases/{}/edit", draft.id),
646- Some(&fx.tahinli_cookie),
647- None,
648- Vec::new(),
649- )
650- .await;
651- assert_eq!(page.status, 200, "body: {}", page.text());
652- let html = page.text();
653- assert!(html.contains("name=\"tag\" value=\"v1.0\""), "{html}");
654- assert!(html.contains("name=\"target\""), "a draft shows the target");
655-
656- let page = send(
657- &fx.app,
658- "GET",
659- &format!("/tahinli/proj/releases/{}/edit", published.id),
660- Some(&fx.tahinli_cookie),
661- None,
662- Vec::new(),
663- )
664- .await;
665- let html = page.text();
666- assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}");
667- assert!(
668- !html.contains("name=\"target\""),
669- "published hides the target"
670- );
671- }
583+ let draft = fx.release("v1.0", true).await;
584+ let published = fx.release("v2.0", false).await;
585+
586+ let page = send(
587+ &fx.app,
588+ "GET",
589+ &format!("/tahinli/proj/releases/{}/edit", draft.id),
590+ Some(&fx.tahinli_cookie),
591+ None,
592+ Vec::new(),
593+ )
594+ .await;
595+ assert_eq!(page.status, 200, "body: {}", page.text());
596+ let html = page.text();
597+ assert!(html.contains("name=\"tag\" value=\"v1.0\""), "{html}");
598+ assert!(html.contains("name=\"target\""), "a draft shows the target");
599+
600+ let page = send(
601+ &fx.app,
602+ "GET",
603+ &format!("/tahinli/proj/releases/{}/edit", published.id),
604+ Some(&fx.tahinli_cookie),
605+ None,
606+ Vec::new(),
607+ )
608+ .await;
609+ let html = page.text();
610+ assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}");
611+ assert!(
612+ !html.contains("name=\"target\""),
613+ "published hides the target"
614+ );
672615
673- // A published release can be retagged through the form and keeps its commit.
674- {
675- git(&fx.bare, &["tag", "v4.0", "refs/heads/main"]);
676- let published = fx.release("v4.0", false).await;
677- let reply = send(
678- &fx.app,
679- "POST",
680- &format!("/tahinli/proj/releases/{}/edit", published.id),
681- Some(&fx.tahinli_cookie),
682- Some(FORM_TYPE),
683- form(&[
684- ("csrf", CSRF),
685- ("tag", "v4.1"),
686- ("target", ""),
687- ("title", "Release v4.0"),
688- ("body", "notes"),
689- ]),
690- )
691- .await;
692- assert_eq!(reply.status, 303, "body: {}", reply.text());
693- assert!(reply.location.unwrap_or_default().contains("notice=saved"));
694- let moved = fx
695- .store
696- .release(&published.id)
697- .await
698- .expect("read")
699- .expect("row");
700- assert_eq!(moved.tag, "v4.1");
701- assert_eq!(fx.tag_target("v4.1"), Some(fx.main_tip()));
702- assert_eq!(
703- fx.tag_target("v4.0"),
704- Some(fx.main_tip()),
705- "old git tag kept"
706- );
707- }
616+ git(&fx.bare, &["tag", "v4.0", "refs/heads/main"]);
617+ let published = fx.release("v4.0", false).await;
618+ let reply = send(
619+ &fx.app,
620+ "POST",
621+ &format!("/tahinli/proj/releases/{}/edit", published.id),
622+ Some(&fx.tahinli_cookie),
623+ Some(FORM_TYPE),
624+ form(&[
625+ ("csrf", CSRF),
626+ ("tag", "v4.1"),
627+ ("target", ""),
628+ ("title", "Release v4.0"),
629+ ("body", "notes"),
630+ ]),
631+ )
632+ .await;
633+ assert_eq!(reply.status, 303, "body: {}", reply.text());
634+ assert!(reply.location.unwrap_or_default().contains("notice=saved"));
635+ let moved = fx
636+ .store
637+ .release(&published.id)
638+ .await
639+ .expect("read")
640+ .expect("row");
641+ assert_eq!(moved.tag, "v4.1");
642+ assert_eq!(fx.tag_target("v4.1"), Some(fx.main_tip()));
643+ assert_eq!(
644+ fx.tag_target("v4.0"),
645+ Some(fx.main_tip()),
646+ "old git tag kept"
647+ );
708648
709- // A published target move is refused on the page, and the typed values stay.
710- {
711- git(&fx.bare, &["tag", "v5.0", "refs/heads/main"]);
712- second_commit(&fx);
713- fx.release("v5.0", false).await;
714- let published = fx
715- .store
716- .release_by_tag(&fx.repo.id, "v5.0")
717- .await
718- .expect("read")
719- .expect("row");
720- let reply = send(
721- &fx.app,
722- "POST",
723- &format!("/tahinli/proj/releases/{}/edit", published.id),
724- Some(&fx.tahinli_cookie),
725- Some(FORM_TYPE),
726- form(&[
727- ("csrf", CSRF),
728- ("tag", "v5.0"),
729- ("target", "next"),
730- ("title", "Typed title"),
731- ("body", "notes"),
732- ]),
733- )
734- .await;
735- assert_eq!(
736- reply.status,
737- 200,
738- "a refused save re-renders: {}",
739- reply.text()
740- );
741- let html = reply.text();
742- assert!(html.contains("pick a new tag"), "{html}");
743- assert!(
744- html.contains("Typed title"),
745- "the typed title stays: {html}"
746- );
747- assert_eq!(fx.tag_target("v5.0"), Some(fx.main_tip()));
748- }
649+ git(&fx.bare, &["tag", "v5.0", "refs/heads/main"]);
650+ second_commit(&fx);
651+ fx.release("v5.0", false).await;
652+ let published = fx
653+ .store
654+ .release_by_tag(&fx.repo.id, "v5.0")
655+ .await
656+ .expect("read")
657+ .expect("row");
658+ let reply = send(
659+ &fx.app,
660+ "POST",
661+ &format!("/tahinli/proj/releases/{}/edit", published.id),
662+ Some(&fx.tahinli_cookie),
663+ Some(FORM_TYPE),
664+ form(&[
665+ ("csrf", CSRF),
666+ ("tag", "v5.0"),
667+ ("target", "next"),
668+ ("title", "Typed title"),
669+ ("body", "notes"),
670+ ]),
671+ )
672+ .await;
673+ assert_eq!(
674+ reply.status,
675+ 200,
676+ "a refused save re-renders: {}",
677+ reply.text()
678+ );
679+ let html = reply.text();
680+ assert!(html.contains("pick a new tag"), "{html}");
681+ assert!(
682+ html.contains("Typed title"),
683+ "the typed title stays: {html}"
684+ );
685+ assert_eq!(fx.tag_target("v5.0"), Some(fx.main_tip()));
749686 }
750687
751688 #[tokio::test]
752689 async fn asset_upload_replace_download_delete_and_csrf_rules() {
753690 let fx = fixture(None).await;
754691
755- // Upload then download round-trips the bytes and counts each download.
756- {
757- let rel = fx.release("v1.0", false).await;
758- let payload = b"<html>not rendered</html>";
759- let reply = fx
760- .upload(&rel.id, "app.bin", payload, &fx.tahinli_cookie)
761- .await;
762- assert_eq!(reply.status, 303, "body: {}", reply.text());
763- assert!(
764- reply
765- .location
766- .unwrap_or_default()
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- }
692+ let rel = fx.release("v1.0", false).await;
693+ let payload = b"<html>not rendered</html>";
694+ let reply = fx
695+ .upload(&rel.id, "app.bin", payload, &fx.tahinli_cookie)
696+ .await;
697+ assert_eq!(reply.status, 303, "body: {}", reply.text());
698+ assert!(
699+ reply
700+ .location
701+ .unwrap_or_default()
702+ .contains("notice=asset-uploaded")
703+ );
816704
817- // A same-name upload replaces the file and keeps its download counter.
818- {
819- let rel = fx.release("v1.1", false).await;
820- let first = fx
821- .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)
822- .await;
823- assert_eq!(first.status, 303);
824- let before = fx
705+ let row = fx
706+ .store
707+ .release_asset(&rel.id, "app.bin")
708+ .await
709+ .expect("read")
710+ .expect("asset row");
711+ assert_eq!(row.size, payload.len() as u64);
712+ 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
825735 .store
826736 .release_asset(&rel.id, "app.bin")
827737 .await
828738 .expect("read")
829739 .expect("row");
830- fx.store
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");
740+ assert_eq!(counted.download_count, expected, "download counter");
870741 }
871742
872- // Replacing by asset name keeps the name, whatever the new file is called.
873- {
874- let rel = fx.release("v1.2", false).await;
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- )
743+ let rel = fx.release("v1.1", false).await;
744+ let first = fx
745+ .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)
888746 .await;
889- assert!(
890- page.text().contains("name=\"name\" value=\"app.bin\""),
891- "each asset has a replace form"
892- );
747+ assert_eq!(first.status, 303);
748+ let before = fx
749+ .store
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");
893758
894- let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[
895- ("csrf", None, CSRF.as_bytes()),
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- )
759+ let second = fx
760+ .upload(&rel.id, "app.bin", b"second bytes", &fx.tahinli_cookie)
931761 .await;
932- assert_eq!(got.body, b"second bytes");
933- }
762+ assert!(
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");
934786
935- // A wrong CSRF token on upload is refused and stores nothing.
936- {
937- let rel = fx.release("v1.3", false).await;
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- )
787+ let rel = fx.release("v1.2", false).await;
788+ let first = fx
789+ .upload(&rel.id, "app.bin", b"first", &fx.tahinli_cookie)
950790 .await;
951- assert_ne!(reply.status, 303, "csrf mismatch");
952- assert!(
953- fx.store
954- .list_release_assets(&rel.id)
955- .await
956- .expect("assets")
957- .is_empty()
958- );
959- }
791+ assert_eq!(first.status, 303);
792+
793+ let page = send(
794+ &fx.app,
795+ "GET",
796+ &format!("/tahinli/proj/releases/{}/edit", rel.id),
797+ Some(&fx.tahinli_cookie),
798+ None,
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+ );
960806
961- // Deleting a release keeps its git tag and removes its assets and blobs.
962- {
963- git(&fx.bare, &["tag", "v1.4", "refs/heads/main"]);
964- let rel = fx.release("v1.4", false).await;
965- let up = fx
966- .upload(&rel.id, "gone.bin", b"bytes", &fx.tahinli_cookie)
967- .await;
968- assert_eq!(up.status, 303);
969- let asset = fx
970- .store
971- .release_asset(&rel.id, "gone.bin")
807+ let (content_type, body) = crate::pages::settings_profile::tests::multipart(&[
808+ ("csrf", None, CSRF.as_bytes()),
809+ ("name", None, "app.bin".as_bytes()),
810+ (
811+ "file",
812+ Some(("renamed-build.zip", "application/octet-stream")),
813+ "second bytes".as_bytes(),
814+ ),
815+ ]);
816+ let reply = send(
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)
972857 .await
973- .expect("read")
974- .expect("row");
975- let blob = crate::blobs::asset_key(&asset.id);
976- assert!(fx.state.blobs.read(&blob).await.expect("read").is_some());
858+ .expect("assets")
859+ .is_empty()
860+ );
977861
978- let reply = send(
979- &fx.app,
980- "POST",
981- &format!("/tahinli/proj/releases/{}/delete", rel.id),
982- Some(&fx.tahinli_cookie),
983- Some(FORM_TYPE),
984- form(&[("csrf", CSRF), ("confirm", "on")]),
985- )
862+ git(&fx.bare, &["tag", "v1.4", "refs/heads/main"]);
863+ let rel = fx.release("v1.4", false).await;
864+ let up = fx
865+ .upload(&rel.id, "gone.bin", b"bytes", &fx.tahinli_cookie)
986866 .await;
987- assert_eq!(reply.status, 303);
988- assert!(fx.store.release(&rel.id).await.expect("read").is_none());
989- assert!(fx.tag_target("v1.4").is_some(), "the git tag survives");
990- assert!(
991- fx.state.blobs.read(&blob).await.expect("read").is_none(),
992- "the blob is gone"
993- );
994- let download = send(
995- &fx.app,
996- "GET",
997- "/tahinli/proj/releases/download/v1.4/gone.bin",
998- None,
999- None,
1000- Vec::new(),
1001- )
1002- .await;
1003- assert_eq!(download.status, 404, "a deleted asset does not download");
1004- }
867+ assert_eq!(up.status, 303);
868+ let asset = fx
869+ .store
870+ .release_asset(&rel.id, "gone.bin")
871+ .await
872+ .expect("read")
873+ .expect("row");
874+ let blob = asset_key(&asset.id);
875+ assert!(fx.state.blobs.read(&blob).await.expect("read").is_some());
876+
877+ let reply = send(
878+ &fx.app,
879+ "POST",
880+ &format!("/tahinli/proj/releases/{}/delete", rel.id),
881+ Some(&fx.tahinli_cookie),
882+ Some(FORM_TYPE),
883+ form(&[("csrf", CSRF), ("confirm", "on")]),
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");
1005895 }
1006896
1007897 #[tokio::test]
@@ -1009,175 +899,131 @@ async fn the_size_cap_refuses_new_and_replacement_uploads() {
1009899 let fx = fixture(Some(1)).await;
1010900 let big = vec![7u8; 1024 * 1024 + 4096];
1011901
1012- // Runs first: no blob may exist yet, so the blob directory must stay empty.
1013- {
1014- let rel = fx.release("v1.0", false).await;
1015- let reply = fx
1016- .upload(&rel.id, "big.bin", &big, &fx.tahinli_cookie)
1017- .await;
1018- assert_eq!(reply.status, 303);
1019- assert!(
1020- reply
1021- .location
1022- .unwrap_or_default()
1023- .contains("notice=asset-too-large"),
1024- "the cap refuses the file"
1025- );
1026- assert!(
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")
902+ let rel = fx.release("v1.0", false).await;
903+ let reply = fx
904+ .upload(&rel.id, "big.bin", &big, &fx.tahinli_cookie)
905+ .await;
906+ assert_eq!(reply.status, 303);
907+ assert!(
908+ reply
909+ .location
910+ .unwrap_or_default()
911+ .contains("notice=asset-too-large"),
912+ "the cap refuses the file"
913+ );
914+ assert!(
915+ fx.store
916+ .list_release_assets(&rel.id)
1058917 .await
1059- .expect("read")
1060- .expect("row");
1061- assert_eq!(row.size, 7, "the old size stays");
1062- let got = send(
1063- &fx.app,
1064- "GET",
1065- "/tahinli/proj/releases/download/v1.1/app.bin",
1066- None,
1067- None,
1068- Vec::new(),
1069- )
918+ .expect("assets")
919+ .is_empty()
920+ );
921+ let assets_dir = fx.state.config.data_dir.join("blobs").join("assets");
922+ let leftovers = std::fs::read_dir(&assets_dir)
923+ .map(|entries| entries.count())
924+ .unwrap_or(0);
925+ assert_eq!(leftovers, 0, "no partial blob is left behind");
926+
927+ let rel = fx.release("v1.1", false).await;
928+ fx.upload(&rel.id, "app.bin", b"keep me", &fx.tahinli_cookie)
1070929 .await;
1071- assert_eq!(got.body, b"keep me", "the old bytes stay");
1072- }
930+ let reply = fx
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");
1073949 }
1074950
1075-/// The live streams of the release list and a release page: a change from another session wakes
1076-/// them, and a reader without the access the page needs gets the page's 404.
1077-mod live_tests {
1078- use super::*;
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
951+async fn open(fx: &Fixture, uri: &str, cookie: Option<&str>) -> Response {
952+ let mut builder = Request::builder().method("GET").uri(uri);
953+ if let Some(cookie) = cookie {
954+ builder = builder.header("cookie", cookie);
1091955 }
956+ fx.app
957+ .handle(builder.body(Body::empty()).expect("request"))
958+ .await
959+}
1092960
1093- const CHANGED: &[u8] = b"event: changed\ndata: 1\n\n";
1094-
1095- #[tokio::test]
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- }
961+#[tokio::test]
962+async fn live_streams_wake_on_changes_and_hide_drafts() {
963+ let fx = fixture(None).await;
1127964
1128- #[tokio::test]
1129- async fn an_asset_upload_and_a_download_each_wake_the_list() {
1130- let fx = fixture(None).await;
1131- let rel = fx.release("v1.0", false).await;
1132- let mut list = open(&fx, "/tahinli/proj/releases/events", None)
1133- .await
1134- .into_body()
1135- .into_data_stream();
1136- let retry = list.next().await.expect("a frame").expect("data");
1137- assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1138-
1139- let uploaded = fx
1140- .upload(&rel.id, "app.tar.gz", b"bytes", &fx.tahinli_cookie)
1141- .await;
1142- assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());
1143- assert_eq!(
1144- &list.next().await.expect("a frame").expect("data")[..],
1145- CHANGED
1146- );
965+ let rel = fx.release("v1.0", false).await;
966+ let list = open(&fx, "/tahinli/proj/releases/events", None).await;
967+ assert_eq!(list.status().as_u16(), 200);
968+ let mut list = list.into_body().into_data_stream();
969+ let page = open(&fx, "/tahinli/proj/releases/tag/v1.0/events", None).await;
970+ assert_eq!(page.status().as_u16(), 200);
971+ let mut page = page.into_body().into_data_stream();
972+ let retry = list.next().await.expect("a frame").expect("data");
973+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
974+ let retry = page.next().await.expect("a frame").expect("data");
975+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
976+
977+ let edit = EditRelease {
978+ title: "Renamed".to_owned(),
979+ ..keep(&rel)
980+ };
981+ release_ops::update(&fx.state, &fx.repo, &fx.tahinli, &rel, edit)
982+ .await
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+ );
1147992
1148- let download = send(
1149- &fx.app,
1150- "GET",
1151- "/tahinli/proj/releases/download/v1.0/app.tar.gz",
1152- None,
1153- None,
1154- Vec::new(),
1155- )
993+ let rel = fx.release("v1.1", false).await;
994+ let mut list = open(&fx, "/tahinli/proj/releases/events", None)
995+ .await
996+ .into_body()
997+ .into_data_stream();
998+ let retry = list.next().await.expect("a frame").expect("data");
999+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1000+ let uploaded = fx
1001+ .upload(&rel.id, "app.tar.gz", b"bytes", &fx.tahinli_cookie)
11561002 .await;
1157- assert_eq!(download.status, 200);
1158- assert_eq!(
1159- &list.next().await.expect("a frame").expect("data")[..],
1160- CHANGED
1161- );
1162- }
1163-
1164- #[tokio::test]
1165- async fn a_draft_is_not_streamed_to_a_reader_and_its_page_is_404() {
1166- let fx = fixture(None).await;
1167- fx.release("v2.0", true).await;
1168- let uri = "/tahinli/proj/releases/tag/v2.0/events";
1003+ assert_eq!(uploaded.status, 303, "body: {}", uploaded.text());
1004+ assert_eq!(
1005+ &list.next().await.expect("a frame").expect("data")[..],
1006+ CHANGED
1007+ );
1008+ let download = fx.download("v1.1/app.tar.gz").await;
1009+ assert_eq!(download.status, 200);
1010+ assert_eq!(
1011+ &list.next().await.expect("a frame").expect("data")[..],
1012+ CHANGED
1013+ );
11691014
1170- assert_eq!(open(&fx, uri, None).await.status().as_u16(), 404);
1171- assert_eq!(
1172- open(&fx, uri, Some(&fx.bob_cookie)).await.status().as_u16(),
1173- 404
1174- );
1175- assert_eq!(
1176- open(&fx, uri, Some(&fx.tahinli_cookie))
1177- .await
1178- .status()
1179- .as_u16(),
1180- 200
1181- );
1182- }
1015+ fx.release("v2.0", true).await;
1016+ let uri = "/tahinli/proj/releases/tag/v2.0/events";
1017+ assert_eq!(open(&fx, uri, None).await.status().as_u16(), 404);
1018+ assert_eq!(
1019+ open(&fx, uri, Some(&fx.bob_cookie)).await.status().as_u16(),
1020+ 404
1021+ );
1022+ assert_eq!(
1023+ open(&fx, uri, Some(&fx.tahinli_cookie))
1024+ .await
1025+ .status()
1026+ .as_u16(),
1027+ 200
1028+ );
11831029 }
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-
61 use std::collections::HashMap;
72
83 use forge_core::AuditAction;
@@ -29,18 +24,10 @@ use crate::state::AppState;
2924 use crate::views::parts::{SubPart, head};
3025 use crate::views::shell;
3126
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.
3427 pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"];
3528
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.
4029 const TAB_CODES: &[&str] = &["light", "dark"];
4130
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.
4431 fn present_string<'de, D: Deserializer<'de>>(
4532 de: D,
4633 ) -> std::result::Result<Option<String>, D::Error> {
@@ -55,9 +42,6 @@ struct AppearanceForm {
5542 theme: String,
5643 #[serde(default)]
5744 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.
6145 #[serde(default, deserialize_with = "present_string")]
6246 accent_light: Option<String>,
6347 #[serde(default, deserialize_with = "present_string")]
@@ -68,8 +52,6 @@ struct AppearanceForm {
6852 base_dark: Option<String>,
6953 #[serde(default, deserialize_with = "present_string")]
7054 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.
7355 #[serde(default, deserialize_with = "present_string")]
7456 sound_shown: Option<String>,
7557 #[serde(default, deserialize_with = "present_string")]
@@ -80,12 +62,9 @@ struct Choice {
8062 value: &'static str,
8163 label: &'static str,
8264 selected: bool,
83- /// The hue a preset moves the stripe knob to, as text; empty when the preset has none.
8465 hue: String,
8566 }
8667
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.
8968 struct Stripe {
9069 hue: u16,
9170 vivid: u8,
@@ -93,12 +72,9 @@ struct Stripe {
9372 hex: String,
9473 }
9574
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`.
9875 const ACCENT_VIVID: u8 = 50;
9976 const BASE_VIVID: u8 = 30;
10077
101-/// The lightness a row's hex box uses, in one theme: the accent's, or the background's.
10278 fn row_lightness(base: bool, dark: bool) -> f64 {
10379 match (base, dark) {
10480 (false, true) => 0.75,
@@ -108,8 +84,6 @@ fn row_lightness(base: bool, dark: bool) -> f64 {
10884 }
10985 }
11086
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.
11387 fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String {
11488 let v = f64::from(vivid);
11589 let chroma = if base {
@@ -122,36 +96,14 @@ fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String {
12296 custom_colour::colour(row_lightness(base, dark), chroma, f64::from(hue))
12397 }
12498
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.
14499 struct ColourRow {
100+ lang: Lang,
145101 dark: bool,
146102 base: bool,
147103 legend: &'static str,
148104 field: &'static str,
149105 choices: Vec<Choice>,
150106 stripe: Stripe,
151- custom_label: &'static str,
152- hue_label: &'static str,
153- vivid_label: &'static str,
154- hex_label: &'static str,
155107 }
156108
157109 struct AppearancePage {
@@ -160,16 +112,13 @@ struct AppearancePage {
160112 theme: Vec<Choice>,
161113 language: Vec<Choice>,
162114 colours: &'static str,
163- /// The tab that opens first: the light or the dark colours.
164115 tab: &'static str,
165116 tabs: Vec<Choice>,
166- light: ColourGroup,
167- dark: ColourGroup,
168- /// Whether the run-finished tone is on: the sound switch's checked state.
117+ light: [ColourRow; 2],
118+ dark: [ColourRow; 2],
169119 sound_on: bool,
170120 }
171121
172-/// The label of a language code. The two native names stay as they are in every language.
173122 fn language_label(lang: Lang, code: &str) -> &'static str {
174123 match code {
175124 "auto" => g::t(lang, K::MatchBrowser),
@@ -179,8 +128,6 @@ fn language_label(lang: Lang, code: &str) -> &'static str {
179128 }
180129 }
181130
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.
184131 fn theme_label(lang: Lang, code: &str) -> &'static str {
185132 match code {
186133 "light" => match lang {
@@ -208,7 +155,6 @@ fn choices(
208155 .collect()
209156 }
210157
211-/// The label of a colour tab: the light or the dark theme.
212158 fn tab_label(lang: Lang, code: &str) -> &'static str {
213159 if code == "dark" {
214160 g::t(lang, K::Dark)
@@ -217,7 +163,6 @@ fn tab_label(lang: Lang, code: &str) -> &'static str {
217163 }
218164 }
219165
220-/// Fills in the hue each preset moves the stripe knob to.
221166 fn with_hues(mut list: Vec<Choice>, hue: fn(&str) -> Option<u16>) -> Vec<Choice> {
222167 for choice in &mut list {
223168 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>
225170 list
226171 }
227172
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>`.
230173 fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str {
231174 if hue_of(stored).is_some() {
232175 stored
@@ -235,9 +178,6 @@ fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str {
235178 }
236179 }
237180
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.
241181 fn stripe(stored: &str, preset: Option<u16>, base: bool, dark: bool) -> Stripe {
242182 let default_vivid = if base { BASE_VIVID } else { ACCENT_VIVID };
243183 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 {
252192 }
253193 }
254194
255-/// One theme's colour choices, with the stored background and accent selected.
256-fn colour_group(lang: Lang, dark: bool, base: &str, accent_id: &str) -> ColourGroup {
195+fn colour_group(lang: Lang, dark: bool, base: &str, accent_id: &str) -> [ColourRow; 2] {
257196 let base_codes: Vec<&'static str> = accent::base_ids().collect();
258197 let accent_codes: Vec<&'static str> = accent::ids().collect();
259198 let base_shown = shown(base, accent::resolve_base(base).id);
260199 let accent_shown = shown(accent_id, accent::resolve(accent_id).id);
261- ColourGroup {
262- dark,
263- background: g::t(lang, K::BackgroundLabel),
264- accent: g::t(lang, K::AccentRowLabel),
265- custom: g::t(lang, K::CustomLabel),
266- hue: g::t(lang, K::HueLabel),
267- vividness: g::t(lang, K::VividnessLabel),
268- hex: g::t(lang, K::HexLabel),
269- bases: with_hues(
270- choices(&base_codes, base_shown, |id| base_name(lang, id)),
271- preset_base_hue,
272- ),
273- accents: with_hues(
274- choices(&accent_codes, accent_shown, |id| accent_name(lang, id)),
275- preset_accent_hue,
276- ),
277- base_stripe: stripe(base, preset_base_hue(base_shown), true, dark),
278- accent_stripe: stripe(accent_id, preset_accent_hue(accent_shown), false, dark),
279- }
200+ let (base_field, accent_field) = if dark {
201+ ("base_dark", "accent_dark")
202+ } else {
203+ ("base_light", "accent_light")
204+ };
205+ [
206+ ColourRow {
207+ lang,
208+ dark,
209+ base: true,
210+ legend: g::t(lang, K::BackgroundLabel),
211+ field: base_field,
212+ choices: with_hues(
213+ choices(&base_codes, base_shown, |id| base_name(lang, id)),
214+ preset_base_hue,
215+ ),
216+ stripe: stripe(base, preset_base_hue(base_shown), true, dark),
217+ },
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+ ]
280231 }
281232
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.
285233 #[component]
286234 async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> {
287235 let ColourRow {
236+ lang,
288237 dark,
289238 base,
290239 legend,
291240 field,
292241 choices,
293242 stripe,
294- custom_label,
295- hue_label,
296- vivid_label,
297- hex_label,
298243 } = 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);
299248 let value = custom_id(stripe.hue, stripe.vivid);
300249 let hue_value = stripe.hue.to_string();
301250 let vivid_value = stripe.vivid.to_string();
@@ -350,57 +299,6 @@ async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> {
350299 })
351300 }
352301
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-
404302 #[component]
405303 async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
406304 let AppearancePage {
@@ -411,8 +309,8 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
411309 colours,
412310 tab,
413311 tabs,
414- light,
415- dark,
312+ light: [light_base, light_accent],
313+ dark: [dark_base, dark_accent],
416314 sound_on,
417315 } = page;
418316 Ok(view! {
@@ -456,8 +354,14 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
456354 }
457355 </div>
458356 </div>
459- colour_panel(group: light)
460- colour_panel(group: dark)
357+ <div class="colour-panel" data-colour-panel="light">
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>
461365 </fieldset>
462366 </section>
463367 <section class="sec">
@@ -486,7 +390,6 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> {
486390 })
487391 }
488392
489-/// Rejects a theme or a language that is not offered. Nothing is saved for either of them.
490393 fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> {
491394 if !THEMES.contains(&theme) {
492395 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<(
497400 Ok(())
498401 }
499402
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.
502403 fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
503404 match posted {
504405 None => Ok(stored.to_owned()),
@@ -507,8 +408,6 @@ fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::
507408 }
508409 }
509410
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.
512411 fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
513412 match posted {
514413 None => Ok(stored.to_owned()),
@@ -517,8 +416,6 @@ fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Re
517416 }
518417 }
519418
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.
522419 fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> {
523420 match posted {
524421 None => Ok(stored.to_owned()),
@@ -527,15 +424,11 @@ fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core:
527424 }
528425 }
529426
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`).
532427 #[cfg(test)]
533428 pub fn sidebar_stored(stored: &str) -> &'static str {
534429 if stored == "right" { "right" } else { "left" }
535430 }
536431
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.
539432 fn page_for(
540433 viewer: &(User, Session),
541434 lang: Lang,
@@ -543,8 +436,6 @@ fn page_for(
543436 ) -> AppearancePage {
544437 let user = &viewer.0;
545438 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.
548439 let tab = if user.theme == "dark" {
549440 "dark"
550441 } else {
@@ -553,7 +444,7 @@ fn page_for(
553444 AppearancePage {
554445 lang,
555446 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)),
557448 language: choices(LANGUAGE_CODES, &user.language, |code| {
558449 language_label(lang, code)
559450 }),
@@ -566,8 +457,6 @@ fn page_for(
566457 }
567458 }
568459
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.
571460 fn pref_choice(
572461 lang: Lang,
573462 posted: Option<&str>,
@@ -612,8 +501,6 @@ async fn appearance_save(cx: &Cx, Form(form): Form<AppearanceForm>) -> Result<Se
612501 let base_light = base_choice(lang, form.base_light.as_deref(), &user.base_light)?;
613502 let base_dark = base_choice(lang, form.base_dark.as_deref(), &user.base_dark)?;
614503 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.
617504 let posted_sound = match (&form.sound_shown, &form.sound) {
618505 (Some(_), None) => Some("off"),
619506 (_, Some(value)) => Some(value.as_str()),
@@ -738,7 +625,6 @@ mod tests {
738625 "base upper case {id}"
739626 );
740627 }
741- // Removed presets, and hue values that are out of range or not canonical, are refused.
742628 for id in [
743629 "teal",
744630 "moss",
@@ -772,7 +658,6 @@ mod tests {
772658 );
773659 }
774660
775- // An absent colour keeps the stored value.
776661 assert_eq!(
777662 accent_choice(Lang::En, None, "plum").unwrap(),
778663 "plum",
@@ -796,11 +681,9 @@ mod tests {
796681 assert!(base_err.to_string().contains("background"), "{base_err}");
797682 }
798683
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.
801684 #[test]
802685 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));
804687 let selected: Vec<&str> = options
805688 .iter()
806689 .filter(|c| c.selected)
@@ -822,44 +705,42 @@ mod tests {
822705 "accent: default first"
823706 );
824707
825- let group = colour_group(Lang::En, true, "ink", "plum");
826- let bases: Vec<&str> = group
827- .bases
708+ let [base_row, _] = colour_group(Lang::En, true, "ink", "plum");
709+ let bases: Vec<&str> = base_row
710+ .choices
828711 .iter()
829712 .filter(|c| c.selected)
830713 .map(|c| c.value)
831714 .collect();
832715 assert_eq!(bases, ["ink"], "base: selected");
833716 assert_eq!(
834- group.bases[0].value,
717+ base_row.choices[0].value,
835718 forge_web_app::accent_palette::BASE_DEFAULT,
836719 "base: default first"
837720 );
838721
839- // A custom hue fills the stripe and checks no preset.
840- let group = colour_group(Lang::En, false, "hue-200", "hue-40");
841- assert!(group.base_stripe.custom, "custom base hue");
842- assert_eq!(group.base_stripe.hue, 200, "custom base hue value");
843- assert!(group.accent_stripe.custom, "custom accent hue");
844- assert_eq!(group.accent_stripe.hue, 40, "custom accent hue value");
722+ let [base_row, accent_row] = colour_group(Lang::En, false, "hue-200", "hue-40");
723+ assert!(base_row.stripe.custom, "custom base hue");
724+ assert_eq!(base_row.stripe.hue, 200, "custom base hue value");
725+ assert!(accent_row.stripe.custom, "custom accent hue");
726+ assert_eq!(accent_row.stripe.hue, 40, "custom accent hue value");
845727 assert!(
846- group.bases.iter().all(|c| !c.selected),
728+ base_row.choices.iter().all(|c| !c.selected),
847729 "custom hue: no base preset checked"
848730 );
849731 assert!(
850- group.accents.iter().all(|c| !c.selected),
732+ accent_row.choices.iter().all(|c| !c.selected),
851733 "custom hue: no accent preset checked"
852734 );
853735
854- // A preset moves the knob to its own hue.
855- let group = colour_group(Lang::En, true, "ink", "plum");
736+ let [base_row, accent_row] = colour_group(Lang::En, true, "ink", "plum");
856737 let plum_hue = preset_accent_hue("plum").unwrap();
857738 let ink_hue = preset_base_hue("ink").unwrap();
858- assert!(!group.accent_stripe.custom, "preset accent: not custom");
859- assert_eq!(group.accent_stripe.hue, plum_hue, "preset accent: knob hue");
860- assert!(!group.base_stripe.custom, "preset base: not custom");
861- assert_eq!(group.base_stripe.hue, ink_hue, "preset base: knob hue");
862- let plum = group.accents.iter().find(|c| c.value == "plum").unwrap();
739+ assert!(!accent_row.stripe.custom, "preset accent: not custom");
740+ assert_eq!(accent_row.stripe.hue, plum_hue, "preset accent: knob hue");
741+ assert!(!base_row.stripe.custom, "preset base: not custom");
742+ assert_eq!(base_row.stripe.hue, ink_hue, "preset base: knob hue");
743+ let plum = accent_row.choices.iter().find(|c| c.value == "plum").unwrap();
863744 assert!(plum.selected, "preset accent: checked");
864745 assert_eq!(plum.hue, plum_hue.to_string(), "preset accent: hue value");
865746
@@ -870,11 +751,10 @@ mod tests {
870751 assert_eq!(hue_of("sage"), None, "hue: preset id");
871752 }
872753
873- /// A stored `hue-95-v80` fills the hue and vividness sliders, and the Custom value is that id again.
874754 #[test]
875755 fn a_stored_hue_and_vividness_fill_the_sliders() {
876- let group = colour_group(Lang::En, true, "hue-95-v80", "hue-95-v80");
877- let accent = &group.accent_stripe;
756+ let [base_row, accent_row] = colour_group(Lang::En, true, "hue-95-v80", "hue-95-v80");
757+ let accent = &accent_row.stripe;
878758 assert_eq!((accent.hue, accent.vivid), (95, 80), "accent: sliders");
879759 assert!(accent.custom, "accent: custom");
880760 assert_eq!(
@@ -883,7 +763,7 @@ mod tests {
883763 "accent: value"
884764 );
885765 assert_eq!(
886- (group.base_stripe.hue, group.base_stripe.vivid),
766+ (base_row.stripe.hue, base_row.stripe.vivid),
887767 (95, 80),
888768 "base: sliders"
889769 );
crates/forge-web-account/src/pages/settings_export.rsmodified+9 -11
@@ -59,6 +59,10 @@ fn signature(exports: &[DataExport]) -> String {
5959 .join(",")
6060 }
6161
62+fn is_building(exports: &[DataExport]) -> bool {
63+ exports.iter().any(|e| e.state == ExportState::Building)
64+}
65+
6266 /// The rail of the Data page: the archives, and the delete-account topic.
6367 fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> {
6468 vec![
@@ -85,7 +89,7 @@ async fn export_sheet(
8589 csrf: &str,
8690 exports: Vec<DataExport>,
8791 ) -> Result<impl View> {
88- let building = exports.iter().any(|e| e.state == ExportState::Building);
92+ let building = is_building(&exports);
8993 let live = building.then(|| {
9094 format!(
9195 "/settings/export/events?v={}",
@@ -93,10 +97,6 @@ async fn export_sheet(
9397 )
9498 });
9599 let empty = exports.is_empty();
96- let deletes: Vec<String> = exports
97- .iter()
98- .map(|e| format!("/settings/export/{}/delete", e.id))
99- .collect();
100100 Ok(view! {
101101 <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })>
102102 <section class="sec">
@@ -104,7 +104,8 @@ async fn export_sheet(
104104 if empty {
105105 <p class="state">(g::t(lang, K::ExportNone))</p>
106106 }
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);
108109 <div class="export-row">
109110 <div class="line">
110111 <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(
217218 } else {
218219 g::t(lang, K::ExportTitle)
219220 };
220- let building = exports.iter().any(|e| e.state == ExportState::Building);
221+ let building = is_building(&exports);
221222 Ok(view! {
222223 head(title: title, sub: Vec::<SubPart>::new(),
223224 if !delete {
@@ -267,9 +268,6 @@ async fn page_view(
267268 None => StatusCode::OK,
268269 };
269270 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;
273271 Ok(view! {
274272 (status)
275273 (headers)
@@ -349,7 +347,7 @@ async fn export_events(cx: &Cx) -> Result<Response> {
349347 loop {
350348 let exports = store.list_exports(&user_id).await.ok()?;
351349 let sig = signature(&exports);
352- let building = exports.iter().any(|e| e.state == ExportState::Building);
350+ let building = is_building(&exports);
353351 if sig != seen {
354352 seen = sig;
355353 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;
88 use topcoat::context::{Cx, context};
99 use topcoat::router::content::Form;
1010 use topcoat::router::error::{SeeOther, not_found, see_other};
11-use topcoat::router::{page, query_params, route};
11+use topcoat::router::{page, route};
1212 use topcoat::view::{View, component, view};
1313
1414 use crate::audit::{self, Actor, Target};
15-use crate::auth::{require_csrf, require_user};
15+use crate::auth::require_csrf;
1616 use crate::i18n::s;
1717 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};
1919 use crate::signatures;
2020 use crate::state::AppState;
2121 use crate::views::parts::confirm_act;
@@ -86,16 +86,7 @@ pub(crate) async fn gpg_section(
8686
8787 #[page("/settings/gpg")]
8888 async fn gpg_page(cx: &Cx) -> Result<impl View> {
89- let viewer = require_user(cx).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- })
89+ kind_page(cx, KeyKind::Gpg).await
9990 }
10091
10192 #[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};
1919 use crate::pages::settings_gpg::gpg_section;
2020 use crate::pages::settings_tokens::tokens_section;
2121 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};
2323 use crate::views::{added_status, alert, shell, user_facing_message};
2424
2525 /// Algorithms accepted for web-registered keys. `ssh-rsa` is rejected with its own message.
@@ -32,6 +32,7 @@ const ACCEPTED: &[&str] = &[
3232 "sk-ecdsa-sha2-nistp256@openssh.com",
3333 ];
3434 const MAX_KEY_CHARS: usize = 16 * 1024;
35+const MAX_TITLE_CHARS: usize = 100;
3536
3637 /// Why a pasted key line is refused. `message` says it in the viewer's language.
3738 #[derive(Debug, PartialEq, Eq)]
@@ -221,7 +222,6 @@ pub(crate) async fn keys_page_view(
221222 current: k == kind,
222223 })
223224 .collect();
224- let sub = Vec::<SubPart>::new();
225225 let add_href = format!("{}?add=1", kind.href());
226226 let add_open = draft.add
227227 || draft.ssh_error.is_some()
@@ -231,7 +231,7 @@ pub(crate) async fn keys_page_view(
231231 let parents = vec![(pk_title(lang).to_owned(), "/settings/keys".to_owned())];
232232 Ok(view! {
233233 shell(title: kind.title(lang), viewer: Some(viewer), parents: parents,
234- head(title: kind.title(lang), sub: sub,
234+ head(title: kind.title(lang),
235235 <a class="button primary" href=(add_href)>(kind.add_label(lang))</a>
236236 )
237237 <div class="work">
@@ -301,8 +301,7 @@ async fn ssh_section(
301301 })
302302 }
303303
304-#[page("/settings/keys")]
305-async fn keys_page(cx: &Cx) -> Result<impl View> {
304+pub(crate) async fn kind_page(cx: &Cx, kind: KeyKind) -> Result<impl View> {
306305 let viewer = require_user(cx).await?;
307306 let lang = i18n::lang(cx, Some(&viewer.0));
308307 let state = context::<AppState>(cx);
@@ -311,10 +310,15 @@ async fn keys_page(cx: &Cx) -> Result<impl View> {
311310 ..KeysDraft::default()
312311 };
313312 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)
315314 })
316315 }
317316
317+#[page("/settings/keys")]
318+async fn keys_page(cx: &Cx) -> Result<impl View> {
319+ kind_page(cx, KeyKind::Ssh).await
320+}
321+
318322 #[page(POST "/settings/keys")]
319323 async fn keys_add(cx: &Cx, Form(form): Form<AddKeyForm>) -> Result<impl View> {
320324 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> {
330334 "" => parsed.algorithm.clone(),
331335 t => t.to_owned(),
332336 };
337+ let title: String = title.chars().take(MAX_TITLE_CHARS).collect();
333338 match store
334339 .add_ssh_key(
335340 &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-
241 use std::collections::VecDeque;
252
263 use forge_core::server_settings::{self, FIELDS, Kind};
@@ -36,8 +13,6 @@ use crate::auth::current_user;
3613 use crate::live::{LiveHub, Topic, events_response, stream_wakes};
3714 use crate::state::AppState;
3815
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.
4116 #[route(GET "/settings/events")]
4217 async fn settings_events(cx: &Cx) -> Result<Response> {
4318 let Some((user, _)) = current_user(cx).await? else {
@@ -49,22 +24,16 @@ async fn settings_events(cx: &Cx) -> Result<Response> {
4924 stream_wakes(cx, hub, &[Topic::Account(user.id)])
5025 }
5126
52-/// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value means
53-/// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so
54-/// a tab that applies it shows what a fresh load of the page would show. The last pair, `custom_css`,
55-/// is the stylesheet of the hue choices (empty for presets only); `nav.js` applies only `data-*`
56-/// pairs, so it reads this one itself.
57-/// The account state the alive stream compares: the appearance (see below), the language
58-/// preference, which changes the page text rather than its attributes, and the identity the
59-/// header shows (the username, the avatar's hash, admin rights) with whether the viewer's session
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> {
27+#[derive(Default, PartialEq)]
28+struct AccountState {
29+ appearance: String,
30+ language: String,
31+ identity: String,
32+}
33+
34+async fn account_state(state: &AppState, user_id: &str, session_id: &str) -> Result<AccountState> {
6635 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());
6837 };
6938 let theme = match crate::theme::Theme::from_stored(&user.theme) {
7039 crate::theme::Theme::Auto => "",
@@ -79,7 +48,6 @@ pub async fn account_state(
7948 let accent_dark = crate::accent::accent_id(&user.accent_dark);
8049 let base_light = crate::accent::base_id(&user.base_light);
8150 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`).
8351 let custom_css =
8452 crate::accent::custom_css_href(accent_light, accent_dark, base_light, base_dark)
8553 .unwrap_or_default();
@@ -97,15 +65,13 @@ pub async fn account_state(
9765 "{}\n{avatar}\n{}\n{session_open}",
9866 user.username, user.is_admin
9967 );
100- Ok((appearance, user.language.clone(), identity))
68+ Ok(AccountState {
69+ appearance,
70+ language: user.language.clone(),
71+ identity,
72+ })
10173 }
10274
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.
10975 struct AccountFollow {
11076 user_id: String,
11177 session_id: String,
@@ -113,25 +79,19 @@ struct AccountFollow {
11379 last: AccountState,
11480 }
11581
116-/// What the alive stream holds between events.
11782 struct Alive {
11883 state: AppState,
119- /// Present for a signed-in viewer only.
12084 account: Option<AccountFollow>,
12185 server_wake: watch::Receiver<u64>,
122- /// The server settings fingerprint last sent or seen (see [`settings_fingerprint`]).
12386 settings_last: String,
12487 queue: VecDeque<Event>,
12588 }
12689
127-/// What woke the alive stream.
12890 enum Wake {
12991 Account,
13092 Settings,
13193 }
13294
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.
13595 pub fn settings_fingerprint(state: &AppState) -> String {
13696 let live = state.live();
13797 FIELDS
@@ -142,7 +102,6 @@ pub fn settings_fingerprint(state: &AppState) -> String {
142102 .join("\n")
143103 }
144104
145-/// Waits for the viewer's account topic. A stream with no signed-in viewer waits on nothing.
146105 async fn wait_account(account: &mut Option<AccountFollow>) -> bool {
147106 match account {
148107 Some(follow) => follow.wake.changed().await.is_ok(),
@@ -150,15 +109,7 @@ async fn wait_account(account: &mut Option<AccountFollow>) -> bool {
150109 }
151110 }
152111
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.
160112 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.
162113 let Some(state) = try_context::<AppState>(cx).cloned() else {
163114 return events_response(cx, stream::pending::<Result<Event>>());
164115 };
@@ -169,14 +120,10 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> {
169120 events_response(cx, events)
170121 }
171122
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.
175123 pub async fn alive_stream(
176124 state: AppState,
177125 viewer: Option<(String, String)>,
178126 ) -> Result<BoxStream<'static, Result<Event>>> {
179- // Subscribed before each baseline is read, so a change in between is not lost.
180127 let server_wake = state.live.subscribe(&Topic::ServerSettings);
181128 let settings_last = settings_fingerprint(&state);
182129 let account = match viewer {
@@ -202,8 +149,6 @@ pub async fn alive_stream(
202149 Ok(stream::unfold(alive, next_alive_event).boxed())
203150 }
204151
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.
207152 async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {
208153 loop {
209154 if let Some(event) = alive.queue.pop_front() {
@@ -251,16 +196,13 @@ async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> {
251196 };
252197 let last = &mut follow.last;
253198 if now != *last {
254- // One change can move several parts: each gets its own event.
255- if now.0 != last.0 {
256- queue.push_back(Event::new().event("theme").data(now.0.clone()));
199+ if now.appearance != last.appearance {
200+ queue.push_back(Event::new().event("theme").data(now.appearance.clone()));
257201 }
258- if now.1 != last.1 {
259- // The page text is re-rendered by the client (a soft refresh, see `nav.js`).
202+ if now.language != last.language {
260203 queue.push_back(Event::new().event("language").data("1"));
261204 }
262- if now.2 != last.2 {
263- // The header or the session changed: the page re-renders (see `nav.js`).
205+ if now.identity != last.identity {
264206 queue.push_back(Event::new().event("account").data("1"));
265207 }
266208 *last = now;
@@ -284,8 +226,6 @@ mod tests {
284226
285227 const CSRF: &str = "settings-live-csrf";
286228
287- /// The settings stream needs a session, and the settings pages name it (and not the old
288- /// theme stream).
289229 #[tokio::test]
290230 async fn the_settings_stream_needs_a_session_and_the_sidebar_names_it() {
291231 let dir = tempfile::tempdir().expect("tempdir");
@@ -369,10 +309,6 @@ mod tests {
369309 );
370310 }
371311
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.
376312 #[tokio::test]
377313 async fn the_settings_stream_sends_changes_and_the_alive_stream_sends_appearance() {
378314 let dir = tempfile::tempdir().expect("tempdir");
@@ -390,7 +326,6 @@ mod tests {
390326 .expect("prefs");
391327 let router = app_router(state);
392328
393- // Settings stream: a retry hint first, then one changed event per write.
394329 let request = Request::builder()
395330 .method("GET")
396331 .uri("/settings/events")
@@ -414,7 +349,6 @@ mod tests {
414349 "settings stream: changed event"
415350 );
416351
417- // Alive stream: no event for a bump that changes no appearance.
418352 let request = Request::builder()
419353 .method("GET")
420354 .uri("/-/alive")
@@ -427,7 +361,6 @@ mod tests {
427361 assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}");
428362
429363 live.bump(&Topic::Account(owner.id.clone()));
430- // One change of theme and language: the theme event first, then the language event.
431364 store
432365 .set_ui_prefs(&owner.id, "dark", "tr")
433366 .await
@@ -451,8 +384,6 @@ mod tests {
451384 );
452385 }
453386
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.
456387 #[tokio::test]
457388 async fn the_alive_stream_sends_settings_to_anonymous_viewers() {
458389 let dir = tempfile::tempdir().expect("tempdir");
@@ -485,8 +416,6 @@ mod tests {
485416 );
486417 }
487418
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.
490419 #[tokio::test]
491420 async fn the_alive_stream_sends_account_when_the_header_changes() {
492421 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};
66
77 use forge_core::AuditAction;
88 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};
1010 use forge_core::tz::{all_timezones, validate_timezone};
1111 use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar};
1212 use serde::Deserialize;
@@ -27,9 +27,6 @@ use crate::state::AppState;
2727 use crate::views::parts::{SubPart, confirm_act, head, reveal};
2828 use crate::views::{alert, avatar_url, shell, user_facing_message};
2929
30-/// Longest "about" text, in characters.
31-pub const MAX_ABOUT_CHARS: usize = 2000;
32-
3330 /// Multipart framing overhead allowed on top of the image itself.
3431 const MULTIPART_OVERHEAD: usize = 64 * 1024;
3532
@@ -210,13 +207,13 @@ async fn profile_body(cx: &Cx, page: ProfilePage) -> Result<impl View> {
210207 }
211208
212209 /// Collects what the profile page shows. `draft` fills the forms; `errors` shows under each section.
213-async fn page_data(
210+fn page_data(
214211 viewer: &(User, Session),
215212 lang: Lang,
216213 draft: Draft,
217214 errors: Errors,
218215 notice: Option<&'static str>,
219-) -> Result<ProfilePage> {
216+) -> ProfilePage {
220217 let hash = viewer.0.avatar_hash.clone();
221218 let zones = all_timezones()
222219 .into_iter()
@@ -225,7 +222,7 @@ async fn page_data(
225222 Zone { name, selected }
226223 })
227224 .collect();
228- Ok(ProfilePage {
225+ ProfilePage {
229226 lang,
230227 csrf: viewer.1.csrf_token.clone(),
231228 draft,
@@ -234,7 +231,7 @@ async fn page_data(
234231 avatar_src: avatar_url(&viewer.0.username, hash.as_deref()),
235232 has_avatar: hash.is_some(),
236233 zones,
237- })
234+ }
238235 }
239236
240237 fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {
@@ -330,8 +327,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> {
330327 draft,
331328 Errors::default(),
332329 notice_for(lang, saved.as_deref()),
333- )
334- .await?;
330+ );
335331 Ok(view! {
336332 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))
337333 })
@@ -374,7 +370,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie
374370 about,
375371 timezone: form.timezone,
376372 };
377- let page = page_data(&viewer, lang, draft, errors, None).await?;
373+ let page = page_data(&viewer, lang, draft, errors, None);
378374 return Ok(view! {
379375 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))
380376 });
@@ -382,10 +378,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie
382378 };
383379
384380 store
385- .set_profile(&viewer.0.id, &about, &form.timezone)
386- .await?;
387- store
388- .set_display_name(&viewer.0.id, &form.display_name)
381+ .save_profile(&viewer.0.id, &form.display_name, &about, &form.timezone)
389382 .await?;
390383 if display != viewer.0.username {
391384 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> {
444437 avatar: Some(message),
445438 ..Errors::default()
446439 };
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);
448441 Ok(view! {
449442 shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page))
450443 })
crates/forge-web-account/src/pages/settings_security.rsmodified+65 -96
@@ -25,8 +25,9 @@ use crate::auth::{
2525 use crate::i18n::packages::{self as pk, K as PK};
2626 use crate::i18n::releases_ci::{self as rc, K as RC};
2727 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};
2929 use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel};
30+use crate::pages::register::check_new_password;
3031 use crate::pages::settings_export;
3132 use crate::pages::settings_sessions::session_label;
3233 use crate::state::AppState;
@@ -34,9 +35,6 @@ use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
3435 use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail};
3536 use crate::views::{added_status, alert, rel_time, shell, user_facing_message};
3637
37-/// Shortest and longest new passwords, in characters.
38-const MIN_PASSWORD_CHARS: usize = 10;
39-const MAX_PASSWORD_CHARS: usize = 1024;
4038 /// Recovery codes issued by each enrollment or regeneration.
4139 const RECOVERY_CODE_COUNT: usize = 10;
4240 /// At or below this many unused recovery codes the page warns and suggests regenerating.
@@ -176,12 +174,6 @@ struct SecurityPage {
176174 email_sent: Option<String>,
177175 /// Whether this server can send mail at all. The resend link shows only when it can.
178176 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>>,
185177 /// Secret (base32) and `otpauth://` URI while enrollment is waiting for a code.
186178 pending: Option<(String, String)>,
187179 /// When the password last changed, shown as a live time, when known.
@@ -193,8 +185,7 @@ struct SecurityPage {
193185 sessions: Vec<Session>,
194186 /// The id of the session that is viewing the page.
195187 current_session_id: String,
196- /// The topic asked for in the address, when no error or notice picks one.
197- part: Option<String>,
188+ shown: Shown,
198189 }
199190
200191 /// 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(
258249 viewer: &(User, Session),
259250 active: &str,
260251 ) -> forge_core::Result<Vec<RailItem>> {
261- let two_factor_on = state
262- .store
263- .totp_state(&viewer.0.id)
264- .await?
265- .is_some_and(|totp| totp.enabled);
252+ let two_factor_on = two_factor_enabled(&state.store, &viewer.0.id).await?;
266253 let passkey_count = state.store.list_passkeys(&viewer.0.id).await?.len();
267254 let session_count = state.store.list_sessions(&viewer.0.id).await?.len();
268255 Ok(security_rail_items(
@@ -284,20 +271,24 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V
284271 email_status,
285272 email_sent,
286273 mail_ready,
287- notice,
288- password_error,
289- email_error,
290- two_factor_error,
291- two_factor_panel,
292- codes,
293274 pending,
294275 password_changed,
295276 two_factor,
296277 passkeys,
297278 sessions,
298279 current_session_id,
299- part,
280+ shown,
300281 } = 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;
301292 let two_factor_on = two_factor.is_some();
302293 let passkey_count = passkeys.items.len();
303294 let session_count = sessions.len();
@@ -310,13 +301,11 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V
310301 let email_open = email_error.is_some();
311302 let email_set = !email.is_empty();
312303 let show_resend = email_set && !email_verified && mail_ready;
313- let regenerate_error = two_factor_error
314- .clone()
315- .filter(|_| two_factor_panel == TwoFactorPanel::Regenerate);
316- let disable_error = two_factor_error
317- .clone()
318- .filter(|_| two_factor_panel == TwoFactorPanel::Disable);
319- let setup_error = two_factor_error.filter(|_| two_factor_panel == TwoFactorPanel::Setup);
304+ let (regenerate_error, disable_error, setup_error) = match two_factor_panel {
305+ TwoFactorPanel::Regenerate => (two_factor_error, None, None),
306+ TwoFactorPanel::Disable => (None, two_factor_error, None),
307+ TwoFactorPanel::Setup => (None, None, two_factor_error),
308+ };
320309 let regenerate_open = regenerate_error.is_some();
321310 let disable_open = disable_error.is_some();
322311 // 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(
629618 }
630619 status
631620 };
621+ let email = shown
622+ .email_draft
623+ .clone()
624+ .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default());
632625 Ok(SecurityPage {
633626 lang,
634627 passkeys: build_panel(state, &viewer.0.id).await?,
@@ -637,30 +630,19 @@ async fn build_page(
637630 email_status,
638631 email_sent,
639632 mail_ready: mail_can_send(state).await,
640- email: shown
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,
633+ email,
649634 pending,
650635 password_changed,
651636 two_factor,
652637 sessions: state.store.list_sessions(&viewer.0.id).await?,
653638 current_session_id: viewer.1.id.clone(),
654- part: shown.part,
639+ shown,
655640 })
656641 }
657642
658643 /// Renders the page. A throttled check answers 429 with `Retry-After`.
659644 async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result<impl View> {
660645 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;
664646 let mut headers = HeaderMap::new();
665647 let status = match shown.throttled {
666648 Some(retry) => {
@@ -722,6 +704,31 @@ fn second_factor_blocked(state: &AppState, user_id: &str) -> Option<Duration> {
722704 )
723705 }
724706
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+
725732 /// Fresh recovery codes and their hashes. The plain codes are for display only.
726733 fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
727734 let codes: Vec<String> = (0..RECOVERY_CODE_COUNT)
@@ -731,21 +738,6 @@ fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
731738 (codes, hashes)
732739 }
733740
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-
749741 #[page("/settings/security")]
750742 async fn security_page(cx: &Cx) -> Result<impl View> {
751743 let viewer = require_user(cx).await?;
@@ -953,18 +945,11 @@ async fn two_factor_disable(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im
953945 shown.throttled = refused.retry;
954946 return respond(cx, viewer, shown).await;
955947 }
956- if let Some(retry) = second_factor_blocked(state, &user_id) {
957- shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into());
958- shown.throttled = Some(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());
948+ if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
949+ shown.two_factor_error = Some(refused.message.into());
950+ shown.throttled = refused.retry;
965951 return respond(cx, viewer, shown).await;
966952 }
967- state.throttle.clear(&key);
968953 state.store.disable_totp(&user_id).await?;
969954 audit::record(
970955 &state.store,
@@ -993,17 +978,10 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result<
993978 return settings_export::respond_delete(cx, viewer, error, refused.retry).await;
994979 }
995980 if two_factor_enabled(&state.store, &user_id).await? {
996- if let Some(retry) = second_factor_blocked(state, &user_id) {
997- let error = Some(t(lang, Key::ErrThrottled).into());
998- return settings_export::respond_delete(cx, viewer, error, Some(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;
981+ if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
982+ let error = Some(refused.message.into());
983+ return settings_export::respond_delete(cx, viewer, error, refused.retry).await;
1005984 }
1006- state.throttle.clear(&key);
1007985 }
1008986 let ghost = state.store.ensure_ghost_user().await?;
1009987 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
10511029 shown.throttled = refused.retry;
10521030 return respond(cx, viewer, shown).await;
10531031 }
1054- if let Some(retry) = second_factor_blocked(state, &user_id) {
1055- shown.two_factor_error = Some(t(lang, Key::ErrThrottled).into());
1056- shown.throttled = Some(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());
1032+ if let Err(refused) = check_second_factor(state, lang, &user_id, &form.code).await? {
1033+ shown.two_factor_error = Some(refused.message.into());
1034+ shown.throttled = refused.retry;
10631035 return respond(cx, viewer, shown).await;
10641036 }
1065- state.throttle.clear(&key);
10661037 let (codes, hashes) = new_recovery_codes();
10671038 state
10681039 .store
@@ -1291,7 +1262,7 @@ mod tests {
12911262 )
12921263 .await;
12931264 assert!(
1294- reply.body.contains("at least 10 characters"),
1265+ reply.body.contains("at least 12 characters"),
12951266 "short password"
12961267 );
12971268 let mismatch = format!(
@@ -1586,9 +1557,8 @@ mod tests {
15861557 &wrong,
15871558 )
15881559 .await;
1589- if reply.status == 200 && !reply.body.contains("Recovery codes") {
1590- assert!(reply.body.contains("That code is not right"), "wrong code");
1591- }
1560+ assert_eq!(reply.status, 200);
1561+ assert!(reply.body.contains("That code is not right"), "wrong code");
15921562 let state = fx
15931563 .state
15941564 .store
@@ -1596,9 +1566,8 @@ mod tests {
15961566 .await
15971567 .unwrap()
15981568 .unwrap();
1599- if !state.enabled {
1600- assert!(state.sealed_secret.is_some(), "wrong code keeps the secret");
1601- }
1569+ assert!(!state.enabled, "wrong code does not enable");
1570+ assert!(state.sealed_secret.is_some(), "wrong code keeps the secret");
16021571
16031572 // An over-long device name is refused before the code is checked, so the code is
16041573 // not spent on it.
crates/forge-web-account/src/pages/settings_tokens.rsmodified+4 -13
@@ -13,17 +13,17 @@ use topcoat::context::{Cx, context};
1313 use topcoat::router::content::Form;
1414 use topcoat::router::error::{SeeOther, see_other};
1515 use topcoat::router::response::response_headers;
16-use topcoat::router::{page, query_params, route};
16+use topcoat::router::{page, route};
1717 use topcoat::view::{View, component, view};
1818
1919 use crate::api::packages::PACKAGES_SCOPE;
2020 use crate::audit::{self, Actor, Target};
21-use crate::auth::{require_csrf, require_user};
21+use crate::auth::require_csrf;
2222 use crate::i18n::packages::{self as pk, K as PK};
2323 use crate::i18n::releases_ci::{self as rc, K as RC};
2424 use crate::i18n::s;
2525 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};
2727 use crate::state::AppState;
2828 use crate::views::parts::confirm_act;
2929 use crate::views::{alert, rel_time, rel_time_or_never};
@@ -132,16 +132,7 @@ pub(crate) async fn tokens_section(
132132
133133 #[page("/settings/tokens")]
134134 async fn tokens_page(cx: &Cx) -> Result<impl View> {
135- let viewer = require_user(cx).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- })
135+ kind_page(cx, KeyKind::Tokens).await
145136 }
146137
147138 #[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>
9999 }
100100
101101 let lang = i18n::lang(cx, None);
102- let problem = match validate_username(&form.username) {
103- Err(e) => user_facing_message(&e),
102+ let checked = validate_username(&form.username);
103+ let problem = match &checked {
104+ Err(e) => user_facing_message(e),
104105 Ok(_) if form.password.chars().count() < MIN_PASSWORD_CHARS => {
105106 Some(password_too_short(lang, MIN_PASSWORD_CHARS))
106107 }
@@ -118,7 +119,7 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View>
118119 });
119120 }
120121
121- let (username, _) = validate_username(&form.username)?;
122+ let (username, _) = checked?;
122123 let email = form.email.trim();
123124 let email = (!email.is_empty()).then_some(email);
124125 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>
130131 else {
131132 return Err(not_found().into());
132133 };
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- }
137134 audit::record(
138135 &state.store,
139136 Some(cx),
@@ -149,6 +146,11 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View>
149146 .await;
150147 login(cx, &user).await?;
151148 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+ }
152154 Err(see_other("/").into())
153155 }
154156
crates/forge-web-account/src/pages/shell_events.rsmodified+27 -3
@@ -38,13 +38,37 @@ async fn shell_events(cx: &Cx) -> Result<Response> {
3838 .map(|(user, session)| (user.id.clone(), session.id.clone()));
3939 let mut parts: Vec<BoxStream<'static, Result<Event>>> =
4040 vec![alive_stream(state.clone(), ids).await?];
41- if let Some((user, _)) = viewer {
42- parts.push(unread_changes(&state, &user.id).await?.boxed());
43- parts.push(activity_changes(state.clone(), user.clone(), "activity").boxed());
41+ if let Some((user, session)) = viewer {
42+ let unread = unread_changes(&state, &user.id).await?.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));
4446 }
4547 events_response(cx, stream::select_all(parts))
4648 }
4749
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+
4872 #[cfg(test)]
4973 mod tests {
5074 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-
71 use std::collections::HashMap;
82
93 use forge_core::store::snippets::{
@@ -32,22 +26,17 @@ use crate::views::{alert, empty_state, rel_time, shell, user_facing_message};
3226
3327 path_param!(id);
3428
35-/// What the form shows for one file slot.
3629 struct Slot {
3730 number: usize,
3831 name: String,
3932 content: String,
4033 }
4134
42-/// The editable state of a snippet, as typed or as saved.
4335 #[derive(Clone, Default)]
4436 struct Draft {
4537 title: String,
4638 description: String,
4739 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.
5140 files: Vec<(usize, SnippetFile)>,
5241 }
5342
@@ -68,8 +57,6 @@ impl Draft {
6857 }
6958 }
7059
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`).
7360 fn from_form(form: &HashMap<String, String>) -> Self {
7461 let field = |key: String| form.get(&key).cloned().unwrap_or_default();
7562 let mut files = Vec::new();
@@ -89,7 +76,6 @@ impl Draft {
8976 }
9077 }
9178
92- /// The files to save: cards with neither a name nor contents are dropped.
9379 fn saved_files(&self) -> Vec<SnippetFile> {
9480 self.files
9581 .iter()
@@ -99,17 +85,14 @@ impl Draft {
9985 .collect()
10086 }
10187
102- /// Drops the card whose fields are `number`. Other cards keep their numbers.
10388 fn remove(&mut self, number: usize) {
10489 self.files.retain(|(n, _)| *n != number);
10590 }
10691
107- /// The position of the file whose fields are `number`, if there is one.
10892 fn position(&self, number: usize) -> Option<usize> {
10993 self.files.iter().position(|(n, _)| *n == number)
11094 }
11195
112- /// Adds an empty card under the lowest free field number, unless the snippet is full.
11396 fn add_blank(&mut self) {
11497 if self.files.len() >= MAX_FILES {
11598 return;
@@ -124,7 +107,6 @@ impl Draft {
124107 }
125108 }
126109
127- /// The cards to render: one per file, or one empty card for a new snippet.
128110 fn slots(&self) -> Vec<Slot> {
129111 if self.files.is_empty() {
130112 return vec![Slot {
@@ -136,7 +118,6 @@ impl Draft {
136118 self.files
137119 .iter()
138120 .map(|(number, file)| {
139- // A browser drops one newline right after <textarea>, so keep a leading one.
140121 let content = if file.content.starts_with('\n') {
141122 format!("\n{}", file.content)
142123 } else {
@@ -152,9 +133,6 @@ impl Draft {
152133 }
153134 }
154135
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.
158136 fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option<usize> {
159137 if form.get("op").map(String::as_str) == Some("add") {
160138 draft.add_blank();
@@ -169,7 +147,6 @@ fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option<
169147 }
170148 }
171149
172-/// The tab that was checked when a save failed, so the user stays on the file they were editing.
173150 fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize {
174151 form.get("tab")
175152 .and_then(|tab| tab.parse().ok())
@@ -177,17 +154,18 @@ fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize {
177154 .unwrap_or(0)
178155 }
179156
180-/// One file as the view page shows it. `body` is trusted HTML when `markdown` or `highlighted`
181-/// is set, and plain text otherwise.
157+enum FileBody {
158+ Markdown(String),
159+ Highlighted(String),
160+ Plain(String),
161+}
162+
182163 struct FileView {
183164 name: String,
184165 raw: String,
185- markdown: bool,
186- highlighted: bool,
187- body: String,
166+ body: FileBody,
188167 }
189168
190-/// One revision as the history page shows it.
191169 struct RevisionView {
192170 number: usize,
193171 author: String,
@@ -195,18 +173,15 @@ struct RevisionView {
195173 file_names: String,
196174 }
197175
198-/// One row of the list page and of a profile's Snippets tab.
199176 pub(crate) struct ListRow {
200177 id: String,
201178 title: String,
202179 owner: String,
203180 visibility: &'static str,
204- /// The file count and the last update, as one line.
205181 files: String,
206182 updated_at: String,
207183 }
208184
209-/// The list row for a snippet summary, with its strings ready for the view.
210185 pub(crate) fn list_row(lang: Lang, summary: SnippetSummary) -> ListRow {
211186 ListRow {
212187 id: summary.id,
@@ -233,25 +208,21 @@ fn extension(name: &str) -> String {
233208 }
234209
235210 fn file_view(state: &AppState, snippet: &Snippet, file: &SnippetFile) -> FileView {
236- let markdown = matches!(extension(&file.name).as_str(), "md" | "markdown");
237- let (body, highlighted) = if markdown {
238- (render_markdown(&file.content, None), false)
211+ let body = if matches!(extension(&file.name).as_str(), "md" | "markdown") {
212+ FileBody::Markdown(render_markdown(&file.content, None))
239213 } else {
240214 match highlight_lines(&file.name, &file.content) {
241- Some(lines) => (lines.join("\n"), true),
242- None => (file.content.clone(), false),
215+ Some(lines) => FileBody::Highlighted(lines.join("\n")),
216+ None => FileBody::Plain(file.content.clone()),
243217 }
244218 };
245219 FileView {
246220 name: file.name.clone(),
247221 raw: snippet_raw_url(state, snippet, &file.name),
248- markdown,
249- highlighted,
250222 body,
251223 }
252224 }
253225
254-/// The snippet if the viewer may read it, else 404.
255226 pub(crate) async fn readable(
256227 cx: &Cx,
257228 viewer_id: Option<&str>,
@@ -264,7 +235,6 @@ pub(crate) async fn readable(
264235 }
265236 }
266237
267-/// The snippet if the user owns it, else 404. Edits and deletes go through this check.
268238 async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> {
269239 let store = &context::<AppState>(cx).store;
270240 match store.get_snippet(snippet_id).await? {
@@ -273,7 +243,23 @@ async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> {
273243 }
274244 }
275245
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+
277263 #[component]
278264 pub(crate) async fn snippet_rows(cx: &Cx, lang: Lang, rows: Vec<ListRow>) -> Result<impl View> {
279265 Ok(view! {
@@ -312,10 +298,6 @@ async fn snippet_list_body(
312298 })
313299 }
314300
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.
319301 #[component]
320302 async fn snippet_files(
321303 cx: &Cx,
@@ -387,24 +369,22 @@ async fn snippet_files(
387369 })
388370 }
389371
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.
392372 #[component]
393373 async fn snippet_form(
394374 cx: &Cx,
395375 lang: Lang,
396376 csrf: &str,
397377 action: &str,
398- title: &str,
399- description: &str,
400- visibility: &str,
401- slots: Vec<Slot>,
378+ draft: &Draft,
402379 active: usize,
403380 error: Option<String>,
404381 ) -> Result<impl View> {
405- let public = visibility == "public";
406- let unlisted = visibility == "unlisted";
407- let private = visibility == "private";
382+ let title = draft.title.as_str();
383+ let description = draft.description.as_str();
384+ let public = draft.visibility == "public";
385+ let unlisted = draft.visibility == "unlisted";
386+ let private = draft.visibility == "private";
387+ let slots = draft.slots();
408388 let removable = slots.len() > 1;
409389 let can_add = slots.len() < MAX_FILES;
410390 let counter = g::files_limit(
@@ -480,7 +460,7 @@ async fn snippet_body(
480460 }
481461 )
482462 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)
484464 }
485465 <div class="sheet" data-live=(live.as_deref())>
486466 <section class="sec">
@@ -488,8 +468,6 @@ async fn snippet_body(
488468 <p>(description)</p>
489469 }
490470 <p class="hint">(g::updated_before(lang)) rel_time(lang: lang, stamp: updated_at) (g::updated_after(lang))</p>
491- if !is_owner {
492- }
493471 </section>
494472 for file in files.into_iter() {
495473 <section class="sec snippet-file">
@@ -497,12 +475,12 @@ async fn snippet_body(
497475 <strong>(file.name.clone())</strong>
498476 <a class="act" href=(file.raw.clone())>(g::t(lang, K::Raw))</a>
499477 </div>
500- if file.markdown {
501- <div class="markdown-body">(Unescaped::new_unchecked(file.body.clone()))</div>
502- } else if file.highlighted {
503- <pre class="code snippet-code"><code>(Unescaped::new_unchecked(file.body.clone()))</code></pre>
504- } else {
505- <pre class="code snippet-code"><code>(file.body.clone())</code></pre>
478+ if let FileBody::Markdown(html) = &file.body {
479+ <div class="markdown-body">(Unescaped::new_unchecked(html.clone()))</div>
480+ } else if let FileBody::Highlighted(html) = &file.body {
481+ <pre class="code snippet-code"><code>(Unescaped::new_unchecked(html.clone()))</code></pre>
482+ } else if let FileBody::Plain(text) = &file.body {
483+ <pre class="code snippet-code"><code>(text.clone())</code></pre>
506484 }
507485 </section>
508486 }
@@ -527,7 +505,7 @@ async fn revisions_body(
527505 <a class="button" href=(back)>(g::t(lang, K::BackToSnippet))</a>
528506 )
529507 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)
531509 }
532510 <div class="sheet" data-live=(live.as_deref())>
533511 if revisions.is_empty() {
@@ -556,19 +534,14 @@ async fn snippet_form_page(
556534 active: usize,
557535 ) -> Result<impl View> {
558536 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();
563537 let tab_user = viewer.0.username.clone();
564538 Ok(view! {
565539 shell(title: heading, viewer: Some(viewer),
566540 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)
568542 <div class="sheet">
569543 snippet_form(lang: lang, csrf: csrf.as_str(), action: action,
570- title: title.as_str(), description: description.as_str(),
571- visibility: visibility.as_str(), slots: slots, active: active, error: error)
544+ draft: &draft, active: active, error: error)
572545 </div>
573546 )
574547 })
@@ -634,20 +607,7 @@ async fn snippet_create(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
634607 };
635608 match saved {
636609 Ok(snippet) => {
637- audit::record(
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);
610+ record_snippet(cx, &user, AuditAction::SnippetCreated, &snippet).await;
651611 return Err(see_other(format!("/snippets/{}", snippet.id)).into());
652612 }
653613 Err(message) => error = Some(message),
@@ -737,20 +697,7 @@ async fn snippet_update(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
737697 };
738698 match saved {
739699 Ok(snippet) => {
740- audit::record(
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);
700+ record_snippet(cx, &user, AuditAction::SnippetUpdated, &snippet).await;
754701 return Err(see_other(format!("/snippets/{}", snippet.id)).into());
755702 }
756703 Err(message) => error = Some(message),
@@ -774,7 +721,6 @@ async fn snippet_revisions(cx: &Cx) -> Result<impl View> {
774721 let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user));
775722 let store = &context::<AppState>(cx).store;
776723 let revisions: Vec<SnippetRevision> = store.list_snippet_revisions(&snippet.id).await?;
777- // Stored oldest first; the page shows the newest first with its number.
778724 let rows: Vec<RevisionView> = revisions
779725 .into_iter()
780726 .enumerate()
@@ -807,20 +753,7 @@ async fn snippet_delete(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R
807753 let snippet = owned(cx, &user, &snippet_id).await?;
808754 let store = &context::<AppState>(cx).store;
809755 if store.delete_snippet(&user.id, &snippet.id).await? {
810- audit::record(
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);
756+ record_snippet(cx, &user, AuditAction::SnippetDeleted, &snippet).await;
824757 }
825758 Ok(see_other("/snippets"))
826759 }
@@ -836,11 +769,8 @@ mod tests {
836769 .collect()
837770 }
838771
839- /// Saving drops blank cards but editing keeps them, and a leading newline survives the
840- /// textarea.
841772 #[test]
842773 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.
844774 let draft = Draft::from_form(&form(&[
845775 ("title", "t"),
846776 ("visibility", "public"),
@@ -864,7 +794,6 @@ mod tests {
864794 );
865795 assert_eq!(saved[1].name, "b.rs", "blank cards: the kept file");
866796
867- // Case: a leading newline in a file survives the textarea.
868797 let mut draft = Draft::blank();
869798 draft.files = vec![(
870799 0,
@@ -876,11 +805,8 @@ mod tests {
876805 assert_eq!(draft.slots()[0].content, "\n\nx", "leading newline");
877806 }
878807
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.
881808 #[test]
882809 fn card_steps_add_remove_and_show_the_right_tab() {
883- // Case: a new form shows one empty card.
884810 let draft = Draft::blank();
885811 let slots = draft.slots();
886812 assert_eq!(slots.len(), 1, "new form: one card");
@@ -890,7 +816,6 @@ mod tests {
890816 "new form: the card is empty"
891817 );
892818
893- // Case: add appends a card until the snippet is full.
894819 let mut draft = Draft::blank();
895820 for _ in 0..MAX_FILES + 3 {
896821 draft.add_blank();
@@ -903,7 +828,6 @@ mod tests {
903828 "add: numbers run from zero"
904829 );
905830
906- // Case: removing a card keeps the other field numbers.
907831 let mut draft = Draft::blank();
908832 draft.add_blank();
909833 draft.add_blank();
@@ -918,7 +842,6 @@ mod tests {
918842 "remove: the other card's name"
919843 );
920844
921- // Case: add and remove clicks are told apart from a save.
922845 let add = form(&[("op", "add"), ("name_0", "a")]);
923846 let mut draft = Draft::from_form(&add);
924847 assert_eq!(apply_slot_step(&mut draft, &add), Some(1), "add click: tab");
@@ -937,7 +860,6 @@ mod tests {
937860 "save: not a card step"
938861 );
939862
940- // Case: add shows the new last file.
941863 let mut draft = Draft::blank();
942864 let add = form(&[("op", "add"), ("name_0", "a")]);
943865 assert_eq!(
@@ -952,19 +874,16 @@ mod tests {
952874 );
953875 assert_eq!(draft.slots().len(), 2, "add shows: two cards");
954876
955- // Case: removing a card shows the file before it, and the first one when it is first.
956877 let mut draft = Draft::blank();
957878 for _ in 0..3 {
958879 draft.add_blank();
959880 }
960- // Files 0..=2 at positions 0..=2; removing the file at position 2 shows position 1.
961881 let remove = form(&[("remove", "2")]);
962882 assert_eq!(
963883 apply_slot_step(&mut draft, &remove),
964884 Some(1),
965885 "remove shows: before"
966886 );
967- // Removing the first file shows the new first one.
968887 let remove = form(&[("remove", "0")]);
969888 assert_eq!(
970889 apply_slot_step(&mut draft, &remove),
@@ -972,7 +891,6 @@ mod tests {
972891 "remove shows: first"
973892 );
974893
975- // Case: a failed save keeps the posted tab, and falls back to the first.
976894 let mut draft = Draft::blank();
977895 for _ in 0..3 {
978896 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> {
264264 .and_then(|value| value.to_str().ok())
265265 .map(str::to_owned);
266266 let max_bytes = state
267- .config
267+ .live()
268268 .releases
269269 .max_asset_mb
270270 .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> {
388388 Ok(Event::new().event("changed").data(status))
389389 }
390390
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+
391401 /// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event
392402 /// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when
393403 /// 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 {
4343 }
4444 }
4545
46+impl From<PackageError> for Error {
47+ fn from(e: PackageError) -> Self {
48+ Self::Database(format!("{e:?}"))
49+ }
50+}
51+
4652 /// The user or org a registry path names. `None` when no such account exists.
4753 pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> {
4854 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> {
11211121 })
11221122 }
11231123
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+
11241135 /// What a list shows when it has nothing yet: one line saying so, an optional hint, and an optional
11251136 /// next step as the child (a button, a link, or a command to copy). Pages use it so every empty list
11261137 /// reads the same way.
crates/forge-web-base/src/i18n/merge_queue.rsmodified+8 -0
@@ -32,6 +32,8 @@ pub enum K {
3232 ReasonPermission,
3333 ReasonBlocked,
3434 ReasonNoBranch,
35+ ReasonDraft,
36+ ReasonHeadMissing,
3537 ErrQueueRequired,
3638 ErrQueueAlready,
3739 }
@@ -66,6 +68,8 @@ pub const ALL: &[K] = &[
6668 K::ReasonPermission,
6769 K::ReasonBlocked,
6870 K::ReasonNoBranch,
71+ K::ReasonDraft,
72+ K::ReasonHeadMissing,
6973 K::ErrQueueRequired,
7074 K::ErrQueueAlready,
7175 ];
@@ -128,6 +132,10 @@ pub fn t(lang: Lang, key: K) -> &'static str {
128132 (ReasonBlocked, Tr) => "bir birleştirme denetimi artık geçmiyor",
129133 (ReasonNoBranch, En) => "the branch is gone",
130134 (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",
131139 (ErrQueueRequired, En) => {
132140 "This branch requires the merge queue. Add the pull request to the queue instead."
133141 }
crates/forge-web-pages/src/pages/admin_runners.rsmodified+32 -87
@@ -11,6 +11,7 @@ use forge_ci::proto::RunnerSample;
1111 use forge_core::AuditAction;
1212 use forge_core::ci::{
1313 CiRunner, FieldKind, JobState, RUNNER_FIELDS, RestartMode, RunnerJob, runner_field,
14+ validate_runner_field,
1415 };
1516 use forge_core::store::health::runner_is_online;
1617 use serde::Deserialize;
@@ -31,7 +32,7 @@ use crate::ci::metrics_chart::{self, Bucket};
3132 use crate::ci::runner_log::Line;
3233 use crate::i18n::admin::{self as g, K};
3334 use crate::i18n::releases_ci as rc;
34-use crate::i18n::{self, Key, Lang};
35+use crate::i18n::{self, Key, Lang, s};
3536 use crate::live::events_response;
3637 use crate::pages::admin_users::admin_only;
3738 use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text};
@@ -54,14 +55,6 @@ struct RunnersQuery {
5455 notice: Option<String>,
5556 }
5657
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-
6558 /// Extra notice words: (word, English, Turkish, is an error).
6659 const EXTRA_NOTICES: [(&str, &str, &str, bool); 8] = [
6760 ("saved", "Saved.", "Kaydedildi.", false),
@@ -460,15 +453,19 @@ async fn load_meter(cx: &Cx, lang: Lang, running: u32, max: u32) -> Result<impl
460453 let running_text = running.to_string();
461454 let meter_max = max.max(1).to_string();
462455 let use_pips = (1..=PIP_MAX).contains(&max);
463- let pips: Vec<&'static str> = (0..max)
464- .map(|slot| {
465- if slot < running {
466- "runner-pip is-on"
467- } else {
468- "runner-pip"
469- }
470- })
471- .collect();
456+ let pips: Vec<&'static str> = if use_pips {
457+ (0..max)
458+ .map(|slot| {
459+ if slot < running {
460+ "runner-pip is-on"
461+ } else {
462+ "runner-pip"
463+ }
464+ })
465+ .collect()
466+ } else {
467+ Vec::new()
468+ };
472469 let pips_label = match lang {
473470 Lang::En => format!("{running} of {max} jobs running"),
474471 Lang::Tr => format!("{running}/{max} iş çalışıyor"),
@@ -696,7 +693,6 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> {
696693 .clone()
697694 .or_else(|| overridden.clone())
698695 .or_else(|| reported.cloned());
699- // Restart fields wait for a start; a live concurrency waits for the next check-in.
700696 let pending = match (&overridden, field.kind) {
701697 (Some(want), FieldKind::Restart) => reported != Some(want),
702698 (Some(want), FieldKind::Live) if field.key == "concurrency" => {
@@ -722,10 +718,6 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> {
722718 .collect()
723719 }
724720
725-fn sel(on: bool) -> Option<&'static str> {
726- on.then_some("selected")
727-}
728-
729721 /// The detail page tabs: slug and the config keys on it. `overview`, `jobs`, `identity` and `logs`
730722 /// are read-only.
731723 const TABS: [(&str, &[&str]); 8] = [
@@ -942,7 +934,6 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField>
942934 options: if choices.is_empty() {
943935 Vec::new()
944936 } else {
945- // An unreported field gets a blank first option, so saving the tab leaves it alone.
946937 std::iter::once(("", s(lang, "(from runner.toml)", "(runner.toml'dan)")))
947938 .filter(|_| f.value.is_empty())
948939 .chain(choices)
@@ -1096,10 +1087,9 @@ async fn runner_job_rows(
10961087 let (running, finished): (Vec<&RunnerJob>, Vec<&RunnerJob>) = jobs
10971088 .iter()
10981089 .partition(|job| job.job.state == JobState::Running);
1099- let to_row = |job: &RunnerJob| runner_job_row(lang, job);
11001090 Ok((
1101- running.into_iter().map(to_row).collect(),
1102- finished.into_iter().map(to_row).collect(),
1091+ running.into_iter().map(|job| runner_job_row(lang, job)).collect(),
1092+ finished.into_iter().map(|job| runner_job_row(lang, job)).collect(),
11031093 ))
11041094 }
11051095
@@ -1175,26 +1165,6 @@ fn n(value: f64) -> String {
11751165 format!("{value:.1}")
11761166 }
11771167
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-
11981168 /// A rate in bytes per second as `80 KiB/s`, one decimal below ten units.
11991169 fn rate_text(bytes: f64) -> String {
12001170 const KIB: f64 = 1024.0;
@@ -1350,7 +1320,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
13501320 let cpu = mx_chart(
13511321 &points,
13521322 100.0,
1353- &[(cpu_of, "mx-line")],
1323+ &[(|b: &Bucket| b.cpu, "mx-line")],
13541324 true,
13551325 &|v| format!("{v:.0}%"),
13561326 &|b| {
@@ -1366,7 +1336,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
13661336 let mem = mx_chart(
13671337 &points,
13681338 mem_total,
1369- &[(mem_of, "mx-line")],
1339+ &[(|b: &Bucket| b.mem_used, "mx-line")],
13701340 false,
13711341 &|v| bytes_text(v as u64),
13721342 &|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
13771347 let disk = mx_chart(
13781348 &points,
13791349 disk_total,
1380- &[(disk_of, "mx-line")],
1350+ &[(|b: &Bucket| b.disk_used, "mx-line")],
13811351 false,
13821352 &|v| bytes_text(v as u64),
13831353 &|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
13881358 let net = mx_chart(
13891359 &points,
13901360 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")],
13921362 false,
13931363 &rate_text,
13941364 &|b| {
@@ -1423,11 +1393,6 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie
14231393 }
14241394 }
14251395
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-
14311396 #[component]
14321397 async fn runner_detail_view(
14331398 cx: &Cx,
@@ -1487,8 +1452,6 @@ async fn runner_detail_view(
14871452 let jobs_href = format!("{}?tab=jobs", row.detail_href);
14881453 let save_action = format!("{}/settings", row.detail_href);
14891454 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.
14921455 let cpu_facts = format!("{cpus} {}", s(lang, "CPUs", "CPU"));
14931456 let budget_facts = format!(
14941457 "{} {budget_text} · {} {reserved_text} · {} {free_text}",
@@ -1502,7 +1465,6 @@ async fn runner_detail_view(
15021465 budget_facts
15031466 };
15041467 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.
15061468 let has_host = !metrics.empty || runner.reported.cpus.is_some();
15071469 Ok(view! {
15081470 head(title: runner.name.as_str(), sub: sub, live: Some("/admin/runners/events"),
@@ -1523,7 +1485,7 @@ async fn runner_detail_view(
15231485 }
15241486 <nav class="tabs" aria-label=(s(lang, "Configuration", "Yapılandırma"))>
15251487 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>
15271489 }
15281490 </nav>
15291491 <div class="sheet">
@@ -1637,7 +1599,7 @@ async fn runner_detail_view(
16371599 if f.input == "select" {
16381600 <select id=(format!("rf-{}", f.key)) name=(f.key)>
16391601 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>
16411603 }
16421604 </select>
16431605 } else if f.input == "number" {
@@ -1765,8 +1727,7 @@ async fn runner_save_settings(
17651727 return Ok(back_to_list("missing"));
17661728 };
17671729 let current = field_rows(&runner);
1768- let mut saved_live = false;
1769- let mut saved_restart = false;
1730+ let mut changes = Vec::new();
17701731 for key in tab_keys(tab) {
17711732 let (Some(field), Some(posted), Some(now)) = (
17721733 runner_field(key),
@@ -1778,6 +1739,14 @@ async fn runner_save_settings(
17781739 if field.kind == FieldKind::ReadOnly || posted.trim() == now.value {
17791740 continue;
17801741 }
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 {
17811750 match state
17821751 .store
17831752 .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
19711940 Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")),
19721941 Err(e) => return Err(e.into()),
19731942 }
1974- // Wakes a runner that is waiting on a claim, and the live runners pages.
19751943 state.ci_waker.notify_waiters();
19761944 state.ci_live.bump_runners();
19771945 tracing::info!(actor_id = %viewer.0.id, runner_id = %id, mode = mode.as_str(), "ci runner restart requested");
@@ -2110,13 +2078,11 @@ mod tests {
21102078 assert!(body.contains("event: go\ndata: /admin/runners"), "{body}");
21112079 }
21122080
2113- // Scenario: the page gates, the one-time token, and labels as chips with a state badge.
21142081 #[tokio::test]
21152082 async fn gates_token_once_and_labels_render_as_chips() {
21162083 let dir = tempfile::tempdir().expect("tempdir");
21172084 let (store, router) = fixture(dir.path()).await;
21182085
2119- // Anonymous and non-admin users get 404 on every runner route.
21202086 let (anon, _) = send(&router, "GET", "/admin/runners", None, None).await;
21212087 assert_eq!(anon, 404, "anonymous gets 404 here, not a login redirect");
21222088 let (user, _) = send(&router, "GET", "/admin/runners", Some(USER_TOKEN), None).await;
@@ -2140,7 +2106,6 @@ mod tests {
21402106 .await;
21412107 assert_eq!(del, 404);
21422108
2143- // An admin post without a valid CSRF token is forbidden and changes nothing.
21442109 let (tok, _) = send(
21452110 &router,
21462111 "POST",
@@ -2170,7 +2135,6 @@ mod tests {
21702135 assert_eq!(dis, 403);
21712136 assert!(store.list_runners().await.expect("list").is_empty());
21722137
2173- // The token is shown once, in the box and in the command, and never in the list.
21742138 let (status, created) = send(
21752139 &router,
21762140 "POST",
@@ -2192,12 +2156,9 @@ mod tests {
21922156 "token in the box and the command"
21932157 );
21942158 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.
21962159 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.
21982160 assert!(store.list_runners().await.expect("list").is_empty());
21992161
2200- // Labels are one plain line joined by " · ", and the dot follows disabling.
22012162 store
22022163 .register_runner(
22032164 &token,
@@ -2210,7 +2171,6 @@ mod tests {
22102171 assert_eq!(status, 200);
22112172 assert!(page.contains(r#"<span class="runner-labels">linux · x86_64</span>"#));
22122173 assert!(!page.contains("linux, x86_64"), "labels are not joined");
2213- // Never seen, so offline; not disabled, so no disabled word.
22142174 assert!(page.contains(r#"class="runner-dot is-offline""#));
22152175 assert!(!page.contains(r#"<span class="val">idle · disabled</span>"#));
22162176
@@ -2224,7 +2184,6 @@ mod tests {
22242184 assert!(page.contains(r#"<span class="val">idle</span>"#));
22252185 }
22262186
2227- // Scenario: restart is capability-gated and audited, then the runner is disabled, enabled and deleted.
22282187 #[tokio::test]
22292188 async fn restart_then_disable_and_delete_follow_one_runner() {
22302189 let dir = tempfile::tempdir().expect("tempdir");
@@ -2232,7 +2191,6 @@ mod tests {
22322191 let runner = one_runner(&store, &router).await;
22332192 let restart = format!("/admin/runners/{}/restart", runner.id);
22342193
2235- // Not logged in as an admin, or a bad token, changes nothing.
22362194 let (status, _) = send(&router, "POST", &restart, Some(USER_TOKEN), csrf_form("")).await;
22372195 assert_eq!(status, 404);
22382196 let (status, _) = send(
@@ -2245,7 +2203,6 @@ mod tests {
22452203 .await;
22462204 assert_eq!(status, 403);
22472205
2248- // A runner that never advertised the capability: the button is off and the post refused.
22492206 let runner_page = format!("/admin/runners/{}", runner.id);
22502207 let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await;
22512208 assert!(list.contains("Runner too old, update it first"), "{list}");
@@ -2260,7 +2217,6 @@ mod tests {
22602217 assert_eq!(status, 303);
22612218 assert_eq!(store.runner_restart(&runner.id).await.unwrap(), None);
22622219
2263- // With the capability the page offers both choices, and the post is stored and audited.
22642220 store
22652221 .record_runner_report(
22662222 &runner.id,
@@ -2301,7 +2257,6 @@ mod tests {
23012257 && e.data.contains("drain"))
23022258 );
23032259
2304- // The runner comes back with a new boot id and the pending state goes away.
23052260 store
23062261 .record_runner_report(
23072262 &runner.id,
@@ -2315,7 +2270,6 @@ mod tests {
23152270 let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await;
23162271 assert!(!list.contains("restart pending"));
23172272
2318- // Disable, then enable again.
23192273 let disable = format!("/admin/runners/{}/disabled", runner.id);
23202274 let (status, _) = send(
23212275 &router,
@@ -2337,7 +2291,6 @@ mod tests {
23372291 .await;
23382292 assert!(!store.list_runners().await.expect("list")[0].disabled);
23392293
2340- // Delete it, then a second delete reports that the id is gone.
23412294 let delete = format!("/admin/runners/{}/delete", runner.id);
23422295 let (status, _) = send(&router, "POST", &delete, Some(ADMIN_TOKEN), csrf_form("")).await;
23432296 assert_eq!(status, 303);
@@ -2354,8 +2307,6 @@ mod tests {
23542307 assert!(page.contains("No runner has that id"));
23552308 }
23562309
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.
23592310 #[tokio::test]
23602311 async fn settings_save_per_field_reset_and_stay_admin_only() {
23612312 let dir = tempfile::tempdir().expect("tempdir");
@@ -2365,7 +2316,6 @@ mod tests {
23652316 let settings = format!("/admin/runners/{}/settings", runner.id);
23662317 let detail_uri = format!("/admin/runners/{}", runner.id);
23672318
2368- // Non-admins get 404 on every route, and a bad CSRF token is forbidden.
23692319 let (status, _) = send(
23702320 &router,
23712321 "POST",
@@ -2409,7 +2359,6 @@ mod tests {
24092359 .await;
24102360 assert_eq!(status, 404);
24112361
2412- // One post saves the changed fields of a tab; blank fields stay unset.
24132362 let (status, _) = send(
24142363 &router,
24152364 "POST",
@@ -2441,7 +2390,6 @@ mod tests {
24412390 );
24422391 assert!(page.contains("Reset to runner.toml"));
24432392
2444- // Concurrency: set it, show it in the list and the detail page, and refuse bad values.
24452393 let (status, _) = send(
24462394 &router,
24472395 "POST",
@@ -2467,7 +2415,6 @@ mod tests {
24672415 assert!(list.contains("Reset to runner.toml"));
24682416 assert!(list.contains(r#"data-live="/admin/runners/events""#));
24692417
2470- // Out of range, wrong kind of field and a read-only field change nothing.
24712418 for form in [
24722419 "&key=concurrency&value=65",
24732420 "&key=concurrency&value=0",
@@ -2484,7 +2431,6 @@ mod tests {
24842431 Some(3)
24852432 );
24862433
2487- // A config field saved from the detail page shows there, live.
24882434 let (status, _) = send(
24892435 &router,
24902436 "POST",
@@ -2506,7 +2452,6 @@ mod tests {
25062452 assert!(detail.contains("Concurrency"));
25072453 assert!(detail.contains(r#"data-live="/admin/runners/events""#));
25082454
2509- // Reset both overrides; the runner goes back to its runner.toml values.
25102455 let (_, _) = send(
25112456 &router,
25122457 "POST",
crates/forge-web-pages/src/pages/admin_users.rsmodified+29 -31
@@ -166,6 +166,19 @@ impl UserRow {
166166 }
167167 }
168168
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+
169182 #[component]
170183 async fn users_view(
171184 cx: &Cx,
@@ -262,23 +275,11 @@ async fn users_view(
262275 for row in rows.into_iter() {
263276 if row.linkable {
264277 <a class="line" href=(row.href.as_str()) data-kb-row="">
265- <span class="name">(row.username.as_str())</span>
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>
278+ row_body(lang: lang, row: &row)
272279 </a>
273280 } else {
274281 <div class="line" data-kb-row="">
275- <span class="name">(row.username.as_str())</span>
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+ row_body(lang: lang, row: &row)
282283 </div>
283284 }
284285 }
@@ -592,21 +593,26 @@ async fn org_delete_note(
592593 })
593594 }
594595
595-#[page("/admin/users/{user_id}/delete")]
596-async fn user_delete_page(cx: &Cx) -> Result<impl View> {
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 {
596+async fn delete_target(store: &Store, viewer: &User, target_id: &str) -> Result<User> {
597+ let Some(target) = store.user_by_id(target_id).await? else {
602598 return Err(not_found().into());
603599 };
604- if target.id == viewer.0.id {
600+ if target.id == viewer.id {
605601 return Err(see_other("/settings/security").into());
606602 }
607603 if is_ghost(&target) {
608604 return Err(not_found().into());
609605 }
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?;
610616 let (repos, outcome) = review_target(store, &target, lang).await?;
611617 let (impact, refusal) = match outcome {
612618 Ok(impact) => (Some(impact), None),
@@ -637,15 +643,7 @@ async fn user_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View>
637643 let lang = i18n::lang(cx, Some(&viewer.0));
638644 let store = &context::<AppState>(cx).store;
639645 let target_id = path_param_segment(cx, "user_id").to_owned();
640- let Some(target) = store.user_by_id(&target_id).await? else {
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- }
646+ let target = delete_target(store, &viewer.0, &target_id).await?;
649647 if target.is_org() {
650648 // The note with its links is on the GET page: send the browser there.
651649 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;
2525 use topcoat::context::{Cx, context};
2626 use topcoat::router::content::sse::{Event, last_event_id};
2727 use topcoat::router::error::not_found;
28-use topcoat::router::request::uri;
2928 use topcoat::router::response::Response;
3029 use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_param, route};
3130 use topcoat::view::{View, component, view};
@@ -37,8 +36,8 @@ use crate::i18n::{
3736 };
3837 use crate::live::{changed_event, events_response};
3938 use crate::pages::ci_runs::{
40- age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, run_href,
41- state_text,
39+ age_text, can_write, commit_reachable_for, dock_bars, duration_text, job_href, query_value,
40+ run_href, state_text,
4241 };
4342 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
4443 use crate::state::AppState;
@@ -644,7 +643,7 @@ async fn job_events(cx: &Cx) -> Result<Response> {
644643 let (job, _) = job_of(state, &ctx, &id).await?;
645644 let offset = last_event_id(cx)
646645 .and_then(|id| id.parse::<u64>().ok())
647- .or_else(|| from_query(cx))
646+ .or_else(|| query_value(cx, "from")?.parse().ok())
648647 .unwrap_or(0);
649648 // Subscribed before the first read, so a change in between is sent.
650649 let wake = state.ci_live.subscribe_job(&job.id);
@@ -659,24 +658,13 @@ async fn job_events(cx: &Cx) -> Result<Response> {
659658 primed: false,
660659 pending_fingerprint: None,
661660 pending_log: None,
662- plain: uri(cx)
663- .query()
664- .is_some_and(|query| query.split('&').any(|pair| pair == "plain=1")),
661+ plain: query_value(cx, "plain").as_deref() == Some("1"),
665662 viewer: ctx.viewer.as_ref().map(|(user, _)| user.clone()),
666663 repo_id: ctx.repo.id.clone(),
667664 };
668665 events_response(cx, job_stream(follow))
669666 }
670667
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-
680668 /// One job's stream state. Each read of the status and the log happens after a wake, and a read that
681669 /// sent log bytes is followed by another read at once, so a long append drains in order.
682670 struct JobFollow {
@@ -864,14 +852,26 @@ fn artifact_response(
864852 let mut res = Response::new(Body::new(StreamBody::new(chunks)));
865853 *res.status_mut() = StatusCode::OK;
866854 let headers = res.headers_mut();
867- headers.insert(
868- CONTENT_TYPE,
869- HeaderValue::from_static("application/octet-stream"),
870- );
871855 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));
872872 if let Ok(value) = HeaderValue::from_str(&format!(
873873 "attachment; filename=\"{}\"",
874- attachment_name(&artifact.name)
874+ attachment_name(file_name)
875875 )) {
876876 headers.insert(CONTENT_DISPOSITION, value);
877877 }
@@ -881,9 +881,8 @@ fn artifact_response(
881881 );
882882 headers.insert(
883883 HeaderName::from_static("cache-control"),
884- HeaderValue::from_static("private, no-cache"),
884+ HeaderValue::from_static(cache),
885885 );
886- Ok(res)
887886 }
888887
889888 #[cfg(test)]
crates/forge-web-pages/src/pages/ci_runs.rsmodified+12 -52
@@ -29,7 +29,7 @@ use topcoat::router::content::sse::Event;
2929 use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
3030 use topcoat::router::request::uri;
3131 use topcoat::router::response::{IntoResponse, Response};
32-use topcoat::router::{HeaderValue, page, path_param, route};
32+use topcoat::router::{page, path_param, route};
3333 use topcoat::view::{View, component, view};
3434
3535 use crate::auth::{current_user, require_csrf};
@@ -44,7 +44,7 @@ use crate::live::{Status, changed_event, changed_stream, events_response};
4444 use crate::pages::admin_runners::confirm_post;
4545 use crate::pages::ci_estimate::{self, Est, Step};
4646 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};
4848 use crate::pages::refs::load_refs;
4949 use crate::pages::repo::repo_head;
5050 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
155155 BadgeInfo { image, snippet }
156156 }
157157
158-/// The notice from `?notice=<word>`. Anything else is ignored.
159158 fn notice_from_query(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> {
160- let query = uri(cx).query()?;
161- let word = form_urlencoded::parse(query.as_bytes())
162- .find(|(key, _)| key == "notice")
163- .map(|(_, value)| value.into_owned())?;
159+ let word = query_value(cx, "notice")?;
164160 NOTICES
165161 .iter()
166162 .find(|(name, _, _)| *name == word)
@@ -173,13 +169,8 @@ fn notice_redirect(href: &str, word: &str) -> SeeOther {
173169
174170 /// The page number from `?page=`. Anything unreadable or out of range is page 1.
175171 fn page_from_query(cx: &Cx) -> u32 {
176- uri(cx)
177- .query()
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- })
172+ query_value(cx, "page")
173+ .and_then(|value| value.parse::<u32>().ok())
183174 .filter(|page| (1..=MAX_PAGE).contains(page))
184175 .unwrap_or(1)
185176 }
@@ -1436,7 +1427,6 @@ fn job_steps(
14361427 lines
14371428 }
14381429
1439-/// "test OOM" for a failed run: the first failed job's message, or its name and state.
14401430 /// One row's meta line: `#50 · e62e309 · tahinli · ` then the age, then the failure hint if any.
14411431 struct RowMeta {
14421432 head: String,
@@ -2131,7 +2121,7 @@ fn step_from_query(cx: &Cx) -> Option<i64> {
21312121 }
21322122
21332123 /// 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> {
21352125 let query = uri(cx).query()?;
21362126 form_urlencoded::parse(query.as_bytes())
21372127 .find(|(name, _)| name == key)
@@ -2213,18 +2203,12 @@ async fn runs_sheet(cx: &Cx, lang: Lang, list: &ListView) -> Result<impl View> {
22132203 </svg>
22142204 if let Some(est) = row.est.as_ref() {
22152205 <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>
22272206 }
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>
22282212 </a>
22292213 if let Some((action, token)) = row.rerun.as_ref() {
22302214 <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> {
30663050 .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))?
30673051 .map_err(forge_core::Error::Io)?;
30683052 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- );
30743053 let file = format!("{}-run-{}-artifacts.zip", ctx.repo.name, run.number);
3075- if let Ok(value) = HeaderValue::from_str(&format!(
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- );
3054+ attachment_headers(res.headers_mut(), "application/zip", &file, "private, no-cache");
30953055 Ok(res)
30963056 }
30973057
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> {
144144 /// sent to log in, a bad token is 403, and a viewer without Triage (or an archived repo) is 403.
145145 pub async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<User> {
146146 let (user, _session) = require_csrf(cx, csrf).await?;
147- if ctx.repo.archived
148- || authorize(
149- Some(&user),
150- &ctx.repo,
151- ctx.role,
152- ctx.org_role,
153- Action::Triage,
154- )
155- .is_err()
156- {
147+ if !can_triage(ctx) {
157148 return Err(forbidden().into());
158149 }
159150 Ok(user)
@@ -208,6 +199,42 @@ pub async fn action_error_at(
208199 })
209200 }
210201
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+
211238 /// Sets the labels on an item. The form repeats `label` once per label id.
212239 #[page(POST "/{owner}/{repo}/issues/{number}/labels")]
213240 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)>) ->
231258 let before = item_labels(state, &item.id).await;
232259 let result = state.store.set_issue_labels(&item.id, &user.id, &ids).await;
233260 if let Err(e) = result {
234- let message = refusal_message(e)?;
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- });
261+ return save_refused(cx, ctx, lang, back, e).await;
239262 }
240263 bump_live(state, &ctx.repo.id, &item, kind);
241264 let after = item_labels(state, &item.id).await;
@@ -279,11 +302,7 @@ async fn assignees_save(
279302 .set_issue_assignees(&item.id, &user.id, &usernames)
280303 .await;
281304 if let Err(e) = result {
282- let message = refusal_message(e)?;
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- });
305+ return save_refused(cx, ctx, lang, back, e).await;
287306 }
288307 bump_live(state, &ctx.repo.id, &item, kind);
289308 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
345364 .await;
346365 let changed = match result {
347366 Ok(changed) => changed,
348- Err(e) => {
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- }
367+ Err(e) => return save_refused(cx, ctx, lang, back, e).await,
355368 };
356369 if changed {
357370 bump_live(state, &ctx.repo.id, &item, kind);
@@ -396,11 +409,7 @@ async fn milestone_save(
396409 .set_issue_milestone(&item.id, &user.id, milestone)
397410 .await;
398411 if let Err(e) = result {
399- let message = refusal_message(e)?;
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- });
412+ return save_refused(cx, ctx, lang, back, e).await;
404413 }
405414 let after = match milestone {
406415 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 {
5252 ItemKind::Pull => "pulls",
5353 }
5454 }
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+ }
5562 }
5663
5764
@@ -752,10 +759,7 @@ pub async fn load_discussion(
752759 } else {
753760 item.body.as_str()
754761 };
755- let body_anchor = match kind {
756- ItemKind::Issue => format!("issue-{number}"),
757- ItemKind::Pull => format!("pull-{number}"),
758- };
762+ let body_anchor = kind.anchor(number);
759763 let opened = When::new(lang, &item.created_at, &tz, now);
760764 let body_edits = state.store.edit_count(EditTarget::Issue, &[item.id.as_str()]).await?;
761765 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};
2929 use crate::views::parts::{RailItem, SubPart, rail};
3030 use crate::views::{
3131 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,
3333 };
3434 use crate::webhooks::emit::{Sender, emit_issue};
3535
@@ -238,12 +238,6 @@ pub fn list_href(base: &str, params: &[(&str, &str)]) -> String {
238238 }
239239 }
240240
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-
247241 pub struct AssigneeView {
248242 pub name: String,
249243 pub avatar: String,
@@ -879,6 +873,22 @@ async fn new_issue_page(cx: &Cx) -> Result<impl View> {
879873 })
880874 }
881875
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+
882892 #[page(POST "/{owner}/{repo}/issues/new")]
883893 async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
884894 let owner = owner(cx);
@@ -900,17 +910,12 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
900910 .store
901911 .create_issue(&ctx.repo.id, &viewer.0.id, &title, &typed_body)
902912 .await?;
903- if can_triage(&ctx) && !picked.is_empty() {
904- let repo_labels = state.store.list_labels(&ctx.repo.id).await?;
905- let ids: Vec<String> = repo_labels
906- .iter()
907- .filter(|l| picked.contains(&l.id))
908- .map(|l| l.id.clone())
909- .collect();
910- state
911- .store
912- .set_issue_labels(&issue.id, &viewer.0.id, &ids)
913- .await?;
913+ if can_triage(&ctx)
914+ && !picked.is_empty()
915+ && let Err(e) = set_picked_labels(state, &ctx.repo.id, &issue.id, &viewer.0.id, &picked)
916+ .await
917+ {
918+ tracing::error!(error = %e, issue_id = %issue.id, "new issue: labels not set");
914919 }
915920 state.live.bump_issue(&ctx.repo.id, &issue.id);
916921 // The author's contribution calendar counts the issue.
crates/forge-web-pages/src/pages/notifications.rsmodified+86 -101
@@ -158,6 +158,23 @@ impl Entry {
158158 }
159159 }
160160
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+
161178 /// The row for an issue or pull inbox entry.
162179 fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView {
163180 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 {
170187 .last_actor_name
171188 .as_deref()
172189 .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);
174191 RowView {
175- item_class: if note.unread {
176- "notif-row unread"
177- } else {
178- "notif-row"
179- },
192+ item_class: item_class(note.unread),
180193 icon_class,
181194 kind_label,
182195 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 {
187200 ),
188201 reason: reason_label(lang, note.reason),
189202 activity: g::activity_line(lang, activity_verb(&note.last_activity), actor.as_deref()),
190- iso: iso_time(unix),
191- absolute: forge_core::tz::format_in_tz(unix, tz),
192- relative: relative_time(lang, unix, now),
203+ iso,
204+ absolute,
205+ relative,
193206 unread: note.unread,
194207 }
195208 }
@@ -204,13 +217,9 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64)
204217 .last_actor_name
205218 .as_deref()
206219 .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);
208221 RowView {
209- item_class: if note.unread {
210- "notif-row unread"
211- } else {
212- "notif-row"
213- },
222+ item_class: item_class(note.unread),
214223 icon_class: "notif-icon discussion",
215224 kind_label: g::t(lang, K::KindDiscussion),
216225 open_href: format!(
@@ -227,9 +236,9 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64)
227236 ),
228237 reason,
229238 activity: g::activity_line(lang, activity, actor.as_deref()),
230- iso: iso_time(unix),
231- absolute: forge_core::tz::format_in_tz(unix, tz),
232- relative: relative_time(lang, unix, now),
239+ iso,
240+ absolute,
241+ relative,
233242 unread: note.unread,
234243 }
235244 }
@@ -237,14 +246,10 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64)
237246 /// The row for a repo's security alerts: how many alerts a scan opened since the viewer last read
238247 /// the row. It links to the repo's security page through the open route.
239248 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);
241250 let count = note.new_alerts;
242251 RowView {
243- item_class: if note.unread {
244- "notif-row unread"
245- } else {
246- "notif-row"
247- },
252+ item_class: item_class(note.unread),
248253 icon_class: "notif-icon advisory",
249254 kind_label: g::t(lang, K::KindSecurityAlerts),
250255 open_href: format!(
@@ -258,9 +263,9 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie
258263 title_line: format!("{}/{}", note.repo_owner, note.repo_name),
259264 reason: g::t(lang, K::ReasonSecurity),
260265 activity: g::new_alerts(lang, count),
261- iso: iso_time(unix),
262- absolute: forge_core::tz::format_in_tz(unix, tz),
263- relative: relative_time(lang, unix, now),
266+ iso,
267+ absolute,
268+ relative,
264269 unread: note.unread,
265270 }
266271 }
@@ -268,13 +273,9 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie
268273 /// The row for an admin alert: the headline as the title and the explanation as the activity. It
269274 /// opens the health page.
270275 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);
272277 RowView {
273- item_class: if note.unread {
274- "notif-row unread"
275- } else {
276- "notif-row"
277- },
278+ item_class: item_class(note.unread),
278279 icon_class: if note.resolved {
279280 "notif-icon admin-resolved"
280281 } else {
@@ -286,13 +287,29 @@ fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView {
286287 title_line: alert_text::title(lang, &note.kind, &note.subject, note.resolved),
287288 reason: g::t(lang, K::ReasonAdmin),
288289 activity: alert_text::body(lang, &note.kind, &note.subject, &note.detail, note.resolved),
289- iso: iso_time(unix),
290- absolute: forge_core::tz::format_in_tz(unix, tz),
291- relative: relative_time(lang, unix, now),
290+ iso,
291+ absolute,
292+ relative,
292293 unread: note.unread,
293294 }
294295 }
295296
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+
296313 /// Whether the viewer may see an inbox entry: its repo must be readable, and security alerts need
297314 /// the repo's managers, the same rule as the security page. `readable` caches the repo checks.
298315 /// Admin alerts need no repo.
@@ -309,14 +326,14 @@ async fn entry_visible(
309326 let visible = match readable.get(repo_id) {
310327 Some(visible) => *visible,
311328 None => {
312- let visible = can_read(state, user, repo_id).await?;
329+ let visible = repo_allows(state, user, repo_id, Action::Read).await?;
313330 readable.insert(repo_id.to_owned(), visible);
314331 visible
315332 }
316333 };
317334 Ok(visible
318335 && (!matches!(entry, Entry::Advisory(_))
319- || can_manage_alerts(state, user, repo_id).await?))
336+ || repo_allows(state, user, repo_id, Action::Write).await?))
320337 }
321338 #[page("/notifications")]
322339 async fn inbox(cx: &Cx) -> Result<impl View> {
@@ -386,48 +403,30 @@ async fn inbox(cx: &Cx) -> Result<impl View> {
386403 let mut groups: Vec<RepoGroup> = Vec::new();
387404 let mut index: HashMap<String, usize> = HashMap::new();
388405 for entry in merged {
389- let repo_id = entry.repo_id().to_owned();
390- if let Entry::Admin(_) = &entry {
391- // Admin alerts need no repo access.
392- let slot = match index.get(&repo_id) {
393- Some(slot) => *slot,
394- None => {
395- groups.push(RepoGroup {
396- heading: alert_text::inbox_heading(lang).to_owned(),
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- }
406+ if let Entry::Admin(note) = &entry {
407+ let slot = group_slot(&mut groups, &mut index, ADMIN_GROUP, || RepoGroup {
408+ heading: alert_text::inbox_heading(lang).to_owned(),
409+ href: "/admin/health".to_owned(),
410+ mark_action: format!("/notifications/mark_all_read?repo={ADMIN_GROUP}"),
411+ rows: Vec::new(),
412+ });
413+ groups[slot].rows.push(admin_row(lang, note, &tz, now));
408414 continue;
409415 }
410416 if !entry_visible(state, user, &mut readable, &entry).await? {
411417 hidden.push(entry);
412418 continue;
413419 }
414- let slot = match index.get(&repo_id) {
415- Some(slot) => *slot,
416- None => {
417- let heading = format!("{}/{}", entry.repo_owner(), entry.repo_name());
418- groups.push(RepoGroup {
419- href: repo_href(entry.repo_owner(), entry.repo_name(), "", ""),
420- mark_action: format!(
421- "/notifications/mark_all_read?repo={}",
422- percent_encode(&repo_id)
423- ),
424- heading,
425- rows: Vec::new(),
426- });
427- index.insert(repo_id.clone(), groups.len() - 1);
428- groups.len() - 1
429- }
430- };
420+ let repo_id = entry.repo_id().to_owned();
421+ let slot = group_slot(&mut groups, &mut index, &repo_id, || RepoGroup {
422+ heading: format!("{}/{}", entry.repo_owner(), entry.repo_name()),
423+ href: repo_href(entry.repo_owner(), entry.repo_name(), "", ""),
424+ mark_action: format!(
425+ "/notifications/mark_all_read?repo={}",
426+ percent_encode(&repo_id)
427+ ),
428+ rows: Vec::new(),
429+ });
431430 let row = match entry {
432431 Entry::Issue(note) => issue_row(lang, &note, &tz, now),
433432 Entry::Discussion(note) => discussion_row(lang, &note, &tz, now),
@@ -572,7 +571,7 @@ async fn open_notification(cx: &Cx) -> Result<SeeOther> {
572571 };
573572 state.store.mark_read(&user.id, id).await?;
574573 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? {
576575 return Err(not_found().into());
577576 }
578577 let section = if target.is_pull { "pulls" } else { "issues" };
@@ -600,7 +599,7 @@ async fn open_discussion_notification(cx: &Cx) -> Result<SeeOther> {
600599 .mark_discussion_notification_read(&user.id, id)
601600 .await?;
602601 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? {
604603 return Err(not_found().into());
605604 }
606605 let href = repo_href(
@@ -641,7 +640,7 @@ async fn open_advisory_notification(cx: &Cx) -> Result<SeeOther> {
641640 .mark_advisory_notification_read(&user.id, repo_id)
642641 .await?;
643642 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? {
645644 return Err(not_found().into());
646645 }
647646 Ok(see_other(repo_href(
@@ -673,13 +672,7 @@ async fn open_admin_notification(cx: &Cx) -> Result<SeeOther> {
673672 let (user, _) = require_user(cx).await?;
674673 let state = context::<AppState>(cx);
675674 let id = admin_note(cx);
676- let owned = state
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 {
675+ if !user.is_admin || state.store.admin_notice(&user.id, id).await?.is_none() {
683676 return Err(not_found().into());
684677 }
685678 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> {
865858 )))
866859 }
867860
868-/// Whether the viewer may manage the repo's security alerts: Write on the repo, the same rule as
869-/// the security page. Rows for a repo the viewer may not manage are hidden from the inbox.
870-async fn can_manage_alerts(state: &AppState, user: &User, repo_id: &str) -> Result<bool> {
871- let Some(repo) = state.store.repo_by_id(repo_id).await? else {
872- return Ok(false);
873- };
874- let role: Option<Role> = state.store.collaborator_role(&repo.id, &user.id).await?;
875- let org_role = state
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> {
861+/// Whether the viewer may do `action` on the repo right now, by their current collaborator role.
862+/// Security alerts need Write, the same rule as the security page.
863+pub async fn repo_allows(
864+ state: &AppState,
865+ user: &User,
866+ repo_id: &str,
867+ action: Action,
868+) -> Result<bool> {
884869 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
885870 return Ok(false);
886871 };
@@ -889,7 +874,7 @@ pub async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Result<bo
889874 .store
890875 .org_repo_role(&repo.owner_id, &user.id, &repo.id)
891876 .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())
893878 }
894879
895880 /// 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 @@
44 //! rendered by the profile page.
55
66 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};
88 use futures_util::{Stream, stream};
99 use serde::Deserialize;
1010 use tokio::sync::watch;
@@ -70,9 +70,7 @@ pub async fn package_rows(
7070 if summary.version_count == 0 {
7171 continue;
7272 }
73- let readable = package_ops::may_read(state, viewer, owner, &summary.package)
74- .await
75- .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?;
73+ let readable = package_ops::may_read(state, viewer, owner, &summary.package).await?;
7674 if !readable {
7775 continue;
7876 }
@@ -112,8 +110,12 @@ async fn package_page(cx: &Cx) -> Result<impl View> {
112110 };
113111 let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await {
114112 Ok(package) => package,
113+ Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg).into()),
115114 Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await {
116115 Ok(package) => package,
116+ Err(PackageError::Internal(msg)) => {
117+ return Err(forge_core::Error::Database(msg).into());
118+ }
117119 Err(_) => return Err(not_found().into()),
118120 },
119121 };
@@ -159,17 +161,6 @@ async fn package_page(cx: &Cx) -> Result<impl View> {
159161 let publish_cmd = format!("cargo publish --registry {}", owner.username);
160162 let login_cmd = format!("cargo login --registry {}", owner.username);
161163 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();
173164 let readme_href = format!(
174165 "{}?tab=readme",
175166 package_href(&owner.username, &package.name)
@@ -199,7 +190,7 @@ async fn package_page(cx: &Cx) -> Result<impl View> {
199190 add_cmd,
200191 publish_cmd,
201192 login_cmd,
202- version_rows,
193+ versions,
203194 lang,
204195 };
205196 Ok(view! {
@@ -235,7 +226,7 @@ async fn tag_delete(cx: &Cx, Form(form): Form<TagDeleteForm>) -> Result<SeeOther
235226 };
236227 let allowed = package_ops::may_publish(state, &viewer, &owner)
237228 .await
238- .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?;
229+ .map_err(forge_core::Error::from)?;
239230 if !allowed {
240231 return Err(forbidden().into());
241232 }
@@ -266,7 +257,7 @@ struct PackagePage {
266257 add_cmd: String,
267258 publish_cmd: String,
268259 login_cmd: String,
269- version_rows: Vec<(String, String, bool, String)>,
260+ versions: Vec<PackageVersion>,
270261 lang: Lang,
271262 }
272263
@@ -289,7 +280,7 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> {
289280 add_cmd,
290281 publish_cmd,
291282 login_cmd,
292- version_rows,
283+ versions,
293284 ..
294285 } = page;
295286 let has_readme = !readme_html.is_empty();
@@ -299,8 +290,14 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> {
299290 let readme_on = !versions_tab;
300291 let readme_current: Option<&str> = readme_on.then_some("page");
301292 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();
303294 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+ ];
304301 let copy_label = pk::t(lang, K::CopyCommand);
305302 let readme_label = pk::t(lang, K::Readme);
306303 let versions_label = pk::t(lang, K::PackageVersions);
@@ -334,42 +331,29 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> {
334331 <p>(description.as_str())</p>
335332 }
336333 <h2>(install)</h2>
337- <p class="hint">(pk::t(lang, K::InstallRegistryConfig))</p>
338- <div class="copy-box">
339- <code id="pkg-config">(config_block.as_str())</code>
340- <button type="button" data-copy="pkg-config">(copy_label)</button>
341- </div>
342- <p class="hint">(pk::t(lang, K::InstallAdd))</p>
343- <div class="copy-box">
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>
334+ for (hint, id, cmd) in install_cmds {
335+ <p class="hint">(hint)</p>
336+ <div class="copy-box">
337+ <code id=(id)>(cmd.as_str())</code>
338+ <button type="button" data-copy=(id)>(copy_label)</button>
339+ </div>
340+ }
357341 </section>
358342 if versions_tab {
359343 if has_versions {
360- for (version, date, yanked, checksum) in version_rows.iter() {
344+ for v in versions.iter() {
361345 <details class="row-open" data-kb-row="">
362346 <summary class="line">
363347 <span class="name">
364- (version.as_str())
365- if *yanked {
348+ (v.version.as_str())
349+ if v.yanked {
366350 " " <span class="badge">(pk::t(lang, K::VersionYanked))</span>
367351 }
368352 </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>
370354 </summary>
371355 <div class="opened">
372- <code class="hint">(checksum.as_str())</code>
356+ <code class="hint">(v.checksum.as_str())</code>
373357 </div>
374358 </details>
375359 }
crates/forge-web-pages/src/pages/packages_oci.rsmodified+5 -19
@@ -39,9 +39,7 @@ pub async fn model(
3939 ) -> forge_core::Result<OciPage> {
4040 let tags = state.store.oci_tags(&package.id).await?;
4141 let can_delete = match viewer {
42- Some(user) => package_ops::may_publish(state, user, owner)
43- .await
44- .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?,
42+ Some(user) => package_ops::may_publish(state, user, owner).await?,
4543 None => false,
4644 };
4745 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> {
9997 let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name));
10098 let private = package.private;
10199 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();
114100 // The head holds the name, the owner, the newest tag and the private note; the install and tag
115101 // topics sit in one sheet below it.
116102 let mut sub = vec![SubPart::text(format!(
@@ -150,13 +136,13 @@ pub async fn oci_package_view(cx: &Cx, page: OciPage) -> Result<impl View> {
150136 <h2>(pk::t(lang, K::ContainerTags)) " " <span class="tab-count">(tag_count.as_str())</span></h2>
151137 if has_tags {
152138 <div>
153- for (tag, short, full, size, created) in rows.iter() {
139+ for t in tags.iter() {
154140 <div class="line" data-kb-row="">
155- <span class="name"><code>(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>
141+ <span class="name"><code>(t.tag.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>
157143 if can_delete {
158144 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())])
160146 }
161147 </div>
162148 }
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> {
8080 }
8181
8282 /// 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> {
8484 let request = uri(cx);
8585 let query = request.query()?;
8686 let (_, code) =
@@ -569,16 +569,7 @@ async fn review_comment_resolve(cx: &Cx, Form(form): Form<ReviewForm>) -> Result
569569 let pr = pull_for(state, &ctx, number).await?;
570570 let comment = comment_on_pull(state, &pr, &user, comment_id(cx)).await?;
571571 let is_pr_author = pr.issue.author_id == user.id;
572- if !is_pr_author
573- && authorize(
574- Some(&user),
575- &ctx.repo,
576- ctx.role,
577- ctx.org_role,
578- Action::Write,
579- )
580- .is_err()
581- {
572+ if !is_pr_author && !ctx.can_write() {
582573 return Err(forbidden().into());
583574 }
584575 let root = root_of(&comment);
@@ -788,15 +779,7 @@ async fn review_dismiss(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOthe
788779 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
789780 let (user, session) = require_user(cx).await?;
790781 check_write(&ctx, &session, &form.csrf)?;
791- if authorize(
792- Some(&user),
793- &ctx.repo,
794- ctx.role,
795- ctx.org_role,
796- Action::Write,
797- )
798- .is_err()
799- {
782+ if !ctx.can_write() {
800783 return Err(forbidden().into());
801784 }
802785 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 {
152152 see_other(format!("{href}?notice={word}"))
153153 }
154154
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+
155162 /// A byte count for people: "512 B", "1.5 KiB", "3.2 MiB".
156163 pub fn size_text(bytes: u64) -> String {
157164 const KIB: f64 = 1024.0;
@@ -186,6 +193,20 @@ fn asset_link(title: &str, tag: &str, asset: &ReleaseAsset) -> AssetLink {
186193 }
187194 }
188195
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+
189210 /// One release card on the list page.
190211 pub struct ReleaseCard {
191212 pub title: String,
@@ -215,25 +236,18 @@ fn card_of(
215236 latest_id: Option<&str>,
216237 ) -> ReleaseCard {
217238 let title = title_of(ctx);
218- let when = release
219- .published_at
220- .as_deref()
221- .unwrap_or(&release.created_at);
222239 ReleaseCard {
223240 title: release.title.clone(),
224241 tag: release.tag.clone(),
225242 href: tag_href(&title, &release.tag),
226243 edit_href: release_edit_href(&title, &release.id),
227244 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()),
229246 author: release.author_name.clone(),
230247 draft: release.draft,
231248 prerelease: release.prerelease,
232249 latest: latest_id == Some(release.id.as_str()),
233- assets: assets
234- .iter()
235- .map(|asset| asset_link(&title, &release.tag, asset))
236- .collect(),
250+ assets: asset_links(&title, &release.tag, assets),
237251 }
238252 }
239253
@@ -250,10 +264,7 @@ pub async fn latest_release_for_home(
250264 Ok(Some(LatestRelease {
251265 tag: release.tag.clone(),
252266 href: tag_href(&title, &release.tag),
253- assets: assets
254- .iter()
255- .map(|asset| asset_link(&title, &release.tag, asset))
256- .collect(),
267+ assets: asset_links(&title, &release.tag, &assets),
257268 }))
258269 }
259270
@@ -269,6 +280,27 @@ struct FormDraft {
269280 error: Option<String>,
270281 }
271282
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+
272304 /// The new-release form fields.
273305 #[derive(Deserialize)]
274306 struct CreateForm {
@@ -636,10 +668,7 @@ async fn release_new_page(cx: &Cx) -> Result<impl View> {
636668 require_write(&ctx)?;
637669 let lang = i18n::lang(cx, viewer_user(&ctx));
638670 let state = context::<AppState>(cx);
639- let csrf = match crate::auth::current_user(cx).await? {
640- Some((_, session)) => session.csrf_token.clone(),
641- None => String::new(),
642- };
671+ let csrf = csrf_token(cx).await?;
643672 let draft = FormDraft {
644673 target: ctx.repo.default_branch.clone(),
645674 draft: false,
@@ -664,15 +693,14 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi
664693 require_write(&ctx)?;
665694 let lang = i18n::lang(cx, viewer_user(&ctx));
666695 let state = context::<AppState>(cx);
667- let draft = FormDraft {
668- tag: form.tag.trim().to_owned(),
669- target: form.target.trim().to_owned(),
670- title: form.title.trim().to_owned(),
671- body: form.body.trim_end().to_owned(),
672- prerelease: form.prerelease.is_some(),
673- draft: form.draft.is_some(),
674- error: None,
675- };
696+ let draft = FormDraft::from_fields(
697+ &form.tag,
698+ &form.target,
699+ &form.title,
700+ &form.body,
701+ form.prerelease.is_some(),
702+ form.draft.is_some(),
703+ );
676704 match create_checked(state, &ctx, &user, &draft, lang).await? {
677705 Ok(release) => {
678706 let title = title_of(&ctx);
@@ -752,15 +780,8 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> {
752780 }
753781 let title = title_of(&ctx);
754782 let assets = state.store.list_release_assets(&release.id).await?;
755- let links: Vec<AssetLink> = assets
756- .iter()
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());
783+ let links = asset_links(&title, &release.tag, &assets);
784+ let when = When::new(ctx.lang, when_of(&release), ctx.viewer_tz(), now_unix());
764785 let body_html = render_markdown(&release.body, None);
765786 let page_title = format!("{title} \u{b7} {}", release.title);
766787 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> {
784805 let notice = notice_from_query(cx, lang);
785806 let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id));
786807 let live = releases_live::tag_live_url(&title, &release.tag);
787- let csrf = match crate::auth::current_user(cx).await? {
788- Some((_, session)) => session.csrf_token.clone(),
789- None => String::new(),
790- };
808+ let csrf = csrf_token(cx).await?;
791809 Ok(view! {
792810 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
793811 repo_head(head: head, title: Some(card.title.clone()),
@@ -958,10 +976,7 @@ async fn edit_parts(
958976 )
959977 })
960978 .collect();
961- let links: Vec<AssetLink> = assets
962- .iter()
963- .map(|asset| asset_link(&title, &release.tag, asset))
964- .collect();
979+ let links = asset_links(&title, &release.tag, &assets);
965980 let refs = load_refs(ctx.path.clone()).await?;
966981 Ok(EditParts {
967982 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> {
9941009 if release.repo_id != ctx.repo.id {
9951010 return Err(not_found().into());
9961011 }
997- let csrf = match crate::auth::current_user(cx).await? {
998- Some((_, session)) => session.csrf_token.clone(),
999- None => String::new(),
1000- };
1012+ let csrf = csrf_token(cx).await?;
10011013 let draft = FormDraft {
10021014 tag: release.tag.clone(),
10031015 title: release.title.clone(),
@@ -1032,15 +1044,14 @@ async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View
10321044 let Some(before) = state.store.release(&id).await? else {
10331045 return Err(not_found().into());
10341046 };
1035- let draft = FormDraft {
1036- tag: form.tag.trim().to_owned(),
1037- target: form.target.trim().to_owned(),
1038- title: form.title.trim().to_owned(),
1039- body: form.body.trim_end().to_owned(),
1040- prerelease: form.prerelease.is_some(),
1041- draft: form.draft.is_some(),
1042- error: None,
1043- };
1047+ let draft = FormDraft::from_fields(
1048+ &form.tag,
1049+ &form.target,
1050+ &form.title,
1051+ &form.body,
1052+ form.prerelease.is_some(),
1053+ form.draft.is_some(),
1054+ );
10441055 let edit = EditRelease {
10451056 title: draft.title.clone(),
10461057 body: draft.body.clone(),
@@ -1135,7 +1146,7 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> {
11351146 let state = context::<AppState>(cx);
11361147 let href = release_edit_href(&title_of(&ctx), &id);
11371148 let max_bytes = state
1138- .config
1149+ .live()
11391150 .releases
11401151 .max_asset_mb
11411152 .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 {
3636 format!("/{title}/releases/tag/{}/events", enc(tag))
3737 }
3838
39-// Fingerprints. Each reads what the page shows; any change to it changes the string. `writer`
40-// decides whether drafts are part of it, the same way the pages decide.
39+async fn asset_lines(store: &Store, release_id: &str) -> Result<Vec<String>> {
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+}
4146
4247 /// What the release list shows: the latest release and every release the viewer may see, with
4348 /// their assets (names, sizes, download counts).
@@ -52,9 +57,7 @@ pub async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool) -> Res
5257 continue;
5358 }
5459 lines.push(format!("{release:?}"));
55- for asset in store.list_release_assets(&release.id).await? {
56- lines.push(format!("asset {asset:?}"));
57- }
60+ lines.extend(asset_lines(store, &release.id).await?);
5861 }
5962 Ok(lines.join("\n"))
6063 }
@@ -74,9 +77,7 @@ pub async fn release_fingerprint(
7477 return Ok("gone".to_owned());
7578 }
7679 let mut lines = vec![format!("{release:?}")];
77- for asset in store.list_release_assets(&release.id).await? {
78- lines.push(format!("asset {asset:?}"));
79- }
80+ lines.extend(asset_lines(store, &release.id).await?);
8081 Ok(lines.join("\n"))
8182 }
8283
@@ -106,16 +107,12 @@ async fn release_events(cx: &Cx) -> Result<Response> {
106107 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
107108 let state = context::<AppState>(cx);
108109 let writer = can_write(&ctx);
109- let visible = match state.store.release_by_tag(&ctx.repo.id, &tag).await? {
110- Some(release) => writer || !release.draft,
111- None => false,
112- };
113- if !visible {
110+ let store = state.store.clone();
111+ let repo_id = ctx.repo.id.clone();
112+ if release_fingerprint(&store, &repo_id, &tag, writer).await? == "gone" {
114113 return Err(not_found().into());
115114 }
116115 let topic = Topic::RepoReleases(ctx.repo.id.clone());
117- let store = state.store.clone();
118- let repo_id = ctx.repo.id.clone();
119116 stream_changes(cx, &state.live, &[topic], move || {
120117 let store = store.clone();
121118 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> {
397397 facts = Some(tree_facts(state, repo, &ctx.path, commit, &names).await?);
398398 let (last, latest) = tokio::join!(
399399 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()),
401401 );
402402 bar = latest;
403403 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 {
121121 }
122122
123123 impl RepoCtx {
124+ pub fn title(&self) -> String {
125+ format!("{}/{}", self.repo.owner_name, self.repo.name)
126+ }
127+
124128 /// Whether the viewer may delete this repo: its owner or an instance admin only.
125129 pub fn can_delete(&self) -> bool {
126130 let actor = self.viewer.as_ref().map(|(user, _)| user);
@@ -138,8 +142,7 @@ impl RepoCtx {
138142 /// Write role or higher, an org role that grants it, or the owner. Archived repos stay read-only.
139143 pub fn can_write(&self) -> bool {
140144 let actor = self.viewer.as_ref().map(|(user, _)| user);
141- !self.repo.archived
142- && authorize(actor, &self.repo, self.role, self.org_role, Action::Write).is_ok()
145+ authorize(actor, &self.repo, self.role, self.org_role, Action::Write).is_ok()
143146 }
144147
145148 /// Open issue count for the Issues tab: one indexed COUNT query.
@@ -155,17 +158,8 @@ impl RepoCtx {
155158 let Some(source) = state.store.repo_by_id(source_id).await? else {
156159 return Ok(None);
157160 };
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- };
168161 let actor = self.viewer.as_ref().map(|(user, _)| user);
162+ let (role, org_role) = access(&state.store, actor, &source).await?;
169163 if authorize(actor, &source, role, org_role, Action::Read).is_err() {
170164 return Ok(None);
171165 }
@@ -200,8 +194,7 @@ impl RepoCtx {
200194 let forks = fork_count(state, &self.repo.id).await?;
201195 let discussions = state.store.discussions_enabled(&self.repo.id).await?;
202196 let wiki = state.store.wiki_enabled(&self.repo.id).await?;
203- let security =
204- state.config.advisories.enabled && crate::pages::repo_security::can_write(self);
197+ let security = state.config.advisories.enabled && self.can_write();
205198 let mirror = state
206199 .store
207200 .pull_mirror(&self.repo.id)
@@ -264,12 +257,29 @@ impl RepoCtx {
264257 }
265258 }
266259
267-/// Load `owner/name` for the current viewer, or 404.
268260 /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`).
269261 pub async fn fork_count(state: &AppState, repo_id: &str) -> Result<u64> {
270262 Ok(state.store.public_fork_count(repo_id).await?)
271263 }
272264
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.
273283 pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {
274284 let state = context::<AppState>(cx);
275285 let viewer = current_user(cx).await?;
@@ -280,17 +290,8 @@ pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> {
280290 }
281291 return Err(not_found().into());
282292 };
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- };
293293 let actor = viewer.as_ref().map(|(user, _)| user);
294+ let (role, org_role) = access(&state.store, actor, &repo).await?;
294295 if authorize(actor, &repo, role, org_role, Action::Read).is_err() {
295296 return Err(not_found().into());
296297 }
@@ -313,20 +314,8 @@ pub async fn still_readable(store: &Store, viewer: Option<&User>, repo_id: &str)
313314 let Ok(Some(repo)) = store.repo_by_id(repo_id).await else {
314315 return false;
315316 };
316- let (role, org_role) = match viewer {
317- Some(user) => {
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),
317+ let Ok((role, org_role)) = access(store, viewer, &repo).await else {
318+ return false;
330319 };
331320 authorize(viewer, &repo, role, org_role, Action::Read).is_ok()
332321 }
@@ -357,17 +346,8 @@ async fn moved_location(
357346 None => return Ok(None),
358347 },
359348 };
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- };
370349 let actor = viewer.map(|(user, _)| user);
350+ let (role, org_role) = access(&state.store, actor, &target).await?;
371351 if authorize(actor, &target, role, org_role, Action::Read).is_err() {
372352 return Ok(None);
373353 }
crates/forge-web-pages/src/pages/repo_mirrors.rsmodified+44 -37
@@ -262,12 +262,34 @@ fn interval_text(lang: Lang, minutes: u32) -> String {
262262 }
263263 }
264264
265-/// The last sync, as the list and the header show it: ok, failed (with the error) or not run yet.
266-fn status_of(lang: Lang, mirror: &Mirror) -> (&'static str, &'static str) {
265+#[derive(Clone, Copy)]
266+enum SyncStatus {
267+ Ok,
268+ Failed,
269+ NotRun,
270+}
271+
272+fn sync_status(mirror: &Mirror) -> SyncStatus {
267273 match mirror.last_ok {
268- Some(true) => ("ok", g::t(lang, K::StatusOk)),
269- Some(false) => ("failed", g::t(lang, K::StatusFailed)),
270- None => ("none", g::t(lang, K::StatusNotRun)),
274+ Some(true) => SyncStatus::Ok,
275+ Some(false) => SyncStatus::Failed,
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",
271293 }
272294 }
273295
@@ -338,12 +360,7 @@ struct MirrorRow {
338360 }
339361
340362 fn mirror_row(lang: Lang, mirror: &Mirror, title: &str, tz: &str) -> MirrorRow {
341- let (status_class, status_text) = status_of(lang, 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- };
363+ let status = sync_status(mirror);
347364 let (sync_prefix, sync_suffix) = match lang {
348365 Lang::En => ("synced ", ""),
349366 Lang::Tr => ("", " eşitlendi"),
@@ -370,8 +387,8 @@ fn mirror_row(lang: Lang, mirror: &Mirror, title: &str, tz: &str) -> MirrorRow {
370387 last_sync_rel,
371388 sync_prefix,
372389 sync_suffix,
373- dot_class,
374- status_text,
390+ dot_class: dot_class(mirror.enabled, status),
391+ status_text: status_label(lang, status),
375392 error: mirror.last_error.clone().unwrap_or_default(),
376393 }
377394 }
@@ -697,12 +714,7 @@ async fn mirror_create(cx: &Cx, Form(form): Form<PushForm>) -> Result<impl View>
697714 let name = repo(cx);
698715 let ctx = load_repo(cx, owner, name).await?;
699716 let (user, session) = require_csrf(cx, &form.csrf).await?;
700- if !ctx.can_admin() {
701- return Err(not_found().into());
702- }
703- if ctx.repo.archived {
704- return Err(forbidden().into());
705- }
717+ require_mirror_admin(&ctx)?;
706718 let state = context::<AppState>(cx);
707719 let lang = lang_of(cx, &ctx);
708720 let pull = form.direction == "pull";
@@ -760,6 +772,16 @@ async fn mirror_create(cx: &Cx, Form(form): Form<PushForm>) -> Result<impl View>
760772 Err(back_to_list(&title_of(&ctx), notice).into())
761773 }
762774
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+
763785 /// The mirror in the path, when it belongs to this repo. Any other mirror answers 404.
764786 async fn repo_mirror(state: &AppState, ctx: &RepoCtx, id: &str) -> Result<Mirror> {
765787 match state.store.mirror(id).await? {
@@ -881,12 +903,7 @@ async fn mirror_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View>
881903 let id = mirror_id(cx);
882904 let ctx = load_repo(cx, owner, name).await?;
883905 let (user, session) = require_csrf(cx, &form.csrf).await?;
884- if !ctx.can_admin() {
885- return Err(not_found().into());
886- }
887- if ctx.repo.archived {
888- return Err(forbidden().into());
889- }
906+ require_mirror_admin(&ctx)?;
890907 let state = context::<AppState>(cx);
891908 let mirror = repo_mirror(state, &ctx, id).await?;
892909 let url = if form.url.trim().is_empty() {
@@ -975,12 +992,7 @@ async fn mirror_sync(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
975992 let id = mirror_id(cx);
976993 let ctx = load_repo(cx, owner, name).await?;
977994 require_csrf(cx, &form.csrf).await?;
978- if !ctx.can_admin() {
979- return Err(not_found().into());
980- }
981- if ctx.repo.archived {
982- return Err(forbidden().into());
983- }
995+ require_mirror_admin(&ctx)?;
984996 let state = context::<AppState>(cx);
985997 let mirror = repo_mirror(state, &ctx, id).await?;
986998 state
@@ -999,12 +1011,7 @@ async fn mirror_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther
9991011 let id = mirror_id(cx);
10001012 let ctx = load_repo(cx, owner, name).await?;
10011013 let (user, _) = require_csrf(cx, &form.csrf).await?;
1002- if !ctx.can_admin() {
1003- return Err(not_found().into());
1004- }
1005- if ctx.repo.archived {
1006- return Err(forbidden().into());
1007- }
1014+ require_mirror_admin(&ctx)?;
10081015 let state = context::<AppState>(cx);
10091016 let mirror = repo_mirror(state, &ctx, id).await?;
10101017 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-
91 use std::path::Path;
102
113 use forge_core::protection::{
@@ -49,14 +41,11 @@ use crate::views::{alert, enc, shell};
4941 path_param!(owner);
5042 path_param!(repo);
5143
52-/// The `?section=` query of the settings page. Unknown values show General.
5344 #[query_params(error = bad_request)]
5445 pub struct SectionQuery {
5546 section: Option<String>,
5647 }
5748
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`.
6049 fn pick_section(raw: Option<&str>) -> &'static str {
6150 match raw {
6251 Some("branches") => "branches",
@@ -65,14 +54,10 @@ fn pick_section(raw: Option<&str>) -> &'static str {
6554 }
6655 }
6756
68-/// Cookie that carries a one-shot notice (the deleted repo's `owner/name`) to the next profile page.
6957 pub const NOTICE_COOKIE: &str = "forge_notice";
7058
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.
7359 const SETTINGS_NOTICE_COOKIE: &str = "forge_settings_notice";
7460
75-/// Notice words, the text each one shows, and whether it is an error (shown as an alert).
7661 const SETTINGS_NOTICES: [(&str, K, bool); 13] = [
7762 ("saved", K::BranchRuleSaved, false),
7863 ("removed", K::BranchRuleRemoved, false),
@@ -89,7 +74,6 @@ const SETTINGS_NOTICES: [(&str, K, bool); 13] = [
8974 ("bad_form", K::BadForm, true),
9075 ];
9176
92-/// Longest accepted `owner/name` in the notice cookie.
9377 const MAX_NOTICE_CHARS: usize = 256;
9478
9579 #[derive(Deserialize)]
@@ -100,19 +84,16 @@ struct DeleteForm {
10084 confirm: String,
10185 }
10286
103-/// The General form: description and default branch, saved together.
10487 #[derive(Deserialize)]
10588 struct GeneralForm {
10689 #[serde(default)]
10790 csrf: String,
10891 #[serde(default)]
10992 description: String,
110- /// Empty when the repo has no branches yet; the current default branch is then kept.
11193 #[serde(default)]
11294 default_branch: String,
11395 }
11496
115-/// The visibility form. `understand` is the confirm popup's hidden field; a request without it is refused.
11697 #[derive(Deserialize)]
11798 struct VisibilityForm {
11899 #[serde(default)]
@@ -127,12 +108,10 @@ struct VisibilityForm {
127108 struct ArchiveForm {
128109 #[serde(default)]
129110 csrf: String,
130- /// `1` archives the repo, `0` unarchives it.
131111 #[serde(default)]
132112 archived: String,
133113 }
134114
135-/// The add/update rule form. An unchecked box is absent from the body, so `Option` is `None`.
136115 #[derive(Deserialize)]
137116 struct BranchForm {
138117 #[serde(default)]
@@ -143,7 +122,6 @@ struct BranchForm {
143122 allow_force_push: Option<String>,
144123 #[serde(default)]
145124 allow_deletion: Option<String>,
146- /// Text from the number field; blank means 0.
147125 #[serde(default)]
148126 required_approvals: String,
149127 #[serde(default)]
@@ -154,11 +132,8 @@ struct BranchForm {
154132 restrict_push: Option<String>,
155133 #[serde(default)]
156134 require_merge_queue: Option<String>,
157- /// Required check contexts, separated by commas or new lines.
158135 #[serde(default)]
159136 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.
162137 #[serde(default)]
163138 existing: Option<String>,
164139 }
@@ -171,10 +146,9 @@ struct BranchDeleteForm {
171146 rule_id: String,
172147 }
173148
174-/// Sets the notice shown on the next profile page view.
175-pub fn set_notice(cx: &Cx, title: &str) {
149+fn set_cookie(cx: &Cx, name: &'static str, value: String) {
176150 cookies(cx).add(
177- Cookie::build((NOTICE_COOKIE, title.to_owned()))
151+ Cookie::build((name, value))
178152 .path("/")
179153 .http_only(true)
180154 .same_site(SameSite::Lax)
@@ -182,11 +156,19 @@ pub fn set_notice(cx: &Cx, title: &str) {
182156 );
183157 }
184158
185-/// Reads and clears the notice cookie. Anything that is not a plain `owner/name` is ignored.
186-pub fn take_notice(cx: &Cx) -> Option<String> {
159+fn take_cookie(cx: &Cx, name: &'static str) -> Option<String> {
187160 let jar = cookies(cx);
188- let value = jar.get(NOTICE_COOKIE)?.value().to_owned();
189- jar.remove(Cookie::build((NOTICE_COOKIE, "")).path("/"));
161+ let value = jar.get(name)?.value().to_owned();
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)?;
190172 let plain = !value.is_empty()
191173 && value.chars().count() <= MAX_NOTICE_CHARS
192174 && value
@@ -195,40 +177,26 @@ pub fn take_notice(cx: &Cx) -> Option<String> {
195177 plain.then_some(value)
196178 }
197179
198-/// Sets the one-line notice shown on the next settings page view.
199180 pub fn set_settings_notice(cx: &Cx, word: &'static str) {
200- cookies(cx).add(
201- Cookie::build((SETTINGS_NOTICE_COOKIE, word))
202- .path("/")
203- .http_only(true)
204- .same_site(SameSite::Lax)
205- .build(),
206- );
181+ set_cookie(cx, SETTINGS_NOTICE_COOKIE, word.to_owned());
207182 }
208183
209-/// Reads and clears the settings notice cookie. Only the fixed words are shown. The flag says
210-/// whether the notice is an error.
211184 fn take_settings_notice(cx: &Cx) -> Option<(K, bool)> {
212- let jar = cookies(cx);
213- let value = jar.get(SETTINGS_NOTICE_COOKIE)?.value().to_owned();
214- jar.remove(Cookie::build((SETTINGS_NOTICE_COOKIE, "")).path("/"));
185+ let value = take_cookie(cx, SETTINGS_NOTICE_COOKIE)?;
215186 SETTINGS_NOTICES
216187 .iter()
217188 .find(|(word, _, _)| *word == value)
218189 .map(|(_, key, is_error)| (*key, *is_error))
219190 }
220191
221-/// Redirect back to the General section, which shows the notice set just before.
222192 fn back_to_settings(title: &str) -> SeeOther {
223193 see_other(format!("/{title}/settings"))
224194 }
225195
226-/// Redirect back to one section of the settings page (its `?section=` value).
227196 fn back_to_section(title: &str, section: &str) -> SeeOther {
228197 see_other(format!("/{title}/settings?section={section}"))
229198 }
230199
231-/// Drops control characters (so the text is one line) and surrounding spaces.
232200 fn clean_description(raw: &str) -> String {
233201 raw.chars()
234202 .filter(|c| !c.is_control())
@@ -237,8 +205,6 @@ fn clean_description(raw: &str) -> String {
237205 .to_owned()
238206 }
239207
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.
242208 async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git::Result<()> {
243209 GitCommand::new(env, "symbolic-ref")
244210 .git_dir(repo_path)
@@ -248,7 +214,6 @@ async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git::
248214 .await
249215 }
250216
251-/// Branch names of the repo. Empty for an empty repo.
252217 async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> {
253218 let refs = load_refs(ctx.path.clone()).await?;
254219 Ok(refs
@@ -258,7 +223,6 @@ async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> {
258223 .collect())
259224 }
260225
261-/// The one-line notice on the profile page after a delete.
262226 #[component]
263227 pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Result<impl View> {
264228 Ok(view! {
@@ -270,8 +234,6 @@ pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Re
270234 })
271235 }
272236
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.
275237 pub struct DangerForms {
276238 pub rename_name: String,
277239 pub rename_error: Option<String>,
@@ -292,7 +254,6 @@ impl DangerForms {
292254 }
293255 }
294256
295-/// The Visibility topic: the current value as a line, and the other side behind a confirm.
296257 #[component]
297258 async fn visibility_section(
298259 cx: &Cx,
@@ -331,7 +292,6 @@ async fn visibility_section(
331292 })
332293 }
333294
334-/// The Archive topic: what archiving does, and the one action for the repo's state.
335295 #[component]
336296 async fn archive_section(
337297 cx: &Cx,
@@ -359,9 +319,6 @@ async fn archive_section(
359319 })
360320 }
361321
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.
365322 #[component]
366323 async fn danger_section(
367324 cx: &Cx,
@@ -395,7 +352,6 @@ async fn danger_section(
395352 })
396353 }
397354
398-/// The Delete topic: what deleting does, and the confirmation form, which opens in place.
399355 #[component]
400356 async fn delete_section(
401357 cx: &Cx,
@@ -434,10 +390,6 @@ async fn delete_section(
434390 })
435391 }
436392
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.
441393 #[component]
442394 pub async fn settings_frame(
443395 cx: &Cx,
@@ -499,9 +451,6 @@ pub async fn settings_frame(
499451 })
500452 }
501453
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.
505454 #[component]
506455 async fn general_section(
507456 cx: &Cx,
@@ -554,8 +503,6 @@ async fn general_section(
554503 })
555504 }
556505
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.
559506 fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFlags, String> {
560507 let approvals_msg = || g::t(lang, K::ApprovalsRange).to_owned();
561508 let raw = form.required_approvals.trim();
@@ -583,13 +530,11 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFl
583530 })
584531 }
585532
586-/// One pill in a rule card's summary: its text and its classes.
587533 struct RulePill {
588534 text: String,
589535 class: &'static str,
590536 }
591537
592-/// The pills that describe a rule in its card summary. A rule that sets nothing gets one muted pill.
593538 fn rule_pills(lang: Lang, rule: &BranchRule) -> Vec<RulePill> {
594539 let warn = "warn";
595540 let plain = "";
@@ -634,7 +579,6 @@ fn pill(text: &str, class: &'static str) -> RulePill {
634579 }
635580 }
636581
637-/// A rule as the settings page shows it: its id, its summary pills, and the form it opens with.
638582 struct RuleCard {
639583 id: String,
640584 pills: Vec<RulePill>,
@@ -642,11 +586,6 @@ struct RuleCard {
642586 draft: RuleDraft,
643587 }
644588
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.
650589 #[component]
651590 async fn branch_rule_cards(
652591 cx: &Cx,
@@ -699,11 +638,6 @@ async fn branch_rule_cards(
699638 })
700639 }
701640
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.
707641 #[component]
708642 async fn branch_rule_form(
709643 cx: &Cx,
@@ -728,7 +662,6 @@ async fn branch_rule_form(
728662 error,
729663 is_new: _,
730664 } = draft;
731- // A pull request setting that is not the default keeps its group in view while the switch is off.
732665 let pr_saved = !matches!(required_approvals.trim(), "" | "0")
733666 || block_on_changes_requested
734667 || require_up_to_date
@@ -739,7 +672,6 @@ async fn branch_rule_form(
739672 } else {
740673 "rule-pr"
741674 };
742- // Field ids are per rule, so two open rule forms never share an id.
743675 let prefix = match &rule_id {
744676 Some(id) => format!("rule-{id}"),
745677 None => "rule-new".to_owned(),
@@ -755,8 +687,6 @@ async fn branch_rule_form(
755687 alert(message: message.as_str())
756688 }
757689 <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.
760690 if rule_id.is_some() {
761691 <input type="hidden" name="pattern" value=(pattern.as_str())>
762692 <input type="hidden" name="existing" value="1">
@@ -837,7 +767,6 @@ async fn branch_rule_form(
837767 })
838768 }
839769
840-/// The form values to show: the pattern and checkboxes, plus any validation error.
841770 #[derive(Clone)]
842771 struct RuleDraft {
843772 pattern: String,
@@ -850,12 +779,10 @@ struct RuleDraft {
850779 require_merge_queue: bool,
851780 required_checks: String,
852781 error: Option<String>,
853- /// True for the New rule form's draft, so a refused new rule never opens an existing rule's card.
854782 is_new: bool,
855783 }
856784
857785 impl RuleDraft {
858- /// The values a saved rule opens with.
859786 fn from_rule(rule: &BranchRule) -> Self {
860787 Self {
861788 pattern: rule.pattern.clone(),
@@ -872,7 +799,6 @@ impl RuleDraft {
872799 }
873800 }
874801
875- /// The default values for the add form, with the default branch as the pattern.
876802 fn for_default_branch(default_branch: &str) -> Self {
877803 Self {
878804 pattern: default_branch.to_owned(),
@@ -890,21 +816,16 @@ impl RuleDraft {
890816 }
891817 }
892818
893-/// Everything the settings page shows besides the repo header.
894819 struct SettingsView {
895820 rules: Vec<BranchRule>,
896- /// A settings notice: its text and whether it is an error.
897821 notice: Option<(K, bool)>,
898822 draft: RuleDraft,
899823 danger: DangerForms,
900824 transfer: TransferStatus,
901825 wiki_on: bool,
902- /// Recently reported status contexts, offered as required-check suggestions.
903826 contexts: Vec<String>,
904827 }
905828
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.
908829 pub struct Shown {
909830 section: &'static str,
910831 notice: Option<(K, bool)>,
@@ -913,7 +834,6 @@ pub struct Shown {
913834 }
914835
915836 impl Shown {
916- /// The danger zone, with its forms as they came back.
917837 pub fn danger(danger: DangerForms) -> Self {
918838 Self {
919839 section: "danger",
@@ -924,8 +844,6 @@ impl Shown {
924844 }
925845 }
926846
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.
929847 pub async fn render_settings(
930848 cx: &Cx,
931849 ctx: RepoCtx,
@@ -965,8 +883,6 @@ pub async fn render_settings(
965883 })
966884 }
967885
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.
970886 #[component]
971887 async fn settings_body(
972888 cx: &Cx,
@@ -996,8 +912,6 @@ async fn settings_body(
996912 wiki_on,
997913 contexts,
998914 } = 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.
1001915 let mut draft = Some(draft);
1002916 let mut cards = Vec::with_capacity(rules.len());
1003917 for rule in rules {
@@ -1016,9 +930,7 @@ async fn settings_body(
1016930 });
1017931 }
1018932 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.
1020933 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.
1022934 if !new_open && !cards.iter().any(|card| card.open) {
1023935 match cards.first_mut() {
1024936 Some(first) => first.open = true,
@@ -1033,7 +945,6 @@ async fn settings_body(
1033945 "danger" => g::t(lang, K::DangerZone),
1034946 _ => g::t(lang, K::General),
1035947 };
1036- // Only one section is rendered.
1037948 Ok(view! {
1038949 repo_head(head: head, title: Some(section_name.to_owned()))
1039950 settings_frame(lang: lang, title: title.clone(), current: section,
@@ -1065,7 +976,6 @@ async fn settings_body(
1065976 })
1066977 }
1067978
1068-/// The repo fields the settings page shows, read once from the repo context.
1069979 struct SettingsFrame {
1070980 page_title: String,
1071981 default_branch: String,
@@ -1077,7 +987,7 @@ struct SettingsFrame {
1077987
1078988 impl SettingsFrame {
1079989 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();
1081991 Ok(Self {
1082992 page_title: g::settings_page_title(lang, &title),
1083993 default_branch: ctx.repo.default_branch.clone(),
@@ -1089,8 +999,6 @@ impl SettingsFrame {
1089999 }
10901000 }
10911001
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.
10941002 #[page("/{owner}/{repo}/settings")]
10951003 async fn settings_page(cx: &Cx) -> Result<impl View> {
10961004 let owner = owner(cx);
@@ -1111,9 +1019,6 @@ async fn settings_page(cx: &Cx) -> Result<impl View> {
11111019 render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await
11121020 }
11131021
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.
11171022 #[route(POST "/{owner}/{repo}/settings/general")]
11181023 async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result<SeeOther> {
11191024 let owner = owner(cx);
@@ -1123,7 +1028,7 @@ async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result
11231028 if !ctx.can_admin() {
11241029 return Err(forbidden().into());
11251030 }
1126- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
1031+ let title = ctx.title();
11271032 let state = context::<AppState>(cx);
11281033
11291034 let description = clean_description(&form.description);
@@ -1181,8 +1086,6 @@ async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result
11811086 Ok(back_to_settings(&title))
11821087 }
11831088
1184-/// Changes the visibility. Changing it needs `understand`, which only the confirm popup sends. Picking the current value
1185-/// changes nothing.
11861089 #[route(POST "/{owner}/{repo}/settings/visibility")]
11871090 async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) -> Result<SeeOther> {
11881091 let owner = owner(cx);
@@ -1192,7 +1095,7 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) ->
11921095 if !ctx.can_admin() {
11931096 return Err(forbidden().into());
11941097 }
1195- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
1098+ let title = ctx.title();
11961099 let Ok(target) = form.visibility.parse::<Visibility>() else {
11971100 set_settings_notice(cx, "bad_form");
11981101 return Ok(back_to_section(&title, "danger"));
@@ -1233,8 +1136,6 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) ->
12331136 Ok(back_to_section(&title, "danger"))
12341137 }
12351138
1236-/// Archives (`archived=1`) or unarchives (`archived=0`) the repo. Archiving is an Admin action, and
1237-/// the archived flag does not block Admin.
12381139 #[route(POST "/{owner}/{repo}/settings/archive")]
12391140 async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result<SeeOther> {
12401141 let owner = owner(cx);
@@ -1244,7 +1145,7 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result
12441145 if !ctx.can_admin() {
12451146 return Err(forbidden().into());
12461147 }
1247- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
1148+ let title = ctx.title();
12481149 let archived = match form.archived.as_str() {
12491150 "1" => true,
12501151 "0" => false,
@@ -1288,10 +1189,6 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result
12881189 Ok(back_to_section(&title, "danger"))
12891190 }
12901191
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.
12951192 #[page(POST "/{owner}/{repo}/settings/delete")]
12961193 async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View> {
12971194 let owner = owner(cx);
@@ -1302,7 +1199,7 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
13021199 return Err(forbidden().into());
13031200 }
13041201 let lang = i18n::lang(cx, Some(&user));
1305- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
1202+ let title = ctx.title();
13061203 let error = if form.confirm.trim() == title {
13071204 None
13081205 } else {
@@ -1313,8 +1210,7 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
13131210 let state = context::<AppState>(cx);
13141211 let repo: &RepoRow = &ctx.repo;
13151212 let data_dir = &state.config.data_dir;
1316- // A missing directory (already removed by hand) has nothing to trash, so only the rows go.
1317- // Any other failure to inspect or move the directory aborts before the database is touched.
1213+ let release_assets = state.store.repo_release_asset_ids(&repo.id).await?;
13181214 let trash_path = if repo_dir_missing(data_dir, &repo.id).map_err(forge_core::Error::from)? {
13191215 tracing::warn!(repo_id = %repo.id, "repo dir missing, deleting DB rows only");
13201216 None
@@ -1325,7 +1221,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
13251221 .map_err(forge_core::Error::from)?,
13261222 )
13271223 };
1328- // The wiki goes to the trash with the repo. A failure here puts the repo back first.
13291224 let wiki_trash = match move_wiki_to_trash(data_dir, &repo.id).await {
13301225 Ok(path) => path,
13311226 Err(e) => {
@@ -1338,8 +1233,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
13381233 return Err(forge_core::Error::from(e).into());
13391234 }
13401235 };
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?;
13431236 let deleted = state.store.delete_repo(&repo.id).await;
13441237 state.live.bump_repo(&repo.owner_id, &repo.id);
13451238 if let Err(e) = deleted {
@@ -1393,11 +1286,9 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
13931286 )
13941287 .await;
13951288 set_notice(cx, &title);
1396- // The owner's profile repository list shows the notice (the profile reads the cookie).
13971289 return Err(see_other(format!("/{}?tab=repositories", enc(&ctx.repo.owner_name))).into());
13981290 }
13991291
1400- // The delete form lives in the danger zone, so a failed confirmation draws that section again.
14011292 let shown = Shown {
14021293 section: "danger",
14031294 notice: None,
@@ -1410,8 +1301,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V
14101301 render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await
14111302 }
14121303
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.
14151304 #[page(POST "/{owner}/{repo}/settings/branches")]
14161305 async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<impl View> {
14171306 let owner = owner(cx);
@@ -1423,7 +1312,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
14231312 }
14241313 let lang = i18n::lang(cx, Some(&user));
14251314 let pattern = form.pattern.trim().to_owned();
1426- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
1315+ let title = ctx.title();
14271316
14281317 let is_new = form.existing.is_none();
14291318 let taken = is_new
@@ -1491,7 +1380,6 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
14911380 Err(back_to_section(&title, "branches").into())
14921381 }
14931382
1494-/// Removes a branch rule by id, scoped to this repo. Same checks as the save form.
14951383 #[route(POST "/{owner}/{repo}/settings/branches/delete")]
14961384 async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) -> Result<SeeOther> {
14971385 let owner = owner(cx);
@@ -1520,7 +1408,7 @@ async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) ->
15201408 )
15211409 .await;
15221410 set_settings_notice(cx, "removed");
1523- let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name);
1411+ let title = ctx.title();
15241412 Ok(back_to_section(&title, "branches"))
15251413 }
15261414
@@ -1536,7 +1424,6 @@ mod tests {
15361424
15371425 const CSRF: &str = "settings-test-csrf";
15381426
1539- /// Posts the branch form as `tahinli` and returns the status and body.
15401427 async fn post_rule(app: &Router, cookie: &str, fields: &[(&str, &str)]) -> (u16, String) {
15411428 let mut form = form_urlencoded::Serializer::new(String::new());
15421429 form.append_pair("csrf", CSRF);
@@ -1600,7 +1487,6 @@ mod tests {
16001487 assert!(rule.restrict_push);
16011488 assert!(!rule.allow_force_push && !rule.allow_deletion);
16021489
1603- // A blank count means 0 and unchecked boxes are off.
16041490 let (status, _) = post_rule(
16051491 &app,
16061492 &cookie,
@@ -1618,7 +1504,6 @@ mod tests {
16181504 !rule.block_on_changes_requested && !rule.require_up_to_date && !rule.restrict_push
16191505 );
16201506
1621- // Out of range re-renders the form with the error and saves nothing.
16221507 let (status, body) = post_rule(
16231508 &app,
16241509 &cookie,
@@ -1639,7 +1524,6 @@ mod tests {
16391524 assert_eq!(rule.required_approvals, 0);
16401525 assert!(!rule.restrict_push);
16411526
1642- // Not a number is refused the same way.
16431527 let (status, body) = post_rule(
16441528 &app,
16451529 &cookie,
crates/forge-web-pages/src/pages/tree.rsmodified+3 -6
@@ -125,21 +125,18 @@ pub struct LatestBar {
125125 pub author: String,
126126 }
127127
128-/// Latest commit bar for `dir` at `commit` (`""` is the root). Errors and timeouts leave the bar
129-/// out.
128+/// Latest commit bar at `commit`. Errors and timeouts leave the bar out.
130129 pub async fn latest_bar(
131130 state: &AppState,
132131 repo: &RepoRow,
133132 path: &Path,
134133 commit: &str,
135- dir: &str,
136134 lang: Lang,
137135 tz: &str,
138136 ) -> Option<LatestBar> {
139- let filter = (!dir.is_empty()).then_some(dir);
140137 let log = tokio::time::timeout(
141138 LAST_COMMIT_TIMEOUT,
142- history::log(&state.git, path, commit, filter, 0, 1),
139+ history::log(&state.git, path, commit, None, 0, 1),
143140 )
144141 .await;
145142 let info = match log {
@@ -476,7 +473,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> {
476473 };
477474 let (last, bar, strip, runs) = tokio::join!(
478475 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()),
480477 commit_strip(state, repo, &ctx.path, &commit),
481478 run_rows(state, lang, repo),
482479 );
crates/forge-web-pages/src/pages/wiki.rsmodified+7 -14
@@ -364,16 +364,6 @@ async fn wiki_edit_body(
364364 })
365365 }
366366
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-
377367 #[page("/{owner}/{repo}/wiki")]
378368 async fn wiki_home(cx: &Cx) -> Result<impl View> {
379369 let owner = owner(cx);
@@ -383,7 +373,7 @@ async fn wiki_home(cx: &Cx) -> Result<impl View> {
383373 ensure_enabled(state, &ctx).await?;
384374 let dir = wiki_dir(state, &ctx)?;
385375 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?;
387377 let can_write = ctx.can_write();
388378 let owner_name = ctx.repo.owner_name.clone();
389379 let repo_name = ctx.repo.name.clone();
@@ -469,7 +459,8 @@ async fn wiki_page_view(cx: &Cx) -> Result<impl View> {
469459 }
470460 let dir = wiki_dir(state, &ctx)?;
471461 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?;
473464 let Some(text) = text else {
474465 return Err(not_found().into());
475466 };
@@ -646,7 +637,8 @@ async fn wiki_edit_page(cx: &Cx) -> Result<impl View> {
646637 return Err(not_found().into());
647638 }
648639 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?;
650642 edit_screen(cx, ctx, page_name, false, text.unwrap_or_default(), None).await
651643 }
652644
@@ -667,7 +659,8 @@ async fn wiki_new_post(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View>
667659 Some(g::t(lang, K::PageNameRules).to_owned())
668660 } else {
669661 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?;
671664 if existing.is_some() {
672665 Some(g::t(lang, K::PageExists).to_owned())
673666 } else {
crates/forge-web-repo/src/pages/authoring.rsmodified+7 -43
@@ -29,7 +29,7 @@ use crate::api;
2929 use crate::auth::{current_user, require_csrf};
3030 use crate::blobs::attachment_key;
3131 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};
3333 use crate::render::markdown::{set_task, task_progress};
3434 use crate::state::AppState;
3535
@@ -86,33 +86,6 @@ pub fn clean_name(raw: &str) -> String {
8686 out
8787 }
8888
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-
11689 fn fail(status: StatusCode, message: &str) -> Response {
11790 api::error(status, message)
11891 }
@@ -239,17 +212,8 @@ async fn download(cx: &Cx) -> Result<Response> {
239212 return Err(not_found().into());
240213 };
241214 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- };
252215 let actor = viewer.as_ref().map(|(user, _)| user);
216+ let (role, org_role) = access(&state.store, actor, &repo).await?;
253217 if authorize(actor, &repo, role, org_role, Action::Read).is_err() {
254218 return Err(not_found().into());
255219 }
@@ -296,11 +260,11 @@ async fn suggest(cx: &Cx) -> Result<Response> {
296260 }
297261 let mut kind = "";
298262 let mut q = String::new();
299- for pair in uri(cx).query().unwrap_or_default().split('&') {
300- if let Some(v) = pair.strip_prefix("kind=") {
301- kind = if v == "issue" { "issue" } else { "user" };
302- } else if let Some(v) = pair.strip_prefix("q=") {
303- q = percent_decode(v);
263+ for (key, value) in form_urlencoded::parse(uri(cx).query().unwrap_or_default().as_bytes()) {
264+ match &*key {
265+ "kind" => kind = if value == "issue" { "issue" } else { "user" },
266+ "q" => q = value.into_owned(),
267+ _ => {}
304268 }
305269 }
306270 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;
1616 use crate::i18n::code::{self as g, K};
1717 use crate::i18n::s;
1818 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};
2020 use crate::pages::ref_live;
2121 use crate::pages::repo::repo_head;
2222 use crate::pages::repo_ctx::load_repo;
@@ -191,31 +191,14 @@ async fn blame_page(cx: &Cx) -> Result<impl View> {
191191 }
192192 }
193193
194- let blob_href = repo_href(
195- &repo.owner_name,
196- &repo.name,
197- "blob",
198- &format!("{ref_name}/{file}"),
199- );
194+ let blob_href = file_href(&repo.owner_name, &repo.name, "blob", &ref_name, &file);
200195 // Blame sits beside the file's source: a markdown file's plain view, any other file's own page.
201- let markdown = matches!(
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 {
196+ let source_href = if is_markdown(&file_name) {
209197 format!("{blob_href}?plain=1")
210198 } else {
211199 blob_href.clone()
212200 };
213- let history = repo_href(
214- &repo.owner_name,
215- &repo.name,
216- "commits",
217- &format!("{ref_name}/{file}"),
218- );
201+ let history = file_href(&repo.owner_name, &repo.name, "commits", &ref_name, &file);
219202 let title = format!(
220203 "{}/{} \u{b7} {} \u{b7} {file}",
221204 repo.owner_name,
crates/forge-web-repo/src/pages/blob.rsmodified+49 -81
@@ -45,21 +45,25 @@ struct BlobQuery {
4545 }
4646
4747 /// One line of a text file. `highlighted` is true when `code` is trusted highlighter output.
48+#[derive(Clone)]
4849 pub struct Line {
4950 pub num: String,
5051 pub code: String,
5152 pub highlighted: bool,
5253 }
5354
54-/// What the page shows for the file. `kind` is one of: image, submodule, symlink, binary,
55-/// markdown, text.
55+enum ViewerKind {
56+ Submodule(String),
57+ Symlink(String),
58+ Lfs(String),
59+ Image,
60+ Binary(String),
61+ Markdown(String),
62+ Text(Vec<Line>),
63+}
64+
5665 struct Viewer {
57- kind: &'static str,
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>,
66+ kind: ViewerKind,
6367 truncated: bool,
6468 }
6569
@@ -69,6 +73,14 @@ fn extension(name: &str) -> String {
6973 .unwrap_or_default()
7074 }
7175
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+
7284 pub fn text_lines(text: &str, file_name: &str) -> Vec<Line> {
7385 let plain: Vec<&str> = text.lines().collect();
7486 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> {
140152 .unwrap_or("")
141153 .to_owned();
142154 let ext = extension(&file_name);
143- let is_markdown = MARKDOWN_EXTS.contains(&ext.as_str());
155+ let is_markdown = is_markdown(&file_name);
144156
145157 // A Git LFS pointer is a small text blob that names an object the forge stores.
146158 let pointer = match blob.kind {
@@ -158,7 +170,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
158170 Ok(None) => (Some(g::lfs_missing(lang, &size)), None),
159171 Err(e) => {
160172 tracing::warn!(error = %e, "blob: LFS object link lookup failed");
161- (Some(g::lfs_stored(lang, &size)), None)
173+ (None, None)
162174 }
163175 }
164176 }
@@ -167,38 +179,23 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
167179
168180 let viewer = match blob.kind {
169181 EntryKind::Submodule => Viewer {
170- kind: "submodule",
171- note: blob.oid.clone(),
172- html: String::new(),
173- lines: Vec::new(),
182+ kind: ViewerKind::Submodule(blob.oid.clone()),
174183 truncated: false,
175184 },
176185 EntryKind::Symlink => Viewer {
177- kind: "symlink",
178- note: String::from_utf8_lossy(&blob.data).into_owned(),
179- html: String::new(),
180- lines: Vec::new(),
186+ kind: ViewerKind::Symlink(String::from_utf8_lossy(&blob.data).into_owned()),
181187 truncated: false,
182188 },
183189 _ if lfs_note.is_some() => Viewer {
184- kind: "lfs",
185- note: lfs_note.clone().unwrap_or_default(),
186- html: String::new(),
187- lines: Vec::new(),
190+ kind: ViewerKind::Lfs(lfs_note.clone().unwrap_or_default()),
188191 truncated: false,
189192 },
190193 _ if IMAGE_EXTS.contains(&ext.as_str()) => Viewer {
191- kind: "image",
192- note: String::new(),
193- html: String::new(),
194- lines: Vec::new(),
194+ kind: ViewerKind::Image,
195195 truncated: blob.truncated,
196196 },
197197 _ if blob.is_binary => Viewer {
198- kind: "binary",
199- note: g::binary_note(lang, blob.size),
200- html: String::new(),
201- lines: Vec::new(),
198+ kind: ViewerKind::Binary(g::binary_note(lang, blob.size)),
202199 truncated: false,
203200 },
204201 _ => {
@@ -206,18 +203,12 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
206203 if is_markdown && !plain {
207204 let link_ctx = link_context(state, repo, &ref_name, &dir);
208205 Viewer {
209- kind: "markdown",
210- note: String::new(),
211- html: render_markdown(&text, Some(&link_ctx)),
212- lines: Vec::new(),
206+ kind: ViewerKind::Markdown(render_markdown(&text, Some(&link_ctx))),
213207 truncated: blob.truncated,
214208 }
215209 } else {
216210 Viewer {
217- kind: "text",
218- note: String::new(),
219- html: String::new(),
220- lines: text_lines(&text, &file_name),
211+ kind: ViewerKind::Text(text_lines(&text, &file_name)),
221212 truncated: blob.truncated,
222213 }
223214 }
@@ -225,38 +216,17 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
225216 };
226217
227218 let raw = raw_url(state, repo, &ref_name, &file);
228- let base = repo_href(
229- &repo.owner_name,
230- &repo.name,
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- );
219+ let base = file_href(&repo.owner_name, &repo.name, "blob", &ref_name, &file);
220+ let history = file_href(&repo.owner_name, &repo.name, "commits", &ref_name, &file);
221+ let blame = file_href(&repo.owner_name, &repo.name, "blame", &ref_name, &file);
246222 // The same file pinned to this exact commit, for sharing and for the `y` shortcut.
247- let permalink = repo_href(
248- &repo.owner_name,
249- &repo.name,
250- "blob",
251- &format!("{commit}/{file}"),
252- );
223+ let permalink = file_href(&repo.owner_name, &repo.name, "blob", &commit, &file);
253224 let finder_owner = repo.owner_name.clone();
254225 let finder_repo = repo.name.clone();
255226 let finder_ref = ref_name.clone();
256227 let title = format!("{}/{} \u{b7} {file}", repo.owner_name, repo.name);
257228
258- let kind = viewer.kind;
259- let is_text = kind == "text";
229+ let is_text = matches!(viewer.kind, ViewerKind::Text(_));
260230 // The ways to read the file, one switch with the current one marked, the same on every view of
261231 // it: Rendered and Source for markdown, Source alone otherwise, and Blame for any text.
262232 let mut views: Vec<(&'static str, String, bool)> = Vec::new();
@@ -274,9 +244,6 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
274244 if can_blame {
275245 views.push((b::t(lang, b::K::BlameLink), blame.clone(), false));
276246 }
277- let note = viewer.note;
278- let html = viewer.html;
279- let lines = viewer.lines;
280247 let truncated = viewer.truncated;
281248 let image_alt = file_name.clone();
282249 let download_name = file_name.clone();
@@ -301,7 +268,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
301268 };
302269 let (last, bar, strip, runs) = tokio::join!(
303270 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()),
305272 commit_strip(state, repo, &ctx.path, &commit),
306273 run_rows(state, lang, repo),
307274 );
@@ -325,10 +292,11 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
325292 let mut header = ctx.head(state, "code").await?;
326293 header.live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name);
327294 let size = human_size(lang, blob.size);
328- let size_line = if is_text {
329- format!("{} {}, {size}", lines.len(), s(lang, "lines", "satır"))
330- } else {
331- size
295+ let size_line = match &viewer.kind {
296+ ViewerKind::Text(lines) => {
297+ format!("{} {}, {size}", lines.len(), s(lang, "lines", "satır"))
298+ }
299+ _ => size,
332300 };
333301 Ok(view! {
334302 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
@@ -363,27 +331,27 @@ async fn blob_page(cx: &Cx) -> Result<impl View> {
363331 }
364332 </div>
365333 <section class="file" data-lines="" data-permalink=(permalink.as_str())>
366- if kind == "image" {
334+ if let ViewerKind::Image = &viewer.kind {
367335 <div class="file-image">
368336 <img src=(raw.clone()) alt=(image_alt)>
369337 </div>
370338 }
371- if kind == "markdown" {
372- <div class="markdown-body">(Unescaped::new_unchecked(html))</div>
339+ if let ViewerKind::Markdown(html) = &viewer.kind {
340+ <div class="markdown-body">(Unescaped::new_unchecked(html.clone()))</div>
373341 }
374- if kind == "text" {
375- file_table(lines: lines)
342+ if let ViewerKind::Text(lines) = &viewer.kind {
343+ file_table(lines: lines.clone())
376344 }
377- if kind == "lfs" {
345+ if let ViewerKind::Lfs(note) = &viewer.kind {
378346 <p class="state">(note.clone())</p>
379347 }
380- if kind == "binary" {
348+ if let ViewerKind::Binary(note) = &viewer.kind {
381349 <p class="state">(note.clone())</p>
382350 }
383- if kind == "symlink" {
351+ if let ViewerKind::Symlink(note) = &viewer.kind {
384352 <p class="state">(g::t(lang, K::SymlinkPrefix)) <code>(note.clone())</code></p>
385353 }
386- if kind == "submodule" {
354+ if let ViewerKind::Submodule(note) = &viewer.kind {
387355 <p class="state">(g::t(lang, K::SubmodulePrefix)) <code>(note.clone())</code> (g::t(lang, K::SubmoduleSuffix))</p>
388356 }
389357 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-
41 use forge_core::Visibility;
52 use forge_core::protection::RuleFlags;
63 use topcoat::router::request::Request;
@@ -49,7 +46,6 @@ async fn send(
4946 )
5047 }
5148
52-/// A commit whose changes are a whitespace-only edit of `a.txt` and a real edit of `ws.txt`.
5349 fn whitespace_commit(fx: &Fixture) -> String {
5450 std::fs::write(fx.work.join("ws.txt"), "x\ny\n").unwrap();
5551 git(&fx.work, &["add", "-A"]);
@@ -71,7 +67,6 @@ fn whitespace_commit(fx: &Fixture) -> String {
7167 oid
7268 }
7369
74-/// The commit toolbar, and the whitespace toggle that hides whitespace-only files.
7570 async fn scenario_whitespace_toolbar(fx: &Fixture) {
7671 let oid = whitespace_commit(fx);
7772 let base = format!("/{OWNER}/{REPO}/commit/{oid}");
@@ -84,7 +79,6 @@ async fn scenario_whitespace_toolbar(fx: &Fixture) {
8479 assert!(html.contains(&format!("{base}.diff")));
8580 assert!(html.contains("a.txt"));
8681 assert!(html.contains("ws.txt"));
87- // The toggle links to the same page with w=1.
8882 assert!(html.contains("w=1"));
8983
9084 let (_, _, body) = get(&fx.router, &format!("{base}?w=1")).await;
@@ -98,7 +92,6 @@ async fn scenario_whitespace_toolbar(fx: &Fixture) {
9892 assert!(main.contains("aria-pressed=\"true\""));
9993 }
10094
101-/// The split view renders two sides and is remembered in a cookie.
10295 async fn scenario_split_view(fx: &Fixture) {
10396 let uri = format!("/{OWNER}/{REPO}/commit/{}?view=split", fx.modified);
10497
@@ -107,7 +100,6 @@ async fn scenario_split_view(fx: &Fixture) {
107100 let html = String::from_utf8(body).unwrap();
108101 assert!(html.contains("diff-split"));
109102 assert!(html.contains("diff-split-row"));
110- // The deleted "two" and the added "TWO" sit in one row.
111103 let row = html
112104 .split("diff-split-row")
113105 .find(|r| r.contains("-two") && r.contains("+TWO"))
@@ -121,7 +113,6 @@ async fn scenario_split_view(fx: &Fixture) {
121113 .expect("view cookie");
122114 assert!(cookie.starts_with("forge_diff=split"));
123115
124- // With the cookie and no query, the page is split; ?view=unified switches back.
125116 let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);
126117 let req = Request::builder()
127118 .method("GET")
@@ -136,7 +127,6 @@ async fn scenario_split_view(fx: &Fixture) {
136127 assert!(!String::from_utf8(body).unwrap().contains("diff-split-row"));
137128 }
138129
139-/// Patch and diff downloads for a commit and a root commit, and 404s for bad or private ones.
140130 async fn scenario_patch_and_diff(fx: &Fixture) {
141131 let base = format!("/{OWNER}/{REPO}/commit/{}", fx.modified);
142132
@@ -159,7 +149,6 @@ async fn scenario_patch_and_diff(fx: &Fixture) {
159149 assert!(text.starts_with("diff --git a/a.txt b/a.txt"));
160150 assert!(!text.contains("Subject:"));
161151
162- // Root commits work.
163152 let (status, _, _) = get(
164153 &fx.router,
165154 &format!("/{OWNER}/{REPO}/commit/{}.patch", fx.root),
@@ -170,7 +159,6 @@ async fn scenario_patch_and_diff(fx: &Fixture) {
170159 assert_eq!(status, 404);
171160 }
172161
173-/// Compare lists the commits on the head side, as a patch and as a diff.
174162 async fn scenario_compare(fx: &Fixture) {
175163 git(&fx.work, &["checkout", "-q", "-b", "topic", &fx.root]);
176164 std::fs::write(fx.work.join("topic.txt"), "topic\n").unwrap();
@@ -204,14 +192,12 @@ async fn scenario_compare(fx: &Fixture) {
204192 assert!(text.contains("+++ b/topic.txt"));
205193 }
206194
207-/// The blob page offers blame, a commit-pinned permalink and the finder.
208195 async fn scenario_blob_page(fx: &Fixture) {
209196 let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blob/main/a.txt")).await;
210197 assert_eq!(status, 200);
211198 let html = String::from_utf8(body).unwrap();
212199 assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/main/a.txt")));
213200 assert!(html.contains("data-copy-permalink"));
214- // The permalink is pinned to a full commit oid, not the branch.
215201 let permalink = html
216202 .split("data-permalink=\"")
217203 .nth(1)
@@ -226,12 +212,10 @@ async fn scenario_blob_page(fx: &Fixture) {
226212 assert!(html.contains("data-finder"));
227213 assert!(html.contains(&format!("/{OWNER}/{REPO}/paths/main")));
228214
229- // The tree page has the finder too.
230215 let (_, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/tree/main")).await;
231216 assert!(String::from_utf8(body).unwrap().contains("data-finder"));
232217 }
233218
234-/// The paths endpoint lists every file on the ref, and refuses unknown refs and subpaths.
235219 async fn scenario_paths(fx: &Fixture) {
236220 let (status, headers, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/main")).await;
237221 assert_eq!(status, 200);
@@ -258,7 +242,6 @@ async fn scenario_paths(fx: &Fixture) {
258242 assert_eq!(status, 404);
259243 }
260244
261-/// The branches page shows counts, creates and deletes branches, and refuses bad input.
262245 async fn scenario_branches(fx: &Fixture, cookie: &str) {
263246 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
264247 std::fs::write(fx.work.join("f.txt"), "f\n").unwrap();
@@ -277,18 +260,15 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
277260
278261 let (status, _, html) = send(&fx.router, "GET", &page, Some(cookie), &[]).await;
279262 assert_eq!(status, 200);
280- // feature is 1 ahead of and 54 behind main (the root is its base, main has 54 more commits).
281263 assert!(html.contains("1 ahead, 54 behind"), "{html}");
282264 assert!(html.contains(&format!("/{OWNER}/{REPO}/compare/main...feature")));
283265 assert!(html.contains("tahinli"));
284266 let delete_form = format!("action=\"/{OWNER}/{REPO}/branches/delete\"");
285267 assert!(html.contains(&delete_form), "{html}");
286- // Anonymous viewers get no create or delete controls.
287268 let (_, _, anon) = send(&fx.router, "GET", &page, None, &[]).await;
288269 assert!(!anon.contains(&delete_form));
289270 assert!(!anon.contains("new-branch"));
290271
291- // Create from a ref.
292272 let (status, headers, _) = send(
293273 &fx.router,
294274 "POST",
@@ -305,11 +285,25 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
305285 feature_tip
306286 );
307287
308- // Existing name, bad name and missing source change nothing and report why.
309- for (name, from, word) in [
310- ("topic/one", "feature", "exists"),
311- ("bad..name", "feature", "invalid"),
312- ("other", "no-such-ref", "source"),
288+ for (name, from, word, message) in [
289+ (
290+ "topic/one",
291+ "feature",
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+ ),
313307 ] {
314308 let (status, _, _) = send(
315309 &fx.router,
@@ -328,13 +322,9 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
328322 &[],
329323 )
330324 .await;
331- assert!(
332- html.contains("role=\"alert\"") || html.contains("alert"),
333- "{word}"
334- );
325+ assert!(html.contains(message), "{word}");
335326 }
336327
337- // A bad CSRF token is refused.
338328 let (status, _, _) = send(
339329 &fx.router,
340330 "POST",
@@ -345,7 +335,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
345335 .await;
346336 assert_eq!(status, 403);
347337
348- // Delete: a moved branch is left alone, the right oid deletes it.
349338 let delete = format!("{page}/delete");
350339 let (status, _, _) = send(
351340 &fx.router,
@@ -369,7 +358,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
369358 let listing = git(&fx.bare, &["branch", "--list", "topic/one"]);
370359 assert!(listing.is_empty(), "branch should be gone: {listing}");
371360
372- // The default branch can never be deleted.
373361 let main_tip = git(&fx.bare, &["rev-parse", "refs/heads/main"]);
374362 send(
375363 &fx.router,
@@ -382,7 +370,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) {
382370 git(&fx.bare, &["rev-parse", "--verify", "refs/heads/main"]);
383371 }
384372
385-/// A branch rule blocks deleting the branches it matches.
386373 async fn scenario_protection(fx: &Fixture, cookie: &str) {
387374 git(&fx.bare, &["branch", "release/1", "main"]);
388375 git(&fx.bare, &["branch", "scratch", "main"]);
@@ -420,7 +407,6 @@ async fn scenario_protection(fx: &Fixture, cookie: &str) {
420407 assert!(git(&fx.bare, &["branch", "--list", "scratch"]).is_empty());
421408 }
422409
423-/// Changing the default branch moves HEAD and the record; a missing branch changes nothing.
424410 async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
425411 git(&fx.bare, &["branch", "trunk", "main"]);
426412 let settings = format!("/{OWNER}/{REPO}/settings/general");
@@ -448,7 +434,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
448434 assert_eq!(repo.default_branch, "trunk");
449435 assert_eq!(repo.description, "demo");
450436
451- // A branch that does not exist changes nothing.
452437 send(
453438 &fx.router,
454439 "POST",
@@ -470,7 +455,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
470455 .unwrap();
471456 assert_eq!(repo.default_branch, "trunk");
472457
473- // The settings page offers the branches and marks the current one.
474458 let (_, _, html) = send(
475459 &fx.router,
476460 "GET",
@@ -482,8 +466,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) {
482466 assert!(html.contains("name=\"default_branch\""));
483467 }
484468
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.
487469 #[tokio::test]
488470 async fn public_repo_pages_and_downloads() {
489471 let fx = Fixture::new(Visibility::Public).await;
@@ -493,8 +475,6 @@ async fn public_repo_pages_and_downloads() {
493475 scenario_blob_page(&fx).await;
494476 }
495477
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.
498478 #[tokio::test]
499479 async fn public_repo_commit_views_and_compare() {
500480 let fx = Fixture::new(Visibility::Public).await;
@@ -502,8 +482,6 @@ async fn public_repo_commit_views_and_compare() {
502482 scenario_compare(&fx).await;
503483 }
504484
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.
507485 #[tokio::test]
508486 async fn public_repo_branches_rules_and_default_branch() {
509487 let fx = Fixture::new(Visibility::Public).await;
@@ -513,7 +491,6 @@ async fn public_repo_branches_rules_and_default_branch() {
513491 scenario_default_branch(&fx, &cookie).await;
514492 }
515493
516-/// A private repo hides its patch download and its file list from anonymous viewers.
517494 #[tokio::test]
518495 async fn private_repo_hides_downloads_and_paths() {
519496 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";
3737
3838 /// What the right-hand half of the badge says.
3939 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
40-pub enum BadgeStatus {
40+enum BadgeStatus {
4141 Passing,
4242 Failing,
4343 Error,
@@ -76,7 +76,7 @@ impl BadgeStatus {
7676 }
7777
7878 /// 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 {
8080 match state {
8181 RunState::Success => BadgeStatus::Passing,
8282 RunState::Failure => BadgeStatus::Failing,
@@ -88,7 +88,7 @@ pub fn status_of_run(state: RunState) -> BadgeStatus {
8888 }
8989
9090 /// The badge status of one job.
91-pub fn status_of_job(state: JobState) -> BadgeStatus {
91+fn status_of_job(state: JobState) -> BadgeStatus {
9292 match state {
9393 JobState::Success => BadgeStatus::Passing,
9494 JobState::Failure => BadgeStatus::Failing,
@@ -101,7 +101,7 @@ pub fn status_of_job(state: JobState) -> BadgeStatus {
101101
102102 /// Escapes text for XML element content and attribute values. Control characters, which XML
103103 /// does not allow, become spaces.
104-pub fn escape_xml(text: &str) -> String {
104+fn escape_xml(text: &str) -> String {
105105 let mut out = String::with_capacity(text.len());
106106 for c in text.chars() {
107107 match c {
@@ -124,7 +124,7 @@ fn text_box(text: &str) -> u32 {
124124 }
125125
126126 /// 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 {
128128 let label: String = label.chars().take(MAX_LABEL_CHARS).collect();
129129 let status_text = status.text();
130130 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-
41 use std::io::Write;
52 use std::path::{Path, PathBuf};
63 use std::sync::Arc;
@@ -18,7 +15,6 @@ use crate::ci::{CiLive, artifact_key, log_path};
1815 use crate::test_support::{app_router, create_session, test_state};
1916
2017 const CSRF: &str = "ci-test-csrf";
21-/// A hash no ref reaches, standing in for a commit that was overwritten.
2218 const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
2319 const SPEC: &str = r#"{"runs_on":[]}"#;
2420 const RUN_BASE: &str = "/tahinli/proj/ci";
@@ -29,7 +25,6 @@ struct Fixture {
2925 live: Arc<CiLive>,
3026 repo: forge_core::Repo,
3127 tahinli: String,
32- /// The commit `main` points at in `proj`.
3328 head: String,
3429 data_dir: PathBuf,
3530 blobs: BlobStore,
@@ -90,7 +85,6 @@ async fn fixture(dir: &Path) -> Fixture {
9085 }
9186 }
9287
93-/// Puts one empty commit on `main` and returns its hash.
9488 fn commit_main(bare: &Path) -> String {
9589 let git = |args: &[&str]| {
9690 let out = std::process::Command::new("git")
@@ -113,7 +107,6 @@ fn cookie_for(token: &str) -> String {
113107 format!("__Host-{SESSION_COOKIE}={token}")
114108 }
115109
116-/// A response: status, headers and the whole body.
117110 struct Reply {
118111 status: u16,
119112 headers: HeaderMap,
@@ -150,7 +143,6 @@ async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply {
150143 collect(app.handle(req).await).await
151144 }
152145
153-/// A POST with the CSRF token and the given form fields.
154146 async fn post(app: &Router, uri: &str, cookie: &str, fields: &[(&str, &str)]) -> Reply {
155147 let mut form = form_urlencoded::Serializer::new(String::new());
156148 form.append_pair("csrf", CSRF);
@@ -178,7 +170,6 @@ async fn collect(res: topcoat::router::response::Response) -> Reply {
178170 }
179171 }
180172
181-/// Creates a run on `main` with one job per name. Jobs wait for approval when `needs_approval`.
182173 async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {
183174 let needs: &[String] = &[];
184175 let specs: Vec<NewJob<'_>> = jobs
@@ -207,7 +198,6 @@ async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun {
207198 .expect("run")
208199 }
209200
210-/// Claims the one queued job with a fresh runner and finishes it as a success.
211201 async fn finish_job(fx: &Fixture) -> CiJob {
212202 let token = fx
213203 .store
@@ -232,6 +222,10 @@ async fn finish_job(fx: &Fixture) -> CiJob {
232222 job
233223 }
234224
225+async fn run_now(fx: &Fixture, id: &str) -> CiRun {
226+ fx.store.run_by_id(id).await.expect("run").expect("run")
227+}
228+
235229 async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob {
236230 fx.store
237231 .jobs_for_run(&run.id)
@@ -242,7 +236,6 @@ async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob {
242236 .expect("a job")
243237 }
244238
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.
246239 #[tokio::test]
247240 async fn access_follows_the_repo_role_on_every_route() {
248241 let dir = tempfile::tempdir().expect("tempdir");
@@ -298,12 +291,7 @@ async fn access_follows_the_repo_role_on_every_route() {
298291 )
299292 .await;
300293 assert_eq!(refused.status, 403, "reader cannot cancel");
301- let still = fx
302- .store
303- .run_by_id(&run.id)
304- .await
305- .expect("run")
306- .expect("run");
294+ let still = run_now(&fx, &run.id).await;
307295 assert_eq!(still.state, RunState::Queued);
308296 }
309297
@@ -326,7 +314,6 @@ async fn access_follows_the_repo_role_on_every_route() {
326314 }
327315 }
328316
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.
330317 #[tokio::test]
331318 async fn run_list_pages_and_its_live_marker() {
332319 let dir = tempfile::tempdir().expect("tempdir");
@@ -337,7 +324,6 @@ async fn run_list_pages_and_its_live_marker() {
337324 }
338325 let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await;
339326 let text = first.text();
340- // The topbar's live strip links the viewer's own running runs too; only the list counts.
341327 let list = text
342328 .split_once("</header>")
343329 .map_or(text.as_str(), |(_, rest)| rest);
@@ -395,7 +381,6 @@ async fn run_list_pages_and_its_live_marker() {
395381 }
396382 }
397383
398-/// Opens an event stream without reading it. The response head carries the status.
399384 async fn open(
400385 app: &Router,
401386 uri: &str,
@@ -409,7 +394,6 @@ async fn open(
409394 .await
410395 }
411396
412-/// The next frame of an event stream, or None once the stream has ended. Fails after five seconds.
413397 async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>>
414398 where
415399 S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
@@ -430,7 +414,6 @@ where
430414 {
431415 use futures_util::StreamExt;
432416
433- // Every stream opens with its `retry` field (one frame): skip it, the tests want the events.
434417 loop {
435418 let frame = tokio::time::timeout(Duration::from_secs(5), frames.next())
436419 .await
@@ -442,7 +425,6 @@ where
442425 }
443426 }
444427
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.
446428 #[tokio::test]
447429 async fn live_pages_and_streams_follow_a_job_to_its_end() {
448430 let dir = tempfile::tempdir().expect("tempdir");
@@ -455,7 +437,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
455437 let url = format!("/tahinli/proj/ci/jobs/{}", job.id);
456438 let run_url = format!("{RUN_BASE}/runs/{}", run.number);
457439 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.
459440 let run_marker = format!("data-live=\"{RUN_BASE}/events\"");
460441
461442 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() {
474455
475456 finish_job(&fx).await;
476457 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.
478458 assert!(
479459 done.text().contains(&job_marker),
480460 "job still live when finished"
@@ -518,26 +498,18 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() {
518498 format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes()
519499 );
520500
521- // A bump with no new log bytes and no status change sends nothing.
522501 fx.live.bump_job(&job.id);
523502 let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await;
524503 assert!(quiet.is_err(), "a log append sends no status event");
525504
526- // The run stream sends its status on every bump of the run.
527505 fx.live.bump_run(&run.id);
528506 let bumped = next_event(&mut run_frames).await.expect("the run status");
529- let now = fx
530- .store
531- .run_by_id(&run.id)
532- .await
533- .expect("run")
534- .expect("run");
507+ let now = run_now(&fx, &run.id).await;
535508 assert_eq!(
536509 bumped,
537510 format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes()
538511 );
539512
540- // The job finishes: its final status is sent, then the stream ends.
541513 finish_job(&fx).await;
542514 fx.live.close_job(&job.id);
543515 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() {
553525 }
554526 }
555527
556-/// The href of the list row marked as current, from the markup of the runs page.
557528 fn current_href(html: &str) -> Option<&str> {
558529 let mark = html.find("aria-current=\"true\"")?;
559530 let start = html[..mark].rfind("<a ")?;
@@ -562,8 +533,6 @@ fn current_href(html: &str) -> Option<&str> {
562533 link[at..].split('"').next()
563534 }
564535
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.
567536 #[tokio::test]
568537 async fn split_view_draws_the_newest_run_or_the_one_named() {
569538 let dir = tempfile::tempdir().expect("tempdir");
@@ -585,8 +554,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
585554 .await
586555 .text();
587556 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.
590557 assert!(
591558 named.contains(&format!("href=\"{RUN_BASE}\"")),
592559 "All runs link"
@@ -594,7 +561,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
594561 assert!(!named.contains("ci-run-list"));
595562 assert_eq!(named.matches("aria-current=\"true\"").count(), 0);
596563
597- // Thirty runs make two pages. Run 1 is on page 2, so page 1 marks no row and draws run 1.
598564 for _ in 0..28 {
599565 run_with(&fx, &["build"], false).await;
600566 }
@@ -606,7 +572,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
606572 .await
607573 .text();
608574 assert!(off_page.contains(&format!("data-run=\"{}\"", first.number)));
609- // A run off the list's first page opens all the same.
610575 assert!(off_page.contains(&format!("data-live=\"{RUN_BASE}/events\"")));
611576 let rows = get(&fx.app, &format!("{RUN_BASE}?page=2"), tahinli.as_deref())
612577 .await
@@ -617,7 +582,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() {
617582 );
618583 }
619584
620-/// The list stream sends nothing on connect, then one `changed` event per change of the repo.
621585 #[tokio::test]
622586 async fn run_list_events_follow_repo_changes() {
623587 use futures_util::StreamExt;
@@ -633,7 +597,6 @@ async fn run_list_events_follow_repo_changes() {
633597 .into_body()
634598 .into_data_stream();
635599
636- // The retry field comes first; after it nothing is sent until a change.
637600 let retry = next_frame(&mut frames).await.expect("the retry field");
638601 assert!(retry.starts_with(b"retry: "), "{retry:?}");
639602 let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await;
@@ -645,7 +608,6 @@ async fn run_list_events_follow_repo_changes() {
645608 assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec());
646609 }
647610
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`.
649611 #[tokio::test]
650612 async fn job_log_events() {
651613 let dir = tempfile::tempdir().expect("tempdir");
@@ -750,7 +712,6 @@ async fn job_log_events() {
750712 }
751713 }
752714
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.
754715 #[tokio::test]
755716 async fn job_page_log_tail() {
756717 let dir = tempfile::tempdir().expect("tempdir");
@@ -814,7 +775,6 @@ async fn job_page_log_tail() {
814775 let path = log_path(&fx.data_dir, &job.id);
815776 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
816777 let mut file = std::fs::File::create(&path).unwrap();
817- // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000.
818778 for n in 0..11_000 {
819779 writeln!(file, "{n:0>98}").unwrap();
820780 }
@@ -840,7 +800,6 @@ async fn job_page_log_tail() {
840800 }
841801 }
842802
843-/// The next chunk a follower sends. Fails the test when none comes within five seconds.
844803 async fn next_chunk(
845804 chunks: &mut tokio::sync::mpsc::UnboundedReceiver<bytes::Bytes>,
846805 ) -> Option<bytes::Bytes> {
@@ -849,7 +808,6 @@ async fn next_chunk(
849808 .expect("a chunk within five seconds")
850809 }
851810
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.
853811 #[tokio::test]
854812 async fn log_txt_and_log_follower() {
855813 let dir = tempfile::tempdir().expect("tempdir");
@@ -933,7 +891,6 @@ async fn log_txt_and_log_follower() {
933891 }
934892 }
935893
936-/// Artifact downloads send attachment headers, and a run's artifacts list and zip for readers only.
937894 #[tokio::test]
938895 async fn artifact_downloads_and_zip() {
939896 let dir = tempfile::tempdir().expect("tempdir");
@@ -1069,12 +1026,7 @@ async fn approve_only_works_while_waiting_for_approval() {
10691026 )
10701027 .await;
10711028 assert_notice(&approved, "approved");
1072- let now = fx
1073- .store
1074- .run_by_id(&run.id)
1075- .await
1076- .expect("run")
1077- .expect("run");
1029+ let now = run_now(&fx, &run.id).await;
10781030 assert_eq!(now.state, RunState::Queued);
10791031 let page = get(&fx.app, &run_url, Some(&cookie_for("bob-token"))).await;
10801032 assert!(
@@ -1090,12 +1042,7 @@ async fn approve_only_works_while_waiting_for_approval() {
10901042 )
10911043 .await;
10921044 assert_notice(&again, "not-waiting");
1093- let still = fx
1094- .store
1095- .run_by_id(&run.id)
1096- .await
1097- .expect("run")
1098- .expect("run");
1045+ let still = run_now(&fx, &run.id).await;
10991046 assert_eq!(still.state, RunState::Queued);
11001047 }
11011048
@@ -1113,12 +1060,7 @@ async fn cancel_and_rerun_post_and_redirect() {
11131060 )
11141061 .await;
11151062 assert_notice(&cancelled, "cancelled");
1116- let now = fx
1117- .store
1118- .run_by_id(&run.id)
1119- .await
1120- .expect("run")
1121- .expect("run");
1063+ let now = run_now(&fx, &run.id).await;
11221064 assert_eq!(now.state, RunState::Cancelled);
11231065 let finished = post(
11241066 &fx.app,
@@ -1171,7 +1113,6 @@ async fn manual_run_refuses_an_unknown_branch() {
11711113 assert_eq!(reader.status, 403, "reader cannot start a manual run");
11721114 }
11731115
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.
11751116 #[tokio::test]
11761117 async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
11771118 let dir = tempfile::tempdir().expect("tempdir");
@@ -1202,7 +1143,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
12021143 .expect("public repo");
12031144 let svg_path = "/tahinli/proj/badge.svg";
12041145
1205- // The private repo: a run exists, but only readers see its badge.
12061146 run_with(&fx, &["build"], false).await;
12071147 finish_job(&fx).await;
12081148 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() {
12261166 Some("no-cache, max-age=0")
12271167 );
12281168
1229- // The public repo: anyone sees the badge. Unknown branches and jobs have no status.
12301169 let needs: &[String] = &[];
12311170 let specs = [NewJob {
12321171 name: "build",
@@ -1266,7 +1205,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() {
12661205 }
12671206 }
12681207
1269-/// Writes `.forge/ci.toml` with `text` into a new commit of the bare repo and returns its id.
12701208 fn commit_ci_toml(bare: &Path, text: &str) -> String {
12711209 fn git(bare: &Path, args: &[&str], stdin: &str) -> String {
12721210 let mut child = std::process::Command::new("git")
@@ -1305,7 +1243,6 @@ fn commit_ci_toml(bare: &Path, text: &str) -> String {
13051243 git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], "")
13061244 }
13071245
1308-/// Creates a queued run of one job `build` at `commit` on `main`.
13091246 async fn run_at(fx: &Fixture, commit: &str) {
13101247 let needs: &[String] = &[];
13111248 let specs = [NewJob {
@@ -1331,7 +1268,6 @@ async fn run_at(fx: &Fixture, commit: &str) {
13311268 .expect("run");
13321269 }
13331270
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.
13351271 #[tokio::test]
13361272 async fn badge_label_comes_from_the_query_job_or_name() {
13371273 let dir = tempfile::tempdir().expect("tempdir");
@@ -1414,7 +1350,6 @@ async fn badge_label_comes_from_the_query_job_or_name() {
14141350
14151351 {
14161352 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.
14181353 let commit = commit_ci_toml(
14191354 &bare,
14201355 "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n",
@@ -1429,7 +1364,6 @@ async fn badge_label_comes_from_the_query_job_or_name() {
14291364 }
14301365 }
14311366
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.
14331367 #[tokio::test]
14341368 async fn running_runs_and_run_page_previews() {
14351369 let dir = tempfile::tempdir().expect("tempdir");
@@ -1474,7 +1408,6 @@ async fn running_runs_and_run_page_previews() {
14741408 html.contains("data-tick=\"rest\""),
14751409 "the hatched remainder follows the clock"
14761410 );
1477- // The timeline is on the run's own page.
14781411 let html = get(&fx.app, &format!("{RUN_BASE}/runs/1"), Some(&cookie))
14791412 .await
14801413 .text()
@@ -1570,7 +1503,6 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() {
15701503 let run_url = format!("{RUN_BASE}/runs/{}", run.number);
15711504 let writer = cookie_for("bob-token");
15721505
1573- // A live run offers neither control and refuses the request.
15741506 let page = get(&fx.app, &run_url, Some(&writer)).await.text();
15751507 assert!(!page.contains("Re-run failed jobs"));
15761508 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() {
16041536 .unwrap();
16051537 assert_eq!(fx.store.jobs_for_run(&second.id).await.unwrap().len(), 2);
16061538
1607- // One job: it must have finished, and the request needs Write.
16081539 let job = job_of(&fx, &run).await;
16091540 let single = post(
16101541 &fx.app,
crates/forge-web-repo/src/pages/commit.rsmodified+24 -24
@@ -8,12 +8,12 @@ use topcoat::Result;
88 use topcoat::context::{Cx, context};
99 use topcoat::router::error::{content_too_large, not_found};
1010 use topcoat::router::{page, path_param, route};
11-use topcoat::view::{View, view};
11+use topcoat::view::{View, component, view};
1212
1313 use crate::i18n::code::{self as g, K};
1414 use crate::i18n::{self};
1515 use crate::layers::RawDownload;
16-use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid};
16+use crate::pages::commits::{SigBadgeView, blocking};
1717 use crate::pages::ref_live;
1818 use crate::pages::repo::repo_head;
1919 use crate::pages::repo_ctx::load_repo;
@@ -24,7 +24,9 @@ use crate::state::AppState;
2424 use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary};
2525 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
2626 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+};
2830
2931 path_param!(owner);
3032 path_param!(repo);
@@ -54,6 +56,22 @@ struct CoAuthorView {
5456 sep: bool,
5557 }
5658
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+
5775 fn is_hex_prefix(s: &str) -> bool {
5876 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
5977 }
@@ -146,7 +164,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> {
146164 let tz = ctx.viewer_tz().to_owned();
147165 let parent = info.parents.first().cloned();
148166
149- let now = now_secs();
167+ let now = now_unix();
150168 let author = Person {
151169 name: info.author_name.clone(),
152170 email: info.author_email.clone(),
@@ -277,16 +295,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> {
277295 (g::t(lang, K::CoAuthorAnd))
278296 for c in coauthors.iter() {
279297 if c.sep { ", " }
280- if let Some(href) = c.href.as_ref() {
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- }
298+ coauthor_link(c: c)
290299 }
291300 if folded {
292301 ", "
@@ -295,16 +304,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> {
295304 <ul class="coauthors-list" aria-label=(coauthors_label)>
296305 for c in rest.iter() {
297306 <li>
298- if let Some(href) = c.href.as_ref() {
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- }
307+ coauthor_link(c: c)
308308 </li>
309309 }
310310 </ul>
crates/forge-web-repo/src/pages/commits.rsmodified+2 -47
@@ -1,8 +1,6 @@
11 //! Page: commit history for a ref and optional path, at `/{owner}/{repo}/commits/{*rest}`.
22 //! Also home of the helpers shared by the commit and archive pages.
33
4-use std::time::{SystemTime, UNIX_EPOCH};
5-
64 use std::collections::HashMap;
75
86 use forge_core::store::commit_status::CommitStatus;
@@ -28,7 +26,7 @@ use crate::signatures::{self, SigBadge};
2826 use crate::state::AppState;
2927 use crate::views::commit_line::commit_line;
3028 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};
3230
3331 path_param!(owner);
3432 path_param!(repo);
@@ -53,46 +51,6 @@ where
5351 Ok(tokio::task::spawn_blocking(f).await??)
5452 }
5553
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-
9654 /// One commit as shown in the history list.
9755 pub(crate) struct CommitRow {
9856 /// The full oid: the row's `data-arrive` value.
@@ -279,7 +237,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
279237 let older_href = href_for(page_no + 1);
280238 let has_newer = page_no > 1;
281239
282- let now = now_secs();
240+ let now = now_unix();
283241 let tz = ctx.viewer_tz().to_owned();
284242 let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect();
285243 let statuses = state
@@ -403,7 +361,6 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
403361 mod tests {
404362 use forge_core::Visibility;
405363
406- use super::iso_time;
407364 use crate::i18n::Lang;
408365 use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};
409366 use crate::views::relative_time;
@@ -411,8 +368,6 @@ mod tests {
411368
412369 #[test]
413370 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");
416371 assert_eq!(relative_time(Lang::En, 990, 1000), "just now");
417372 assert_eq!(
418373 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 @@
1111
1212 use std::path::PathBuf;
1313
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};
1515 use forge_git::browse::{self, CommitInfo, RefKind};
1616 use forge_git::command::ObjectSource;
1717 use forge_git::history;
@@ -21,16 +21,18 @@ use serde::Deserialize;
2121 use topcoat::Result;
2222 use topcoat::context::{Cx, context};
2323 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};
2525 use topcoat::router::{page, path_param, query_params};
2626 use topcoat::view::{View, view};
2727
28-use crate::auth::{check_csrf, require_user};
28+use crate::auth::require_user;
2929 use crate::i18n;
3030 use crate::i18n::pulls::{self as g, K};
3131 use crate::notify::{self, Activity};
3232 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;
3436 use crate::pages::ref_live;
3537 use crate::pages::repo::repo_head;
3638 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -39,7 +41,7 @@ use crate::templates;
3941 use crate::views::commit_line::commit_line;
4042 use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section};
4143 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};
4345 use crate::webhooks::emit::{Sender, emit_pull};
4446
4547 path_param!(owner);
@@ -195,30 +197,6 @@ async fn resolve_comparison(
195197 }))
196198 }
197199
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-
222200 /// The body the pull request form starts with: the default branch's pull request template, or
223201 /// empty when there is none.
224202 async fn pull_template_body(ctx: &RepoCtx) -> Result<String> {
@@ -241,7 +219,7 @@ async fn compare_view(
241219 let owner = ctx.repo.owner_name.clone();
242220 let name = ctx.repo.name.clone();
243221 let tz = ctx.viewer_tz().to_owned();
244- let now = now_secs();
222+ let now = now_unix();
245223 let title = format!("{owner}/{name}");
246224 let base = cmp.base.clone();
247225 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> {
5454 let discussion = discussion_by_number(state, &ctx, number(cx)).await?;
5555 stream_wakes(cx, &state.live, &[Topic::Discussion(discussion.id.clone())])
5656 }
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> {
4848 }
4949
5050 // One fork per viewer and source: an existing one is reused.
51- let forks = state.store.list_forks(&source_repo.id).await?;
52- if let Some(existing) = forks.iter().find(|fork| fork.owner_id == viewer.id) {
51+ if let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? {
5352 return Ok(see_other(repo_href(
5453 &existing.owner_name,
5554 &existing.name,
@@ -59,10 +58,25 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> {
5958 }
6059
6160 let fork_name = free_name(state, &viewer.username, &source_repo.name).await?;
62- let fork = state
61+ let fork = match state
6362 .store
6463 .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+ };
6680 let dst = repo_path(&state.config.data_dir, &fork.id)?;
6781 if let Err(e) = fork_bare(&state.git, &source.path, &dst).await {
6882 // 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> {
107121 Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", "")))
108122 }
109123
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+
110137 /// `base` when `owner` has no repo of that name, else the first of `base-1`, `base-2`, ... that is
111138 /// free.
112139 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)> {
3232 if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
3333 return None;
3434 }
35- let value = u32::from_str_radix(hex, 16).ok()?;
36- Some((
37- u8::try_from(value >> 16).ok()?,
38- u8::try_from((value >> 8) & 0xff).ok()?,
39- u8::try_from(value & 0xff).ok()?,
40- ))
35+ let [_, r, g, b] = u32::from_str_radix(hex, 16).ok()?.to_be_bytes();
36+ Some((r, g, b))
4137 }
4238
4339 /// 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;
88 use topcoat::Result;
99 use topcoat::context::{Cx, context};
1010 use topcoat::router::content::Form;
11-use topcoat::router::error::see_other;
1211 use topcoat::router::{page, path_param, query_params};
1312 use topcoat::view::{View, component, view};
1413
1514 use crate::i18n::issues::{self as g, K};
1615 use crate::i18n::{self, Lang};
17-use crate::pages::issue_meta::{
18- RepoFrame, action_error_at, issue_subnav, refusal_message, triage_guard,
19-};
16+use crate::pages::issue_meta::{RepoFrame, finish_write, issue_subnav, triage_guard};
2017 use crate::pages::issues_live::list_live_url;
2118 use crate::pages::repo::repo_head;
22-use crate::pages::repo_ctx::load_repo;
19+use crate::pages::repo_ctx::{RepoCtx, load_repo};
2320 use crate::state::AppState;
2421 use crate::views::parts::{confirm_act, post_act, reveal};
2522 use crate::views::repo_list::{PageLink, pager, pager_links};
@@ -77,6 +74,10 @@ fn labels_href(title: &str) -> String {
7774 format!("/{title}/labels")
7875 }
7976
77+fn labels_back(ctx: &RepoCtx) -> String {
78+ labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name))
79+}
80+
8081 /// The header, the label list and, for triage holders, the forms.
8182 #[component]
8283 async fn labels_body(
@@ -249,24 +250,12 @@ async fn label_create(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View>
249250 let ctx = load_repo(cx, owner, name).await?;
250251 triage_guard(cx, &ctx, &form.csrf).await?;
251252 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);
253254 let result = context::<AppState>(cx)
254255 .store
255256 .create_label(&ctx.repo.id, &form.name, &form.color, &form.description)
256257 .await;
257- match result {
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- }
258+ finish_write(cx, ctx, lang, back, result).await
270259 }
271260
272261 /// 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>
278267 let ctx = load_repo(cx, owner, name).await?;
279268 triage_guard(cx, &ctx, &form.csrf).await?;
280269 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);
282271 let result = context::<AppState>(cx)
283272 .store
284273 .update_label(&ctx.repo.id, id, &form.name, &form.color, &form.description)
285274 .await;
286- match result {
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- }
275+ finish_write(cx, ctx, lang, back, result).await
299276 }
300277
301278 /// 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
307284 let ctx = load_repo(cx, owner, name).await?;
308285 triage_guard(cx, &ctx, &form.csrf).await?;
309286 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);
311288 let result = context::<AppState>(cx)
312289 .store
313290 .create_default_labels(&ctx.repo.id)
314291 .await;
315- match result {
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- }
292+ finish_write(cx, ctx, lang, back, result).await
328293 }
329294
330295 /// 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>
336301 let ctx = load_repo(cx, owner, name).await?;
337302 triage_guard(cx, &ctx, &form.csrf).await?;
338303 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);
340305 let result = context::<AppState>(cx)
341306 .store
342307 .delete_label(&ctx.repo.id, id)
343308 .await;
344- match result {
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- }
309+ finish_write(cx, ctx, lang, back, result).await
357310 }
358311
359312 #[cfg(test)]
crates/forge-web-repo/src/pages/merge_queue.rsmodified+28 -66
@@ -13,13 +13,10 @@ use std::collections::HashMap;
1313
1414 use forge_core::merge_queue::{QueueEntry, QueueState};
1515 use forge_core::{Action, MergeStyle, PullRequest, authorize};
16-use futures_util::{Stream, stream};
1716 use serde::Deserialize;
18-use tokio::sync::watch;
1917 use topcoat::Result;
2018 use topcoat::context::{Cx, context};
2119 use topcoat::router::content::Form;
22-use topcoat::router::content::sse::Event;
2320 use topcoat::router::error::{bad_request, forbidden, not_found, see_other};
2421 use topcoat::router::response::Response;
2522 use topcoat::router::{page, path_param, query_params, route};
@@ -28,10 +25,11 @@ use topcoat::view::{View, component, view};
2825 use crate::auth::require_csrf;
2926 use crate::i18n::merge_queue::{self as g, K};
3027 use crate::i18n::{self, Lang};
31-use crate::live::{changed_event, events_response};
28+use crate::live::{events_response, wake_stream};
3229 use crate::merge::ERR_NOT_OPEN;
3330 use crate::merge_queue as queue;
3431 use crate::pages::issue_parts::parse_number;
32+use crate::pages::pull_flow::pull_href;
3533 use crate::pages::repo::repo_head;
3634 use crate::pages::repo_ctx::{RepoCtx, load_repo};
3735 use crate::state::AppState;
@@ -55,15 +53,6 @@ struct QueueQuery {
5553 show: Option<String>,
5654 }
5755
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-
6756 fn queue_href(ctx: &RepoCtx) -> String {
6857 repo_href(&ctx.repo.owner_name, &ctx.repo.name, "merge-queue", "")
6958 }
@@ -323,6 +312,8 @@ fn reason_label(lang: Lang, reason: &str) -> String {
323312 "permission" => K::ReasonPermission,
324313 "blocked" => K::ReasonBlocked,
325314 "no_branch" => K::ReasonNoBranch,
315+ "draft" => K::ReasonDraft,
316+ "head_missing" => K::ReasonHeadMissing,
326317 _ => return reason.to_owned(),
327318 };
328319 g::t(lang, key).to_owned()
@@ -335,14 +326,7 @@ async fn queue_events(cx: &Cx) -> Result<Response> {
335326 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
336327 let state = context::<AppState>(cx);
337328 let wake = state.ci_live.subscribe_queue(&ctx.repo.id);
338- events_response(cx, queue_changes(wake))
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- })
329+ events_response(cx, wake_stream(wake, "queue"))
346330 }
347331
348332 #[component]
@@ -378,52 +362,30 @@ async fn queue_body(
378362 }
379363 } else {
380364 for row in rows.iter() {
381- if row.remove {
382- <div class="line" data-kb-row="">
383- <span class="name"><a href=(row.pull_href.as_str())>"#"(row.pull_number)" "(row.pull_title.as_str())</a></span>
384- <span class="val">
385- if !row.position.is_empty() {
386- (g::t(lang, K::QueueColPosition)) " " (row.position.as_str()) " · "
387- }
388- <span class=(row.state_class)>(row.state)</span>
389- " · " <code>(row.branch.as_str())</code>
390- " · " (row.by.as_str())
391- " · " rel_time(lang: lang, stamp: row.queued_at.as_str())
392- " · "
393- if let Some(href) = row.run_href.as_ref() {
394- <a href=(href.as_str())>(row.run_label.as_str())</a>
395- } else {
396- <span>(row.run_label.as_str())</span>
397- }
398- if !row.reason.is_empty() {
399- " · " (row.reason.as_str())
400- }
401- </span>
365+ <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>
367+ <span class="val">
368+ if !row.position.is_empty() {
369+ (g::t(lang, K::QueueColPosition)) " " (row.position.as_str()) " · "
370+ }
371+ <span class=(row.state_class)>(row.state)</span>
372+ " · " <code>(row.branch.as_str())</code>
373+ " · " (row.by.as_str())
374+ " · " rel_time(lang: lang, stamp: row.queued_at.as_str())
375+ " · "
376+ if let Some(href) = row.run_href.as_ref() {
377+ <a href=(href.as_str())>(row.run_label.as_str())</a>
378+ } else {
379+ <span>(row.run_label.as_str())</span>
380+ }
381+ if !row.reason.is_empty() {
382+ " · " (row.reason.as_str())
383+ }
384+ </span>
385+ if row.remove {
402386 confirm_act(lang: lang, label: remove_label, action: row.remove_action.as_str(), csrf: csrf.as_str(), note: Some(remove_note.clone()))
403- </div>
404- } else {
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- }
387+ }
388+ </div>
427389 }
428390 }
429391 </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> {
100100 let head = head_repo(state, &pr).await?;
101101 match &head {
102102 Some(head) => {
103- let role = state.store.collaborator_role(&head.id, &user.id).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- {
103+ if !head_writable(state, head, &user).await? {
110104 return Err(forbidden().into());
111105 }
112106 }
@@ -149,6 +143,29 @@ fn finished(pr: &PullRequest) -> bool {
149143 pr.merged_at.is_some() || pr.issue.state != IssueState::Open
150144 }
151145
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+
152169 /// The head repo of `pr` when it still exists.
153170 async fn head_repo(
154171 state: &AppState,
@@ -177,10 +194,10 @@ async fn delete_branch(
177194 Some(tip) if tip != pr.head_oid => return Ok(Some(ERR_MOVED)),
178195 Some(_) => {}
179196 }
180- match delete_ref_cas(&state.git, &path, &refname, &pr.head_oid).await {
181- Ok(()) => {}
182- Err(forge_git::error::Error::RefMoved(_)) => return Ok(Some(ERR_MOVED)),
183- Err(e) => return Err(e.into()),
197+ if let Some(code) =
198+ cas_refusal(delete_ref_cas(&state.git, &path, &refname, &pr.head_oid).await)?
199+ {
200+ return Ok(Some(code));
184201 }
185202 record_ref_change(state, head, user, &refname, &pr.head_oid, ZERO_OID).await;
186203 state
@@ -214,10 +231,10 @@ async fn restore_branch(
214231 if read_commit(&path, &pr.head_oid)?.is_none() {
215232 return Ok(Some(ERR_MISSING));
216233 }
217- match update_ref_cas(&state.git, &path, &refname, &pr.head_oid, ZERO_OID).await {
218- Ok(()) => {}
219- Err(forge_git::error::Error::RefMoved(_)) => return Ok(Some(ERR_MOVED)),
220- Err(e) => return Err(e.into()),
234+ if let Some(code) = cas_refusal(
235+ update_ref_cas(&state.git, &path, &refname, &pr.head_oid, ZERO_OID).await,
236+ )? {
237+ return Ok(Some(code));
221238 }
222239 record_ref_change(state, head, user, &refname, ZERO_OID, &pr.head_oid).await;
223240 state
@@ -304,12 +321,7 @@ pub(crate) async fn branch_action(
304321 let Some(head) = head_repo(state, pr).await? else {
305322 return Ok(None);
306323 };
307- let role = state.store.collaborator_role(&head.id, &user.id).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() {
324+ if !head_writable(state, &head, user).await? {
313325 return Ok(None);
314326 }
315327 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-
71 use std::collections::{HashMap, HashSet};
82 use std::sync::Arc;
93
@@ -27,7 +21,7 @@ use crate::i18n::pulls::{self as g, K};
2721 use crate::i18n::{self, Lang};
2822 use crate::pages::edit_history::thread_edit_counts;
2923 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};
3125 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header};
3226 use crate::pages::repo_ctx::{RepoCtx, load_repo};
3327 use crate::pages::tree::link_context;
@@ -41,7 +35,6 @@ path_param!(owner);
4135 path_param!(repo);
4236 path_param!(number);
4337
44-/// Parses a non-empty run of ASCII digits. `str::parse` alone would also accept a leading `+`.
4538 fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> {
4639 if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
4740 return None;
@@ -49,7 +42,6 @@ fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> {
4942 raw.parse().ok()
5043 }
5144
52-/// The `comment=<file>:<old|new>:<line>` target of an inline form. Anything else is ignored.
5345 fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> {
5446 let request = uri(cx);
5547 let query = request.query()?;
@@ -61,24 +53,12 @@ fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> {
6153 parts.next().is_none().then_some((index, side, line))
6254 }
6355
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.
7556 fn file_index(diff: &CommitDiff, path: &str) -> Option<usize> {
7657 diff.files
7758 .iter()
7859 .position(|f| f.new_path.as_deref() == Some(path) || f.old_path.as_deref() == Some(path))
7960 }
8061
81-/// The path a file's Viewed mark is kept under: its new path, or the old one when it was deleted.
8262 fn mark_path(file: &FileDiff) -> Option<&str> {
8363 if file.status == DiffStatus::Deleted {
8464 file.old_path.as_deref()
@@ -87,7 +67,6 @@ fn mark_path(file: &FileDiff) -> Option<&str> {
8767 }
8868 }
8969
90-/// The file's heading in the diff, as `diff_section` writes it: `old → new` for a rename.
9170 fn file_label(file: &FileDiff) -> String {
9271 match (&file.old_path, &file.new_path) {
9372 (Some(old), Some(new)) if old != new => format!("{old} → {new}"),
@@ -97,12 +76,9 @@ fn file_label(file: &FileDiff) -> String {
9776 }
9877 }
9978
100-/// Where a file's mark stands for the viewer.
10179 #[derive(Clone, Copy, PartialEq, Eq)]
10280 enum MarkState {
103- /// Marked at the file's current blob.
10481 Viewed,
105- /// Marked at an older blob: the file changed since.
10682 Changed,
10783 Unviewed,
10884 }
@@ -117,29 +93,16 @@ impl MarkState {
11793 }
11894 }
11995
120-/// One file of the full diff, as the Files pane lists it.
12196 struct FileRow {
12297 path: String,
123- /// The heading `diff_section` gives the file, to find its section on the page.
12498 label: String,
12599 state: MarkState,
126100 additions: u32,
127101 deletions: u32,
128- /// The file's index in the diff the page shows, when that diff lists it.
129102 index: Option<usize>,
130- /// A thread on this file is still open.
131103 commented: bool,
132104 }
133105
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.
143106 async fn file_rows(
144107 state: &AppState,
145108 ctx: &RepoCtx,
@@ -179,14 +142,12 @@ async fn file_rows(
179142 Ok(rows)
180143 }
181144
182-/// One segment of the strip above the diff: one file, its size among the files, and its state.
183145 struct SegView {
184146 class: String,
185147 href: String,
186148 label: String,
187149 }
188150
189-/// One row of the Files rail, with its tick and counts worked out.
190151 struct RailFile {
191152 class: String,
192153 tick: String,
@@ -198,9 +159,6 @@ struct RailFile {
198159 counts: String,
199160 }
200161
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.
204162 #[component]
205163 async fn files_rail(
206164 cx: &Cx,
@@ -248,7 +206,6 @@ async fn files_rail(
248206 })
249207 }
250208
251-/// The diff pane's top row: Unified or Split, and whitespace. Its links are the toolbar's own.
252209 #[component]
253210 async fn diff_top(
254211 cx: &Cx,
@@ -271,7 +228,6 @@ async fn diff_top(
271228 })
272229 }
273230
274-/// The Viewed form body: `viewed` is `1` to mark the file, anything else clears the mark.
275231 #[derive(Deserialize)]
276232 struct ViewedForm {
277233 csrf: String,
@@ -279,10 +235,6 @@ struct ViewedForm {
279235 viewed: String,
280236 }
281237
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.
286238 #[route(POST "/{owner}/{repo}/pulls/{number}/viewed")]
287239 async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther> {
288240 let number = parse_number(number(cx))?;
@@ -328,9 +280,6 @@ async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther>
328280 Ok(see_other(files))
329281 }
330282
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.
334283 #[component]
335284 async fn review_bar(
336285 cx: &Cx,
@@ -381,7 +330,6 @@ async fn review_bar(
381330 <label for="review-body">(summary)</label>
382331 <textarea id="review-body" name="body" rows="3"></textarea>
383332 </div>
384- // An author cannot approve or block their own pull, so they only comment.
385333 if !is_author {
386334 <label class="opt"><input type="radio" name="state" value="approve"><span>(approve)</span></label>
387335 <label class="opt"><input type="radio" name="state" value="request_changes"><span>(changes)</span></label>
@@ -403,7 +351,6 @@ async fn review_bar(
403351 })
404352 }
405353
406-/// The `file=<index>` param: the diff file the Files pane marks as current.
407354 fn file_param(cx: &Cx) -> Option<usize> {
408355 let request = uri(cx);
409356 let query = request.query()?;
@@ -411,6 +358,10 @@ fn file_param(cx: &Cx) -> Option<usize> {
411358 digits::<usize>(&raw)
412359 }
413360
361+fn file_href(i: usize) -> String {
362+ format!("?file={i}#file-{}", i + 1)
363+}
364+
414365 #[page("/{owner}/{repo}/pulls/{number}/files")]
415366 async fn pull_files(cx: &Cx) -> Result<impl View> {
416367 let number = parse_number(number(cx))?;
@@ -429,8 +380,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
429380 (add + file.additions, del + file.deletions)
430381 }));
431382 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.
434383 let viewer_user = viewer(&ctx);
435384 let marks = match &viewer_user {
436385 Some(user) => Some(
@@ -441,12 +390,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
441390 ),
442391 None => None,
443392 };
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.
450393 let shown_ws = if opts.ignore_ws {
451394 Some(
452395 range_diff_files_ws(
@@ -484,14 +427,11 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
484427 Action::Write,
485428 )
486429 .is_ok();
487- // Comments and replies stay open on a closed pull request; new reviews do not.
488430 let can_review = can_comment && open;
489- // Approve and request changes are offered to every viewer who may review but did not open it.
490431 let href = frame.href.clone();
491432 let csrf = csrf_of(&ctx);
433+ let panel = signed_in.then(|| (format!("{href}/viewed"), csrf.clone()));
492434
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.
495435 let threads = state
496436 .store
497437 .review_threads(&pr.issue.id, viewer_id.as_deref())
@@ -521,7 +461,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
521461 }
522462 }
523463
524- // The view owns the diff it shows, so the shown diff moves here once every borrow of it is done.
525464 let diff = shown_ws.unwrap_or(full_diff);
526465
527466 let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, "");
@@ -547,7 +486,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
547486 ctx: thread_ctx,
548487 };
549488
550- // The diff pane has its own top row, so the section's toolbar is left off.
551489 let mut section_opts = opts.clone();
552490 section_opts.enabled = false;
553491 section_opts.only = selected;
@@ -557,21 +495,13 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
557495 let split_on = opts.split;
558496 let ws_on = opts.ignore_ws;
559497
560- let error = review_error_from(lang, cx);
561- // The page follows the pull request's event stream: a change re-renders it.
498+ let error = error_from(lang, cx);
562499 let live = format!("{href}/events");
563500 let owner = ctx.repo.owner_name.clone();
564501 let name = ctx.repo.name.clone();
565502 let parent = pr.merge_base.clone();
566503 let page_title = frame.page_title.clone();
567- let panel_action = controls
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();
504+ let (panel_action, panel_csrf) = panel.unwrap_or_default();
575505
576506 let done = rows
577507 .iter()
@@ -596,7 +526,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
596526 let current_path = current.map(|row| row.path.clone()).unwrap_or_default();
597527 let current_viewed = current.is_some_and(|row| row.state == MarkState::Viewed);
598528 let mark_shown = signed_in && !archived && current.is_some();
599- // The next file after the current one that is not viewed, wrapping round.
600529 let next = {
601530 let start = rows
602531 .iter()
@@ -610,9 +539,8 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
610539 row.index.is_some() && row.index != selected && row.state != MarkState::Viewed
611540 })
612541 .and_then(|row| row.index)
613- .map(|i| format!("?file={i}#file-{}", i + 1))
542+ .map(file_href)
614543 };
615- // The strip above the diff: one segment per file, sized by its changed lines.
616544 let segs: Vec<SegView> = rows
617545 .iter()
618546 .map(|row| {
@@ -630,9 +558,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
630558 };
631559 SegView {
632560 class: format!("seg {fr} {state}").trim_end().to_owned(),
633- href: row
634- .index
635- .map_or_else(|| "#".to_owned(), |i| format!("?file={i}#file-{}", i + 1)),
561+ href: row.index.map_or_else(|| "#".to_owned(), file_href),
636562 label: row.path.clone(),
637563 }
638564 })
@@ -656,7 +582,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
656582 }
657583 .to_owned(),
658584 tick,
659- href: row.index.map(|i| format!("?file={i}#file-{}", i + 1)),
585+ href: row.index.map(file_href),
660586 path: row.path,
661587 label: row.label,
662588 state: row.state,
@@ -675,7 +601,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
675601 }
676602 </div>
677603 if let Some(message) = error {
678- alert(message: message.as_str())
604+ alert(message: message)
679605 }
680606 <div class="work" data-live=(live.as_str()) data-viewed-panel="" data-action=(panel_action.as_str()) data-csrf=(panel_csrf.as_str())>
681607 files_rail(lang: lang, rows: rail, done_text: viewed_text.clone(), signed_in: signed_in, archived: archived)
@@ -719,8 +645,6 @@ mod tests {
719645 format!("__Host-{SESSION_COOKIE}={token}")
720646 }
721647
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>`.
724648 fn page_main(body: &str) -> &str {
725649 body.split_once("<main tabindex=\"-1\"")
726650 .and_then(|(_, rest)| rest.split_once('>'))
@@ -729,7 +653,6 @@ mod tests {
729653 .expect("page has a <main> element")
730654 }
731655
732- /// Sends one GET through the router and returns `(status, body)`.
733656 async fn get(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
734657 let mut req = Request::builder().method("GET").uri(uri);
735658 if let Some(token) = token {
@@ -741,7 +664,6 @@ mod tests {
741664 (status, String::from_utf8_lossy(&bytes).into_owned())
742665 }
743666
744- /// A user with a session whose CSRF token is `{token}-csrf`.
745667 async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
746668 let user = fx
747669 .store
@@ -753,14 +675,11 @@ mod tests {
753675 user
754676 }
755677
756- /// The repo owner, signed in with token `tahinli`.
757678 async fn owner_session(fx: &Fixture) {
758679 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
759680 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
760681 }
761682
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.
764683 async fn open_pull(fx: &Fixture) -> i64 {
765684 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
766685 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
@@ -810,7 +729,6 @@ mod tests {
810729 pr.issue.number
811730 }
812731
813- /// The pull request's issue id and head commit.
814732 async fn pull_ids(fx: &Fixture, number: i64) -> (String, String) {
815733 let repo = fx
816734 .store
@@ -831,9 +749,6 @@ mod tests {
831749 format!("/{OWNER}/{REPO}/pulls/{number}/files{query}")
832750 }
833751
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.
837752 #[tokio::test]
838753 async fn files_tab_scenarios_on_one_open_pull() {
839754 let fx = Fixture::new(Visibility::Public).await;
@@ -844,7 +759,6 @@ mod tests {
844759 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
845760 let uri = files_uri(number, "");
846761
847- // Turkish viewers get the translated review bar.
848762 let req = Request::builder()
849763 .method("GET")
850764 .uri(uri.as_str())
@@ -856,13 +770,11 @@ mod tests {
856770 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
857771 let body = String::from_utf8_lossy(&bytes).into_owned();
858772 assert!(body.contains("İncelemeyi tamamla"), "turkish bar: {body}");
859- // With nothing pending there is nothing to discard.
860773 assert!(
861774 !body.contains("Bekleyen yorumları sil"),
862775 "turkish bar: {body}"
863776 );
864777
865- // Signed-in viewer: line anchors and plus links.
866778 let (status, body) = get(&fx.router, &uri, Some("tahinli")).await;
867779 assert_eq!(status, 200, "anchors");
868780 assert!(body.contains("id=\"L-0-new-1\""), "anchors: {body}");
@@ -872,7 +784,6 @@ mod tests {
872784 );
873785 assert!(body.contains("id=\"review-form\""), "review bar: {body}");
874786
875- // A well-formed `comment` param opens the form under its line.
876787 let (status, body) = get(
877788 &fx.router,
878789 &files_uri(number, "?comment=0:new:1"),
@@ -896,7 +807,6 @@ mod tests {
896807 let form = body.find("name=\"file_index\"").unwrap();
897808 assert!(form > line, "the form sits after its line");
898809
899- // Malformed `comment` params are ignored.
900810 for query in [
901811 "?comment=abc",
902812 "?comment=0:bogus:1",
@@ -911,7 +821,6 @@ mod tests {
911821 assert!(!body.contains("name=\"file_index\""), "garbage {query}");
912822 }
913823
914- // The review bar hides approve from the pull's author only.
915824 let (_, author) = get(&fx.router, &uri, Some("tahinli")).await;
916825 assert!(author.contains("value=\"comment\""), "author bar: {author}");
917826 assert!(
@@ -929,7 +838,6 @@ mod tests {
929838 "reader bar: {other}"
930839 );
931840
932- // Anonymous viewers get no comment controls at all.
933841 let (status, body) = get(&fx.router, &files_uri(number, "?comment=0:new:1"), None).await;
934842 assert_eq!(status, 200, "anonymous");
935843 assert!(!page_main(&body).contains("?comment="), "anonymous: {body}");
@@ -938,7 +846,6 @@ mod tests {
938846 assert!(!body.contains("id=\"review-form\""), "anonymous: {body}");
939847 assert!(!body.contains("class=\"diff-plus\""), "anonymous: {body}");
940848
941- // A known review error shows its message, an unknown code shows nothing.
942849 let (_, known) = get(
943850 &fx.router,
944851 &files_uri(number, "?review_error=own_pr"),
@@ -959,7 +866,6 @@ mod tests {
959866 );
960867 assert!(!unknown.contains("<b>hi</b>"), "unknown error: {unknown}");
961868
962- // An outdated thread is hidden. Only the outdated comment exists at this point.
963869 let comment = fx
964870 .store
965871 .add_review_comment(
@@ -987,7 +893,6 @@ mod tests {
987893 "outdated: {body}"
988894 );
989895
990- // A pending comment is visible only to its author.
991896 fx.store
992897 .add_review_comment(
993898 &issue_id,
@@ -1014,7 +919,6 @@ mod tests {
1014919 "pending author: {author}"
1015920 );
1016921
1017- // A submitted thread renders under its line.
1018922 fx.store
1019923 .add_review_comment(
1020924 &issue_id,
crates/forge-web-repo/src/pages/pull_flow.rsmodified+5 -9
@@ -10,7 +10,7 @@
1010 //! or approvals that can still arrive. All of them answer with a redirect back to the pull
1111 //! request (the soft-nav script follows it without a reload).
1212
13-use forge_core::{Action, IssueState, MergeStyle, PullRequest, authorize};
13+use forge_core::{IssueState, MergeStyle, PullRequest};
1414 use serde::Deserialize;
1515 use topcoat::Result;
1616 use topcoat::context::{Cx, context};
@@ -40,7 +40,7 @@ struct FlowForm {
4040 style: String,
4141 }
4242
43-fn pull_href(ctx: &RepoCtx, number: i64) -> String {
43+pub(crate) fn pull_href(ctx: &RepoCtx, number: i64) -> String {
4444 repo_href(
4545 &ctx.repo.owner_name,
4646 &ctx.repo.name,
@@ -49,10 +49,6 @@ fn pull_href(ctx: &RepoCtx, number: i64) -> String {
4949 )
5050 }
5151
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-
5652 async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> {
5753 let state = context::<AppState>(cx);
5854 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> {
7773 let (user, _) = require_csrf(cx, csrf).await?;
7874 let state = context::<AppState>(cx);
7975 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) {
8177 return Err(forbidden().into());
8278 }
8379 let href = pull_href(&ctx, number);
@@ -121,7 +117,7 @@ async fn auto_merge_enable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Respon
121117 let number = parse_number(number(cx))?;
122118 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
123119 let (user, _) = require_csrf(cx, &form.csrf).await?;
124- if ctx.repo.archived || !can_write(&ctx, &user) {
120+ if !ctx.can_write() {
125121 return Err(forbidden().into());
126122 }
127123 let state = context::<AppState>(cx);
@@ -152,7 +148,7 @@ async fn auto_merge_disable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Respo
152148 let number = parse_number(number(cx))?;
153149 let ctx = load_repo(cx, owner(cx), repo(cx)).await?;
154150 let (user, _) = require_csrf(cx, &form.csrf).await?;
155- if ctx.repo.archived || !can_write(&ctx, &user) {
151+ if !ctx.can_write() {
156152 return Err(forbidden().into());
157153 }
158154 let state = context::<AppState>(cx);
crates/forge-web-repo/src/pages/pull_view.rsmodified+29 -38
@@ -29,7 +29,7 @@ use crate::merge::{
2929 ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE,
3030 merge_gate,
3131 };
32-use crate::pages::commits::{CommitRow, now_secs};
32+use crate::pages::commits::CommitRow;
3333 use crate::pages::issue_meta::item_href;
3434 use crate::pages::issue_parts::{
3535 CommentForm, ItemKind, Posted, check_write, comment_form, csrf_of, discussion_timeline,
@@ -38,7 +38,7 @@ use crate::pages::issue_parts::{
3838 };
3939 use crate::pages::notifications::notify_box_for;
4040 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;
4242 use crate::pages::repo_ctx::{RepoCtx, load_repo};
4343 use crate::pages::review_requests::{load_reviewers, reviewers_box};
4444 use crate::state::AppState;
@@ -315,6 +315,20 @@ struct FlowView {
315315 queue_add: Option<String>,
316316 }
317317
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+
318332 /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of
319333 /// `ok`, `bad` or `muted` and picks the box colors.
320334 #[component]
@@ -335,8 +349,6 @@ async fn merge_box(
335349 let class = format!("sec merge-{tone}");
336350 let required_heading = g::t(lang, K::RequiredChecksHeading);
337351 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);
340352 let enable_auto = g::t(lang, K::EnableAutoMerge);
341353 let disable_auto = g::t(lang, K::DisableAutoMerge);
342354 let FlowView {
@@ -425,11 +437,7 @@ async fn merge_box(
425437 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
426438 <div class="field">
427439 <label for="queue-style">(queue_add_label)</label>
428- <select id="queue-style" name="style">
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>
440+ style_select(id: "queue-style", lang: lang)
433441 </div>
434442 <button type="submit" class="primary">(queue_add_label)</button>
435443 </form>
@@ -445,11 +453,7 @@ async fn merge_box(
445453 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
446454 <div class="field">
447455 <label for="auto-style">(enable_auto)</label>
448- <select id="auto-style" name="style">
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>
456+ style_select(id: "auto-style", lang: lang)
453457 </div>
454458 <button type="submit" class="primary">(enable_auto)</button>
455459 </form>
@@ -693,19 +697,15 @@ async fn pull_conversation(
693697 // outdated head does not block it.
694698 let queue_required =
695699 crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await?;
696- let queue_blocker = gate.as_ref().and_then(|gate| {
697- gate.blockers()
698- .into_iter()
699- .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE))
700- });
701- let blocked = if queue_required {
702- queue_blocker.and_then(|code| merge_error_text(lang, code))
703- } else {
704- gate.as_ref()
705- .and_then(|gate| gate.blocked())
706- .and_then(|code| merge_error_text(lang, code))
707- }
708- .map(str::to_owned);
700+ let blocked = gate
701+ .as_ref()
702+ .and_then(|gate| {
703+ gate.blockers()
704+ .into_iter()
705+ .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE))
706+ })
707+ .and_then(|code| merge_error_text(lang, code))
708+ .map(str::to_owned);
709709 let approvals = gate
710710 .as_ref()
711711 .filter(|gate| gate.rule.required_approvals > 0)
@@ -857,7 +857,7 @@ async fn pull_conversation(
857857 .then(|| format!("/{owner}/{name}/commit/{oid}")),
858858 };
859859
860- let review_error = review_error_from(lang, cx);
860+ let review_error = error_from(lang, cx);
861861 let summary = state.store.review_summary(&pr.issue.id).await?;
862862 // Approvals of an earlier head no longer count for the merge rules (see `merge_gate`), so
863863 // they are listed apart from the current ones.
@@ -990,15 +990,6 @@ fn merge_error_from(lang: Lang, cx: &Cx) -> Option<String> {
990990 merge_error_text(lang, &code).map(str::to_owned)
991991 }
992992
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-
1002993 #[page("/{owner}/{repo}/pulls/{number}")]
1003994 async fn pull_show(cx: &Cx) -> Result<impl View> {
1004995 let (ctx, pr) = load_pull(cx).await?;
@@ -1019,7 +1010,7 @@ async fn pull_commits(cx: &Cx) -> Result<impl View> {
10191010 let owner = ctx.repo.owner_name.clone();
10201011 let name = ctx.repo.name.clone();
10211012 let tz = ctx.viewer_tz().to_owned();
1022- let now = now_secs();
1013+ let now = now_unix();
10231014 let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect();
10241015 let statuses = state
10251016 .store
crates/forge-web-repo/src/pages/pulls_list.rsmodified+3 -2
@@ -17,14 +17,15 @@ use crate::i18n::pulls::{self as g, K};
1717 use crate::i18n::s;
1818 use crate::i18n::{self, Lang};
1919 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,
2121 };
2222 use crate::pages::repo::repo_head;
2323 use crate::pages::repo_ctx::load_repo;
2424 use crate::state::AppState;
2525 use crate::views::parts::{RailItem, SubPart, rail};
2626 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,
2829 };
2930
3031 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>
6666 if form.target_id != item.id {
6767 return Err(not_found().into());
6868 }
69- let prefix = match kind {
70- ItemKind::Issue => "issue",
71- ItemKind::Pull => "pull",
72- };
73- (ReactionTarget::Issue, format!("{prefix}-{number}"))
69+ (ReactionTarget::Issue, kind.anchor(number))
7470 }
7571 "comment" => {
7672 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;
3131 use crate::pages::repo_settings_live::settings_head;
3232 use crate::state::AppState;
3333 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};
3535
3636 path_param!(owner);
3737 path_param!(repo);
@@ -128,11 +128,6 @@ async fn owns_repo_org(state: &AppState, ctx: &RepoCtx, actor: &User) -> Result<
128128 ))
129129 }
130130
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-
136131 fn collaborators_redirect(title: &str) -> SeeOther {
137132 see_other(format!("/{title}/settings/collaborators"))
138133 }
@@ -146,7 +141,7 @@ struct FrameData {
146141
147142 impl FrameData {
148143 async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> {
149- let title = title_of(ctx);
144+ let title = ctx.title();
150145 Ok(Self {
151146 page_title: g::collaborators_page_title(lang, &title),
152147 title,
@@ -215,11 +210,7 @@ async fn collaborators_body(
215210 repo_head(head: header, title: Some(section_name))
216211 settings_frame(lang: lang, title: nav_title, current: "collaborators",
217212 if let Some((text, is_error)) = notice {
218- if is_error {
219- alert(message: text)
220- } else {
221- <p class="state" role="status">(text)</p>
222- }
213+ notice_line(text: text, is_error: is_error)
223214 }
224215 people_list(list: list)
225216 )
@@ -282,7 +273,7 @@ async fn collaborators_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOthe
282273 if !ctx.can_admin() {
283274 return Err(forbidden().into());
284275 }
285- let title = title_of(&ctx);
276+ let title = ctx.title();
286277 let state = context::<AppState>(cx);
287278
288279 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
368359 if !ctx.can_admin() {
369360 return Err(forbidden().into());
370361 }
371- let title = title_of(&ctx);
362+ let title = ctx.title();
372363 let state = context::<AppState>(cx);
373364
374365 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
429420 if !ctx.can_admin() {
430421 return Err(forbidden().into());
431422 }
432- let title = title_of(&ctx);
423+ let title = ctx.title();
433424 let state = context::<AppState>(cx);
434425 let target_id = form.user_id.trim();
435426 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);
3030 path_param!(repo);
3131
3232 /// Longest secret value accepted, in bytes.
33-pub const MAX_VALUE_BYTES: usize = 48 * 1024;
33+const MAX_VALUE_BYTES: usize = 48 * 1024;
3434 /// Longest secret name accepted, in characters.
3535 const MAX_NAME_CHARS: usize = 64;
3636
@@ -60,7 +60,7 @@ struct DeleteForm {
6060 }
6161
6262 /// `^[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 {
6464 let bytes = name.as_bytes();
6565 let Some((first, rest)) = bytes.split_first() else {
6666 return false;
@@ -231,19 +231,14 @@ async fn secrets_body(
231231 }
232232 <div>
233233 for row in rows.iter() {
234- if archived {
235- <div class="line">
236- <span class="name"><code>(row.name.as_str())</code></span>
237- <span class="val">rel_time(lang: lang, stamp: row.updated_at.as_str())</span>
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>
234+ <div class="line">
235+ <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+ if !archived {
243238 confirm_act(lang: lang, label: g::t(lang, K::Delete), action: delete_action.as_str(), csrf: csrf.as_str(),
244239 fields: vec![("name".to_owned(), row.name.clone())])
245- </div>
246- }
240+ }
241+ </div>
247242 }
248243 </div>
249244 </section>
@@ -615,20 +610,6 @@ mod tests {
615610 async fn bad_name_and_bad_value_are_rejected() {
616611 let dir = tempfile::tempdir().expect("tempdir");
617612 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- }
632613 let (_, _, body) = send(
633614 &app,
634615 "POST",
crates/forge-web-repo/src/pages/repo_webhooks.rsmodified+25 -58
@@ -4,6 +4,8 @@
44 //! and response. A hook's secret is sealed with the instance key and is never shown again: a blank
55 //! secret on edit keeps the stored one. Archived repos show everything but change nothing.
66
7+use std::collections::HashMap;
8+
79 use forge_core::AuditAction;
810 use forge_core::secret;
911 use forge_core::tz::format_in_tz;
@@ -69,7 +71,6 @@ const EVENT_CHOICES: [(WebhookEvent, K); 8] = [
6971 (WebhookEvent::Release, K::EvRelease),
7072 ];
7173
72-/// The hook form. Unticked boxes are absent from the body, so each event has an `Option`.
7374 #[derive(Deserialize)]
7475 struct HookForm {
7576 #[serde(default)]
@@ -81,44 +82,18 @@ struct HookForm {
8182 secret: String,
8283 #[serde(default)]
8384 active: Option<String>,
84- #[serde(default)]
85- ev_push: Option<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>,
85+ #[serde(flatten)]
86+ boxes: HashMap<String, String>,
10087 }
10188
10289 impl HookForm {
10390 /// The ticked events, in the form's order.
10491 fn events(&self) -> Vec<WebhookEvent> {
105- [
106- (WebhookEvent::Push, &self.ev_push),
107- (WebhookEvent::PullRequest, &self.ev_pull_request),
108- (WebhookEvent::Issues, &self.ev_issues),
109- (WebhookEvent::IssueComment, &self.ev_issue_comment),
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()
92+ EVENT_CHOICES
93+ .iter()
94+ .map(|(event, _)| *event)
95+ .filter(|event| self.boxes.contains_key(&format!("ev_{}", event.as_str())))
96+ .collect()
12297 }
12398 }
12499
@@ -339,15 +314,17 @@ fn hook_row(
339314 tz: &str,
340315 title: &str,
341316 hook: Webhook,
342- last: Option<(&'static str, &'static str)>,
317+ last: Option<DeliveryState>,
343318 last_stamp: &str,
344319 ) -> HookRow {
345- let (dot_class, dot_text) = match last {
346- Some(("ok", text)) if hook.active => ("runner-dot is-online", text),
347- Some(("failed" | "gave_up", text)) if hook.active => ("runner-dot is-failed", text),
348- Some((_, text)) => ("runner-dot", text),
349- None => ("runner-dot", g::t(lang, K::NoneYet)),
320+ let dot_class = match last {
321+ Some(DeliveryState::Ok) if hook.active => "runner-dot is-online",
322+ Some(DeliveryState::Failed | DeliveryState::GaveUp) if hook.active => {
323+ "runner-dot is-failed"
324+ }
325+ _ => "runner-dot",
350326 };
327+ let dot_text = last.map_or(g::t(lang, K::NoneYet), |state| state_label(lang, state).1);
351328 let (last_text, last_rel) = match (last, last_stamp) {
352329 (Some(_), stamp) if !stamp.is_empty() => {
353330 let rel = OffsetDateTime::parse(stamp, &Rfc3339)
@@ -381,8 +358,8 @@ fn hook_row(
381358 last_full: local_stamp(last_stamp, tz),
382359 last_rel,
383360 problem: match last {
384- Some(("ok", _)) | None => "",
385- Some((_, text)) => text,
361+ None | Some(DeliveryState::Ok) => "",
362+ Some(state) => state_label(lang, state).1,
386363 },
387364 inactive_text: match lang {
388365 Lang::En => "inactive",
@@ -750,19 +727,7 @@ async fn hooks_list_page(cx: &Cx) -> Result<impl View> {
750727 let tz = ctx.viewer_tz();
751728 let mut rows: Vec<HookRow> = Vec::with_capacity(hooks.len());
752729 for (hook, last) in hooks {
753- // The list shows when the newest delivery happened, so it reads the one latest delivery per hook.
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));
730+ let (last, last_stamp) = last.map_or((None, String::new()), |(s, at)| (Some(s), at));
766731 rows.push(hook_row(lang, tz, &frame.title, hook, last, &last_stamp));
767732 }
768733 let notice = notice_from_query(cx, lang);
@@ -816,9 +781,11 @@ async fn hook_new_body(
816781 <a class="act quiet" href=(back.as_str())>(g::t(lang, K::BackToWebhooks))</a>
817782 </div>
818783 </section>
819- hook_form(action: action, csrf: csrf, url: draft.url, events: events,
820- active: draft.active, secret_hint: String::new(),
821- error: draft.error, submit: g::t(lang, K::CreateWebhook), lang: lang)
784+ if !archived {
785+ hook_form(action: action, csrf: csrf, url: draft.url, events: events,
786+ active: draft.active, secret_hint: String::new(),
787+ error: draft.error, submit: g::t(lang, K::CreateWebhook), lang: lang)
788+ }
822789 )
823790 })
824791 }
crates/forge-web-repo/src/pages/review_requests.rsmodified+33 -29
@@ -5,6 +5,7 @@
55 //! clears the reviewer's own request in the store.
66
77 use forge_core::authz::{Action, authorize};
8+use forge_core::{Repo, User};
89 use serde::Deserialize;
910 use topcoat::Result;
1011 use topcoat::context::{Cx, context};
@@ -99,16 +100,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt
99100 if target.id == pull.author_id {
100101 return Ok(refusal("author", &href));
101102 }
102- let role = state
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- {
103+ if target.is_org() || !can_read_repo(state, &target, &ctx.repo).await? {
112104 return Ok(refusal("access", &href));
113105 }
114106 if state
@@ -124,6 +116,15 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt
124116 Ok(see_other(format!("{href}#reviewers")))
125117 }
126118
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+
127128 /// What the Reviewers box shows.
128129 pub(crate) struct ReviewersView {
129130 pub(crate) action: String,
@@ -227,6 +228,14 @@ pub(crate) async fn reviewers_box(
227228 })
228229 }
229230
231+struct ReviewRow {
232+ repo_full: String,
233+ href: String,
234+ title: String,
235+ requested_by: String,
236+ created_at: String,
237+}
238+
230239 /// The open pull requests waiting for the viewer's review, newest request first.
231240 #[page("/review-requests")]
232241 async fn review_requests(cx: &Cx) -> Result<impl View> {
@@ -245,26 +254,21 @@ async fn review_requests(cx: &Cx) -> Result<impl View> {
245254 else {
246255 continue;
247256 };
248- let role = state.store.collaborator_role(&repo.id, &user.id).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() {
257+ if !can_read_repo(state, user, &repo).await? {
254258 continue;
255259 }
256- rows.push((
257- format!("{}/{}", item.repo_owner, item.repo_name),
258- repo_href(
260+ rows.push(ReviewRow {
261+ repo_full: format!("{}/{}", item.repo_owner, item.repo_name),
262+ href: repo_href(
259263 &item.repo_owner,
260264 &item.repo_name,
261- "pulls",
265+ ItemKind::Pull.segment(),
262266 &item.number.to_string(),
263267 ),
264- format!("#{} {}", item.number, item.title),
265- ga::requested_by(lang, &item.requested_by),
266- item.created_at.clone(),
267- ));
268+ title: format!("#{} {}", item.number, item.title),
269+ requested_by: ga::requested_by(lang, &item.requested_by),
270+ created_at: item.created_at.clone(),
271+ });
268272 }
269273 let heading = ga::t(lang, AK::ReviewRequests);
270274 let empty = rows.is_empty();
@@ -280,11 +284,11 @@ async fn review_requests(cx: &Cx) -> Result<impl View> {
280284 <p class="state">(ga::t(lang, AK::NoReviewRequests))</p>
281285 }
282286 for row in rows.iter() {
283- <a class="line" href=(row.1.as_str()) data-kb-row="">
284- <span class="name">(row.2.as_str())</span>
285- <span class="val">(row.0.as_str())</span>
286- <span class="val">(row.3.as_str())</span>
287- <span class="val">rel_time(lang: lang, stamp: row.4.as_str())</span>
287+ <a class="line" href=(row.href.as_str()) data-kb-row="">
288+ <span class="name">(row.title.as_str())</span>
289+ <span class="val">(row.repo_full.as_str())</span>
290+ <span class="val">(row.requested_by.as_str())</span>
291+ <span class="val">rel_time(lang: lang, stamp: row.created_at.as_str())</span>
288292 </a>
289293 }
290294 </div>
crates/forge-web/src/admin_cli.rsmodified+3 -7
@@ -40,13 +40,13 @@ const TEMPORARY_PASSWORD_CHARS: usize = 20;
4040
4141 const MIN_PASSWORD_CHARS: usize = 12;
4242
43-/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty.
4443 /// Refusal text for admin commands that would give a login to an organization.
4544 const ORG_NO_LOGIN: &str =
4645 "an organization cannot sign in, so it has no password or login name here";
4746 /// Refusal text for `create-user` on a name that an organization already holds.
4847 const ORG_NAME_TAKEN: &str = "that name belongs to an organization";
4948
49+/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty.
5050 pub async fn create_user(
5151 config_path: &Path,
5252 username: &str,
@@ -74,8 +74,6 @@ pub async fn create_user(
7474 }
7575
7676 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.
7977 let user = match store.create_first_admin(&username, None, &hash).await? {
8078 Some(user) => user,
8179 None => {
@@ -117,7 +115,6 @@ pub async fn create_user(
117115 pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> {
118116 let config = Config::load(config_path)?;
119117 let store = Store::open(&config.database).await?;
120- // The id is gone once the account is deleted, so it is read first.
121118 let user_id = store.user_by_username(username).await?.map(|u| u.id);
122119 let report = delete_user_in(&store, username, yes).await?;
123120 if let Some(id) = user_id {
@@ -134,7 +131,7 @@ pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge
134131 /// The store-level part of [`delete_user`]. Returns the report of what was (or, with `yes`
135132 /// unset, would be) done. Without `yes` nothing is written and an error is returned, so the
136133 /// 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(
138135 store: &Store,
139136 username: &str,
140137 yes: bool,
@@ -258,7 +255,7 @@ pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::R
258255 }
259256
260257 /// 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(
262259 store: &Store,
263260 username: &str,
264261 ) -> forge_core::Result<(String, String)> {
@@ -574,7 +571,6 @@ pub async fn backup_verify(path: &Path) -> forge_core::Result<()> {
574571 .parent()
575572 .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?
576573 .to_path_buf();
577- // Git runs with the set's parent as its HOME, so no user gitconfig is read.
578574 let git = GitEnv {
579575 git_bin: find_git(),
580576 data_dir: parent,
crates/forge-web/src/boot.rsmodified+7 -0
@@ -47,6 +47,13 @@ pub async fn serve(
4747 // The data dir holds the instance key and the internal socket. Keep it private to this user.
4848 std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?;
4949 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+ })?;
5057
5158 let key = Arc::new(secret::load_or_create_key(&data_dir.join("forge.key"))?);
5259 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};
2424
2525 const TOKEN: &str = "ghp_supersecret_token_value";
2626
27+fn all_issues() -> IssueFilter {
28+ IssueFilter {
29+ state: None,
30+ per_page: 100,
31+ ..IssueFilter::default()
32+ }
33+}
34+
2735 #[derive(Default)]
2836 struct Fake {
2937 labels: Vec<ExtLabel>,
@@ -343,12 +351,10 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() {
343351 let job = store.import_job(&job.id).await.unwrap().unwrap();
344352 assert_eq!(job.state, ImportState::Done, "{:?}", job.error);
345353
346- let all = IssueFilter {
347- state: None,
348- per_page: 100,
349- ..IssueFilter::default()
350- };
351- let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap();
354+ let (items, total) = store
355+ .list_issues(&fx.repo.id, &all_issues())
356+ .await
357+ .unwrap();
352358 assert_eq!(total, 2);
353359 let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap();
354360 assert_eq!(issue.issue.state, IssueState::Closed);
@@ -407,7 +413,10 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() {
407413 .await;
408414 let again = store.import_job(&again.id).await.unwrap().unwrap();
409415 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();
411420 assert_eq!(total, 2);
412421 let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap();
413422 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() {
456465 let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap();
457466 assert_eq!(done.state, ImportState::Done, "{:?}", done.error);
458467 assert!(done.error.is_none());
459- let all = IssueFilter {
460- state: None,
461- per_page: 100,
462- ..IssueFilter::default()
463- };
464- let (_, total) = fx.state.store.list_issues(&fx.repo.id, &all).await.unwrap();
468+ let (_, total) = fx
469+ .state
470+ .store
471+ .list_issues(&fx.repo.id, &all_issues())
472+ .await
473+ .unwrap();
465474 assert_eq!(total, 2);
466475 }
467476
crates/forge-web/src/main.rsmodified+11 -25
@@ -94,25 +94,11 @@ fn parse_args(
9494 /// the binary, never the unit, so the server sets it itself: `serve` re-runs itself once with the
9595 /// variable set (same PID, so systemd is unaffected). An explicit value is left alone, and
9696 /// 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>) {
9898 const VAR: &str = "MIMALLOC_ALLOW_THP";
9999 if std::env::var_os(VAR).is_some() {
100100 return;
101101 }
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- }
116102 if command.is_some_and(|c| c != "serve") {
117103 return;
118104 }
@@ -157,7 +143,14 @@ fn main() -> ExitCode {
157143 if let Err(e) = nix::sys::prctl::set_thp_disable(true) {
158144 eprintln!("forge: cannot disable transparent huge pages: {e}");
159145 }
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));
161154 let runtime = match tokio::runtime::Builder::new_multi_thread()
162155 .enable_all()
163156 .build()
@@ -168,10 +161,10 @@ fn main() -> ExitCode {
168161 return ExitCode::FAILURE;
169162 }
170163 };
171- runtime.block_on(real_main())
164+ runtime.block_on(real_main(flag_config, admin, positional))
172165 }
173166
174-async fn real_main() -> ExitCode {
167+async fn real_main(flag_config: Option<PathBuf>, admin: bool, positional: Vec<String>) -> ExitCode {
175168 // Logs go to stderr: the hook stages write protocol output to stdout.
176169 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
177170 tracing_subscriber::fmt()
@@ -179,13 +172,6 @@ async fn real_main() -> ExitCode {
179172 .with_writer(std::io::stderr)
180173 .init();
181174
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- };
189175 let config_path = flag_config
190176 .or_else(|| std::env::var_os("FORGE_CONFIG").map(PathBuf::from))
191177 .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};
55 use crate::auth::SESSION_COOKIE;
66 use crate::test_support::fixture::{Fixture, OWNER, REPO};
77
8-/// Sends one request and returns `(status, body)`.
98 async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
109 let mut req = Request::builder().method("GET").uri(uri);
1110 if let Some(token) = token {
@@ -17,7 +16,6 @@ async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String)
1716 (status, String::from_utf8_lossy(&bytes).into_owned())
1817 }
1918
20-/// The repo owner with a session whose token is `tahinli`.
2119 async fn tahinli(fx: &Fixture) -> forge_core::User {
2220 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
2321 crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
@@ -37,15 +35,12 @@ fn hex_oid(c: char) -> String {
3735 std::iter::repeat_n(c, 40).collect()
3836 }
3937
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.
4238 #[tokio::test]
4339 async fn public_histories_show_diffs_markers_and_refusals() {
4440 let fx = Fixture::new(Visibility::Public).await;
4541 let owner = tahinli(&fx).await;
4642 let id = repo_id(&fx).await;
4743
48- // A comment edited twice: a marker on the item page and two versions with diffs.
4944 let issue = fx
5045 .store
5146 .create_issue(&id, &owner.id, "bug", "body")
@@ -97,7 +92,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
9792 "edited comment: editor {history}"
9893 );
9994
100- // A comment that was never edited has no marker.
10195 let plain = fx
10296 .store
10397 .create_issue(&id, &owner.id, "plain", "body")
@@ -119,7 +113,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
119113 "unedited comment: no marker {page}"
120114 );
121115
122- // An issue body and title edit: the old title and the changed lines show.
123116 let titled = fx
124117 .store
125118 .create_issue(&id, &owner.id, "old title", "a\nb\nc")
@@ -153,7 +146,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
153146 assert!(history.contains("-b"), "body edit: -b {history}");
154147 assert!(history.contains("+B"), "body edit: +B {history}");
155148
156- // A comment on one issue is not found under another issue's URL.
157149 let other = fx
158150 .store
159151 .create_issue(&id, &owner.id, "second", "body")
@@ -189,7 +181,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
189181 .await;
190182 assert_eq!(status, 200, "right item: found");
191183
192- // An unknown kind and a missing target are both not found.
193184 let (status, _) = send(
194185 &fx.router,
195186 &format!(
@@ -211,7 +202,6 @@ async fn public_histories_show_diffs_markers_and_refusals() {
211202 .await;
212203 assert_eq!(status, 404, "missing target");
213204
214- // Review comment history on a pull request, and not under the issue URL of the same number.
215205 let pr = fx
216206 .store
217207 .create_pull(
crates/forge-web/src/page_route_tests/notifications.rsmodified+0 -15
@@ -34,7 +34,6 @@ async fn site() -> Site {
3434 }
3535 }
3636
37-/// Signs `user_id` in with `token` and returns the cookie header value.
3837 async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
3938 crate::test_support::create_session(store, user_id, token, CSRF).await;
4039 format!("__Host-{SESSION_COOKIE}={token}")
@@ -91,7 +90,6 @@ async fn post(site: &Site, uri: &str, cookie: &str, extra: &str) -> Reply {
9190 .await
9291 }
9392
94-/// Tahinli owns `demo` with one issue (#1), and Bob has a notification row for it.
9593 struct World {
9694 tahinli: forge_core::User,
9795 bob: forge_core::User,
@@ -185,8 +183,6 @@ async fn unread_inbox_lists_unread_rows_grouped_by_repo() {
185183 assert!(page.body.contains("Mark all as read"));
186184 }
187185
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.
190186 #[tokio::test]
191187 async fn another_users_notification_is_404_and_the_owner_opens_it() {
192188 let site = site().await;
@@ -215,7 +211,6 @@ async fn another_users_notification_is_404_and_the_owner_opens_it() {
215211 assert_eq!(read.status, 303);
216212 assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
217213
218- // Bob opens his own row: it redirects to the issue and marks the row read.
219214 let res = get(
220215 &site,
221216 &format!("/notifications/{id}/open"),
@@ -261,13 +256,11 @@ async fn the_stream_sends_the_count_then_each_change() {
261256 assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");
262257
263258 let mut frames = res.into_body().into_data_stream();
264- // The stream opens with its retry field, then the count.
265259 let retry = frames.next().await.expect("a frame").expect("data");
266260 assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
267261 let first = frames.next().await.expect("a frame").expect("data");
268262 assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");
269263
270- // Marking the row read pushes the new count to the open stream.
271264 let read = post(&site, "/notifications/mark_all_read", &cookie, "").await;
272265 assert_eq!(read.status, 303);
273266 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() {
328321 .expect("sub");
329322 assert_eq!(sub, Some((SubState::Ignored, Reason::Subscribed)));
330323
331- // A pull request number that does not exist is a 404 on the pulls subscription.
332324 let res = post(
333325 &site,
334326 "/tahinli/demo/pulls/1/subscription",
@@ -355,7 +347,6 @@ async fn watch_form_sets_the_level() {
355347 WatchLevel::Watching
356348 );
357349
358- // The watch menu sits in the repo head on the code tab, which reads the repository.
359350 let bare = forge_git::repo::repo_path(&site.git.data_dir, &w.repo.id).expect("repo path");
360351 forge_git::repo::init_bare(&site.git, &bare, "main")
361352 .await
@@ -364,7 +355,6 @@ async fn watch_form_sets_the_level() {
364355 assert!(header.body.contains("action=\"/tahinli/demo/watch\""));
365356 assert!(header.body.contains("<details class=\"menu watch-menu\">"));
366357 assert!(!header.body.contains("<select"));
367- // One form per level, and only the watched level is marked current.
368358 assert_eq!(header.body.matches("name=\"level\"").count(), 3);
369359 assert_eq!(
370360 header
@@ -417,7 +407,6 @@ async fn row_for_a_repo_the_viewer_lost_access_to_is_hidden() {
417407 async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
418408 let site = site().await;
419409 let w = world(&site, Visibility::Public).await;
420- // The world's issue takes number 1, so the discussion is #2.
421410 let discussion = site
422411 .store
423412 .create_discussion(
@@ -446,7 +435,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
446435 1
447436 );
448437
449- // Bob has no row for the discussion, so he cannot open it.
450438 let other = get(&site, &open, Some(&bob)).await;
451439 assert_eq!(other.status, 404);
452440
@@ -458,7 +446,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
458446 0
459447 );
460448
461- // A second discussion, cleared by mark all read.
462449 let discussion = site
463450 .store
464451 .create_discussion(
@@ -491,7 +478,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
491478 async fn advisory_alerts_show_for_managers_and_open_marks_read() {
492479 let site = site().await;
493480 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.
495481 site.store
496482 .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2)
497483 .await
@@ -514,7 +500,6 @@ async fn advisory_alerts_show_for_managers_and_open_marks_read() {
514500 1
515501 );
516502
517- // Bob cannot manage the alerts: his row is hidden and marked read, as lost-access rows are.
518503 let bob_page = get(&site, "/notifications", Some(&bob)).await;
519504 assert_eq!(bob_page.status, 200);
520505 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 {
1111 format!("__Host-{SESSION_COOKIE}={token}")
1212 }
1313
14-/// Sends one request through the router and returns `(status, location, body)`.
1514 async fn send(
1615 router: &Router,
1716 method: &str,
@@ -44,7 +43,6 @@ async fn send(
4443 )
4544 }
4645
47-/// A user with a session whose CSRF token is `{token}-csrf`.
4846 async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
4947 let user = fx
5048 .store
@@ -55,7 +53,6 @@ async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
5553 user
5654 }
5755
58-/// The repo owner, signed in with token `tahinli` (CSRF `tahinli-csrf`).
5956 async fn owner_session(fx: &Fixture) {
6057 let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
6158 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 {
6966 form
7067 }
7168
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+
7285 async fn pull(fx: &Fixture, number: i64) -> PullRequest {
7386 let repo = fx
7487 .store
@@ -83,8 +96,6 @@ async fn pull(fx: &Fixture, number: i64) -> PullRequest {
8396 .unwrap()
8497 }
8598
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.
8899 async fn open_pull(fx: &Fixture) -> i64 {
89100 let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
90101 git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
@@ -126,12 +137,10 @@ async fn open_pull(fx: &Fixture) -> i64 {
126137 pr.issue.number
127138 }
128139
129-/// The pull request's current head, for the `head_oid` field of a comment form.
130140 async fn head_of(fx: &Fixture, number: i64) -> String {
131141 pull(fx, number).await.head_oid
132142 }
133143
134-/// Posts a single line comment on line `line` of the new side of `a.txt` (file index 0).
135144 async fn comment_on(
136145 fx: &Fixture,
137146 number: i64,
@@ -140,7 +149,9 @@ async fn comment_on(
140149 body: &str,
141150 ) -> (u16, Option<String>) {
142151 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"),
144155 token,
145156 &[
146157 ("file_index", "0"),
@@ -150,19 +161,11 @@ async fn comment_on(
150161 ("action", "single"),
151162 ("body", body),
152163 ],
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),
160164 )
161165 .await;
162166 (status, location)
163167 }
164168
165-/// The id of the thread at `index` (in creation order) on the pull request.
166169 async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {
167170 let pr = pull(fx, number).await;
168171 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 {
171174 .clone()
172175 }
173176
174-/// The comment body that proposes replacing line 2 of `a.txt` with `text`.
175177 fn suggestion(text: &str) -> String {
176178 format!("Try this:\n```suggestion\n{text}\n```")
177179 }
178180
179-/// Posts the apply form for suggestion block 0 of comment `comment_id`.
180181 async fn apply_as(
181182 fx: &Fixture,
182183 number: i64,
183184 token: &str,
184185 comment_id: &str,
185186 ) -> (u16, Option<String>) {
186- let form = csrf_form(token, &[("block", "0"), ("return", "files")]);
187187 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;
189190 (status, location)
190191 }
191192
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.
194193 #[tokio::test]
195194 async fn comment_rules_and_pending_review_on_one_pull() {
196195 let fx = Fixture::new(Visibility::Public).await;
@@ -198,7 +197,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
198197 let number = open_pull(&fx).await;
199198 let pr = pull(&fx, number).await;
200199
201- // A line outside the diff is rejected and leaves no thread.
202200 let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await;
203201 assert_eq!(status, 303, "outside diff");
204202 assert!(
@@ -214,9 +212,10 @@ async fn comment_rules_and_pending_review_on_one_pull() {
214212 "outside diff left a thread"
215213 );
216214
217- // A head that is not the pull's current head is rejected.
218215 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"),
220219 "tahinli",
221220 &[
222221 ("file_index", "0"),
@@ -226,13 +225,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
226225 ("action", "single"),
227226 ("body", "Stale"),
228227 ],
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),
236228 )
237229 .await;
238230 assert_eq!(status, 303, "stale head");
@@ -250,7 +242,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
250242 "stale head left a thread"
251243 );
252244
253- // A single comment on an added line creates a thread that carries its hunk.
254245 let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await;
255246 assert_eq!(status, 303, "single comment");
256247 assert_eq!(
@@ -269,10 +260,11 @@ async fn comment_rules_and_pending_review_on_one_pull() {
269260 assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment");
270261 assert!(!root.pending, "single comment");
271262
272- // A pending review comment is hidden from everyone but its author until submitted.
273263 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
274264 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"),
276268 "tahinli",
277269 &[
278270 ("file_index", "0"),
@@ -282,13 +274,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
282274 ("action", "review"),
283275 ("body", "Draft"),
284276 ],
285- );
286- let (status, _, _) = send(
287- &fx.router,
288- "POST",
289- &format!("/tahinli/demo/pulls/{number}/review_comments"),
290- Some("tahinli"),
291- Some(form),
292277 )
293278 .await;
294279 assert_eq!(status, 303, "pending start");
@@ -326,7 +311,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
326311 assert_eq!(threads.len(), 2, "submitted review is public");
327312 assert!(threads.iter().all(|t| !t.root.pending), "submitted review");
328313
329- // Anonymous writes redirect to login, and a missing CSRF token is forbidden.
330314 let uri = format!("/tahinli/demo/pulls/{number}/review_comments");
331315 let form = csrf_form(
332316 "tahinli",
@@ -347,8 +331,6 @@ async fn comment_rules_and_pending_review_on_one_pull() {
347331 assert_eq!(status, 403, "missing csrf");
348332 }
349333
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).
352334 #[tokio::test]
353335 async fn thread_reply_edit_resolve_and_delete() {
354336 let fx = Fixture::new(Visibility::Public).await;
@@ -359,14 +341,11 @@ async fn thread_reply_edit_resolve_and_delete() {
359341 let pr = pull(&fx, number).await;
360342 let root = root_at(&fx, number, 0).await;
361343
362- // A reader replies into the thread and is sent back to its root.
363- let form = csrf_form("bob", &[("body", "Reply")]);
364- let (status, location, _) = send(
365- &fx.router,
366- "POST",
344+ let (status, location, _) = post_form(
345+ &fx,
367346 &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"),
368- Some("bob"),
369- Some(form),
347+ "bob",
348+ &[("body", "Reply")],
370349 )
371350 .await;
372351 assert_eq!(status, 303, "reply");
@@ -379,18 +358,15 @@ async fn thread_reply_edit_resolve_and_delete() {
379358 assert_eq!(threads[0].replies.len(), 1, "reply");
380359 assert_eq!(threads[0].replies[0].author_name, "bob", "reply");
381360
382- // Only the author may open the edit form, post an edit, or resolve.
383361 let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit");
384362 let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await;
385363 assert_eq!(status, 200, "edit form");
386364 assert!(body.contains("Save comment"), "edit form");
387365 let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await;
388366 assert_eq!(status, 403, "edit form for a non-author");
389- let form = csrf_form("bob", &[("body", "Hijacked")]);
390- let (status, _, _) = send(&fx.router, "POST", &edit, Some("bob"), Some(form)).await;
367+ let (status, _, _) = post_form(&fx, &edit, "bob", &[("body", "Hijacked")]).await;
391368 assert_eq!(status, 403, "edit by a non-author");
392- let form = csrf_form("tahinli", &[("body", "Edited")]);
393- let (status, location, _) = send(&fx.router, "POST", &edit, Some("tahinli"), Some(form)).await;
369+ let (status, location, _) = post_form(&fx, &edit, "tahinli", &[("body", "Edited")]).await;
394370 assert_eq!(status, 303, "edit");
395371 assert_eq!(
396372 location.as_deref(),
@@ -401,32 +377,25 @@ async fn thread_reply_edit_resolve_and_delete() {
401377 assert_eq!(threads[0].root.body, "Edited", "edit");
402378
403379 let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve");
404- let form = csrf_form("bob", &[("resolved", "1")]);
405- let (status, _, _) = send(&fx.router, "POST", &resolve, Some("bob"), Some(form)).await;
380+ let (status, _, _) = post_form(&fx, &resolve, "bob", &[("resolved", "1")]).await;
406381 assert_eq!(status, 403, "resolve by a reader");
407- let form = csrf_form("tahinli", &[("resolved", "1")]);
408- let (status, _, _) = send(&fx.router, "POST", &resolve, Some("tahinli"), Some(form)).await;
382+ let (status, _, _) = post_form(&fx, &resolve, "tahinli", &[("resolved", "1")]).await;
409383 assert_eq!(status, 303, "resolve");
410384 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
411385 assert!(threads[0].root.resolved, "resolve");
412386
413- // Delete removes only the second thread, and only for its author.
414387 comment_on(&fx, number, "tahinli", "2", "Doomed").await;
415388 let doomed = root_at(&fx, number, 1).await;
416389 let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete");
417- let form = csrf_form("bob", &[]);
418- let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
390+ let (status, _, _) = post_form(&fx, &uri, "bob", &[]).await;
419391 assert_eq!(status, 403, "delete by a non-author");
420- let form = csrf_form("tahinli", &[]);
421- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
392+ let (status, _, _) = post_form(&fx, &uri, "tahinli", &[]).await;
422393 assert_eq!(status, 303, "delete");
423394 let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
424395 assert_eq!(threads.len(), 1, "delete");
425396 assert_eq!(threads[0].root.id, root, "delete kept the other thread");
426397 }
427398
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.
430399 #[tokio::test]
431400 async fn reviews_approve_then_close_the_pull() {
432401 let fx = Fixture::new(Visibility::Public).await;
@@ -436,18 +405,14 @@ async fn reviews_approve_then_close_the_pull() {
436405 let pr = pull(&fx, number).await;
437406 let uri = format!("/tahinli/demo/pulls/{number}/reviews");
438407
439- // A reader's approval is recorded.
440- let form = csrf_form("bob", &[("state", "approve")]);
441- let (status, location, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
408+ let (status, location, _) = post_form(&fx, &uri, "bob", &[("state", "approve")]).await;
442409 assert_eq!(status, 303, "reader approval");
443410 assert!(location.unwrap().contains("#review-"), "reader approval");
444411 let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap();
445412 assert_eq!(reviews.len(), 1, "reader approval");
446413 assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval");
447414
448- // The author's approval is refused.
449- let form = csrf_form("tahinli", &[("state", "approve")]);
450- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
415+ let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await;
451416 assert_eq!(status, 303, "author approval");
452417 assert_eq!(
453418 location.as_deref(),
@@ -460,7 +425,6 @@ async fn reviews_approve_then_close_the_pull() {
460425 "author approval"
461426 );
462427
463- // Once closed, comments still land but reviews are refused.
464428 let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
465429 fx.store
466430 .set_issue_state(
@@ -478,8 +442,7 @@ async fn reviews_approve_then_close_the_pull() {
478442 location.unwrap().contains("#L-0-new-2"),
479443 "comment on a closed pull"
480444 );
481- let form = csrf_form("tahinli", &[("state", "approve")]);
482- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
445+ let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("state", "approve")]).await;
483446 assert_eq!(status, 303, "review on a closed pull");
484447 assert!(
485448 location.unwrap().ends_with("?review_error=closed"),
@@ -494,39 +457,33 @@ async fn dismiss_needs_write_and_a_reason() {
494457 sign_in(&fx, "bob", "bob").await;
495458 let number = open_pull(&fx).await;
496459 let pr = pull(&fx, number).await;
497- let form = csrf_form("bob", &[("state", "request_changes")]);
498- send(
499- &fx.router,
500- "POST",
460+ let (status, _, _) = post_form(
461+ &fx,
501462 &format!("/tahinli/demo/pulls/{number}/reviews"),
502- Some("bob"),
503- Some(form),
463+ "bob",
464+ &[("state", "request_changes")],
504465 )
505466 .await;
467+ assert_eq!(status, 303, "setup review");
506468 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
507469 let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id);
508470
509- let form = csrf_form("bob", &[("reason", "mine")]);
510- let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
471+ let (status, _, _) = post_form(&fx, &uri, "bob", &[("reason", "mine")]).await;
511472 assert_eq!(status, 403, "dismiss by a reader");
512473
513- let form = csrf_form("tahinli", &[("reason", " ")]);
514- let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
474+ let (status, location, _) = post_form(&fx, &uri, "tahinli", &[("reason", " ")]).await;
515475 assert_eq!(status, 303, "blank reason");
516476 assert!(
517477 location.unwrap().ends_with("?review_error=empty"),
518478 "blank reason"
519479 );
520480
521- let form = csrf_form("tahinli", &[("reason", "Addressed")]);
522- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
481+ let (status, _, _) = post_form(&fx, &uri, "tahinli", &[("reason", "Addressed")]).await;
523482 assert_eq!(status, 303, "dismiss");
524483 let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
525484 assert_eq!(review.state, ReviewState::Dismissed, "dismiss");
526485 }
527486
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.
530487 #[tokio::test]
531488 async fn suggestions_reader_outdated_and_apply() {
532489 let fx = Fixture::new(Visibility::Public).await;
@@ -537,7 +494,6 @@ async fn suggestions_reader_outdated_and_apply() {
537494 assert_eq!(status, 303, "first suggestion");
538495 let first = root_at(&fx, number, 0).await;
539496
540- // A reader without push access sees the diff but no apply button, and is refused.
541497 let page = get(&fx, number, "rita").await;
542498 assert!(page.contains("Suggested change"), "the diff still shows");
543499 assert!(
@@ -551,7 +507,6 @@ async fn suggestions_reader_outdated_and_apply() {
551507 "reader apply"
552508 );
553509
554- // The head moves on: the first suggestion is outdated, shown without apply, and refused.
555510 let pr = pull(&fx, number).await;
556511 std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();
557512 git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);
@@ -596,7 +551,6 @@ async fn suggestions_reader_outdated_and_apply() {
596551 "a refused apply leaves the thread open"
597552 );
598553
599- // A fresh suggestion against the moved head applies as a commit by the commenter.
600554 let before = pull(&fx, number).await.head_oid;
601555 assert_eq!(before, moved, "the head is the moved commit");
602556 let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
@@ -639,7 +593,6 @@ async fn suggestions_reader_outdated_and_apply() {
639593 assert!(threads[1].root.resolved, "applying resolves the thread");
640594 }
641595
642-/// The Files tab of the pull request as `token` sees it.
643596 async fn get(fx: &Fixture, number: i64, token: &str) -> String {
644597 let uri = format!("/tahinli/demo/pulls/{number}/files");
645598 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]) {
3131 assert!(status.success(), "git {args:?} failed");
3232 }
3333
34-/// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).
3534 async fn fixture(dir: &Path) -> (Router, AppState) {
3635 let state = crate::test_support::test_state(dir).await;
3736 let router = crate::test_support::app_router(state.clone());
@@ -87,15 +86,11 @@ async fn fixture(dir: &Path) -> (Router, AppState) {
8786 (router, state)
8887 }
8988
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-
9389 #[tokio::test]
9490 async fn demo_pages_render_from_the_repo_contents() {
9591 let dir = tempfile::tempdir().unwrap();
9692 let (router, _) = fixture(dir.path()).await;
9793
98- // Home renders the README, the tree, the clone popover and the archive links.
9994 let (status, body) = get_as(&router, "/tahinli/demo", None).await;
10095 assert_eq!(status, 200);
10196 assert!(body.contains("Hello from the README"), "README rendered");
@@ -117,7 +112,6 @@ async fn demo_pages_render_from_the_repo_contents() {
117112 assert!(body.contains("/tahinli/demo/branches"));
118113 assert!(body.contains("data-ref-filter"), "branch switcher rendered");
119114
120- // Trees list their entries and link to subtrees and blobs.
121115 let (status, body) = get_as(&router, "/tahinli/demo/tree/main/src", None).await;
122116 assert_eq!(status, 200);
123117 assert!(body.contains("main.rs"));
@@ -126,7 +120,6 @@ async fn demo_pages_render_from_the_repo_contents() {
126120 assert_eq!(status, 200);
127121 assert!(body.contains("/tahinli/demo/tree/main/docs"));
128122
129- // Rust source is highlighted with line anchors.
130123 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/src/main.rs", None).await;
131124 assert_eq!(status, 200);
132125 assert!(body.contains("id=\"L1\""));
@@ -134,7 +127,6 @@ async fn demo_pages_render_from_the_repo_contents() {
134127 assert!(body.contains("<span class="), "syntax classes applied");
135128 assert!(body.contains("/assets/highlight.css?v="));
136129
137- // Markdown renders unless the viewer asks for the plain source.
138130 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/docs/guide.md", None).await;
139131 assert_eq!(status, 200);
140132 assert!(
@@ -146,12 +138,10 @@ async fn demo_pages_render_from_the_repo_contents() {
146138 assert!(body.contains("file-table"), "source shown as lines");
147139 assert!(!body.contains("markdown-body"), "not rendered");
148140
149- // Binary blobs show their size instead of content.
150141 let (status, body) = get_as(&router, "/tahinli/demo/blob/main/data.bin", None).await;
151142 assert_eq!(status, 200);
152143 assert!(body.contains("Binary file, 3 bytes"));
153144
154- // Fixed segment routes win over the repo catch-all.
155145 let (status, body) = get_as(&router, "/tahinli/demo/branches", None).await;
156146 assert_eq!(status, 200);
157147 assert!(body.contains("default"), "default branch marked");
@@ -196,7 +186,6 @@ const ZERO_OID: &str = "0000000000000000000000000000000000000000";
196186 const OID: &str = "1111111111111111111111111111111111111111";
197187 const BANNER: &str = "had recent pushes";
198188
199-/// Creates a session for `user_id` and returns the cookie header value.
200189 async fn sign_in(state: &AppState, user_id: &str, token: &str) -> String {
201190 crate::test_support::create_session(&state.store, user_id, token, "csrf").await;
202191 format!("__Host-{SESSION_COOKIE}={token}")
@@ -213,13 +202,11 @@ async fn get_as(router: &Router, uri: &str, cookie: Option<&str>) -> (u16, Strin
213202 (status, String::from_utf8_lossy(&bytes).into_owned())
214203 }
215204
216-/// Points `branch` at the bare repo's `main`, so the branch exists.
217205 fn make_branch(bare: &Path, branch: &str) {
218206 let full = format!("refs/heads/{branch}");
219207 git(bare, &["update-ref", &full, "refs/heads/main"]);
220208 }
221209
222-/// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.
223210 async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) {
224211 let at = stamp_ago(age);
225212 let full = format!("refs/heads/{branch}");
@@ -439,12 +426,10 @@ async fn fork_push_links_to_parent_compare() {
439426 .await;
440427 let cookie = sign_in(&state, &bob.id, "bob-token").await;
441428
442- // On the parent, the viewer's fork branch compares as owner:branch.
443429 let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
444430 assert_eq!(status, 200);
445431 assert!(body.contains("compare/main...bob%3Afeature"), "{body}");
446432
447- // On the fork itself, the link goes to the parent's compare page.
448433 let (status, body) = get_as(&router, "/bob/demo", Some(&cookie)).await;
449434 assert_eq!(status, 200);
450435 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-
51 use topcoat::internal::inventory;
62 use topcoat::router::{Layer, Layout, Page, Route};
73
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-
31 use topcoat::router::request::Request;
42 use topcoat::router::{Body, to_bytes};
53
64 use crate::views::NAV_SCRIPT_HREF;
75
8-/// Every `<script` tag carries a `src`: an inline script could not run under the CSP.
96 fn assert_no_inline_scripts(html: &str) {
107 for (at, _) in html.match_indices("<script") {
118 let tag = &html[at..];
@@ -54,7 +51,6 @@ async fn shell_loads_the_deferred_nav_script_without_inline_scripts() {
5451 assert!(html.contains("<main tabindex=\"-1\" data-width=\"col\">"));
5552 assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\""));
5653
57- // An anonymous page renders the default colours.
5854 let tag = html_tag(&html);
5955 assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
6056 assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
@@ -62,15 +58,12 @@ async fn shell_loads_the_deferred_nav_script_without_inline_scripts() {
6258 assert!(tag.contains("data-base-dark=\"ink\""), "{tag}");
6359 }
6460
65-/// The `<html …>` start tag of a page.
6661 fn html_tag(page: &str) -> &str {
6762 let at = page.find("<html").expect("the page has an html tag");
6863 let len = page[at..].find('>').expect("the html tag closes");
6964 &page[at..at + len + 1]
7065 }
7166
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.
7467 async fn html_tag_for_colours(
7568 router: &topcoat::router::Router,
7669 store: &forge_core::Store,
@@ -101,7 +94,6 @@ async fn html_tag_for_colours(
10194 html_tag(&String::from_utf8_lossy(&bytes)).to_owned()
10295 }
10396
104-/// Every colour case shares one fixture; each has its own user and session.
10597 #[tokio::test]
10698 async fn the_html_tag_carries_the_viewers_colours() {
10799 let dir = tempfile::tempdir().expect("tempdir");
@@ -122,7 +114,6 @@ async fn the_html_tag_carries_the_viewers_colours() {
122114 assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
123115 assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}");
124116 assert!(!tag.contains("data-accent="), "{tag}");
125- // Stored ids that are no longer offered fall back to the defaults, never to nothing.
126117 let removed = html_tag_for_colours(
127118 &router,
128119 &store,
@@ -135,7 +126,6 @@ async fn the_html_tag_carries_the_viewers_colours() {
135126 assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");
136127 assert!(removed.contains("data-base-light=\"ink\""), "{removed}");
137128 assert!(removed.contains("data-base-dark=\"ink\""), "{removed}");
138- // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself.
139129 let retired = html_tag_for_colours(
140130 &router,
141131 &store,
@@ -162,7 +152,6 @@ async fn the_html_tag_carries_the_viewers_colours() {
162152 assert!(hued.contains("data-base-dark=\"ink\""), "{hued}");
163153 }
164154
165-/// Renders `/settings/security` (a page that uses the shell) for a freshly signed-in user.
166155 async fn menu_html(
167156 router: &topcoat::router::Router,
168157 store: &forge_core::Store,
@@ -191,8 +180,6 @@ async fn menu_html(
191180 String::from_utf8_lossy(&bytes).into_owned()
192181 }
193182
194-/// A user sees no admin links and an admin sees the one Admin entry. Both render from one
195-/// fixture.
196183 #[tokio::test]
197184 async fn admin_links_follow_the_role() {
198185 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
66 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";
77 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";
88
9-/// A repo whose default branch gets `files` committed on top of the fixture's history.
10-/// Tahinli is signed in.
119 async fn setup(files: &[(&str, &str)]) -> Fixture {
1210 let fx = Fixture::new(Visibility::Public).await;
1311 for (path, text) in files {
@@ -35,7 +33,6 @@ fn new_issue_uri(query: &str) -> String {
3533 format!("/{OWNER}/{REPO}/issues/new{query}")
3634 }
3735
38-/// The text of the tag that starts at `needle`, up to its closing `>`.
3936 fn tag_at(html: &str, needle: &str) -> String {
4037 let at = html.find(needle).expect("needle in page");
4138 let end = html[at..].find('>').expect("tag end") + at;