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 commit76d78e3e084fd68b2d5d5d3d0fea2758f74e0ec0Parent: 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
100 changed files +2486 -4255
- crates/forge-core/src/store/admin_alerts.rs +11 -0
- crates/forge-core/src/store/imports.rs +16 -0
- crates/forge-core/src/store/mod.rs +57 -0
- crates/forge-core/src/store/webhooks.rs +11 -5
- crates/forge-web-account/Cargo.toml +0 -3
- crates/forge-web-account/src/pages/activity.rs +2 -2
- crates/forge-web-account/src/pages/admin_backups.rs +2 -25
- crates/forge-web-account/src/pages/admin_health.rs +53 -52
- crates/forge-web-account/src/pages/admin_mail.rs +2 -60
- crates/forge-web-account/src/pages/admin_replication.rs +30 -57
- crates/forge-web-account/src/pages/admin_server.rs +4 -110
- crates/forge-web-account/src/pages/admin_user_detail.rs +19 -17
- crates/forge-web-account/src/pages/assets.rs +51 -123
- crates/forge-web-account/src/pages/audit_log.rs +15 -37
- crates/forge-web-account/src/pages/explore.rs +22 -14
- crates/forge-web-account/src/pages/forgot.rs +4 -6
- crates/forge-web-account/src/pages/import.rs +26 -120
- crates/forge-web-account/src/pages/login.rs +41 -56
- crates/forge-web-account/src/pages/new_repo.rs +2 -44
- crates/forge-web-account/src/pages/not_found_page.rs +17 -31
- crates/forge-web-account/src/pages/org_ctx.rs +9 -23
- crates/forge-web-account/src/pages/org_live.rs +2 -2
- crates/forge-web-account/src/pages/org_members.rs +6 -6
- crates/forge-web-account/src/pages/org_new.rs +2 -3
- crates/forge-web-account/src/pages/org_settings.rs +2 -4
- crates/forge-web-account/src/pages/org_teams.rs +0 -12
- crates/forge-web-account/src/pages/profile.rs +87 -181
- crates/forge-web-account/src/pages/profile_calendar.rs +11 -16
- crates/forge-web-account/src/pages/register.rs +13 -11
- crates/forge-web-account/src/pages/releases_tests.rs +730 -884
- crates/forge-web-account/src/pages/settings_appearance.rs +72 -192
- crates/forge-web-account/src/pages/settings_export.rs +9 -11
- crates/forge-web-account/src/pages/settings_gpg.rs +4 -13
- crates/forge-web-account/src/pages/settings_keys.rs +11 -6
- crates/forge-web-account/src/pages/settings_live.rs +18 -89
- crates/forge-web-account/src/pages/settings_profile.rs +9 -16
- crates/forge-web-account/src/pages/settings_security.rs +65 -96
- crates/forge-web-account/src/pages/settings_tokens.rs +4 -13
- crates/forge-web-account/src/pages/setup.rs +9 -7
- crates/forge-web-account/src/pages/shell_events.rs +27 -3
- crates/forge-web-account/src/pages/snippets.rs +48 -130
- crates/forge-web-app/src/api/releases.rs +1 -1
- crates/forge-web-app/src/live.rs +10 -0
- crates/forge-web-app/src/package_ops.rs +6 -0
- crates/forge-web-app/src/views/mod.rs +11 -0
- crates/forge-web-base/src/i18n/merge_queue.rs +8 -0
- crates/forge-web-pages/src/pages/admin_runners.rs +32 -87
- crates/forge-web-pages/src/pages/admin_users.rs +29 -31
- crates/forge-web-pages/src/pages/ci_job.rs +22 -23
- crates/forge-web-pages/src/pages/ci_runs.rs +12 -52
- crates/forge-web-pages/src/pages/issue_meta.rs +41 -32
- crates/forge-web-pages/src/pages/issue_parts.rs +8 -4
- crates/forge-web-pages/src/pages/issues_list.rs +23 -18
- crates/forge-web-pages/src/pages/notifications.rs +86 -101
- crates/forge-web-pages/src/pages/packages.rs +29 -45
- crates/forge-web-pages/src/pages/packages_oci.rs +5 -19
- crates/forge-web-pages/src/pages/pull_reviews.rs +3 -20
- crates/forge-web-pages/src/pages/releases.rs +68 -57
- crates/forge-web-pages/src/pages/releases_live.rs +12 -15
- crates/forge-web-pages/src/pages/repo.rs +1 -1
- crates/forge-web-pages/src/pages/repo_ctx.rs +29 -49
- crates/forge-web-pages/src/pages/repo_mirrors.rs +44 -37
- crates/forge-web-pages/src/pages/repo_settings.rs +24 -140
- crates/forge-web-pages/src/pages/tree.rs +3 -6
- crates/forge-web-pages/src/pages/wiki.rs +7 -14
- crates/forge-web-repo/src/pages/authoring.rs +7 -43
- crates/forge-web-repo/src/pages/blame.rs +4 -21
- crates/forge-web-repo/src/pages/blob.rs +49 -81
- crates/forge-web-repo/src/pages/browse_tests.rs +20 -43
- crates/forge-web-repo/src/pages/ci_badge.rs +5 -5
- crates/forge-web-repo/src/pages/ci_tests.rs +9 -78
- crates/forge-web-repo/src/pages/commit.rs +24 -24
- crates/forge-web-repo/src/pages/commits.rs +2 -47
- crates/forge-web-repo/src/pages/compare.rs +8 -30
- crates/forge-web-repo/src/pages/discussion_live.rs +0 -2
- crates/forge-web-repo/src/pages/fork.rs +31 -4
- crates/forge-web-repo/src/pages/labels_css.rs +2 -6
- crates/forge-web-repo/src/pages/labels_page.rs +14 -61
- crates/forge-web-repo/src/pages/merge_queue.rs +28 -66
- crates/forge-web-repo/src/pages/pull_branch.rs +33 -21
- crates/forge-web-repo/src/pages/pull_files.rs +12 -108
- crates/forge-web-repo/src/pages/pull_flow.rs +5 -9
- crates/forge-web-repo/src/pages/pull_view.rs +29 -38
- crates/forge-web-repo/src/pages/pulls_list.rs +3 -2
- crates/forge-web-repo/src/pages/reactions.rs +1 -5
- crates/forge-web-repo/src/pages/repo_collaborators.rs +6 -15
- crates/forge-web-repo/src/pages/repo_secrets.rs +8 -27
- crates/forge-web-repo/src/pages/repo_webhooks.rs +25 -58
- crates/forge-web-repo/src/pages/review_requests.rs +33 -29
- crates/forge-web/src/admin_cli.rs +3 -7
- crates/forge-web/src/boot.rs +7 -0
- crates/forge-web/src/importer_route_tests.rs +22 -13
- crates/forge-web/src/main.rs +11 -25
- crates/forge-web/src/page_route_tests/edit_history.rs +0 -10
- crates/forge-web/src/page_route_tests/notifications.rs +0 -15
- crates/forge-web/src/page_route_tests/pull_reviews.rs +48 -95
- crates/forge-web/src/page_route_tests/repo.rs +0 -15
- crates/forge-web/src/route_list_tests.rs +0 -4
- crates/forge-web/src/shell_route_tests.rs +0 -13
- crates/forge-web/src/templates_route_tests.rs +0 -3
crates/forge-core/src/store/admin_alerts.rsmodified+11 -0
| @@ -253,6 +253,17 @@ impl Store { | ||
| 253 | 253 | fetch_all(&conn, &sql, params, map_notice).await |
| 254 | 254 | } |
| 255 | 255 | |
| 256 | + pub async fn admin_notice(&self, user_id: &str, id: &str) -> Result<Option<AdminNotice>> { | |
| 257 | + let conn = self.read_conn().await; | |
| 258 | + fetch_opt( | |
| 259 | + &conn, | |
| 260 | + &format!("SELECT {NOTICE_COLS} FROM admin_notifications WHERE id = ?1 AND user_id = ?2"), | |
| 261 | + (id.to_owned(), user_id.to_owned()), | |
| 262 | + map_notice, | |
| 263 | + ) | |
| 264 | + .await | |
| 265 | + } | |
| 266 | + | |
| 256 | 267 | /// Marks one of the user's alert rows read. Another user's row changes nothing. |
| 257 | 268 | pub async fn mark_admin_notice_read(&self, user_id: &str, id: &str) -> Result<()> { |
| 258 | 269 | let conn = self.inner.conn.lock().await; |
crates/forge-core/src/store/imports.rsmodified+16 -0
| @@ -204,6 +204,22 @@ impl Store { | ||
| 204 | 204 | Ok(()) |
| 205 | 205 | } |
| 206 | 206 | |
| 207 | + pub async fn requeue_failed_import(&self, id: &str) -> Result<bool> { | |
| 208 | + let conn = self.inner.conn.lock().await; | |
| 209 | + let changed = conn | |
| 210 | + .execute( | |
| 211 | + "UPDATE import_jobs SET state = 'queued', error = NULL, finished_at = NULL, \ | |
| 212 | + updated_at = ?2 WHERE id = ?1 AND state = 'failed' AND NOT EXISTS (\ | |
| 213 | + SELECT 1 FROM import_jobs other WHERE other.repo_id = \ | |
| 214 | + (SELECT repo_id FROM import_jobs WHERE id = ?1) \ | |
| 215 | + AND other.state IN ('queued', 'running'))", | |
| 216 | + vec![text(id), text(&now_stamp())], | |
| 217 | + ) | |
| 218 | + .await | |
| 219 | + .map_err(db_err)?; | |
| 220 | + Ok(changed > 0) | |
| 221 | + } | |
| 222 | + | |
| 207 | 223 | /// Records the current stage and how far it is. |
| 208 | 224 | pub async fn set_import_progress( |
| 209 | 225 | &self, |
crates/forge-core/src/store/mod.rsmodified+57 -0
| @@ -837,6 +837,39 @@ impl Store { | ||
| 837 | 837 | affected(n) |
| 838 | 838 | } |
| 839 | 839 | |
| 840 | + pub async fn save_profile( | |
| 841 | + &self, | |
| 842 | + user_id: &str, | |
| 843 | + display_name: &str, | |
| 844 | + about: &str, | |
| 845 | + timezone: &str, | |
| 846 | + ) -> Result<()> { | |
| 847 | + let display_name = match validate_display_name(display_name)? { | |
| 848 | + Some(name) => Value::Text(name), | |
| 849 | + None => Value::Null, | |
| 850 | + }; | |
| 851 | + if about.chars().count() > MAX_ABOUT_CHARS { | |
| 852 | + return Err(Error::Invalid(format!( | |
| 853 | + "about is longer than {MAX_ABOUT_CHARS} characters" | |
| 854 | + ))); | |
| 855 | + } | |
| 856 | + crate::tz::validate_timezone(timezone)?; | |
| 857 | + let conn = self.inner.conn.lock().await; | |
| 858 | + let n = conn | |
| 859 | + .execute( | |
| 860 | + "UPDATE users SET display_name = ?2, about = ?3, timezone = ?4 WHERE id = ?1", | |
| 861 | + vec![ | |
| 862 | + Value::Text(user_id.to_owned()), | |
| 863 | + display_name, | |
| 864 | + Value::Text(about.to_owned()), | |
| 865 | + Value::Text(timezone.to_owned()), | |
| 866 | + ], | |
| 867 | + ) | |
| 868 | + .await | |
| 869 | + .map_err(db_err)?; | |
| 870 | + affected(n) | |
| 871 | + } | |
| 872 | + | |
| 840 | 873 | /// Inserts or replaces the user's avatar. `png` is the re-encoded image, `hash` its digest. |
| 841 | 874 | pub async fn set_avatar(&self, user_id: &str, png: &[u8], hash: &str) -> Result<()> { |
| 842 | 875 | let conn = self.inner.conn.lock().await; |
| @@ -1583,6 +1616,30 @@ impl Store { | ||
| 1583 | 1616 | affected(n) |
| 1584 | 1617 | } |
| 1585 | 1618 | |
| 1619 | + pub async fn reset_password(&self, user_id: &str, password_hash: &str) -> Result<()> { | |
| 1620 | + let conn = self.inner.conn.lock().await; | |
| 1621 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 1622 | + let outcome: Result<()> = async { | |
| 1623 | + let n = tx | |
| 1624 | + .execute( | |
| 1625 | + "UPDATE users SET password_hash = ?2, password_changed_at = ?3 WHERE id = ?1", | |
| 1626 | + (user_id.to_string(), password_hash.to_string(), now_stamp()), | |
| 1627 | + ) | |
| 1628 | + .await | |
| 1629 | + .map_err(db_err)?; | |
| 1630 | + affected(n)?; | |
| 1631 | + tx.execute( | |
| 1632 | + "DELETE FROM sessions WHERE user_id = ?1", | |
| 1633 | + (user_id.to_string(),), | |
| 1634 | + ) | |
| 1635 | + .await | |
| 1636 | + .map_err(db_err)?; | |
| 1637 | + Ok(()) | |
| 1638 | + } | |
| 1639 | + .await; | |
| 1640 | + finish(tx, outcome).await | |
| 1641 | + } | |
| 1642 | + | |
| 1586 | 1643 | /// Deletes every session of the user except `keep_session_id`. Returns how many were removed. |
| 1587 | 1644 | pub async fn delete_sessions_except( |
| 1588 | 1645 | &self, |
crates/forge-core/src/store/webhooks.rsmodified+11 -5
| @@ -308,25 +308,28 @@ impl Store { | ||
| 308 | 308 | .await |
| 309 | 309 | } |
| 310 | 310 | |
| 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 | |
| 312 | 312 | /// (`None` when it has none yet). |
| 313 | 313 | pub async fn list_webhooks( |
| 314 | 314 | &self, |
| 315 | 315 | repo_id: &str, |
| 316 | - ) -> Result<Vec<(Webhook, Option<DeliveryState>)>> { | |
| 316 | + ) -> Result<Vec<(Webhook, Option<(DeliveryState, String)>)>> { | |
| 317 | 317 | let sql = format!( |
| 318 | 318 | "SELECT {WEBHOOK_COLS}, \ |
| 319 | 319 | (SELECT d.state FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \ |
| 320 | + ORDER BY d.created_at DESC, d.id DESC LIMIT 1), \ | |
| 321 | + (SELECT d.created_at FROM webhook_deliveries d WHERE d.hook_id = webhooks.id \ | |
| 320 | 322 | ORDER BY d.created_at DESC, d.id DESC LIMIT 1) \ |
| 321 | 323 | FROM webhooks WHERE repo_id = ?1 ORDER BY created_at, id" |
| 322 | 324 | ); |
| 323 | 325 | let conn = self.read_conn().await; |
| 324 | 326 | fetch_all(&conn, &sql, (repo_id.to_string(),), |row| { |
| 325 | 327 | let last = match col_opt_text(row, 7)? { |
| 326 | - Some(s) => Some( | |
| 328 | + Some(s) => Some(( | |
| 327 | 329 | DeliveryState::parse(&s) |
| 328 | 330 | .ok_or_else(|| Error::Database(format!("unknown delivery state {s:?}")))?, |
| 329 | - ), | |
| 331 | + col_text(row, 8)?, | |
| 332 | + )), | |
| 330 | 333 | None => None, |
| 331 | 334 | }; |
| 332 | 335 | Ok((map_webhook(row)?, last)) |
| @@ -922,7 +925,10 @@ mod tests { | ||
| 922 | 925 | assert_eq!(failed.duration_ms, Some(12)); |
| 923 | 926 | assert!(failed.delivered_at.is_none()); |
| 924 | 927 | assert_eq!( |
| 925 | - store.list_webhooks(&repo.id).await.unwrap()[0].1, | |
| 928 | + store.list_webhooks(&repo.id).await.unwrap()[0] | |
| 929 | + .1 | |
| 930 | + .as_ref() | |
| 931 | + .map(|(state, _)| *state), | |
| 926 | 932 | Some(DeliveryState::Failed) |
| 927 | 933 | ); |
| 928 | 934 |
crates/forge-web-account/Cargo.tomlmodified+0 -3
| @@ -12,7 +12,6 @@ forge-web-pages.workspace = true | ||
| 12 | 12 | forge-core.workspace = true |
| 13 | 13 | forge-git.workspace = true |
| 14 | 14 | forge-ci.workspace = true |
| 15 | -forge-web-base.workspace = true | |
| 16 | 15 | topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] } |
| 17 | 16 | tokio.workspace = true |
| 18 | 17 | futures-util.workspace = true |
| @@ -31,8 +30,6 @@ hex.workspace = true | ||
| 31 | 30 | sha2.workspace = true |
| 32 | 31 | time.workspace = true |
| 33 | 32 | ulid.workspace = true |
| 34 | -zip = { workspace = true } | |
| 35 | -tar.workspace = true | |
| 36 | 33 | |
| 37 | 34 | |
| 38 | 35 | webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] } |
crates/forge-web-account/src/pages/activity.rsmodified+2 -2
| @@ -41,7 +41,7 @@ fn run_json(run: &ActorRun) -> Value { | ||
| 41 | 41 | } |
| 42 | 42 | |
| 43 | 43 | /// How a finished run ended, as the activity JSON names it. None for any other state. |
| 44 | -pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> { | |
| 44 | +fn outcome_word(state: RunState) -> Option<&'static str> { | |
| 45 | 45 | match state { |
| 46 | 46 | RunState::Success => Some("passed"), |
| 47 | 47 | RunState::Failure | RunState::Error => Some("failed"), |
| @@ -53,7 +53,7 @@ pub(crate) fn outcome_word(state: RunState) -> Option<&'static str> { | ||
| 53 | 53 | /// The viewer's activity as JSON. `reviews` and `mentions` count unread inbox rows, `failing` counts |
| 54 | 54 | /// refs whose newest run failed, `running` and `finished` list the viewer's CI runs and `waiting` |
| 55 | 55 | /// lists the newest review requests and mentions. Reads only; the caller decides how to send it. |
| 56 | -pub(crate) async fn activity_json(state: &AppState, user: &User) -> Result<Value> { | |
| 56 | +async fn activity_json(state: &AppState, user: &User) -> Result<Value> { | |
| 57 | 57 | let kinds = state.store.inbox_kind_counts(&user.id).await?; |
| 58 | 58 | let runs = state.store.actor_runs(&user.id, RECENT_SECS).await?; |
| 59 | 59 | let waiting = state.store.waiting_on(&user.id, WAITING_LIMIT).await?; |
crates/forge-web-account/src/pages/admin_backups.rsmodified+2 -25
| @@ -29,10 +29,9 @@ use crate::pages::admin_server::{ | ||
| 29 | 29 | BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice, |
| 30 | 30 | }; |
| 31 | 31 | use crate::pages::admin_users::admin_only; |
| 32 | -use crate::pages::issues_list::stamp_unix; | |
| 33 | 32 | use crate::state::AppState; |
| 34 | 33 | use crate::views::parts::{RailItem, head, post_act, rail}; |
| 35 | -use crate::views::{alert, enc, rel_time, shell}; | |
| 34 | +use crate::views::{alert, enc, human_size, rel_time, shell, stamp_unix}; | |
| 36 | 35 | |
| 37 | 36 | /// Runs shown on the page. |
| 38 | 37 | const RUN_LIMIT: u32 = 20; |
| @@ -59,21 +58,6 @@ struct RunRow { | ||
| 59 | 58 | detail: String, |
| 60 | 59 | } |
| 61 | 60 | |
| 62 | -/// `"512 B"`, `"12.3 KiB"`, `"4.0 MiB"` and so on. | |
| 63 | -fn human_bytes(bytes: u64) -> String { | |
| 64 | - const UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"]; | |
| 65 | - if bytes < 1024 { | |
| 66 | - return format!("{bytes} B"); | |
| 67 | - } | |
| 68 | - let mut value = bytes as f64 / 1024.0; | |
| 69 | - let mut unit = 0; | |
| 70 | - while value >= 1024.0 && unit + 1 < UNITS.len() { | |
| 71 | - value /= 1024.0; | |
| 72 | - unit += 1; | |
| 73 | - } | |
| 74 | - format!("{value:.1} {}", UNITS[unit]) | |
| 75 | -} | |
| 76 | - | |
| 77 | 61 | fn duration_text(run: &BackupRun) -> String { |
| 78 | 62 | let start = stamp_unix(&run.started_at); |
| 79 | 63 | let Some(end) = run.finished_at.as_deref().map(stamp_unix) else { |
| @@ -101,7 +85,7 @@ fn run_row(run: &BackupRun, lang: Lang) -> RunRow { | ||
| 101 | 85 | trigger: g::trigger_name(lang, run.trigger).to_owned(), |
| 102 | 86 | started: run.started_at.clone(), |
| 103 | 87 | duration: duration_text(run), |
| 104 | - size: run.bytes.map(human_bytes).unwrap_or_default(), | |
| 88 | + size: run.bytes.map(|b| human_size(lang, b)).unwrap_or_default(), | |
| 105 | 89 | status, |
| 106 | 90 | detail, |
| 107 | 91 | } |
| @@ -583,11 +567,4 @@ mod tests { | ||
| 583 | 567 | ); |
| 584 | 568 | assert_eq!(fx.state.jobs.running(), None); |
| 585 | 569 | } |
| 586 | - | |
| 587 | - #[test] | |
| 588 | - fn human_bytes_scales() { | |
| 589 | - assert_eq!(human_bytes(512), "512 B"); | |
| 590 | - assert_eq!(human_bytes(2048), "2.0 KiB"); | |
| 591 | - assert_eq!(human_bytes(3 * 1024 * 1024), "3.0 MiB"); | |
| 592 | - } | |
| 593 | 570 | } |
crates/forge-web-account/src/pages/admin_health.rsmodified+53 -52
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | //! Page: instance health for admins (`/admin/health`). A summary line, then one sheet with the alerts, |
| 2 | 2 | //! a storage topic with the data disk's usage bar, and a services topic. Every number is a cheap query |
| 3 | -//! or a short external probe (`df`), so there is no polling; reloading the page, or opening it again, | |
| 3 | +//! or a `statvfs` call, so there is no polling; reloading the page, or opening it again, | |
| 4 | 4 | //! reads fresh values. The tree size of the repos (`du`) walks every repo, so a background task caches |
| 5 | 5 | //! it (see [`spawn_repo_size`]) and the page only reads the cache. Non-admins get 404. |
| 6 | 6 | |
| @@ -80,10 +80,12 @@ struct Usage { | ||
| 80 | 80 | path: String, |
| 81 | 81 | /// Percent used, the bar's fill. |
| 82 | 82 | pct: u8, |
| 83 | - /// At least 90% used. | |
| 83 | + /// At least [`DISK_BAD_PCT`] used. | |
| 84 | 84 | bad: bool, |
| 85 | 85 | } |
| 86 | 86 | |
| 87 | +const DISK_BAD_PCT: u8 = 90; | |
| 88 | + | |
| 87 | 89 | /// One fact in the storage topic: one row. |
| 88 | 90 | struct Fact { |
| 89 | 91 | label: &'static str, |
| @@ -102,6 +104,18 @@ struct Service { | ||
| 102 | 104 | stamp: Option<String>, |
| 103 | 105 | } |
| 104 | 106 | |
| 107 | +impl Service { | |
| 108 | + fn new(label: &'static str, dot: Dot, value: String) -> Self { | |
| 109 | + Self { | |
| 110 | + label, | |
| 111 | + dot, | |
| 112 | + value, | |
| 113 | + detail: String::new(), | |
| 114 | + stamp: None, | |
| 115 | + } | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 105 | 119 | /// Everything the page shows, and how many items need attention. |
| 106 | 120 | struct Health { |
| 107 | 121 | usage: Option<Usage>, |
| @@ -127,15 +141,6 @@ fn space(lang: Lang, total: u64, avail: u64) -> (u8, String) { | ||
| 127 | 141 | (pct, text) |
| 128 | 142 | } |
| 129 | 143 | |
| 130 | -/// `(total, available)` bytes from `df -Pk <path>` output. | |
| 131 | -fn parse_df(output: &str) -> Option<(u64, u64)> { | |
| 132 | - let line = output.lines().nth(1)?; | |
| 133 | - let fields: Vec<&str> = line.split_whitespace().collect(); | |
| 134 | - let total: u64 = fields.get(1)?.parse().ok()?; | |
| 135 | - let avail: u64 = fields.get(3)?.parse().ok()?; | |
| 136 | - Some((total.saturating_mul(1024), avail.saturating_mul(1024))) | |
| 137 | -} | |
| 138 | - | |
| 139 | 144 | /// Kilobytes from `du -sk <path>` output, as bytes. |
| 140 | 145 | fn parse_du(output: &str) -> Option<u64> { |
| 141 | 146 | let kb: u64 = output.split_whitespace().next()?.parse().ok()?; |
| @@ -155,7 +160,11 @@ async fn probe(program: &str, args: &[&str], path: &Path, limit: Duration) -> Op | ||
| 155 | 160 | } |
| 156 | 161 | |
| 157 | 162 | async fn disk(path: &Path) -> Option<(u64, u64)> { |
| 158 | - parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) | |
| 163 | + let path = path.to_path_buf(); | |
| 164 | + tokio::task::spawn_blocking(move || crate::alerts::disk_space(&path)) | |
| 165 | + .await | |
| 166 | + .ok() | |
| 167 | + .flatten() | |
| 159 | 168 | } |
| 160 | 169 | |
| 161 | 170 | async fn tree_size(path: &Path, limit: Duration) -> Option<u64> { |
| @@ -255,7 +264,7 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> { | ||
| 255 | 264 | free_of_total, |
| 256 | 265 | path: data_dir.to_string_lossy().into_owned(), |
| 257 | 266 | pct, |
| 258 | - bad: pct >= 90, | |
| 267 | + bad: pct >= DISK_BAD_PCT, | |
| 259 | 268 | } |
| 260 | 269 | }); |
| 261 | 270 | |
| @@ -286,7 +295,11 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> { | ||
| 286 | 295 | label: at(lang, A::BackupDirectory), |
| 287 | 296 | value: text, |
| 288 | 297 | detail: backup, |
| 289 | - dot: if pct >= 90 { Dot::Bad } else { Dot::Neutral }, | |
| 298 | + dot: if pct >= DISK_BAD_PCT { | |
| 299 | + Dot::Bad | |
| 300 | + } else { | |
| 301 | + Dot::Neutral | |
| 302 | + }, | |
| 290 | 303 | } |
| 291 | 304 | } |
| 292 | 305 | None => Fact { |
| @@ -347,20 +360,16 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> { | ||
| 347 | 360 | stamp: Some(run.started_at.clone()), |
| 348 | 361 | } |
| 349 | 362 | } |
| 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 | + ), | |
| 364 | 373 | }); |
| 365 | 374 | |
| 366 | 375 | let replicating = !live.replication.target.trim().is_empty(); |
| @@ -390,22 +399,18 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> { | ||
| 390 | 399 | stamp: status.last_ok_at.clone(), |
| 391 | 400 | } |
| 392 | 401 | } |
| 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 | + ), | |
| 400 | 407 | } |
| 401 | 408 | } 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 | + ) | |
| 409 | 414 | }); |
| 410 | 415 | |
| 411 | 416 | let uptime = uptime_secs().map_or_else( |
| @@ -488,7 +493,6 @@ async fn health_view( | ||
| 488 | 493 | nav: (Vec<PageLink>, Option<String>, Option<String>), |
| 489 | 494 | ) -> Result<impl View> { |
| 490 | 495 | // The heading counts every active alert; the sheet lists the current page of them. |
| 491 | - let count = total; | |
| 492 | 496 | let (links, prev, next) = nav; |
| 493 | 497 | let Health { |
| 494 | 498 | usage, |
| @@ -498,7 +502,7 @@ async fn health_view( | ||
| 498 | 502 | attention, |
| 499 | 503 | } = health; |
| 500 | 504 | // An active alert needs attention as much as a failing service does. |
| 501 | - let attention = attention + count; | |
| 505 | + let attention = attention + total; | |
| 502 | 506 | // The verdict leads the head's line, with its dot, so the page says how things are first. |
| 503 | 507 | let summary = if attention > 0 { |
| 504 | 508 | SubPart { |
| @@ -517,9 +521,9 @@ async fn health_view( | ||
| 517 | 521 | Ok(view! { |
| 518 | 522 | head(title: at(lang, A::Health), sub: sub, live: Some("/admin/health/events")) |
| 519 | 523 | <div class="sheet health-sheet"> |
| 520 | - if count > 0 { | |
| 524 | + if total > 0 { | |
| 521 | 525 | <section class="sec" role="alert"> |
| 522 | - <h2>(alert_text::banner_heading(lang, count))</h2> | |
| 526 | + <h2>(alert_text::banner_heading(lang, total))</h2> | |
| 523 | 527 | for a in alerts.into_iter() { |
| 524 | 528 | <div class="line" data-kb-row=""> |
| 525 | 529 | <span class="name">(a.title.as_str())</span> |
| @@ -612,8 +616,8 @@ async fn health_page(cx: &Cx) -> Result<impl View> { | ||
| 612 | 616 | |
| 613 | 617 | /// What the health page shows that can change between renders, as one string: the alerts, the |
| 614 | 618 | /// 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. | |
| 617 | 621 | async fn health_fingerprint(state: &AppState) -> Result<String> { |
| 618 | 622 | let counts = state.store.health_counts().await?; |
| 619 | 623 | let mail = state |
| @@ -660,10 +664,7 @@ mod tests { | ||
| 660 | 664 | use super::*; |
| 661 | 665 | |
| 662 | 666 | #[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() { | |
| 667 | 668 | assert_eq!(parse_du("12\t/data/repos\n"), Some(12 * 1024), "du"); |
| 668 | 669 | assert_eq!(parse_du(""), None, "du empty"); |
| 669 | 670 | } |
crates/forge-web-account/src/pages/admin_mail.rsmodified+2 -60
| @@ -1,12 +1,3 @@ | ||
| 1 | -//! Page: outgoing mail (`/admin/mail`). Instance admins only; anyone else gets 404. | |
| 2 | -//! | |
| 3 | -//! Two tabs. Settings: the SMTP server, sender and password (the password is write-only: a blank | |
| 4 | -//! field keeps the stored one) and "Send test mail" to the admin's own address. Queue: every | |
| 5 | -//! message in the outbox with its state, kind, tries and last error, filtered by state. A failed | |
| 6 | -//! message can be retried or discarded there. Both tabs carry `data-live`, so each queue change or | |
| 7 | -//! saved setting re-renders the tab through `/admin/mail/events` with no reload and no polling. | |
| 8 | -//! Saving the settings and queuing a test are audited. | |
| 9 | - | |
| 10 | 1 | use std::collections::HashMap; |
| 11 | 2 | |
| 12 | 3 | use forge_core::mail::{ |
| @@ -15,13 +6,10 @@ use forge_core::mail::{ | ||
| 15 | 6 | use forge_core::server_settings::Group; |
| 16 | 7 | use forge_core::time::now_stamp; |
| 17 | 8 | use forge_core::{AuditAction, Error}; |
| 18 | -use futures_util::{Stream, stream}; | |
| 19 | 9 | use serde::Deserialize; |
| 20 | -use tokio::sync::watch; | |
| 21 | 10 | use topcoat::Result; |
| 22 | 11 | use topcoat::context::{Cx, context}; |
| 23 | 12 | use topcoat::router::content::Form; |
| 24 | -use topcoat::router::content::sse::Event; | |
| 25 | 13 | use topcoat::router::error::{forbidden, see_other}; |
| 26 | 14 | use topcoat::router::response::Response; |
| 27 | 15 | use topcoat::router::{page, query_params, route}; |
| @@ -31,7 +19,7 @@ use crate::audit::{self, Actor, Target}; | ||
| 31 | 19 | use crate::auth::check_csrf; |
| 32 | 20 | use crate::i18n::admin::{self as g, K}; |
| 33 | 21 | use crate::i18n::{self, Key, Lang}; |
| 34 | -use crate::live::{changed_event, events_response}; | |
| 22 | +use crate::live::{events_response, wake_stream}; | |
| 35 | 23 | use crate::mail::{enqueue, live, templates}; |
| 36 | 24 | use crate::pages::admin_server::{ |
| 37 | 25 | MAIL_KEYS, Row, refusal, save_topic, setting_lines, setting_rows, |
| @@ -41,7 +29,6 @@ use crate::state::AppState; | ||
| 41 | 29 | use crate::views::parts::{confirm_act, head, post_act}; |
| 42 | 30 | use crate::views::{enc, rel_time, shell}; |
| 43 | 31 | |
| 44 | -/// Rows shown in the queue at most. | |
| 45 | 32 | const LIST_LIMIT: u32 = 100; |
| 46 | 33 | |
| 47 | 34 | #[query_params(error = bad_request)] |
| @@ -51,14 +38,12 @@ pub(crate) struct NoticeQuery { | ||
| 51 | 38 | state: Option<String>, |
| 52 | 39 | } |
| 53 | 40 | |
| 54 | -/// The two tabs of the page. | |
| 55 | 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 56 | 42 | enum Tab { |
| 57 | 43 | Settings, |
| 58 | 44 | Queue, |
| 59 | 45 | } |
| 60 | 46 | |
| 61 | -/// One queue row, already formatted. There is no body field on purpose. | |
| 62 | 47 | struct QueueRow { |
| 63 | 48 | id: String, |
| 64 | 49 | to: String, |
| @@ -73,7 +58,6 @@ struct QueueRow { | ||
| 73 | 58 | failed: bool, |
| 74 | 59 | } |
| 75 | 60 | |
| 76 | -/// One state filter: the link, its label and how many rows it covers. | |
| 77 | 61 | struct FilterChip { |
| 78 | 62 | href: String, |
| 79 | 63 | label: &'static str, |
| @@ -81,14 +65,12 @@ struct FilterChip { | ||
| 81 | 65 | current: bool, |
| 82 | 66 | } |
| 83 | 67 | |
| 84 | -/// The queue tab: the filter chips, the rows and the state the filter is on, for the forms. | |
| 85 | 68 | struct QueueData { |
| 86 | 69 | chips: Vec<FilterChip>, |
| 87 | 70 | rows: Vec<QueueRow>, |
| 88 | 71 | filter_param: String, |
| 89 | 72 | } |
| 90 | 73 | |
| 91 | -/// Everything the page shows. The password is never in here. | |
| 92 | 74 | struct PageData { |
| 93 | 75 | host: String, |
| 94 | 76 | port: String, |
| @@ -98,13 +80,11 @@ struct PageData { | ||
| 98 | 80 | from_name: String, |
| 99 | 81 | enabled: bool, |
| 100 | 82 | has_password: bool, |
| 101 | - /// The delivery setting (`mail.transport`), a settings row saved with the settings form. | |
| 102 | 83 | transport: Vec<Row>, |
| 103 | 84 | tab: Tab, |
| 104 | 85 | queue: Option<QueueData>, |
| 105 | 86 | } |
| 106 | 87 | |
| 107 | -/// The CSS class of a state pill. The pills reuse the CI state colours. | |
| 108 | 88 | fn state_class(state: MailState) -> &'static str { |
| 109 | 89 | match state { |
| 110 | 90 | MailState::Sent => "ci-state ci-success", |
| @@ -133,7 +113,6 @@ fn row_view(entry: &OutboxEntry, now: &str, lang: Lang) -> QueueRow { | ||
| 133 | 113 | } |
| 134 | 114 | } |
| 135 | 115 | |
| 136 | -/// The queue tab's data. `filter` of `None` lists every state. | |
| 137 | 116 | async fn queue_data( |
| 138 | 117 | state: &AppState, |
| 139 | 118 | lang: Lang, |
| @@ -224,8 +203,6 @@ async fn mail_view( | ||
| 224 | 203 | <a href="/admin/mail?tab=queue" aria-current=((!settings_on).then_some("page"))>(g::t(lang, K::MailTabQueue))</a> |
| 225 | 204 | </nav> |
| 226 | 205 | if settings_on { |
| 227 | - // Saved by any admin session: the stream re-renders the settings with the same signal | |
| 228 | - // as the queue (the save bumps it too), and the form keeps what was typed. | |
| 229 | 206 | <div class="sheet" data-live="/admin/mail/events"> |
| 230 | 207 | <form method="post" action="/admin/mail" class="srv-form"> |
| 231 | 208 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| @@ -349,29 +326,17 @@ async fn mail_page(cx: &Cx) -> Result<impl View> { | ||
| 349 | 326 | }) |
| 350 | 327 | } |
| 351 | 328 | |
| 352 | -/// The live `changed` stream of the queue. One event per queue change. Nothing is sent on connect: | |
| 353 | -/// the page was just rendered. | |
| 354 | -fn queue_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static { | |
| 355 | - stream::unfold(wake, |mut wake| async move { | |
| 356 | - wake.changed().await.ok()?; | |
| 357 | - Some((changed_event("queue".to_owned()), wake)) | |
| 358 | - }) | |
| 359 | -} | |
| 360 | - | |
| 361 | -/// The queue's change stream. Admins only. | |
| 362 | 329 | #[route(GET "/admin/mail/events")] |
| 363 | 330 | async fn mail_events(cx: &Cx) -> Result<Response> { |
| 364 | 331 | admin_only(cx).await?; |
| 365 | - // Subscribed before the response is sent, so a change after this point is sent. | |
| 366 | 332 | let wake = live::subscribe(); |
| 367 | - events_response(cx, queue_changes(wake)) | |
| 333 | + events_response(cx, wake_stream(wake, "queue")) | |
| 368 | 334 | } |
| 369 | 335 | |
| 370 | 336 | #[derive(Deserialize, Default)] |
| 371 | 337 | struct SettingsForm { |
| 372 | 338 | #[serde(default)] |
| 373 | 339 | csrf: String, |
| 374 | - /// The delivery setting, saved as an override like the server settings. | |
| 375 | 340 | #[serde(default, rename = "mail.transport")] |
| 376 | 341 | transport: String, |
| 377 | 342 | #[serde(default)] |
| @@ -424,8 +389,6 @@ async fn mail_save(cx: &Cx, Form(form): Form<SettingsForm>) -> Result<Response> | ||
| 424 | 389 | Err(see_other(&location).into()) |
| 425 | 390 | } |
| 426 | 391 | |
| 427 | -/// Validates and stores the settings, wakes the worker, and audits the change. The password is | |
| 428 | -/// not part of the audit entry. | |
| 429 | 392 | async fn save_settings( |
| 430 | 393 | cx: &Cx, |
| 431 | 394 | state: &AppState, |
| @@ -499,8 +462,6 @@ async fn mail_test(cx: &Cx, Form(form): Form<TestForm>) -> Result<Response> { | ||
| 499 | 462 | Err(see_other(&location).into()) |
| 500 | 463 | } |
| 501 | 464 | |
| 502 | -/// Queues a test message to the admin's own address. Refused while mail is off or when the admin | |
| 503 | -/// has no address on the account. | |
| 504 | 465 | async fn queue_test( |
| 505 | 466 | cx: &Cx, |
| 506 | 467 | state: &AppState, |
| @@ -555,7 +516,6 @@ struct QueueForm { | ||
| 555 | 516 | csrf: String, |
| 556 | 517 | #[serde(default)] |
| 557 | 518 | id: String, |
| 558 | - /// The filter the admin was on, so the redirect lands back on it. | |
| 559 | 519 | #[serde(default)] |
| 560 | 520 | state: String, |
| 561 | 521 | } |
| @@ -570,8 +530,6 @@ async fn queue_discard(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response> | ||
| 570 | 530 | queue_action(cx, form, QueueAction::Discard).await |
| 571 | 531 | } |
| 572 | 532 | |
| 573 | -/// Retries or discards one failed message. Anything else is refused with a notice and changes | |
| 574 | -/// nothing. Either way the worker is woken and the queue's watchers are told. | |
| 575 | 533 | async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result<Response> { |
| 576 | 534 | let viewer = admin_only(cx).await?; |
| 577 | 535 | if !check_csrf(&viewer.1, &form.csrf) { |
| @@ -626,7 +584,6 @@ mod tests { | ||
| 626 | 584 | state: AppState, |
| 627 | 585 | } |
| 628 | 586 | |
| 629 | - /// An instance with an admin (who has an address) and a plain user. | |
| 630 | 587 | async fn fixture() -> Fixture { |
| 631 | 588 | let dir = tempfile::tempdir().expect("tempdir"); |
| 632 | 589 | let data_dir = dir.path().join("data"); |
| @@ -692,14 +649,10 @@ mod tests { | ||
| 692 | 649 | .any(|e| e.action == action) |
| 693 | 650 | } |
| 694 | 651 | |
| 695 | - // Scenario: the settings page. Gates and refusals come first while the store is still | |
| 696 | - // pristine, then a save, the page with no password shown, the test mail while mail is on, | |
| 697 | - // and the Turkish page. Each step is a precondition of the next one. | |
| 698 | 652 | #[tokio::test] |
| 699 | 653 | async fn settings_gates_saves_test_mail_and_turkish_page() { |
| 700 | 654 | let fx = fixture().await; |
| 701 | 655 | |
| 702 | - // Anonymous and non-admin users get 404 on the page and its posts. | |
| 703 | 656 | let (anon, _) = send(&fx.router, "GET", "/admin/mail", None, None).await; |
| 704 | 657 | assert_eq!(anon, 404); |
| 705 | 658 | let (user, _) = send(&fx.router, "GET", "/admin/mail", Some(USER_TOKEN), None).await; |
| @@ -731,7 +684,6 @@ mod tests { | ||
| 731 | 684 | .has_password |
| 732 | 685 | ); |
| 733 | 686 | |
| 734 | - // A missing CSRF token is refused. | |
| 735 | 687 | let (status, _) = send( |
| 736 | 688 | &fx.router, |
| 737 | 689 | "POST", |
| @@ -742,7 +694,6 @@ mod tests { | ||
| 742 | 694 | .await; |
| 743 | 695 | assert_eq!(status, 403, "a missing CSRF token is refused"); |
| 744 | 696 | |
| 745 | - // Test mail while mail is off queues nothing. | |
| 746 | 697 | let (status, _) = send( |
| 747 | 698 | &fx.router, |
| 748 | 699 | "POST", |
| @@ -762,7 +713,6 @@ mod tests { | ||
| 762 | 713 | "nothing is queued while mail is off" |
| 763 | 714 | ); |
| 764 | 715 | |
| 765 | - // A bad port is answered with a notice and changes nothing. | |
| 766 | 716 | let (status, _) = send( |
| 767 | 717 | &fx.router, |
| 768 | 718 | "POST", |
| @@ -777,7 +727,6 @@ mod tests { | ||
| 777 | 727 | assert!(!saved.has_password); |
| 778 | 728 | assert!(!audit_has(&fx.state.store, AuditAction::MailSettingsUpdated).await); |
| 779 | 729 | |
| 780 | - // A good save stores the settings, audits them, and the page never shows the password. | |
| 781 | 730 | let (status, _) = send( |
| 782 | 731 | &fx.router, |
| 783 | 732 | "POST", |
| @@ -802,7 +751,6 @@ mod tests { | ||
| 802 | 751 | "the stored password is never rendered" |
| 803 | 752 | ); |
| 804 | 753 | |
| 805 | - // With mail on, a test mail is queued to the admin's address and audited. | |
| 806 | 754 | let (status, _) = send( |
| 807 | 755 | &fx.router, |
| 808 | 756 | "POST", |
| @@ -818,7 +766,6 @@ mod tests { | ||
| 818 | 766 | assert!(rows[0].idem_key.starts_with("test:")); |
| 819 | 767 | assert!(audit_has(&fx.state.store, AuditAction::MailTestQueued).await); |
| 820 | 768 | |
| 821 | - // The page follows the viewer's language. | |
| 822 | 769 | let req = Request::builder() |
| 823 | 770 | .method("GET") |
| 824 | 771 | .uri("/admin/mail") |
| @@ -851,13 +798,10 @@ mod tests { | ||
| 851 | 798 | } |
| 852 | 799 | } |
| 853 | 800 | |
| 854 | - // Scenario: the queue tab is admin only and live, filters by state, and never renders a | |
| 855 | - // body. The queue actions and event stream are gated the same way. | |
| 856 | 801 | #[tokio::test] |
| 857 | 802 | async fn queue_tab_is_admin_only_live_filters_and_never_renders_a_body() { |
| 858 | 803 | let fx = fixture().await; |
| 859 | 804 | |
| 860 | - // Anonymous and plain users get 404 on the stream and on both queue actions. | |
| 861 | 805 | for (method, uri) in [ |
| 862 | 806 | ("GET", "/admin/mail/events"), |
| 863 | 807 | ("POST", "/admin/mail/queue/retry"), |
| @@ -963,7 +907,6 @@ mod tests { | ||
| 963 | 907 | "the queue is on its own tab" |
| 964 | 908 | ); |
| 965 | 909 | |
| 966 | - // An admin gets the queue event stream. | |
| 967 | 910 | let request = Request::builder() |
| 968 | 911 | .method("GET") |
| 969 | 912 | .uri("/admin/mail/events") |
| @@ -1046,7 +989,6 @@ mod tests { | ||
| 1046 | 989 | assert_eq!(discarded.len(), 1); |
| 1047 | 990 | assert_eq!(discarded[0].id, ids[1]); |
| 1048 | 991 | |
| 1049 | - // A queued message cannot be retried, and a bad token changes nothing. | |
| 1050 | 992 | let (status, _) = send( |
| 1051 | 993 | &fx.router, |
| 1052 | 994 | "POST", |
crates/forge-web-account/src/pages/admin_replication.rsmodified+30 -57
| @@ -57,7 +57,7 @@ pub(crate) struct NoticeQuery { | ||
| 57 | 57 | const REPO_ROWS: usize = 10; |
| 58 | 58 | |
| 59 | 59 | /// The health filter's values, in the order the menu lists them. |
| 60 | -const HEALTH_KEYS: [&str; 4] = ["error", "lagging", "never", "ok"]; | |
| 60 | +const HEALTH_MENU: [Health; 4] = [Health::Error, Health::Lagging, Health::Never, Health::Ok]; | |
| 61 | 61 | |
| 62 | 62 | /// How a subject reads on the page. |
| 63 | 63 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| @@ -98,9 +98,7 @@ impl Health { | ||
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | 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) | |
| 104 | 102 | } |
| 105 | 103 | |
| 106 | 104 | fn label(self, lang: Lang) -> &'static str { |
| @@ -127,29 +125,23 @@ fn health(status: Option<&ReplicationStatus>, cutoff: &str) -> Health { | ||
| 127 | 125 | } |
| 128 | 126 | } |
| 129 | 127 | |
| 130 | -/// One line of the repos table, already formatted. | |
| 128 | +/// One line of the repos table. | |
| 131 | 129 | struct RepoRow { |
| 132 | 130 | name: String, |
| 133 | 131 | kind: Health, |
| 134 | - dot: &'static str, | |
| 135 | - tone: &'static str, | |
| 136 | - health: &'static str, | |
| 137 | 132 | /// The last good copy's stamp, shown as a live relative time. |
| 138 | 133 | last_ok: Option<String>, |
| 139 | 134 | error: String, |
| 140 | 135 | } |
| 141 | 136 | |
| 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(), | |
| 153 | 145 | } |
| 154 | 146 | } |
| 155 | 147 | |
| @@ -187,39 +179,21 @@ async fn page_data(state: &AppState, lang: Lang) -> forge_core::Result<PageData> | ||
| 187 | 179 | Some(repo) => format!("{}/{}", repo.owner_name, repo.name), |
| 188 | 180 | None => id.clone(), |
| 189 | 181 | }; |
| 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)); | |
| 202 | 183 | } |
| 203 | 184 | // Repos deleted since their last push: their standby copy is removed at the next reconcile. |
| 204 | 185 | for status in statuses.values() { |
| 205 | 186 | 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)); | |
| 216 | 189 | } |
| 217 | 190 | } |
| 218 | 191 | |
| 192 | + let db_health = health(db, &db_cutoff); | |
| 219 | 193 | Ok(PageData { |
| 220 | 194 | 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), | |
| 223 | 197 | db_last_ok: db.and_then(|s| s.last_ok_at.clone()), |
| 224 | 198 | db_last_attempt: db.and_then(|s| s.last_attempt_at.clone()), |
| 225 | 199 | db_error: db.and_then(|s| s.last_error.clone()).unwrap_or_default(), |
| @@ -238,6 +212,7 @@ async fn replication_view( | ||
| 238 | 212 | list: RepoList, |
| 239 | 213 | ) -> Result<impl View> { |
| 240 | 214 | let RepoList { |
| 215 | + has_repos, | |
| 241 | 216 | finder, |
| 242 | 217 | health, |
| 243 | 218 | rows, |
| @@ -245,7 +220,6 @@ async fn replication_view( | ||
| 245 | 220 | pages, |
| 246 | 221 | nav: (links, prev, next), |
| 247 | 222 | } = list; |
| 248 | - let has_repos = !data.repos.is_empty(); | |
| 249 | 223 | let all_label = s(lang, "All", "Tümü"); |
| 250 | 224 | let health_label = s(lang, "Health", "Durum"); |
| 251 | 225 | let placeholder = s(lang, "Search repositories", "Depolarda ara"); |
| @@ -306,10 +280,8 @@ async fn replication_view( | ||
| 306 | 280 | (health_label) " " |
| 307 | 281 | <select name="health" data-autosubmit="true"> |
| 308 | 282 | <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> | |
| 313 | 285 | } |
| 314 | 286 | </select> |
| 315 | 287 | </label> |
| @@ -320,7 +292,7 @@ async fn replication_view( | ||
| 320 | 292 | for row in rows.into_iter() { |
| 321 | 293 | <div class="line" data-kb-row=""> |
| 322 | 294 | <span class="name">(row.name.as_str())</span> |
| 323 | - <span class="val"><span class=(row.dot) aria-hidden="true"></span> <span class=(row.tone)>(row.health)</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span> | |
| 295 | + <span class="val"><span class=(row.kind.dot()) aria-hidden="true"></span> <span class=(row.kind.tone())>(row.kind.label(lang))</span> " · " (g::t(lang, K::LastSuccess)) ": " rel_time_or_never(lang: lang, stamp: row.last_ok.as_deref())</span> | |
| 324 | 296 | </div> |
| 325 | 297 | if !row.error.is_empty() { |
| 326 | 298 | alert(message: row.error.as_str()) |
| @@ -341,7 +313,7 @@ async fn page_fingerprint(state: &AppState) -> Result<String> { | ||
| 341 | 313 | let rows: Vec<_> = data |
| 342 | 314 | .repos |
| 343 | 315 | .iter() |
| 344 | - .map(|row| (&row.name, row.health, &row.last_ok, &row.error)) | |
| 316 | + .map(|row| (&row.name, row.kind.label(Lang::En), &row.last_ok, &row.error)) | |
| 345 | 317 | .collect(); |
| 346 | 318 | Ok(format!( |
| 347 | 319 | "{}|{}|{:?}|{:?}|{}|{:?}", |
| @@ -368,6 +340,7 @@ async fn replication_events(cx: &Cx) -> Result<Response> { | ||
| 368 | 340 | |
| 369 | 341 | /// One page of the repo list, after the search and the health filter. |
| 370 | 342 | struct RepoList { |
| 343 | + has_repos: bool, | |
| 371 | 344 | finder: Finder, |
| 372 | 345 | health: Option<Health>, |
| 373 | 346 | rows: Vec<RepoRow>, |
| @@ -376,20 +349,19 @@ struct RepoList { | ||
| 376 | 349 | nav: (Vec<PageLink>, Option<String>, Option<String>), |
| 377 | 350 | } |
| 378 | 351 | |
| 379 | -/// Takes the repos that match the query out of `data`, a page of them. | |
| 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 { | |
| 381 | 354 | let finder = Finder::new( |
| 382 | 355 | query.q.as_deref(), |
| 383 | 356 | query.exact.as_deref(), |
| 384 | 357 | query.case.as_deref(), |
| 385 | 358 | ); |
| 386 | 359 | 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() | |
| 390 | 363 | .filter(|row| health.is_none_or(|h| row.kind == h)) |
| 391 | 364 | .filter(|row| finder.matches_any(&[row.name.as_str(), row.error.as_str()])) |
| 392 | - .map(RepoRow::copy) | |
| 393 | 365 | .collect(); |
| 394 | 366 | let pages = (matching.len() as u64).div_ceil(REPO_ROWS as u64).max(1); |
| 395 | 367 | let page = query |
| @@ -412,6 +384,7 @@ fn repo_list(data: &mut PageData, query: &NoticeQuery) -> RepoList { | ||
| 412 | 384 | list_href("/admin/replication", ¶ms) |
| 413 | 385 | }); |
| 414 | 386 | RepoList { |
| 387 | + has_repos, | |
| 415 | 388 | finder, |
| 416 | 389 | health, |
| 417 | 390 | rows, |
| @@ -428,7 +401,7 @@ async fn replication_page(cx: &Cx) -> Result<impl View> { | ||
| 428 | 401 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 429 | 402 | let state = context::<AppState>(cx); |
| 430 | 403 | let mut data = page_data(state, lang).await?; |
| 431 | - let list = repo_list(&mut data, query); | |
| 404 | + let list = repo_list(std::mem::take(&mut data.repos), query); | |
| 432 | 405 | let settings = setting_rows(state, lang, REPLICATION_KEYS).await?; |
| 433 | 406 | let csrf = viewer.1.csrf_token.clone(); |
| 434 | 407 | let title = g::t(lang, K::Replication); |
crates/forge-web-account/src/pages/admin_server.rsmodified+4 -110
| @@ -1,19 +1,3 @@ | ||
| 1 | -//! Page: the forge's own settings (`/admin/server`). Instance admins only; anyone else gets 404. | |
| 2 | -//! | |
| 3 | -//! One category of settings at a time (`?cat=`). Each field shows its effective value, where that value comes | |
| 4 | -//! from (default, config file, or a UI override) and how a change reaches the process: live | |
| 5 | -//! (applied at once), restart (saved, applied at the next start) or read-only. Saving a tab stores | |
| 6 | -//! the changed fields as database overrides on top of the config file, which is never rewritten. | |
| 7 | -//! A field with an override has "Reset to file value". Secret fields are write-only: the page | |
| 8 | -//! shows only whether they are set. See `forge_core::server_settings` for the rules. | |
| 9 | -//! Saving and resetting are audited, with the keys but never the values. | |
| 10 | -//! | |
| 11 | -//! "Restart server" asks for a graceful stop through the self-update path: the process exits with | |
| 12 | -//! `RESTART_EXIT_CODE` and systemd (`Restart=on-failure`) starts the binary again, which picks up a | |
| 13 | -//! newly installed one. The page that follows shows "Restarting" and follows an event stream. The | |
| 14 | -//! stream sends the server's boot id when it connects, so the browser's own reconnect after the | |
| 15 | -//! restart brings a new id, and the page then re-renders itself with no reload and no polling. | |
| 16 | - | |
| 17 | 1 | use std::collections::{BTreeMap, HashMap}; |
| 18 | 2 | |
| 19 | 3 | use forge_core::server_settings::{self as ss, Field, FieldView, Group, Kind, Source, Ty}; |
| @@ -45,32 +29,20 @@ use crate::views::{enc, shell}; | ||
| 45 | 29 | #[query_params(error = bad_request)] |
| 46 | 30 | pub(crate) struct ServerQuery { |
| 47 | 31 | notice: Option<String>, |
| 48 | - /// The category shown: `general`, `limits`, `storage`, `backups`, `integrations` or `alerts`. | |
| 49 | 32 | cat: Option<String>, |
| 50 | - /// The search text: when set, the page lists the matching settings from every category instead. | |
| 51 | 33 | q: Option<String>, |
| 52 | - /// Set when the search asks for the text as typed, as one piece. | |
| 53 | 34 | exact: Option<String>, |
| 54 | - /// Set when the search keeps upper and lower case apart. | |
| 55 | 35 | case: Option<String>, |
| 56 | - /// The older name for `cat`, still read so an old link opens the same category. | |
| 57 | 36 | tab: Option<String>, |
| 58 | - /// The boot id of the server that was asked to restart. | |
| 59 | 37 | restarting: Option<String>, |
| 60 | 38 | } |
| 61 | 39 | |
| 62 | -/// How long the restart waits after the request is answered, so the redirect that follows is | |
| 63 | -/// served by the old process. | |
| 64 | 40 | const RESTART_GRACE: std::time::Duration = std::time::Duration::from_millis(750); |
| 65 | 41 | |
| 66 | -/// Where the page stands in a restart. | |
| 67 | 42 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 68 | 43 | enum Restart { |
| 69 | - /// No restart was asked from this page. | |
| 70 | 44 | None, |
| 71 | - /// Asked, and this process is still the old one or on its way down. | |
| 72 | 45 | Pending, |
| 73 | - /// Asked, and a new process answered. | |
| 74 | 46 | Done, |
| 75 | 47 | } |
| 76 | 48 | |
| @@ -88,12 +60,10 @@ struct OptionRow { | ||
| 88 | 60 | selected: bool, |
| 89 | 61 | } |
| 90 | 62 | |
| 91 | -/// One field, already formatted for the template. A secret's value is never in here. | |
| 92 | 63 | pub(crate) struct Row { |
| 93 | 64 | key: &'static str, |
| 94 | 65 | label: &'static str, |
| 95 | 66 | kind_label: &'static str, |
| 96 | - /// What a line shows for the value: the text, the chosen option, On or Off, or the secret state. | |
| 97 | 67 | value_text: String, |
| 98 | 68 | value: String, |
| 99 | 69 | file_value: String, |
| @@ -112,9 +82,6 @@ pub(crate) struct Row { | ||
| 112 | 82 | fixed: bool, |
| 113 | 83 | } |
| 114 | 84 | |
| 115 | -/// One page of settings: a part of a category small enough to read without scrolling. Saving posts | |
| 116 | -/// the page's slug; the save covers the page's category, and only the page's switches are read as | |
| 117 | -/// off when absent. | |
| 118 | 85 | pub(crate) struct SrvPage { |
| 119 | 86 | pub(crate) slug: &'static str, |
| 120 | 87 | group: Group, |
| @@ -129,9 +96,6 @@ impl SrvPage { | ||
| 129 | 96 | } |
| 130 | 97 | } |
| 131 | 98 | |
| 132 | -/// The pages in rail order. Every setting is on exactly one page: the backup and replication | |
| 133 | -/// settings are on their own pages (`BACKUP_KEYS`, `REPLICATION_KEYS`) and `mail.transport` is on | |
| 134 | -/// the Mail page (`MAIL_KEYS`). | |
| 135 | 99 | pub(crate) const PAGES: &[SrvPage] = &[ |
| 136 | 100 | SrvPage { |
| 137 | 101 | slug: "general", |
| @@ -238,7 +202,6 @@ pub(crate) const PAGES: &[SrvPage] = &[ | ||
| 238 | 202 | group: Group::Alerts, |
| 239 | 203 | en: "Alerts", |
| 240 | 204 | tr: "Uyarılar", |
| 241 | - // Each threshold sits under the alert it tunes. | |
| 242 | 205 | keys: &[ |
| 243 | 206 | "alerts.enabled", |
| 244 | 207 | "alerts.email", |
| @@ -255,7 +218,6 @@ pub(crate) const PAGES: &[SrvPage] = &[ | ||
| 255 | 218 | }, |
| 256 | 219 | ]; |
| 257 | 220 | |
| 258 | -/// The settings of the Backups page. Their group is `Group::Backups`. | |
| 259 | 221 | pub(crate) const BACKUP_KEYS: &[&str] = &[ |
| 260 | 222 | "backup.dir", |
| 261 | 223 | "backup.interval_hours", |
| @@ -264,7 +226,6 @@ pub(crate) const BACKUP_KEYS: &[&str] = &[ | ||
| 264 | 226 | "backup.healthcheck_url", |
| 265 | 227 | ]; |
| 266 | 228 | |
| 267 | -/// The settings of the Replication page. Their group is `Group::Backups`. | |
| 268 | 229 | pub(crate) const REPLICATION_KEYS: &[&str] = &[ |
| 269 | 230 | "replication.target", |
| 270 | 231 | "replication.ssh_port", |
| @@ -275,16 +236,12 @@ pub(crate) const REPLICATION_KEYS: &[&str] = &[ | ||
| 275 | 236 | "replication.healthcheck_url", |
| 276 | 237 | ]; |
| 277 | 238 | |
| 278 | -/// The settings of the Mail page. Their group is `Group::Integrations`. | |
| 279 | 239 | pub(crate) const MAIL_KEYS: &[&str] = &["mail.transport"]; |
| 280 | 240 | |
| 281 | -/// The page named by `slug`. | |
| 282 | 241 | pub(crate) fn page_by_slug(slug: &str) -> Option<&'static SrvPage> { |
| 283 | 242 | PAGES.iter().find(|page| page.slug == slug) |
| 284 | 243 | } |
| 285 | 244 | |
| 286 | -/// Where the old slugs of moved pages went: `retention`, `s3`, `backups` and `replication`. `None` | |
| 287 | -/// for every slug that still names a page. | |
| 288 | 245 | fn moved_slug(slug: &str) -> Option<&'static str> { |
| 289 | 246 | match slug { |
| 290 | 247 | "retention" => Some("/admin/server?cat=limits"), |
| @@ -295,16 +252,12 @@ fn moved_slug(slug: &str) -> Option<&'static str> { | ||
| 295 | 252 | } |
| 296 | 253 | } |
| 297 | 254 | |
| 298 | -/// Where a setting's row lives: the page's name and the link to the row. | |
| 299 | 255 | pub(crate) struct Home { |
| 300 | - /// The page's name, with the area it belongs to when that is not obvious ("Backups"). | |
| 301 | 256 | pub(crate) label: String, |
| 302 | - /// True for a setting on the server settings page, so the area name is written before it. | |
| 303 | 257 | pub(crate) server: bool, |
| 304 | 258 | pub(crate) href: String, |
| 305 | 259 | } |
| 306 | 260 | |
| 307 | -/// The page that holds the setting `key`, and the link to its row. | |
| 308 | 261 | pub(crate) fn page_of(lang: Lang, key: &str) -> Home { |
| 309 | 262 | if BACKUP_KEYS.contains(&key) { |
| 310 | 263 | return Home { |
| @@ -338,8 +291,6 @@ pub(crate) fn page_of(lang: Lang, key: &str) -> Home { | ||
| 338 | 291 | } |
| 339 | 292 | } |
| 340 | 293 | |
| 341 | -/// The keys a topic shows, out of its `keys`, given the values now in effect. Storage shows the | |
| 342 | -/// fields of the chosen backend only: `fs` shows none, `s3` and `r2` their own. | |
| 343 | 294 | fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> { |
| 344 | 295 | let backend = views |
| 345 | 296 | .iter() |
| @@ -360,7 +311,6 @@ fn shown_keys<'a>(keys: &[&'a str], views: &[FieldView]) -> Vec<&'a str> { | ||
| 360 | 311 | .collect() |
| 361 | 312 | } |
| 362 | 313 | |
| 363 | -/// The words for a choice's stored value. Values that are names (smtp, s3, eu) read as they are. | |
| 364 | 314 | fn option_label(lang: Lang, option: &str) -> String { |
| 365 | 315 | let (en, tr) = match option { |
| 366 | 316 | "" => return g::t(lang, K::SrvEmpty).to_owned(), |
| @@ -379,7 +329,6 @@ fn option_label(lang: Lang, option: &str) -> String { | ||
| 379 | 329 | fn row(lang: Lang, view: &FieldView) -> Row { |
| 380 | 330 | let field: &Field = view.field; |
| 381 | 331 | let kind_label = match field.kind { |
| 382 | - // A live field needs no word: applying at once is what a field is expected to do. | |
| 383 | 332 | Kind::Live => "", |
| 384 | 333 | Kind::Restart => g::t(lang, K::SrvKindRestart), |
| 385 | 334 | Kind::ReadOnly => g::t(lang, K::SrvKindReadOnly), |
| @@ -456,7 +405,6 @@ fn row(lang: Lang, view: &FieldView) -> Row { | ||
| 456 | 405 | } |
| 457 | 406 | } |
| 458 | 407 | |
| 459 | -/// The rows of the settings `keys`, in `keys` order. | |
| 460 | 408 | fn rows_of(lang: Lang, views: &[FieldView], keys: &[&str]) -> Vec<Row> { |
| 461 | 409 | keys.iter() |
| 462 | 410 | .filter_map(|key| views.iter().find(|view| view.field.key == *key)) |
| @@ -464,14 +412,6 @@ fn rows_of(lang: Lang, views: &[FieldView], keys: &[&str]) -> Vec<Row> { | ||
| 464 | 412 | .collect() |
| 465 | 413 | } |
| 466 | 414 | |
| 467 | -/// The rows of one server settings page, in the page's order. | |
| 468 | -async fn rows_for(state: &AppState, lang: Lang, page: &SrvPage) -> forge_core::Result<Vec<Row>> { | |
| 469 | - let overrides = state.store.server_overrides().await?; | |
| 470 | - let views = state.settings.views(&overrides); | |
| 471 | - Ok(rows_of(lang, &views, page.keys)) | |
| 472 | -} | |
| 473 | - | |
| 474 | -/// The rows of a settings topic outside the server page (Backups, Replication, Mail), in `keys` order. | |
| 475 | 415 | pub(crate) async fn setting_rows( |
| 476 | 416 | state: &AppState, |
| 477 | 417 | lang: Lang, |
| @@ -482,9 +422,6 @@ pub(crate) async fn setting_rows( | ||
| 482 | 422 | Ok(rows_of(lang, &views, keys)) |
| 483 | 423 | } |
| 484 | 424 | |
| 485 | -/// Saves the posted values of one settings topic. `topic` is every key the topic can show; only | |
| 486 | -/// the ones it shows now (see `shown_keys`) are read, and an unchecked switch of those counts as | |
| 487 | -/// off. `Ok(None)` means nothing differed from what is in effect. | |
| 488 | 425 | pub(crate) async fn save_topic( |
| 489 | 426 | cx: &Cx, |
| 490 | 427 | state: &AppState, |
| @@ -510,7 +447,6 @@ pub(crate) async fn save_topic( | ||
| 510 | 447 | save(cx, state, user, group, &submitted, lang).await |
| 511 | 448 | } |
| 512 | 449 | |
| 513 | -/// The notice a settings save shows: saved, nothing changed, or why it was refused. | |
| 514 | 450 | pub(crate) fn notice_of(lang: Lang, result: forge_core::Result<Option<()>>) -> String { |
| 515 | 451 | match result { |
| 516 | 452 | Ok(Some(())) => g::t(lang, K::SrvSaved).to_owned(), |
| @@ -519,7 +455,6 @@ pub(crate) fn notice_of(lang: Lang, result: forge_core::Result<Option<()>>) -> S | ||
| 519 | 455 | } |
| 520 | 456 | } |
| 521 | 457 | |
| 522 | -/// The words for an error a page shows: the message itself for a refusal the user can fix. | |
| 523 | 458 | pub(crate) fn refusal(error: Error) -> String { |
| 524 | 459 | match error { |
| 525 | 460 | Error::Invalid(message) | Error::Config(message) => message, |
| @@ -527,8 +462,6 @@ pub(crate) fn refusal(error: Error) -> String { | ||
| 527 | 462 | } |
| 528 | 463 | } |
| 529 | 464 | |
| 530 | -/// The page a settings form goes back to. Only a page of the admin area is taken; anything else | |
| 531 | -/// goes to the server settings. | |
| 532 | 465 | pub(crate) fn back_to(raw: &str) -> &str { |
| 533 | 466 | if raw.starts_with("/admin/") && !raw.contains("//") && !raw.contains('\\') { |
| 534 | 467 | raw |
| @@ -537,14 +470,11 @@ pub(crate) fn back_to(raw: &str) -> &str { | ||
| 537 | 470 | } |
| 538 | 471 | } |
| 539 | 472 | |
| 540 | -/// `back` with a notice on its query string. | |
| 541 | 473 | pub(crate) fn with_notice(back: &str, notice: &str) -> String { |
| 542 | 474 | let sep = if back.contains('?') { '&' } else { '?' }; |
| 543 | 475 | format!("{back}{sep}notice={}", enc(notice)) |
| 544 | 476 | } |
| 545 | 477 | |
| 546 | -/// The hidden form that resets one setting: the rows' "Reset to file value" buttons post to it by | |
| 547 | -/// id. It goes outside the forms that save, since a form cannot hold another. | |
| 548 | 478 | #[component] |
| 549 | 479 | pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<impl View> { |
| 550 | 480 | Ok(view! { |
| @@ -555,7 +485,6 @@ pub(crate) async fn reset_form(cx: &Cx, csrf: String, back: String) -> Result<im | ||
| 555 | 485 | }) |
| 556 | 486 | } |
| 557 | 487 | |
| 558 | -/// The rows of a settings topic, one line each. The caller's form holds them. | |
| 559 | 488 | #[component] |
| 560 | 489 | pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result<impl View> { |
| 561 | 490 | Ok(view! { |
| @@ -565,7 +494,6 @@ pub(crate) async fn setting_lines(cx: &Cx, lang: Lang, rows: Vec<Row>) -> Result | ||
| 565 | 494 | }) |
| 566 | 495 | } |
| 567 | 496 | |
| 568 | -/// The settings from every category whose key or label matches the search. | |
| 569 | 497 | async fn search_hits( |
| 570 | 498 | state: &AppState, |
| 571 | 499 | lang: Lang, |
| @@ -581,8 +509,6 @@ async fn search_hits( | ||
| 581 | 509 | .collect()) |
| 582 | 510 | } |
| 583 | 511 | |
| 584 | -/// One setting on one line: its name, then its control (or its value when it cannot be changed | |
| 585 | -/// here), then what to know about it. Every control is the same width, so the notes line up. | |
| 586 | 512 | #[component] |
| 587 | 513 | async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> { |
| 588 | 514 | let id = format!("srv-{}", row.key); |
| @@ -617,7 +543,6 @@ async fn srv_row(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> { | ||
| 617 | 543 | }) |
| 618 | 544 | } |
| 619 | 545 | |
| 620 | -/// The facts after a setting's control: its kind, whether a restart is needed, and its override. | |
| 621 | 546 | #[component] |
| 622 | 547 | async fn srv_hints(cx: &Cx, lang: Lang, row: &Row) -> Result<impl View> { |
| 623 | 548 | Ok(view! { |
| @@ -657,8 +582,6 @@ async fn server_view( | ||
| 657 | 582 | let tab = page.slug; |
| 658 | 583 | let any_editable = rows.iter().any(|r| !r.fixed); |
| 659 | 584 | let search_label = s(lang, "Search server settings", "Sunucu ayarlarında ara"); |
| 660 | - // A pending restart names the boot id it waits for: the stream then sends at once when a new | |
| 661 | - // process answers, and the page re-renders. | |
| 662 | 585 | let live = match restart { |
| 663 | 586 | Restart::Pending => format!( |
| 664 | 587 | "/admin/server/events?restarting={}", |
| @@ -752,7 +675,7 @@ async fn server_page(cx: &Cx) -> Result<impl View> { | ||
| 752 | 675 | query.case.as_deref(), |
| 753 | 676 | ); |
| 754 | 677 | let (rows, search) = if finder.is_empty() { |
| 755 | - (rows_for(state, lang, page).await?, None) | |
| 678 | + (setting_rows(state, lang, page.keys).await?, None) | |
| 756 | 679 | } else { |
| 757 | 680 | (Vec::new(), Some(search_hits(state, lang, &finder).await?)) |
| 758 | 681 | }; |
| @@ -787,8 +710,6 @@ async fn server_save(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> Resu | ||
| 787 | 710 | .into()) |
| 788 | 711 | } |
| 789 | 712 | |
| 790 | -/// Validates the whole tab as one unit, stores it, publishes the live fields and audits the keys. | |
| 791 | -/// `Ok(None)` means nothing differed from what is already in effect. | |
| 792 | 713 | async fn save( |
| 793 | 714 | cx: &Cx, |
| 794 | 715 | state: &AppState, |
| @@ -834,8 +755,6 @@ struct RestartForm { | ||
| 834 | 755 | tab: String, |
| 835 | 756 | } |
| 836 | 757 | |
| 837 | -/// Audits the request, answers with the page that shows "Restarting", and a moment later asks the | |
| 838 | -/// server to stop gracefully. The process then exits with `RESTART_EXIT_CODE` and systemd starts it. | |
| 839 | 758 | #[route(POST "/admin/server/restart")] |
| 840 | 759 | async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Response> { |
| 841 | 760 | let viewer = admin_only(cx).await?; |
| @@ -843,7 +762,7 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon | ||
| 843 | 762 | return Err(forbidden().into()); |
| 844 | 763 | } |
| 845 | 764 | let state = context::<AppState>(cx); |
| 846 | - let group = Group::parse(&form.tab).unwrap_or(Group::General); | |
| 765 | + let page = page_by_slug(&form.tab).unwrap_or(&PAGES[0]); | |
| 847 | 766 | audit::record( |
| 848 | 767 | &state.store, |
| 849 | 768 | Some(cx), |
| @@ -864,16 +783,12 @@ async fn server_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<Respon | ||
| 864 | 783 | }); |
| 865 | 784 | Err(see_other(format!( |
| 866 | 785 | "/admin/server?cat={}&restarting={}", |
| 867 | - group.slug(), | |
| 786 | + page.slug, | |
| 868 | 787 | enc(self_update::boot_id()) |
| 869 | 788 | )) |
| 870 | 789 | .into()) |
| 871 | 790 | } |
| 872 | 791 | |
| 873 | -/// The server settings' change stream. Admins only. It sends `changed` when a setting is saved or | |
| 874 | -/// reset, by any session. When the page waits for a restart (`restarting` names the boot id it | |
| 875 | -/// waits past) and this process is not that one, it sends one `changed` on connect: the browser | |
| 876 | -/// reconnects to the new process after the old one goes down, and that re-renders the page. | |
| 877 | 792 | #[route(GET "/admin/server/events")] |
| 878 | 793 | async fn server_events(cx: &Cx) -> Result<Response> { |
| 879 | 794 | admin_only(cx).await?; |
| @@ -898,7 +813,6 @@ struct ResetForm { | ||
| 898 | 813 | csrf: String, |
| 899 | 814 | #[serde(default)] |
| 900 | 815 | key: String, |
| 901 | - /// The page the reset came from: where the viewer goes back to. | |
| 902 | 816 | #[serde(default)] |
| 903 | 817 | back: String, |
| 904 | 818 | } |
| @@ -913,9 +827,7 @@ async fn server_reset(cx: &Cx, Form(form): Form<ResetForm>) -> Result<Response> | ||
| 913 | 827 | let state = context::<AppState>(cx); |
| 914 | 828 | let notice = match reset(cx, state, &viewer.0, &form.key).await { |
| 915 | 829 | 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), | |
| 919 | 831 | }; |
| 920 | 832 | Err(see_other(with_notice(back_to(&form.back), ¬ice)).into()) |
| 921 | 833 | } |
| @@ -1032,7 +944,6 @@ mod tests { | ||
| 1032 | 944 | body |
| 1033 | 945 | } |
| 1034 | 946 | |
| 1035 | - /// Posts a tab and follows the redirect to read the notice it shows. | |
| 1036 | 947 | async fn save(fx: &Fixture, tab: &str, fields: &str) -> String { |
| 1037 | 948 | let form = format!("csrf={CSRF}&tab={tab}&{fields}"); |
| 1038 | 949 | let (status, _, location) = send( |
| @@ -1047,7 +958,6 @@ mod tests { | ||
| 1047 | 958 | admin_get(fx, &location).await |
| 1048 | 959 | } |
| 1049 | 960 | |
| 1050 | - /// Posts a settings topic of its own page (Backups, Replication) and reads the page it goes to. | |
| 1051 | 961 | async fn save_topic_at(fx: &Fixture, path: &str, fields: &str) -> String { |
| 1052 | 962 | let form = format!("csrf={CSRF}&{fields}"); |
| 1053 | 963 | let (status, _, location) = |
| @@ -1056,8 +966,6 @@ mod tests { | ||
| 1056 | 966 | admin_get(fx, &location).await |
| 1057 | 967 | } |
| 1058 | 968 | |
| 1059 | - // Scenario: non-admins get 404 on every route, bad CSRF is refused and refused values are | |
| 1060 | - // never stored. Nothing here saves, so the store stays pristine for the next scenarios. | |
| 1061 | 969 | #[tokio::test] |
| 1062 | 970 | async fn gates_csrf_read_only_and_bad_values_change_nothing() { |
| 1063 | 971 | let fx = fixture().await; |
| @@ -1086,7 +994,6 @@ mod tests { | ||
| 1086 | 994 | } |
| 1087 | 995 | assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); |
| 1088 | 996 | |
| 1089 | - // A bad CSRF token is refused for a settings save and for a restart. | |
| 1090 | 997 | let form = "csrf=wrong&tab=limits&ci.max_log_mb=99".to_owned(); |
| 1091 | 998 | let (status, _, _) = send( |
| 1092 | 999 | &fx.router, |
| @@ -1108,14 +1015,12 @@ mod tests { | ||
| 1108 | 1015 | assert_eq!(status, 403, "bad csrf restart"); |
| 1109 | 1016 | assert_eq!(fx.state.live().ci.max_log_mb, 16); |
| 1110 | 1017 | |
| 1111 | - // A read-only field is shown but cannot be posted. | |
| 1112 | 1018 | let page = admin_get(&fx, "/admin/server?tab=addresses").await; |
| 1113 | 1019 | assert!(page.contains("127.0.0.1:7660")); |
| 1114 | 1020 | assert!(!page.contains("name=\"listen\"")); |
| 1115 | 1021 | save(&fx, "addresses", "listen=0.0.0.0%3A1").await; |
| 1116 | 1022 | assert!(fx.state.store.server_overrides().await.unwrap().is_empty()); |
| 1117 | 1023 | |
| 1118 | - // Out-of-range, wrong-kind and unknown-storage values are rejected, and nothing is stored. | |
| 1119 | 1024 | for (tab, fields) in [ |
| 1120 | 1025 | ("general", "registration=everyone"), |
| 1121 | 1026 | ("general", "trusted_proxies=not-an-ip"), |
| @@ -1133,8 +1038,6 @@ mod tests { | ||
| 1133 | 1038 | assert_eq!(fx.state.live().ci.max_log_mb, 16); |
| 1134 | 1039 | } |
| 1135 | 1040 | |
| 1136 | - // Scenario: a live override applies at once and reset goes back; registration follows the | |
| 1137 | - // saved general setting. | |
| 1138 | 1041 | #[tokio::test] |
| 1139 | 1042 | async fn live_overrides_apply_reset_and_registration_follows() { |
| 1140 | 1043 | let fx = fixture().await; |
| @@ -1172,13 +1075,10 @@ mod tests { | ||
| 1172 | 1075 | assert_eq!(open, 200, "registration opens at once"); |
| 1173 | 1076 | } |
| 1174 | 1077 | |
| 1175 | - // Scenario: a restart field is stored but waits for a restart, secrets are never rendered | |
| 1176 | - // and are stored sealed, and saves are audited without their values. | |
| 1177 | 1078 | #[tokio::test] |
| 1178 | 1079 | async fn restart_fields_secrets_and_audit_hold_their_rules() { |
| 1179 | 1080 | let fx = fixture().await; |
| 1180 | 1081 | |
| 1181 | - // A restart field is stored, the live value stays, and the page says so. | |
| 1182 | 1082 | save(&fx, "addresses", "base_url=https%3A%2F%2Fnew.example").await; |
| 1183 | 1083 | assert_eq!( |
| 1184 | 1084 | fx.state |
| @@ -1195,7 +1095,6 @@ mod tests { | ||
| 1195 | 1095 | assert!(page.contains("restart needed")); |
| 1196 | 1096 | assert!(page.contains("https://new.example")); |
| 1197 | 1097 | |
| 1198 | - // A secret is saved, never shown on any tab, and a blank post keeps it. | |
| 1199 | 1098 | let secret = "https://hc.example/ping/TOPSECRET-TOKEN"; |
| 1200 | 1099 | let body = save_topic_at( |
| 1201 | 1100 | &fx, |
| @@ -1230,7 +1129,6 @@ mod tests { | ||
| 1230 | 1129 | .unwrap() |
| 1231 | 1130 | .contains_key("backup.healthcheck_url") |
| 1232 | 1131 | ); |
| 1233 | - // Reset removes the secret and leaves the restart field alone. | |
| 1234 | 1132 | let form = format!("csrf={CSRF}&tab=backups&key=backup.healthcheck_url"); |
| 1235 | 1133 | send( |
| 1236 | 1134 | &fx.router, |
| @@ -1244,7 +1142,6 @@ mod tests { | ||
| 1244 | 1142 | assert!(!stored.contains_key("backup.healthcheck_url")); |
| 1245 | 1143 | assert!(stored.contains_key("base_url")); |
| 1246 | 1144 | |
| 1247 | - // Saves are audited by key only: no value, secret or otherwise, reaches the log. | |
| 1248 | 1145 | save(&fx, "limits", "ci.max_log_mb=77").await; |
| 1249 | 1146 | let entries = fx |
| 1250 | 1147 | .state |
| @@ -1268,12 +1165,10 @@ mod tests { | ||
| 1268 | 1165 | } |
| 1269 | 1166 | } |
| 1270 | 1167 | |
| 1271 | - // Scenario: restart is audited, and the page shows the restarting state until a new process runs. | |
| 1272 | 1168 | #[tokio::test] |
| 1273 | 1169 | async fn restart_is_audited_and_the_page_shows_the_restarting_state() { |
| 1274 | 1170 | let fx = fixture().await; |
| 1275 | 1171 | |
| 1276 | - // The page offers the button with a confirm step. | |
| 1277 | 1172 | let page = admin_get(&fx, "/admin/server").await; |
| 1278 | 1173 | assert!(page.contains("Restart server")); |
| 1279 | 1174 | assert!(page.contains("/admin/server/restart")); |
| @@ -1302,7 +1197,6 @@ mod tests { | ||
| 1302 | 1197 | .any(|e| e.action == AuditAction::ServerRestarted) |
| 1303 | 1198 | ); |
| 1304 | 1199 | |
| 1305 | - // Same process: "Restarting" with the event stream. A new process: back to normal. | |
| 1306 | 1200 | let page = admin_get(&fx, &location).await; |
| 1307 | 1201 | assert!(page.contains("Restarting...")); |
| 1308 | 1202 | assert!(page.contains(r#"data-live="/admin/server/events?restarting="#)); |
crates/forge-web-account/src/pages/admin_user_detail.rsmodified+19 -17
| @@ -7,7 +7,7 @@ use forge_core::names::normalize_name; | ||
| 7 | 7 | use forge_core::store::orgs::OrgMemberRole; |
| 8 | 8 | use forge_core::store::suspension::{AccountFacts, Suspension}; |
| 9 | 9 | use forge_core::store::user_delete::GHOST_USERNAME; |
| 10 | -use forge_core::{AuditAction, Store, User}; | |
| 10 | +use forge_core::{AuditAction, Session, Store, User}; | |
| 11 | 11 | use serde::Deserialize; |
| 12 | 12 | use topcoat::Result; |
| 13 | 13 | use topcoat::context::{Cx, context}; |
| @@ -87,15 +87,20 @@ fn is_ghost(user: &User) -> bool { | ||
| 87 | 87 | normalize_name(&user.username) == GHOST_USERNAME |
| 88 | 88 | } |
| 89 | 89 | |
| 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 { | |
| 94 | 92 | return Err(not_found().into()); |
| 95 | 93 | }; |
| 96 | - if target.is_org() || is_ghost(&target) { | |
| 94 | + if user.is_org() || is_ghost(&user) { | |
| 97 | 95 | return Err(not_found().into()); |
| 98 | 96 | } |
| 97 | + Ok(user) | |
| 98 | +} | |
| 99 | + | |
| 100 | +async fn load(cx: &Cx) -> Result<Detail> { | |
| 101 | + let store = &context::<AppState>(cx).store; | |
| 102 | + let id = path_param_segment(cx, "user_id").to_owned(); | |
| 103 | + let target = visible_account(store, &id).await?; | |
| 99 | 104 | let login_filter = forge_core::AuditFilter { |
| 100 | 105 | actor_id: Some(target.id.clone()), |
| 101 | 106 | action: Some(AuditAction::LoginSuccess), |
| @@ -537,12 +542,7 @@ async fn org_body( | ||
| 537 | 542 | |
| 538 | 543 | /// What the page shows of one account, as one string. A missing or hidden account is a 404. |
| 539 | 544 | 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?; | |
| 546 | 546 | let facts = store.account_facts(user_id).await?; |
| 547 | 547 | let suspension = store.suspension(user_id).await?; |
| 548 | 548 | let passkeys = store.passkey_count(user_id).await?; |
| @@ -621,8 +621,12 @@ enum Outcome { | ||
| 621 | 621 | Refused(String), |
| 622 | 622 | } |
| 623 | 623 | |
| 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)> { | |
| 626 | 630 | if !check_csrf(&viewer.1, &form.csrf) { |
| 627 | 631 | return Err(forbidden().into()); |
| 628 | 632 | } |
| @@ -747,10 +751,8 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, | ||
| 747 | 751 | |
| 748 | 752 | /// Redirects to the detail page after a success, or renders it with a message. |
| 749 | 753 | async fn respond(cx: &Cx, form: ActionForm, action: Action) -> Result<impl View> { |
| 750 | - // `view!` expects the `cx` binding that `#[page]` provides. | |
| 751 | - let cx = cx; | |
| 752 | - let (outcome, detail) = perform(cx, &form, action).await?; | |
| 753 | 754 | let viewer = admin_only(cx).await?; |
| 755 | + let (outcome, detail) = perform(cx, &viewer, &form, action).await?; | |
| 754 | 756 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 755 | 757 | let notice = match outcome { |
| 756 | 758 | Outcome::Done(key) => { |
crates/forge-web-account/src/pages/assets.rsmodified+51 -123
| @@ -6,7 +6,7 @@ use topcoat::Result; | ||
| 6 | 6 | use topcoat::context::Cx; |
| 7 | 7 | use topcoat::router::request::uri; |
| 8 | 8 | use topcoat::router::response::Response; |
| 9 | -use topcoat::router::{HeaderMap, StatusCode, header, route}; | |
| 9 | +use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, route}; | |
| 10 | 10 | |
| 11 | 11 | use crate::accent; |
| 12 | 12 | use crate::custom_colour; |
| @@ -15,15 +15,25 @@ use crate::views::{NAV_SCRIPT_HREF, STYLESHEET_HREF, highlight_href}; | ||
| 15 | 15 | /// Immutable only when the request names the current version (`href` is the URL the pages link). |
| 16 | 16 | /// Any other `?v=` (a page from an older or newer build, or none) revalidates, so a mismatched |
| 17 | 17 | /// version is never cached for a year under a URL that later means this build's file. |
| 18 | -fn cache_for(cx: &Cx, href: &str) -> topcoat::router::HeaderValue { | |
| 18 | +fn cache_for(cx: &Cx, href: &str) -> &'static str { | |
| 19 | 19 | let request = uri(cx); |
| 20 | 20 | let current = href.split_once('?').map(|(_, query)| query); |
| 21 | - let value = if request.query() == current { | |
| 21 | + if request.query() == current { | |
| 22 | 22 | "public, max-age=31536000, immutable" |
| 23 | 23 | } else { |
| 24 | 24 | "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) | |
| 27 | 37 | } |
| 28 | 38 | |
| 29 | 39 | const CSS: &str = forge_web_app::build_info::MAIN_CSS; |
| @@ -31,15 +41,7 @@ const CSS: &str = forge_web_app::build_info::MAIN_CSS; | ||
| 31 | 41 | /// Immutable when the URL carries the current content hash, so a changed file gets a new URL. |
| 32 | 42 | #[route(GET "/assets/main.css")] |
| 33 | 43 | 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)) | |
| 43 | 45 | } |
| 44 | 46 | |
| 45 | 47 | /// The soft-navigation script (`assets/nav.js`). Served from the same origin, so the CSP's |
| @@ -49,29 +51,17 @@ const NAV_JS: &str = include_str!("../../../forge-web/assets/nav.js"); | ||
| 49 | 51 | /// Immutable like `main.css`: the URL carries a content hash. |
| 50 | 52 | #[route(GET "/assets/nav.js")] |
| 51 | 53 | 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)) | |
| 61 | 55 | } |
| 62 | 56 | |
| 63 | 57 | /// Immutable like `main.css`: the URL carries a content hash. |
| 64 | 58 | #[route(GET "/assets/highlight.css")] |
| 65 | 59 | 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 | + )) | |
| 75 | 65 | } |
| 76 | 66 | |
| 77 | 67 | /// The colours of the hue choices on one page. The query names the four choices: `al` and `ad` for |
| @@ -101,20 +91,11 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> { | ||
| 101 | 91 | .map(|(id, hue, vivid)| (id.as_str(), *hue, *vivid)) |
| 102 | 92 | }); |
| 103 | 93 | 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 | + )) | |
| 118 | 99 | } |
| 119 | 100 | |
| 120 | 101 | // The offline page (shown by the service worker when a page load finds the server down) and its |
| @@ -124,34 +105,12 @@ const OFFLINE_JS: &str = include_str!("../../../forge-web/assets/offline.js"); | ||
| 124 | 105 | |
| 125 | 106 | #[route(GET "/assets/offline.html")] |
| 126 | 107 | 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)) | |
| 139 | 109 | } |
| 140 | 110 | |
| 141 | 111 | #[route(GET "/assets/offline.js")] |
| 142 | 112 | 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)) | |
| 155 | 114 | } |
| 156 | 115 | |
| 157 | 116 | /// The stream every page and the offline page watch to learn that the server is back. It carries |
| @@ -186,93 +145,62 @@ const FIGTREE_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/Figtree-O | ||
| 186 | 145 | const PLEX_MONO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/IBMPlexMono-OFL.txt"); |
| 187 | 146 | const ARCHIVO_LICENSE: &[u8] = include_bytes!("../../../../style/fonts/Archivo-OFL.txt"); |
| 188 | 147 | |
| 189 | -type Bytes = (StatusCode, HeaderMap, &'static [u8]); | |
| 190 | - | |
| 191 | -fn bytes_response(body: &'static [u8], content_type: &'static str, cache: &'static str) -> Bytes { | |
| 192 | - let mut headers = HeaderMap::new(); | |
| 193 | - headers.insert( | |
| 194 | - header::CONTENT_TYPE, | |
| 195 | - content_type.parse().expect("static header value"), | |
| 196 | - ); | |
| 197 | - headers.insert( | |
| 198 | - header::CACHE_CONTROL, | |
| 199 | - cache.parse().expect("static header value"), | |
| 200 | - ); | |
| 201 | - (StatusCode::OK, headers, body) | |
| 202 | -} | |
| 203 | - | |
| 204 | 148 | const FONT_CACHE: &str = "public, max-age=31536000, immutable"; |
| 205 | 149 | const LICENSE_CACHE: &str = "public, max-age=86400"; |
| 206 | 150 | |
| 207 | 151 | #[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)) | |
| 210 | 154 | } |
| 211 | 155 | |
| 212 | 156 | #[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)) | |
| 215 | 159 | } |
| 216 | 160 | |
| 217 | 161 | #[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)) | |
| 220 | 164 | } |
| 221 | 165 | |
| 222 | 166 | #[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)) | |
| 225 | 169 | } |
| 226 | 170 | |
| 227 | 171 | #[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)) | |
| 230 | 174 | } |
| 231 | 175 | |
| 232 | 176 | #[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)) | |
| 235 | 179 | } |
| 236 | 180 | |
| 237 | 181 | #[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)) | |
| 240 | 184 | } |
| 241 | 185 | |
| 242 | 186 | #[route(GET "/assets/fonts/ibm-plex-mono-2.5.0-400-italic.woff2")] |
| 243 | -async fn plex_mono_400_italic(cx: &Cx) -> Result<Bytes> { | |
| 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)) | |
| 249 | 189 | } |
| 250 | 190 | |
| 251 | 191 | #[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)) | |
| 258 | 194 | } |
| 259 | 195 | |
| 260 | 196 | #[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)) | |
| 267 | 199 | } |
| 268 | 200 | |
| 269 | 201 | #[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)) | |
| 276 | 204 | } |
| 277 | 205 | |
| 278 | 206 | #[cfg(test)] |
crates/forge-web-account/src/pages/audit_log.rsmodified+15 -37
| @@ -50,9 +50,6 @@ pub(crate) struct AuditQuery { | ||
| 50 | 50 | to: Option<String>, |
| 51 | 51 | exact: Option<String>, |
| 52 | 52 | case: Option<String>, |
| 53 | - /// Old cursor links. Still accepted so old bookmarks load, and ignored. | |
| 54 | - #[allow(dead_code)] | |
| 55 | - before: Option<String>, | |
| 56 | 53 | /// The 1-based page number. Anything unreadable is page 1. |
| 57 | 54 | page: Option<String>, |
| 58 | 55 | } |
| @@ -196,27 +193,12 @@ impl Group { | ||
| 196 | 193 | &self.rows[0] |
| 197 | 194 | } |
| 198 | 195 | |
| 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()); | |
| 202 | 199 | self.rows |
| 203 | 200 | .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) | |
| 220 | 202 | .then_some(first) |
| 221 | 203 | } |
| 222 | 204 | } |
| @@ -298,9 +280,10 @@ fn details_words(lang: Lang, data: &str) -> String { | ||
| 298 | 280 | } |
| 299 | 281 | |
| 300 | 282 | 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() | |
| 304 | 287 | }; |
| 305 | 288 | let name = if entry.target_name.is_empty() { |
| 306 | 289 | entry.target_id.as_str() |
| @@ -369,19 +352,14 @@ fn requested_page(query: &AuditQuery) -> u64 { | ||
| 369 | 352 | } |
| 370 | 353 | |
| 371 | 354 | /// The groups of one page, the page clamped to the pages there are, and the page count. |
| 372 | -fn page_of(mut groups: Vec<Group>, page: u64) -> (Vec<Group>, u64, u64) { | |
| 355 | +fn page_of(groups: Vec<Group>, page: u64) -> (Vec<Group>, u64, u64) { | |
| 373 | 356 | let pages = (groups.len() as u64).div_ceil(PAGE_ROWS as u64).max(1); |
| 374 | 357 | let page = page.clamp(1, pages); |
| 375 | 358 | let start = (page - 1) as usize * PAGE_ROWS; |
| 376 | - let shown: Vec<Group> = groups.drain(..).skip(start).take(PAGE_ROWS).collect(); | |
| 359 | + let shown: Vec<Group> = groups.into_iter().skip(start).take(PAGE_ROWS).collect(); | |
| 377 | 360 | (shown, page, pages) |
| 378 | 361 | } |
| 379 | 362 | |
| 380 | -/// The newest entries the filter selects, as many as a search reads. | |
| 381 | -async fn fetch_entries(store: &Store, filter: &AuditFilter) -> forge_core::Result<Vec<AuditEntry>> { | |
| 382 | - store.list_audit_page(filter, 0, SEARCH_CAP).await | |
| 383 | -} | |
| 384 | - | |
| 385 | 363 | /// The numbered pager's entries and links for `page` of `pages`, under `base` with `params`. |
| 386 | 364 | fn nav_for( |
| 387 | 365 | page: u64, |
| @@ -523,13 +501,13 @@ async fn single_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) -> | ||
| 523 | 501 | #[component] |
| 524 | 502 | async fn group_row(cx: &Cx, lang: Lang, mut group: Group, show_actor: bool) -> Result<impl View> { |
| 525 | 503 | let count = group.rows.len().to_string(); |
| 526 | - let target = group.shared_target().map(str::to_owned); | |
| 504 | + let target = group.shared(|row| &row.target).map(str::to_owned); | |
| 527 | 505 | let ip = group |
| 528 | - .shared_ip() | |
| 506 | + .shared(|row| &row.ip) | |
| 529 | 507 | .map(str::to_owned) |
| 530 | 508 | .filter(|ip| !ip.is_empty()); |
| 531 | 509 | let details = group |
| 532 | - .shared_details() | |
| 510 | + .shared(|row| &row.details) | |
| 533 | 511 | .map(str::to_owned) |
| 534 | 512 | .filter(|d| !d.is_empty()); |
| 535 | 513 | let mut seen: Vec<String> = group.rows.iter().map(|row| row.target.clone()).collect(); |
| @@ -702,7 +680,7 @@ async fn admin_audit_page(cx: &Cx) -> Result<impl View> { | ||
| 702 | 680 | let entries = if notice.is_some() { |
| 703 | 681 | Vec::new() |
| 704 | 682 | } else { |
| 705 | - fetch_entries(store, &filter).await? | |
| 683 | + store.list_audit_page(&filter, 0, SEARCH_CAP).await? | |
| 706 | 684 | }; |
| 707 | 685 | let groups = fold_groups(&entries, lang, &finder); |
| 708 | 686 | let total = groups.iter().map(|group| group.rows.len()).sum(); |
| @@ -778,7 +756,7 @@ async fn own_log_page(cx: &Cx) -> Result<impl View> { | ||
| 778 | 756 | if let Some(known) = AuditAction::parse(&action) { |
| 779 | 757 | filter.action = Some(known); |
| 780 | 758 | } |
| 781 | - let entries = fetch_entries(store, &filter).await?; | |
| 759 | + let entries = store.list_audit_page(&filter, 0, SEARCH_CAP).await?; | |
| 782 | 760 | let groups = fold_groups(&entries, lang, &finder); |
| 783 | 761 | let total = groups.iter().map(|group| group.rows.len()).sum(); |
| 784 | 762 | let (groups, page, pages) = page_of(groups, requested_page(query)); |
crates/forge-web-account/src/pages/explore.rsmodified+22 -14
| @@ -65,7 +65,11 @@ fn orgs_href(finder: &Finder, page: u64) -> String { | ||
| 65 | 65 | } |
| 66 | 66 | |
| 67 | 67 | /// The organizations the search matches, by name, and how many there are: one page. |
| 68 | -async fn org_listing(state: &AppState, finder: &Finder, page: u64) -> Result<(Vec<User>, u64)> { | |
| 68 | +async fn org_listing( | |
| 69 | + state: &AppState, | |
| 70 | + finder: &Finder, | |
| 71 | + page: u64, | |
| 72 | +) -> Result<(Vec<User>, u64, u64)> { | |
| 69 | 73 | let mut all: Vec<User> = state |
| 70 | 74 | .store |
| 71 | 75 | .list_orgs() |
| @@ -80,12 +84,13 @@ async fn org_listing(state: &AppState, finder: &Finder, page: u64) -> Result<(Ve | ||
| 80 | 84 | .collect(); |
| 81 | 85 | all.sort_by_key(|org| org.username.to_lowercase()); |
| 82 | 86 | let total = all.len() as u64; |
| 87 | + let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1)); | |
| 83 | 88 | let shown = all |
| 84 | 89 | .into_iter() |
| 85 | - .skip(((page.max(1) - 1) * PER_PAGE) as usize) | |
| 90 | + .skip(((page - 1) * PER_PAGE) as usize) | |
| 86 | 91 | .take(PER_PAGE as usize) |
| 87 | 92 | .collect(); |
| 88 | - Ok((shown, total)) | |
| 93 | + Ok((shown, total, page)) | |
| 89 | 94 | } |
| 90 | 95 | |
| 91 | 96 | /// `/explore` with the given search, sort key and page. An empty search is left out. |
| @@ -129,7 +134,7 @@ async fn listing( | ||
| 129 | 134 | finder: &Finder, |
| 130 | 135 | sort: &'static str, |
| 131 | 136 | page: u64, |
| 132 | -) -> Result<(Vec<(Repo, u64, String)>, u64)> { | |
| 137 | +) -> Result<(Vec<(Repo, u64, String)>, u64, u64)> { | |
| 133 | 138 | let sort_kind = match sort { |
| 134 | 139 | "stars" => RepoSort::MostStars, |
| 135 | 140 | "name" => RepoSort::Name, |
| @@ -147,26 +152,30 @@ async fn listing( | ||
| 147 | 152 | }) |
| 148 | 153 | .collect(); |
| 149 | 154 | let total = matching.len() as u64; |
| 155 | + let page = page.clamp(1, total.div_ceil(PER_PAGE).max(1)); | |
| 150 | 156 | let shown = matching |
| 151 | 157 | .into_iter() |
| 152 | - .skip(((page.max(1) - 1) * PER_PAGE) as usize) | |
| 158 | + .skip(((page - 1) * PER_PAGE) as usize) | |
| 153 | 159 | .take(PER_PAGE as usize) |
| 154 | 160 | .collect(); |
| 155 | - Ok((shown, total)) | |
| 161 | + Ok((shown, total, page)) | |
| 156 | 162 | } |
| 157 | 163 | |
| 158 | 164 | #[page("/explore")] |
| 159 | 165 | async fn explore_page(cx: &Cx) -> Result<impl View> { |
| 160 | 166 | let query = query_params::<ExploreQuery>(cx)?; |
| 161 | 167 | let (finder, sort, page) = listing_args(query); |
| 162 | - let live = explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1); | |
| 163 | 168 | let viewer = current_user(cx).await?; |
| 164 | 169 | let lang = i18n::lang(cx, viewer.as_ref().map(|(u, _)| u)); |
| 165 | 170 | let state = context::<AppState>(cx); |
| 166 | 171 | 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 | + }; | |
| 170 | 179 | let (_, repos_all) = state |
| 171 | 180 | .store |
| 172 | 181 | .list_public_repos(None, RepoSort::RecentlyUpdated, 1, 1) |
| @@ -175,7 +184,7 @@ async fn explore_page(cx: &Cx) -> Result<impl View> { | ||
| 175 | 184 | let live = if on_orgs { |
| 176 | 185 | orgs_href(&finder, page).replacen("/explore?", "/explore/events?", 1) |
| 177 | 186 | } else { |
| 178 | - live | |
| 187 | + explore_href(&finder, sort, page).replacen("/explore?", "/explore/events?", 1) | |
| 179 | 188 | }; |
| 180 | 189 | |
| 181 | 190 | let now = now_unix(); |
| @@ -191,7 +200,6 @@ async fn explore_page(cx: &Cx) -> Result<impl View> { | ||
| 191 | 200 | orgs.push((org.username, avatar)); |
| 192 | 201 | } |
| 193 | 202 | let pages = total.div_ceil(PER_PAGE).max(1); |
| 194 | - let page = page.min(pages); | |
| 195 | 203 | let sort_links: Vec<SortLink> = SORTS |
| 196 | 204 | .iter() |
| 197 | 205 | .map(|(key, label)| SortLink { |
| @@ -255,12 +263,12 @@ async fn explore_fingerprint( | ||
| 255 | 263 | on_orgs: bool, |
| 256 | 264 | ) -> Result<String> { |
| 257 | 265 | if on_orgs { |
| 258 | - let (orgs, total) = org_listing(state, finder, page).await?; | |
| 266 | + let (orgs, total, _) = org_listing(state, finder, page).await?; | |
| 259 | 267 | let mut lines = vec![total.to_string()]; |
| 260 | 268 | lines.extend(orgs.into_iter().map(|org| format!("org {}", org.username))); |
| 261 | 269 | return Ok(lines.join("\n")); |
| 262 | 270 | } |
| 263 | - let (listed, total) = listing(state, finder, sort, page).await?; | |
| 271 | + let (listed, total, _) = listing(state, finder, sort, page).await?; | |
| 264 | 272 | let mut lines = vec![total.to_string()]; |
| 265 | 273 | for (repo, stars, activity) in listed { |
| 266 | 274 | lines.push(format!( |
crates/forge-web-account/src/pages/forgot.rsmodified+4 -6
| @@ -221,9 +221,7 @@ async fn reset_submit(cx: &Cx, Form(form): Form<ResetForm>) -> Result<impl View> | ||
| 221 | 221 | Some(user_id) => { |
| 222 | 222 | // The link is spent before the slow hash, so two redemptions cannot both pass. |
| 223 | 223 | 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?; | |
| 227 | 225 | if let Some(user) = state.store.user_by_id(&user_id).await? { |
| 228 | 226 | audit::record( |
| 229 | 227 | &state.store, |
| @@ -300,9 +298,9 @@ mod tests { | ||
| 300 | 298 | assert_eq!(status, 200, "{address}"); |
| 301 | 299 | assert!(html.contains("a reset link is on its way"), "{address}"); |
| 302 | 300 | } |
| 303 | - // Give the spawned lookups time to finish, then check that nothing was queued: Frank 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 | + } | |
| 306 | 304 | let mail = state.store.recent_mail(20).await.unwrap(); |
| 307 | 305 | assert!(mail.iter().all(|m| !m.body.contains("/reset/"))); |
| 308 | 306 | } |
crates/forge-web-account/src/pages/import.rsmodified+26 -120
| @@ -1,7 +1,3 @@ | ||
| 1 | -//! Pages: import a repository (`/new/import`), import several (`/new/import/bulk`), and watch an | |
| 2 | -//! import (`/import`, `/import/{id}`). The job page follows its event stream (`data-live`), so it | |
| 3 | -//! updates as the import runs with no polling and no reload. | |
| 4 | - | |
| 5 | 1 | use std::collections::HashMap; |
| 6 | 2 | |
| 7 | 3 | use forge_core::store::imports::{ImportJob, ImportState}; |
| @@ -21,7 +17,7 @@ use crate::audit::{self, Actor, Target}; | ||
| 21 | 17 | use crate::auth::{require_csrf, require_user}; |
| 22 | 18 | use crate::i18n::migrate::{self as g, K}; |
| 23 | 19 | use crate::i18n::{self, Lang}; |
| 24 | -use crate::importer::api::{ApiError, RemoteApi}; | |
| 20 | +use crate::importer::api::{ApiError, ExtRepo, RemoteApi}; | |
| 25 | 21 | use crate::importer::{ |
| 26 | 22 | self, ImportOptions, JobSpec, Source, default_name, make_forgejo, make_github, make_gitlab, |
| 27 | 23 | parse_remote, source_ref, |
| @@ -37,7 +33,6 @@ use crate::views::{alert, csrf_field, rel_time, shell, user_facing_message}; | ||
| 37 | 33 | |
| 38 | 34 | path_param!(job_id); |
| 39 | 35 | |
| 40 | -/// Most repositories one bulk submit starts. | |
| 41 | 36 | const MAX_BULK: usize = 50; |
| 42 | 37 | const DEFAULT_BRANCH: &str = "main"; |
| 43 | 38 | |
| @@ -99,7 +94,6 @@ struct BulkForm { | ||
| 99 | 94 | opt_pulls: String, |
| 100 | 95 | #[serde(default)] |
| 101 | 96 | opt_releases: String, |
| 102 | - /// The ticked repositories arrive as `sel_0`, `sel_1`, ... with the repository as the value. | |
| 103 | 97 | #[serde(flatten)] |
| 104 | 98 | extra: HashMap<String, String>, |
| 105 | 99 | } |
| @@ -112,9 +106,7 @@ struct SourceQuery { | ||
| 112 | 106 | |
| 113 | 107 | #[query_params(error = bad_request)] |
| 114 | 108 | struct JobsQuery { |
| 115 | - /// The repositories a bulk import left out, with why, as one line. | |
| 116 | 109 | skipped: Option<String>, |
| 117 | - /// The 1-based page of the history. | |
| 118 | 110 | page: Option<String>, |
| 119 | 111 | } |
| 120 | 112 | |
| @@ -136,7 +128,6 @@ fn source_of(raw: Option<&str>) -> Source { | ||
| 136 | 128 | raw.and_then(Source::parse).unwrap_or(Source::GitHub) |
| 137 | 129 | } |
| 138 | 130 | |
| 139 | -/// The instance a source form starts with. | |
| 140 | 131 | fn default_instance(source: Source) -> &'static str { |
| 141 | 132 | match source { |
| 142 | 133 | Source::Forgejo => "https://codeberg.org", |
| @@ -144,7 +135,6 @@ fn default_instance(source: Source) -> &'static str { | ||
| 144 | 135 | } |
| 145 | 136 | } |
| 146 | 137 | |
| 147 | -/// Sources that are self-hostable and so take an instance address. | |
| 148 | 138 | fn has_instance(source: Source) -> bool { |
| 149 | 139 | matches!(source, Source::GitLab | Source::Forgejo) |
| 150 | 140 | } |
| @@ -162,8 +152,6 @@ fn token_of(raw: &str) -> Option<String> { | ||
| 162 | 152 | (!t.is_empty()).then(|| t.to_owned()) |
| 163 | 153 | } |
| 164 | 154 | |
| 165 | -// ---- shared pieces ---- | |
| 166 | - | |
| 167 | 155 | #[component] |
| 168 | 156 | pub(crate) async fn newrepo_tabs(cx: &Cx, lang: Lang, active: &str) -> Result<impl View> { |
| 169 | 157 | let create = active == "create"; |
| @@ -197,7 +185,6 @@ async fn source_tabs(cx: &Cx, lang: Lang, base: &str, active: Source) -> Result< | ||
| 197 | 185 | }) |
| 198 | 186 | } |
| 199 | 187 | |
| 200 | -/// Public or private, as two switches with what each means under it. Shared with the create page. | |
| 201 | 188 | #[component] |
| 202 | 189 | pub(crate) async fn visibility_pick(cx: &Cx, lang: Lang, private: bool) -> Result<impl View> { |
| 203 | 190 | Ok(view! { |
| @@ -226,8 +213,6 @@ async fn option_boxes(cx: &Cx, lang: Lang, opts: ImportOptions) -> Result<impl V | ||
| 226 | 213 | }) |
| 227 | 214 | } |
| 228 | 215 | |
| 229 | -// ---- single import ---- | |
| 230 | - | |
| 231 | 216 | struct Draft { |
| 232 | 217 | source: Source, |
| 233 | 218 | remote: String, |
| @@ -260,7 +245,6 @@ impl Draft { | ||
| 260 | 245 | } |
| 261 | 246 | } |
| 262 | 247 | |
| 263 | - /// The submitted values, never the token. | |
| 264 | 248 | fn from_form(form: &ImportForm, source: Source) -> Self { |
| 265 | 249 | Draft { |
| 266 | 250 | source, |
| @@ -325,7 +309,7 @@ async fn import_form( | ||
| 325 | 309 | let opts = draft.opts; |
| 326 | 310 | Ok(view! { |
| 327 | 311 | head(title: g::t(lang, K::ImportTitle)) |
| 328 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 312 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 329 | 313 | newrepo_tabs(lang: lang, active: "import") |
| 330 | 314 | <div class="sheet fit"> |
| 331 | 315 | <form method="post" action="/new/import" class="fields"> |
| @@ -389,7 +373,6 @@ async fn import_form( | ||
| 389 | 373 | }) |
| 390 | 374 | } |
| 391 | 375 | |
| 392 | -/// The GET import page: the form. Past imports are on the Import history tab. | |
| 393 | 376 | #[component] |
| 394 | 377 | async fn import_home( |
| 395 | 378 | cx: &Cx, |
| @@ -404,7 +387,6 @@ async fn import_home( | ||
| 404 | 387 | }) |
| 405 | 388 | } |
| 406 | 389 | |
| 407 | -/// The import form again after a rejected submit. | |
| 408 | 390 | #[component] |
| 409 | 391 | async fn import_error_body( |
| 410 | 392 | cx: &Cx, |
| @@ -454,8 +436,6 @@ async fn import_submit(cx: &Cx, Form(form): Form<ImportForm>) -> Result<impl Vie | ||
| 454 | 436 | } |
| 455 | 437 | } |
| 456 | 438 | |
| 457 | -/// Validates the form, creates the repo and the job, and starts it. `Ok(Err(message))` is a | |
| 458 | -/// rejection to show; the token is never part of what is returned. | |
| 459 | 439 | async fn start_single( |
| 460 | 440 | cx: &Cx, |
| 461 | 441 | viewer: &User, |
| @@ -519,7 +499,6 @@ async fn start_single( | ||
| 519 | 499 | .await |
| 520 | 500 | } |
| 521 | 501 | |
| 522 | -/// Creates the repo and the import job for `spec` and starts it. `Ok(Err(message))` is a rejection. | |
| 523 | 502 | async fn begin( |
| 524 | 503 | cx: &Cx, |
| 525 | 504 | actor: &User, |
| @@ -558,9 +537,10 @@ async fn begin( | ||
| 558 | 537 | }; |
| 559 | 538 | let path = repo_path(&state.config.data_dir, &repo.id)?; |
| 560 | 539 | if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await { |
| 540 | + state.store.delete_repo(&repo.id).await?; | |
| 561 | 541 | return Ok(Err(crate::i18n::misc::git_init_failed(lang, e))); |
| 562 | 542 | } |
| 563 | - let job = state | |
| 543 | + let job = match state | |
| 564 | 544 | .store |
| 565 | 545 | .create_import_job( |
| 566 | 546 | &actor.id, |
| @@ -569,7 +549,14 @@ async fn begin( | ||
| 569 | 549 | &source_ref(spec.source, &spec.remote, &spec.instance), |
| 570 | 550 | &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()), |
| 571 | 551 | ) |
| 572 | - .await?; | |
| 552 | + .await | |
| 553 | + { | |
| 554 | + Ok(job) => job, | |
| 555 | + Err(e) => { | |
| 556 | + state.store.delete_repo(&repo.id).await?; | |
| 557 | + return Err(e.into()); | |
| 558 | + } | |
| 559 | + }; | |
| 573 | 560 | let full_name = format!("{}/{}", repo.owner_name, repo.name); |
| 574 | 561 | audit::record( |
| 575 | 562 | &state.store, |
| @@ -588,8 +575,6 @@ async fn begin( | ||
| 588 | 575 | Ok(Ok(job.id)) |
| 589 | 576 | } |
| 590 | 577 | |
| 591 | -// ---- bulk import ---- | |
| 592 | - | |
| 593 | 578 | #[component] |
| 594 | 579 | async fn bulk_form( |
| 595 | 580 | cx: &Cx, |
| @@ -609,11 +594,10 @@ async fn bulk_form( | ||
| 609 | 594 | Source::Forgejo => g::t(lang, K::BulkOwnerForgejo), |
| 610 | 595 | _ => g::t(lang, K::BulkOwnerGitHub), |
| 611 | 596 | }; |
| 612 | - // A Forgejo token can list its own repositories, so the owner may stay empty. | |
| 613 | 597 | let owner_required = source != Source::Forgejo; |
| 614 | 598 | Ok(view! { |
| 615 | 599 | head(title: g::t(lang, K::BulkTitle)) |
| 616 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 600 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 617 | 601 | newrepo_tabs(lang: lang, active: "import") |
| 618 | 602 | <div class="sheet fit"> |
| 619 | 603 | <form method="post" action="/new/import/bulk" class="fields"> |
| @@ -645,15 +629,6 @@ async fn bulk_form( | ||
| 645 | 629 | }) |
| 646 | 630 | } |
| 647 | 631 | |
| 648 | -struct Listed { | |
| 649 | - name: String, | |
| 650 | - full_name: String, | |
| 651 | - description: String, | |
| 652 | - private: bool, | |
| 653 | - fork: bool, | |
| 654 | - archived: bool, | |
| 655 | -} | |
| 656 | - | |
| 657 | 632 | #[component] |
| 658 | 633 | async fn bulk_select( |
| 659 | 634 | cx: &Cx, |
| @@ -661,13 +636,11 @@ async fn bulk_select( | ||
| 661 | 636 | username: String, |
| 662 | 637 | csrf: &str, |
| 663 | 638 | form: BulkFormEcho, |
| 664 | - repos: Vec<Listed>, | |
| 639 | + repos: Vec<ExtRepo>, | |
| 665 | 640 | owners: Vec<String>, |
| 666 | 641 | ) -> Result<impl View> { |
| 667 | 642 | let count = repos.len(); |
| 668 | 643 | let empty = repos.is_empty(); |
| 669 | - let private = form.private; | |
| 670 | - let opts = form.opts; | |
| 671 | 644 | let selected_owner = if form.owner.is_empty() { |
| 672 | 645 | owners.first().cloned().unwrap_or_default() |
| 673 | 646 | } else { |
| @@ -675,7 +648,7 @@ async fn bulk_select( | ||
| 675 | 648 | }; |
| 676 | 649 | Ok(view! { |
| 677 | 650 | head(title: g::t(lang, K::BulkSelectHeading)) |
| 678 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 651 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 679 | 652 | newrepo_tabs(lang: lang, active: "import") |
| 680 | 653 | <div class="sheet"> |
| 681 | 654 | <form method="post" action="/new/import/bulk" class="fields"> |
| @@ -696,10 +669,8 @@ async fn bulk_select( | ||
| 696 | 669 | } |
| 697 | 670 | </select> |
| 698 | 671 | </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 }) | |
| 703 | 674 | <label class="line" data-kb-row=""> |
| 704 | 675 | <input type="checkbox" data-select-all=".import-pick-list"> |
| 705 | 676 | <span class="name">(g::t(lang, K::BulkSelectAll))</span> |
| @@ -732,16 +703,12 @@ async fn bulk_select( | ||
| 732 | 703 | }) |
| 733 | 704 | } |
| 734 | 705 | |
| 735 | -/// The bulk form's values carried to the selection step (the token is in a hidden field, sent back | |
| 736 | -/// once; the server never stores it). | |
| 737 | 706 | struct BulkFormEcho { |
| 738 | 707 | source: String, |
| 739 | 708 | instance: String, |
| 740 | 709 | token: String, |
| 741 | 710 | from: String, |
| 742 | 711 | owner: String, |
| 743 | - private: bool, | |
| 744 | - opts: ImportOptions, | |
| 745 | 712 | } |
| 746 | 713 | |
| 747 | 714 | #[page("/new/import/bulk")] |
| @@ -761,20 +728,14 @@ async fn bulk_page(cx: &Cx) -> Result<impl View> { | ||
| 761 | 728 | }) |
| 762 | 729 | } |
| 763 | 730 | |
| 764 | -fn notice_for(state: &AppState) -> importer::api::Notice { | |
| 765 | - let _ = state; | |
| 766 | - std::sync::Arc::new(|_msg: String| {}) | |
| 767 | -} | |
| 768 | - | |
| 769 | -/// Lists the repos of `from` through the API. The error text is safe to show. | |
| 770 | 731 | async fn list_remote( |
| 771 | 732 | state: &AppState, |
| 772 | 733 | source: Source, |
| 773 | 734 | instance: &str, |
| 774 | 735 | from: &str, |
| 775 | 736 | 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| {}); | |
| 778 | 739 | let listed = match source { |
| 779 | 740 | Source::GitLab => { |
| 780 | 741 | make_gitlab(state, instance, token, notice)? |
| @@ -815,7 +776,6 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> { | ||
| 815 | 776 | |
| 816 | 777 | let from = form.from.trim(); |
| 817 | 778 | let owner_max = if source == Source::GitLab { 20 } else { 1 }; |
| 818 | - // Forgejo lists the token's own repositories for an empty owner. | |
| 819 | 779 | let own_repos = source == Source::Forgejo && from.is_empty() && token_of(&form.token).is_some(); |
| 820 | 780 | let bad_owner = !own_repos && !crate::importer::api::valid_path(from, 1, owner_max); |
| 821 | 781 | let result = if bad_owner { |
| @@ -826,32 +786,14 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> { | ||
| 826 | 786 | let (error, picker) = match result { |
| 827 | 787 | Err(message) => (Some(message), None), |
| 828 | 788 | Ok(found) => { |
| 829 | - let repos: Vec<Listed> = found | |
| 830 | - .into_iter() | |
| 831 | - .map(|r| Listed { | |
| 832 | - name: r.name, | |
| 833 | - full_name: r.full_name, | |
| 834 | - description: r.description, | |
| 835 | - private: r.private, | |
| 836 | - fork: r.fork, | |
| 837 | - archived: r.archived, | |
| 838 | - }) | |
| 839 | - .collect(); | |
| 840 | 789 | let echo = BulkFormEcho { |
| 841 | 790 | source: source.as_str().to_owned(), |
| 842 | 791 | instance: instance.clone(), |
| 843 | 792 | token: form.token.trim().to_owned(), |
| 844 | 793 | from: from.to_owned(), |
| 845 | 794 | owner: form.owner.trim().to_owned(), |
| 846 | - private: false, | |
| 847 | - opts: ImportOptions { | |
| 848 | - labels: true, | |
| 849 | - issues: true, | |
| 850 | - pulls: true, | |
| 851 | - releases: true, | |
| 852 | - }, | |
| 853 | 795 | }; |
| 854 | - (None, Some((echo, repos))) | |
| 796 | + (None, Some((echo, found))) | |
| 855 | 797 | } |
| 856 | 798 | }; |
| 857 | 799 | Ok(view! { |
| @@ -860,7 +802,6 @@ async fn bulk_submit(cx: &Cx, Form(form): Form<BulkForm>) -> Result<impl View> { | ||
| 860 | 802 | }) |
| 861 | 803 | } |
| 862 | 804 | |
| 863 | -/// The bulk page body: the picker once a listing exists, the lookup form otherwise. | |
| 864 | 805 | #[component] |
| 865 | 806 | async fn bulk_stage( |
| 866 | 807 | cx: &Cx, |
| @@ -871,7 +812,7 @@ async fn bulk_stage( | ||
| 871 | 812 | instance: &str, |
| 872 | 813 | owners: Vec<String>, |
| 873 | 814 | error: Option<String>, |
| 874 | - picker: Option<(BulkFormEcho, Vec<Listed>)>, | |
| 815 | + picker: Option<(BulkFormEcho, Vec<ExtRepo>)>, | |
| 875 | 816 | ) -> Result<impl View> { |
| 876 | 817 | Ok(view! { |
| 877 | 818 | if let Some((echo, repos)) = picker { |
| @@ -882,7 +823,6 @@ async fn bulk_stage( | ||
| 882 | 823 | }) |
| 883 | 824 | } |
| 884 | 825 | |
| 885 | -/// Starts one job per ticked repository, then shows the imports list. | |
| 886 | 826 | async fn run_bulk( |
| 887 | 827 | cx: &Cx, |
| 888 | 828 | viewer: &User, |
| @@ -948,8 +888,6 @@ async fn run_bulk( | ||
| 948 | 888 | options, |
| 949 | 889 | }; |
| 950 | 890 | let name = default_name(&remote); |
| 951 | - // The repository from a failed import of this source is there already: retry that import | |
| 952 | - // instead of refusing the name as taken. | |
| 953 | 891 | if let Some(repo) = state |
| 954 | 892 | .store |
| 955 | 893 | .repo_by_owner_and_name(&target.username, &name) |
| @@ -961,7 +899,6 @@ async fn run_bulk( | ||
| 961 | 899 | retry_job(state, job.clone(), &form.token).await?; |
| 962 | 900 | continue; |
| 963 | 901 | } |
| 964 | - // A name already taken, or any refusal, skips that one; the list page says which and why. | |
| 965 | 902 | if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? { |
| 966 | 903 | tracing::info!(repo = %remote, %message, "bulk import: skipped a repository"); |
| 967 | 904 | skipped.push(format!("{name} ({message})")); |
| @@ -978,8 +915,6 @@ async fn run_bulk( | ||
| 978 | 915 | Err(see_other(format!("/import?skipped={}", crate::views::enc(&list))).into()) |
| 979 | 916 | } |
| 980 | 917 | |
| 981 | -// ---- jobs ---- | |
| 982 | - | |
| 983 | 918 | fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) { |
| 984 | 919 | match state { |
| 985 | 920 | ImportState::Queued => ("badge", g::t(lang, K::JobQueued)), |
| @@ -1001,8 +936,6 @@ fn stage_name(lang: Lang, stage: &str) -> &'static str { | ||
| 1001 | 936 | } |
| 1002 | 937 | } |
| 1003 | 938 | |
| 1004 | -/// The job's repository, once it exists and while `user` may still read it: an import into an | |
| 1005 | -/// org the user has since left, or a repo transferred away, is not named. | |
| 1006 | 939 | async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Result<Option<Repo>> { |
| 1007 | 940 | let Some(id) = &job.repo_id else { |
| 1008 | 941 | return Ok(None); |
| @@ -1013,7 +946,6 @@ async fn job_repo(state: &AppState, user: Option<&User>, job: &ImportJob) -> Res | ||
| 1013 | 946 | Ok(state.store.repo_by_id(id).await?) |
| 1014 | 947 | } |
| 1015 | 948 | |
| 1016 | -/// The user's newest import jobs, each with its repository once it exists. | |
| 1017 | 949 | async fn load_job_rows( |
| 1018 | 950 | state: &AppState, |
| 1019 | 951 | user_id: &str, |
| @@ -1029,7 +961,6 @@ async fn load_job_rows( | ||
| 1029 | 961 | Ok(rows) |
| 1030 | 962 | } |
| 1031 | 963 | |
| 1032 | -/// The import job rows, shared by the Import history page and the recent list on the Import tab. | |
| 1033 | 964 | #[component] |
| 1034 | 965 | async fn job_rows(cx: &Cx, lang: Lang, jobs: Vec<(ImportJob, Option<Repo>)>) -> Result<impl View> { |
| 1035 | 966 | Ok(view! { |
| @@ -1066,7 +997,7 @@ async fn jobs_list( | ||
| 1066 | 997 | let retry = jobs.iter().any(|(job, _)| job.state == ImportState::Failed); |
| 1067 | 998 | Ok(view! { |
| 1068 | 999 | head(title: g::t(lang, K::JobsTitle), live: Some("/import/events")) |
| 1069 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 1000 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 1070 | 1001 | newrepo_tabs(lang: lang, active: "history") |
| 1071 | 1002 | <div class="sheet"> |
| 1072 | 1003 | if retry { |
| @@ -1090,7 +1021,6 @@ async fn jobs_list( | ||
| 1090 | 1021 | }) |
| 1091 | 1022 | } |
| 1092 | 1023 | |
| 1093 | -/// What the import list shows for `user_id`: each job's id, state, source and repo, in list order. | |
| 1094 | 1024 | async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> { |
| 1095 | 1025 | let rows = load_job_rows(state, user_id, 50).await?; |
| 1096 | 1026 | Ok(rows |
| @@ -1110,8 +1040,6 @@ async fn jobs_fingerprint(state: &AppState, user_id: &str) -> Result<String> { | ||
| 1110 | 1040 | .join("\n")) |
| 1111 | 1041 | } |
| 1112 | 1042 | |
| 1113 | -/// The import list's change stream: the viewer's own jobs, from the session only. It sends when the | |
| 1114 | -/// list would show something different (see [`Topic::Imports`]). | |
| 1115 | 1043 | #[route(GET "/import/events")] |
| 1116 | 1044 | async fn jobs_events(cx: &Cx) -> Result<Response> { |
| 1117 | 1045 | let viewer = require_user(cx).await?; |
| @@ -1130,7 +1058,6 @@ async fn jobs_events(cx: &Cx) -> Result<Response> { | ||
| 1130 | 1058 | .await |
| 1131 | 1059 | } |
| 1132 | 1060 | |
| 1133 | -/// Imports per page of the history. | |
| 1134 | 1061 | const HISTORY_ROWS: u64 = 10; |
| 1135 | 1062 | |
| 1136 | 1063 | #[page("/import")] |
| @@ -1147,7 +1074,6 @@ async fn jobs_page(cx: &Cx) -> Result<impl View> { | ||
| 1147 | 1074 | .and_then(|p| p.parse::<u64>().ok()) |
| 1148 | 1075 | .unwrap_or(1) |
| 1149 | 1076 | .clamp(1, pages); |
| 1150 | - // Only the shown page's repos are looked up. | |
| 1151 | 1077 | let user = state.store.user_by_id(&viewer.0.id).await?; |
| 1152 | 1078 | let mut rows = Vec::new(); |
| 1153 | 1079 | for job in all |
| @@ -1206,7 +1132,7 @@ async fn job_view( | ||
| 1206 | 1132 | }]; |
| 1207 | 1133 | Ok(view! { |
| 1208 | 1134 | head(title: job.source_ref.as_str(), sub: sub, live: live.as_deref()) |
| 1209 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 1135 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 1210 | 1136 | newrepo_tabs(lang: lang, active: "history") |
| 1211 | 1137 | <div class="sheet import-job" data-live-state=(state_word)> |
| 1212 | 1138 | <section class="sec"> |
| @@ -1262,7 +1188,6 @@ async fn job_view( | ||
| 1262 | 1188 | }) |
| 1263 | 1189 | } |
| 1264 | 1190 | |
| 1265 | -/// The job when the viewer owns it. Anyone else gets 404. | |
| 1266 | 1191 | async fn owned_job(cx: &Cx, viewer: &User) -> Result<ImportJob> { |
| 1267 | 1192 | let id = job_id(cx).to_owned(); |
| 1268 | 1193 | let state = context::<AppState>(cx); |
| @@ -1288,8 +1213,6 @@ async fn job_page(cx: &Cx) -> Result<impl View> { | ||
| 1288 | 1213 | }) |
| 1289 | 1214 | } |
| 1290 | 1215 | |
| 1291 | -/// The job's `changed` stream. It sends when the job differs from the version the page was | |
| 1292 | -/// rendered with, then on every change, and ends once the job is finished. | |
| 1293 | 1216 | #[route(GET "/import/{job_id}/events")] |
| 1294 | 1217 | async fn job_events(cx: &Cx) -> Result<Response> { |
| 1295 | 1218 | let viewer = require_user(cx).await?; |
| @@ -1297,7 +1220,6 @@ async fn job_events(cx: &Cx) -> Result<Response> { | ||
| 1297 | 1220 | let query = query_params::<SeenQuery>(cx)?; |
| 1298 | 1221 | let state = context::<AppState>(cx); |
| 1299 | 1222 | let seen = query.v.clone().unwrap_or_default(); |
| 1300 | - // Subscribed before the job is read again below, so a change in between is not lost. | |
| 1301 | 1223 | let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id)); |
| 1302 | 1224 | let store = state.store.clone(); |
| 1303 | 1225 | let id = job.id.clone(); |
| @@ -1337,9 +1259,6 @@ struct RetryForm { | ||
| 1337 | 1259 | token: String, |
| 1338 | 1260 | } |
| 1339 | 1261 | |
| 1340 | -/// Re-queues a failed import and starts it again; what was imported before is skipped. `Ok(false)` | |
| 1341 | -/// when nothing was started: the job is not failed, its source or remote does not parse, or its | |
| 1342 | -/// repository already has an import running. | |
| 1343 | 1262 | async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool> { |
| 1344 | 1263 | if job.state != ImportState::Failed { |
| 1345 | 1264 | return Ok(false); |
| @@ -1350,16 +1269,10 @@ async fn retry_job(state: &AppState, job: ImportJob, token: &str) -> Result<bool | ||
| 1350 | 1269 | let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else { |
| 1351 | 1270 | return Ok(false); |
| 1352 | 1271 | }; |
| 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? { | |
| 1356 | 1274 | return Ok(false); |
| 1357 | 1275 | } |
| 1358 | - let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default(); | |
| 1359 | - state | |
| 1360 | - .store | |
| 1361 | - .set_import_state(&job.id, ImportState::Queued, None) | |
| 1362 | - .await?; | |
| 1363 | 1276 | state |
| 1364 | 1277 | .store |
| 1365 | 1278 | .add_import_event( |
| @@ -1390,10 +1303,6 @@ async fn job_retry(cx: &Cx, Form(form): Form<RetryForm>) -> Result<SeeOther> { | ||
| 1390 | 1303 | Err(see_other(href).into()) |
| 1391 | 1304 | } |
| 1392 | 1305 | |
| 1393 | -// ---- retry several failed imports ---- | |
| 1394 | - | |
| 1395 | -/// The viewer's failed imports whose repository still exists and is readable, with the repository, | |
| 1396 | -/// and no import running on it. Newest first. | |
| 1397 | 1306 | async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(ImportJob, Repo)>> { |
| 1398 | 1307 | let mut rows = Vec::new(); |
| 1399 | 1308 | for job in state.store.list_import_jobs(&viewer.id, 200).await? { |
| @@ -1416,7 +1325,6 @@ async fn retry_candidates(state: &AppState, viewer: &User) -> Result<Vec<(Import | ||
| 1416 | 1325 | Ok(rows) |
| 1417 | 1326 | } |
| 1418 | 1327 | |
| 1419 | -/// The provider's name for a job's source, as the source tabs show it. | |
| 1420 | 1328 | fn source_label(raw: &str) -> &'static str { |
| 1421 | 1329 | Source::parse(raw).map_or("", Source::label) |
| 1422 | 1330 | } |
| @@ -1433,7 +1341,7 @@ async fn retry_list( | ||
| 1433 | 1341 | let empty = rows.is_empty(); |
| 1434 | 1342 | Ok(view! { |
| 1435 | 1343 | head(title: g::t(lang, K::RetryFailedTitle)) |
| 1436 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 1344 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 1437 | 1345 | newrepo_tabs(lang: lang, active: "history") |
| 1438 | 1346 | <div class="sheet"> |
| 1439 | 1347 | <form method="post" action="/import/retry" class="fields"> |
| @@ -1491,7 +1399,6 @@ struct RetrySelectedForm { | ||
| 1491 | 1399 | csrf: String, |
| 1492 | 1400 | #[serde(default)] |
| 1493 | 1401 | token: String, |
| 1494 | - /// The ticked jobs arrive as `sel_0`, `sel_1`, ... with the job id as the value. | |
| 1495 | 1402 | #[serde(flatten)] |
| 1496 | 1403 | extra: HashMap<String, String>, |
| 1497 | 1404 | } |
| @@ -1510,7 +1417,6 @@ async fn retry_submit(cx: &Cx, Form(form): Form<RetrySelectedForm>) -> Result<Se | ||
| 1510 | 1417 | return Err(see_other("/import/retry").into()); |
| 1511 | 1418 | } |
| 1512 | 1419 | for (_, id) in picked { |
| 1513 | - // Only the viewer's own jobs; anything else is skipped without a word. | |
| 1514 | 1420 | let Some(job) = state.store.import_job(id).await? else { |
| 1515 | 1421 | continue; |
| 1516 | 1422 | }; |
crates/forge-web-account/src/pages/login.rsmodified+41 -56
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | use std::time::{Duration, Instant}; |
| 4 | 4 | |
| 5 | -use forge_core::AuditAction; | |
| 5 | +use forge_core::{AuditAction, User}; | |
| 6 | 6 | use forge_core::names::normalize_name; |
| 7 | 7 | use http::header::{HeaderValue, RETRY_AFTER}; |
| 8 | 8 | use serde::Deserialize; |
| @@ -224,17 +224,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | ||
| 224 | 224 | set_pending_login(cx, &state.key, &user.id, &next)?; |
| 225 | 225 | return Err(see_other("/login/2fa").into()); |
| 226 | 226 | } |
| 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?; | |
| 238 | 228 | return Err(see_other(safe_next(Some(&form.next))).into()); |
| 239 | 229 | } |
| 240 | 230 | _ => { |
| @@ -352,18 +342,8 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | ||
| 352 | 342 | match user { |
| 353 | 343 | Some(user) if verified => { |
| 354 | 344 | 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?; | |
| 365 | 346 | clear_pending_login(cx); |
| 366 | - clear_pre_csrf(cx); | |
| 367 | 347 | return Err(see_other(safe_next(Some(&pending.next))).into()); |
| 368 | 348 | } |
| 369 | 349 | _ => { |
| @@ -395,6 +375,26 @@ async fn two_factor_submit(cx: &Cx, Form(form): Form<TwoFactorForm>) -> Result<i | ||
| 395 | 375 | }) |
| 396 | 376 | } |
| 397 | 377 | |
| 378 | +async fn finish_login( | |
| 379 | + cx: &Cx, | |
| 380 | + state: &AppState, | |
| 381 | + user: &User, | |
| 382 | + audit_data: serde_json::Value, | |
| 383 | +) -> Result<()> { | |
| 384 | + login(cx, user).await?; | |
| 385 | + audit::record( | |
| 386 | + &state.store, | |
| 387 | + Some(cx), | |
| 388 | + Actor::User(user), | |
| 389 | + AuditAction::LoginSuccess, | |
| 390 | + Target::default(), | |
| 391 | + audit_data, | |
| 392 | + ) | |
| 393 | + .await; | |
| 394 | + clear_pre_csrf(cx); | |
| 395 | + Ok(()) | |
| 396 | +} | |
| 397 | + | |
| 398 | 398 | /// Whole seconds for a `Retry-After` header, at least 1. |
| 399 | 399 | fn retry_after_secs(retry: Duration) -> u64 { |
| 400 | 400 | retry.as_secs().max(1) |
| @@ -759,6 +759,14 @@ mod tests { | ||
| 759 | 759 | shared.to_vec() |
| 760 | 760 | } |
| 761 | 761 | |
| 762 | + fn live_code(shared: &[u8], ahead: u64) -> String { | |
| 763 | + let now = std::time::SystemTime::now() | |
| 764 | + .duration_since(std::time::UNIX_EPOCH) | |
| 765 | + .unwrap() | |
| 766 | + .as_secs(); | |
| 767 | + totp::code_at(shared, totp::step_for(now) + ahead) | |
| 768 | + } | |
| 769 | + | |
| 762 | 770 | /// Cookie header for the pending login plus the pre-session CSRF cookie. |
| 763 | 771 | fn both(pending: &str, precsrf_cookie: &str) -> String { |
| 764 | 772 | format!("{pending}; {precsrf_cookie}") |
| @@ -832,22 +840,15 @@ mod tests { | ||
| 832 | 840 | let (cookie, precsrf) = login_page(&router, from).await; |
| 833 | 841 | let step = password_step(&router, from, (&cookie, &precsrf), "grace", PASSWORD).await; |
| 834 | 842 | 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" | |
| 849 | 849 | ); |
| 850 | - let code = totp::code_at(&shared, now_step); | |
| 850 | + | |
| 851 | + let code = live_code(&shared, 0); | |
| 851 | 852 | let ok = second_factor_step(&router, from, &pending, &precsrf, &code).await; |
| 852 | 853 | assert_eq!(ok.status, 303, "right code: body {}", ok.body); |
| 853 | 854 | assert_eq!( |
| @@ -922,15 +923,7 @@ mod tests { | ||
| 922 | 923 | let (cookie, precsrf) = login_page(&router, from).await; |
| 923 | 924 | let stale = secret::seal(&state.key, format!("1|{}|/", user.id).as_bytes()).unwrap(); |
| 924 | 925 | 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); | |
| 934 | 927 | let reply = |
| 935 | 928 | second_factor_step(&router, from, &both(&pending, &cookie), &precsrf, &code).await; |
| 936 | 929 | assert_eq!(reply.status, 303, "expired: status"); |
| @@ -954,15 +947,7 @@ mod tests { | ||
| 954 | 947 | let reply = second_factor_step(&router, from, &pending, &precsrf, "111111").await; |
| 955 | 948 | assert_eq!(reply.status, 200, "limit: wrong code"); |
| 956 | 949 | } |
| 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); | |
| 966 | 951 | let blocked = second_factor_step(&router, from, &pending, &precsrf, &code).await; |
| 967 | 952 | assert_eq!(blocked.status, 429, "limit: right code while locked"); |
| 968 | 953 | assert!(blocked.body.contains("Too many attempts"), "limit: message"); |
crates/forge-web-account/src/pages/new_repo.rsmodified+2 -44
| @@ -1,5 +1,3 @@ | ||
| 1 | -//! Page: create a repository (GET/POST /new). | |
| 2 | - | |
| 3 | 1 | use forge_core::mirrors::{DEFAULT_INTERVAL_MINUTES, MirrorDirection, NewMirror}; |
| 4 | 2 | use forge_core::names::validate_name; |
| 5 | 3 | use forge_core::time::now_stamp; |
| @@ -10,7 +8,6 @@ use topcoat::Result; | ||
| 10 | 8 | use topcoat::context::{Cx, context}; |
| 11 | 9 | use topcoat::router::content::Form; |
| 12 | 10 | use topcoat::router::error::see_other; |
| 13 | -// Named by the `#[query_params]` attribute below, which the unused-import lint does not see. | |
| 14 | 11 | #[allow(unused_imports)] |
| 15 | 12 | use topcoat::router::error::bad_request; |
| 16 | 13 | use topcoat::router::{page, query_params}; |
| @@ -29,7 +26,6 @@ use crate::views::{alert, csrf_field, shell, user_facing_message}; | ||
| 29 | 26 | const MAX_DESCRIPTION_CHARS: usize = 350; |
| 30 | 27 | const DEFAULT_BRANCH: &str = "main"; |
| 31 | 28 | |
| 32 | -/// The licenses the form offers, in menu order: SPDX id, menu label and the full SPDX text. | |
| 33 | 29 | const LICENSES: &[(&str, &str, &str)] = &[ |
| 34 | 30 | ( |
| 35 | 31 | "MIT", |
| @@ -93,8 +89,6 @@ const LICENSES: &[(&str, &str, &str)] = &[ | ||
| 93 | 89 | ), |
| 94 | 90 | ]; |
| 95 | 91 | |
| 96 | -/// The LICENSE file for `spdx` with the copyright line filled in. `None` for an id that is not in | |
| 97 | -/// [`LICENSES`]. The placeholders appear only on the copyright line, so the first match is replaced. | |
| 98 | 92 | fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> { |
| 99 | 93 | let (_, _, text) = LICENSES.iter().find(|(id, _, _)| *id == spdx)?; |
| 100 | 94 | let text = match spdx { |
| @@ -109,7 +103,6 @@ fn license_file(spdx: &str, year: &str, holder: &str) -> Option<String> { | ||
| 109 | 103 | Some(text) |
| 110 | 104 | } |
| 111 | 105 | |
| 112 | -/// The README of a new repo: the name as the heading, then the description when there is one. | |
| 113 | 106 | fn readme_text(name: &str, description: &str) -> String { |
| 114 | 107 | let mut text = format!("# {name}\n"); |
| 115 | 108 | if !description.is_empty() { |
| @@ -132,16 +125,12 @@ struct NewRepoForm { | ||
| 132 | 125 | visibility: String, |
| 133 | 126 | #[serde(default)] |
| 134 | 127 | default_branch: String, |
| 135 | - /// The checkbox sends `on` when checked and nothing when unchecked. | |
| 136 | 128 | #[serde(default)] |
| 137 | 129 | default_labels: String, |
| 138 | - /// The "Add a README" checkbox. Present (`on`) when checked, absent otherwise. | |
| 139 | 130 | #[serde(default)] |
| 140 | 131 | add_readme: Option<String>, |
| 141 | - /// The SPDX id from the license select. Blank means no license. | |
| 142 | 132 | #[serde(default)] |
| 143 | 133 | license: String, |
| 144 | - /// The optional "Mirror an existing repository" section. A blank URL means no mirror. | |
| 145 | 134 | #[serde(default)] |
| 146 | 135 | mirror_url: String, |
| 147 | 136 | #[serde(default)] |
| @@ -150,13 +139,10 @@ struct NewRepoForm { | ||
| 150 | 139 | mirror_secret: String, |
| 151 | 140 | #[serde(default)] |
| 152 | 141 | mirror_interval: String, |
| 153 | - /// The account that will own the repo: the viewer's own name, or an org they may create in. | |
| 154 | - /// Blank means the viewer. | |
| 155 | 142 | #[serde(default)] |
| 156 | 143 | owner: String, |
| 157 | 144 | } |
| 158 | 145 | |
| 159 | -/// The form's values, echoed back when validation fails. | |
| 160 | 146 | struct Draft { |
| 161 | 147 | owner: String, |
| 162 | 148 | name: String, |
| @@ -188,7 +174,6 @@ impl Draft { | ||
| 188 | 174 | } |
| 189 | 175 | } |
| 190 | 176 | |
| 191 | - /// The submitted values. The mirror password is never echoed back. | |
| 192 | 177 | fn from_form(form: &NewRepoForm) -> Self { |
| 193 | 178 | Draft { |
| 194 | 179 | owner: form.owner.trim().to_owned(), |
| @@ -230,14 +215,13 @@ async fn new_repo_form( | ||
| 230 | 215 | let default_labels = draft.default_labels; |
| 231 | 216 | let add_readme = draft.add_readme; |
| 232 | 217 | let draft_license = draft.license; |
| 233 | - // A mirror URL in the draft means the form was re-rendered after a validation error. | |
| 234 | 218 | let mirror_open = !draft.mirror_url.is_empty(); |
| 235 | 219 | let draft_mirror_url = draft.mirror_url; |
| 236 | 220 | let draft_mirror_username = draft.mirror_username; |
| 237 | 221 | let draft_mirror_interval = draft.mirror_interval; |
| 238 | 222 | Ok(view! { |
| 239 | 223 | head(title: i18n::t(lang, Key::NewRepository)) |
| 240 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "repositories".to_owned()) | |
| 224 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Repositories) | |
| 241 | 225 | crate::pages::import::newrepo_tabs(lang: lang, active: "create") |
| 242 | 226 | <div class="sheet fit"> |
| 243 | 227 | <form method="post" action="/new" class="fields"> |
| @@ -307,8 +291,6 @@ async fn new_repo_form( | ||
| 307 | 291 | }) |
| 308 | 292 | } |
| 309 | 293 | |
| 310 | -/// The accounts the viewer may create a repo under: themselves, then the orgs where | |
| 311 | -/// `may_create_repo_in` allows it. | |
| 312 | 294 | pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec<String>> { |
| 313 | 295 | let mut names = vec![viewer.username.clone()]; |
| 314 | 296 | for (org, _) in state.store.orgs_for_user(&viewer.id).await? { |
| @@ -319,7 +301,6 @@ pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result<Vec | ||
| 319 | 301 | Ok(names) |
| 320 | 302 | } |
| 321 | 303 | |
| 322 | -/// `/new?owner=acme` preselects that owner. An owner the viewer cannot pick is ignored. | |
| 323 | 304 | #[query_params(error = bad_request)] |
| 324 | 305 | struct NewRepoQuery { |
| 325 | 306 | owner: Option<String>, |
| @@ -361,8 +342,6 @@ async fn new_repo_submit(cx: &Cx, Form(form): Form<NewRepoForm>) -> Result<impl | ||
| 361 | 342 | } |
| 362 | 343 | } |
| 363 | 344 | |
| 364 | -/// The account the new repo belongs to. Blank or the viewer's own name means the viewer. An org | |
| 365 | -/// name is accepted only when the viewer may create repos under it. | |
| 366 | 345 | pub(crate) async fn repo_owner( |
| 367 | 346 | state: &AppState, |
| 368 | 347 | viewer: &User, |
| @@ -383,8 +362,6 @@ pub(crate) async fn repo_owner( | ||
| 383 | 362 | Ok(Ok(org)) |
| 384 | 363 | } |
| 385 | 364 | |
| 386 | -/// Validates the form and creates the repo. `Ok(Err(message))` is a user-facing rejection; | |
| 387 | -/// the outer `Err` is an internal failure. | |
| 388 | 365 | async fn create_repo( |
| 389 | 366 | cx: &Cx, |
| 390 | 367 | owner: &User, |
| @@ -423,7 +400,6 @@ async fn create_repo( | ||
| 423 | 400 | Ok(target) => target, |
| 424 | 401 | Err(message) => return Ok(Err(message)), |
| 425 | 402 | }; |
| 426 | - // The mirror is checked before anything is created, so a refused URL leaves no repo behind. | |
| 427 | 403 | let mirror = if form.mirror_url.trim().is_empty() { |
| 428 | 404 | None |
| 429 | 405 | } else { |
| @@ -463,11 +439,10 @@ async fn create_repo( | ||
| 463 | 439 | |
| 464 | 440 | let path = repo_path(&state.config.data_dir, &repo.id)?; |
| 465 | 441 | if let Err(e) = init_bare(&state.git, &path, branch).await { |
| 466 | - // TODO: delete the repository row so a failed init does not leave a dangling name. | |
| 442 | + state.store.delete_repo(&repo.id).await?; | |
| 467 | 443 | return Ok(Err(g::git_init_failed(lang, e))); |
| 468 | 444 | } |
| 469 | 445 | if want_files { |
| 470 | - // The copyright holder is the account the repo belongs to; the author is the viewer. | |
| 471 | 446 | let year = jiff::Timestamp::now() |
| 472 | 447 | .to_zoned_datetime(jiff::tz::TimeZone::UTC) |
| 473 | 448 | .year() |
| @@ -494,7 +469,6 @@ async fn create_repo( | ||
| 494 | 469 | |
| 495 | 470 | .clone() |
| 496 | 471 | .unwrap_or_else(|| format!("{}@users.noreply.forge", owner.username)); |
| 497 | - // The repo exists already, so a failed commit is logged rather than shown as an error. | |
| 498 | 472 | if let Err(e) = forge_git::seed::initial_commit( |
| 499 | 473 | &state.git, |
| 500 | 474 | &path, |
| @@ -509,8 +483,6 @@ async fn create_repo( | ||
| 509 | 483 | tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not write the initial commit"); |
| 510 | 484 | } |
| 511 | 485 | } |
| 512 | - // The repo already exists at this point, so a label failure is logged rather than shown as an | |
| 513 | - // error page for a repo that was in fact created. | |
| 514 | 486 | if add_default_labels && let Err(e) = state.store.create_default_labels(&repo.id).await { |
| 515 | 487 | tracing::warn!(error = %e, repo_id = %repo.id, "new repo: could not add default labels"); |
| 516 | 488 | } |
| @@ -534,8 +506,6 @@ async fn create_repo( | ||
| 534 | 506 | Ok(Ok(format!("/{}/{}", repo.owner_name, repo.name))) |
| 535 | 507 | } |
| 536 | 508 | |
| 537 | -/// Creates the pull mirror of a new repo and queues its first sync now. The repo is new and empty, | |
| 538 | -/// so a store failure here is an internal error. | |
| 539 | 509 | async fn create_pull_mirror( |
| 540 | 510 | cx: &Cx, |
| 541 | 511 | state: &AppState, |
| @@ -592,8 +562,6 @@ mod tests { | ||
| 592 | 562 | |
| 593 | 563 | const CSRF: &str = "new-repo-test-csrf"; |
| 594 | 564 | |
| 595 | - /// One store and router with `tahinli` signed in. Every scenario below uses its own repo name, | |
| 596 | - /// so they share this site. | |
| 597 | 565 | struct Site { |
| 598 | 566 | store: Store, |
| 599 | 567 | router: Router, |
| @@ -622,8 +590,6 @@ mod tests { | ||
| 622 | 590 | } |
| 623 | 591 | } |
| 624 | 592 | |
| 625 | - /// POSTs `/new` as tahinli for a repo called `name` with the extra fields. Returns the status | |
| 626 | - /// and the repo created, if any. The form's token is the shared CSRF value. | |
| 627 | 593 | async fn post_new( |
| 628 | 594 | site: &Site, |
| 629 | 595 | name: &str, |
| @@ -657,7 +623,6 @@ mod tests { | ||
| 657 | 623 | (status, repo) |
| 658 | 624 | } |
| 659 | 625 | |
| 660 | - /// The default labels are added only when the box is checked. | |
| 661 | 626 | #[tokio::test] |
| 662 | 627 | async fn default_labels_are_added_only_when_checked() { |
| 663 | 628 | let site = site().await; |
| @@ -680,13 +645,10 @@ mod tests { | ||
| 680 | 645 | } |
| 681 | 646 | } |
| 682 | 647 | |
| 683 | - /// Mirror fields: a valid URL makes a pull mirror, a loopback URL is refused and creates | |
| 684 | - /// nothing, and a blank URL makes the repo without a mirror. | |
| 685 | 648 | #[tokio::test] |
| 686 | 649 | async fn mirror_url_decides_whether_a_pull_mirror_is_made() { |
| 687 | 650 | let site = site().await; |
| 688 | 651 | |
| 689 | - // Case: a valid URL creates a pull mirror with the given settings. | |
| 690 | 652 | let (status, repo) = post_new( |
| 691 | 653 | &site, |
| 692 | 654 | "mirror-ok", |
| @@ -723,7 +685,6 @@ mod tests { | ||
| 723 | 685 | "valid mirror: the first sync is due now" |
| 724 | 686 | ); |
| 725 | 687 | |
| 726 | - // Case: a loopback URL shows the form again and creates nothing. | |
| 727 | 688 | let (status, repo) = post_new( |
| 728 | 689 | &site, |
| 729 | 690 | "mirror-loopback", |
| @@ -739,7 +700,6 @@ mod tests { | ||
| 739 | 700 | "loopback: no repo is created for a refused mirror" |
| 740 | 701 | ); |
| 741 | 702 | |
| 742 | - // Case: a blank URL creates the repo without a mirror. | |
| 743 | 703 | let (status, repo) = post_new(&site, "mirror-blank", &[("mirror_url", " ")]).await; |
| 744 | 704 | assert_eq!(status, 303, "blank: status"); |
| 745 | 705 | let repo = repo.expect("blank: the repo is created"); |
| @@ -753,7 +713,6 @@ mod tests { | ||
| 753 | 713 | ); |
| 754 | 714 | } |
| 755 | 715 | |
| 756 | - /// A README and a license make the first commit, and the README has the name and description. | |
| 757 | 716 | #[tokio::test] |
| 758 | 717 | async fn readme_and_license_make_the_first_commit() { |
| 759 | 718 | let site = site().await; |
| @@ -785,7 +744,6 @@ mod tests { | ||
| 785 | 744 | assert!(!license.contains("<year>"), "{license}"); |
| 786 | 745 | } |
| 787 | 746 | |
| 788 | - /// A viewer who chose Turkish gets the Turkish form. | |
| 789 | 747 | #[tokio::test] |
| 790 | 748 | async fn the_form_is_in_turkish_for_a_turkish_viewer() { |
| 791 | 749 | let site = site().await; |
crates/forge-web-account/src/pages/not_found_page.rsmodified+17 -31
| @@ -14,38 +14,24 @@ use crate::i18n::{self, Lang}; | ||
| 14 | 14 | use crate::views::parts::{SubPart, head}; |
| 15 | 15 | use crate::views::shell; |
| 16 | 16 | |
| 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") => ( | |
| 20 | 20 | "Page not found", |
| 21 | 21 | "This page does not exist, or you cannot see it. Check the address, or go back to the start.", |
| 22 | 22 | "Back to the start", |
| 23 | 23 | ), |
| 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, _) => ( | |
| 44 | 25 | "Not allowed", |
| 45 | 26 | "Your account cannot do this here. Ask an owner for access, or go back to the start.", |
| 46 | 27 | "Back to the start", |
| 47 | 28 | ), |
| 48 | - Lang::Tr => ( | |
| 29 | + (Lang::Tr, "404") => ( | |
| 30 | + "Sayfa bulunamadı", | |
| 31 | + "Bu sayfa yok ya da görme izniniz yok. Adresi kontrol edin ya da başa dönün.", | |
| 32 | + "Başa dön", | |
| 33 | + ), | |
| 34 | + (Lang::Tr, _) => ( | |
| 49 | 35 | "İzin yok", |
| 50 | 36 | "Hesabınız burada bunu yapamaz. Bir sahibinden erişim isteyin ya da başa dönün.", |
| 51 | 37 | "Başa dön", |
| @@ -54,10 +40,10 @@ fn forbidden_texts(lang: Lang) -> (&'static str, &'static str, &'static str) { | ||
| 54 | 40 | } |
| 55 | 41 | |
| 56 | 42 | #[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); | |
| 59 | 45 | Ok(view! { |
| 60 | - head(title: title, sub: vec![SubPart::mono("403")]) | |
| 46 | + head(title: title, sub: vec![SubPart::mono(code)]) | |
| 61 | 47 | <p class="state">(hint) " " <a class="act" href="/">(back)</a></p> |
| 62 | 48 | }) |
| 63 | 49 | } |
| @@ -75,10 +61,10 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> { | ||
| 75 | 61 | } |
| 76 | 62 | } |
| 77 | 63 | let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user)); |
| 78 | - let title = forbidden_texts(lang).0; | |
| 64 | + let title = error_texts(lang, "403").0; | |
| 79 | 65 | Ok(view! { |
| 80 | 66 | (StatusCode::FORBIDDEN) |
| 81 | - shell(title: title, viewer: viewer.as_ref(), forbidden_body(lang: lang)) | |
| 67 | + shell(title: title, viewer: viewer.as_ref(), error_body(lang: lang, code: "403")) | |
| 82 | 68 | }) |
| 83 | 69 | } |
| 84 | 70 | |
| @@ -86,9 +72,9 @@ async fn forbidden_page(cx: &Cx) -> Result<impl View> { | ||
| 86 | 72 | async fn not_found_page(cx: &Cx) -> Result<impl View> { |
| 87 | 73 | let viewer = current_user(cx).await?; |
| 88 | 74 | let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user)); |
| 89 | - let title = texts(lang).0; | |
| 75 | + let title = error_texts(lang, "404").0; | |
| 90 | 76 | Ok(view! { |
| 91 | 77 | (StatusCode::NOT_FOUND) |
| 92 | - shell(title: title, viewer: viewer.as_ref(), not_found_body(lang: lang)) | |
| 78 | + shell(title: title, viewer: viewer.as_ref(), error_body(lang: lang, code: "404")) | |
| 93 | 79 | }) |
| 94 | 80 | } |
crates/forge-web-account/src/pages/org_ctx.rsmodified+9 -23
| @@ -24,7 +24,7 @@ use crate::views::{alert, profile_items}; | ||
| 24 | 24 | /// The query key that carries a notice on an org page. Its value is one of the fixed words in |
| 25 | 25 | /// `NOTICES`, never user text. The notice lives in the URL, not in a cookie: a live refresh of the |
| 26 | 26 | /// page reads the same URL and shows the notice again, where a cookie would be used up by it. |
| 27 | -pub const NOTICE_PARAM: &str = "notice"; | |
| 27 | +const NOTICE_PARAM: &str = "notice"; | |
| 28 | 28 | |
| 29 | 29 | /// Notice words, the text key each one shows, and whether it is an error. |
| 30 | 30 | pub const NOTICES: &[(&str, K, bool)] = &[ |
| @@ -75,6 +75,9 @@ pub const TEAM_ROLES: [Role; 5] = [ | ||
| 75 | 75 | /// Default repo roles for the org settings select. |
| 76 | 76 | pub const DEFAULT_ROLES: [&str; 3] = ["none", "read", "write"]; |
| 77 | 77 | |
| 78 | +/// Longest org description, in characters. | |
| 79 | +pub const MAX_DESCRIPTION_CHARS: usize = 2000; | |
| 80 | + | |
| 78 | 81 | /// The org a request is about, and what the viewer may do in it. |
| 79 | 82 | pub struct OrgCtx { |
| 80 | 83 | pub org: User, |
| @@ -155,16 +158,6 @@ pub async fn may_create_repo_in(state: &AppState, org_id: &str, user_id: &str) - | ||
| 155 | 158 | } |
| 156 | 159 | } |
| 157 | 160 | |
| 158 | -/// The stored word for a member role. | |
| 159 | -pub fn member_role_word(role: OrgMemberRole) -> &'static str { | |
| 160 | - role.as_str() | |
| 161 | -} | |
| 162 | - | |
| 163 | -/// The member role a form sent, if it is one of the two. | |
| 164 | -pub fn parse_member_role(word: &str) -> Option<OrgMemberRole> { | |
| 165 | - OrgMemberRole::parse(word).ok() | |
| 166 | -} | |
| 167 | - | |
| 168 | 161 | /// The redirect target `back` with the notice `word` in its query, so the next view of the page |
| 169 | 162 | /// shows it. `back` is an org path without a query. |
| 170 | 163 | pub fn notice_href(back: &str, word: &'static str) -> String { |
| @@ -209,7 +202,7 @@ pub async fn org_tabs( | ||
| 209 | 202 | repo_count: u64, |
| 210 | 203 | package_count: usize, |
| 211 | 204 | ) -> Result<impl View> { |
| 212 | - let mut tabs: Vec<(String, String, bool, String, bool)> = | |
| 205 | + let mut tabs: Vec<(String, String, bool, Option<String>)> = | |
| 213 | 206 | profile_items(lang, &name, true, false, true) |
| 214 | 207 | .into_iter() |
| 215 | 208 | .map(|item| { |
| @@ -218,13 +211,7 @@ pub async fn org_tabs( | ||
| 218 | 211 | "packages" => Some(package_count.to_string()), |
| 219 | 212 | _ => None, |
| 220 | 213 | }; |
| 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) | |
| 228 | 215 | }) |
| 229 | 216 | .collect(); |
| 230 | 217 | if owner { |
| @@ -232,16 +219,15 @@ pub async fn org_tabs( | ||
| 232 | 219 | format!("/org/{name}/settings"), |
| 233 | 220 | g::t(lang, K::Settings).to_owned(), |
| 234 | 221 | current == "settings", |
| 235 | - String::new(), | |
| 236 | - false, | |
| 222 | + None, | |
| 237 | 223 | )); |
| 238 | 224 | } |
| 239 | 225 | Ok(view! { |
| 240 | 226 | <nav class="tabs" aria-label=(name.as_str())> |
| 241 | - for (href, label, on, count, has_count) in tabs.into_iter() { | |
| 227 | + for (href, label, on, count) in tabs.into_iter() { | |
| 242 | 228 | <a href=(href.as_str()) aria-current=(on.then_some("page"))> |
| 243 | 229 | (label.as_str()) |
| 244 | - if has_count { | |
| 230 | + if let Some(count) = count { | |
| 245 | 231 | " " <span class="tab-count">(count.as_str())</span> |
| 246 | 232 | } |
| 247 | 233 | </a> |
crates/forge-web-account/src/pages/org_live.rsmodified+2 -2
| @@ -20,7 +20,7 @@ use topcoat::router::response::Response; | ||
| 20 | 20 | use topcoat::router::{path_param, route}; |
| 21 | 21 | |
| 22 | 22 | use crate::live::{Topic, stream_changes}; |
| 23 | -use crate::pages::org_ctx::{load_org, member_role_word, require_member, require_owner}; | |
| 23 | +use crate::pages::org_ctx::{load_org, require_member, require_owner}; | |
| 24 | 24 | use crate::pages::org_teams::{team_of, visible_team_repos}; |
| 25 | 25 | use crate::state::AppState; |
| 26 | 26 | |
| @@ -43,7 +43,7 @@ async fn members_fingerprint(store: &Store, org_id: &str) -> Result<String> { | ||
| 43 | 43 | "member {} {} {}", |
| 44 | 44 | user.id, |
| 45 | 45 | user.username, |
| 46 | - member_role_word(role) | |
| 46 | + role.as_str() | |
| 47 | 47 | )); |
| 48 | 48 | } |
| 49 | 49 | Ok(lines.join("\n")) |
crates/forge-web-account/src/pages/org_members.rsmodified+6 -6
| @@ -19,8 +19,8 @@ use crate::audit::{self, Actor, Target}; | ||
| 19 | 19 | use crate::i18n::orgs::{self as g, K}; |
| 20 | 20 | use crate::i18n::{self, Lang}; |
| 21 | 21 | 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, | |
| 24 | 24 | }; |
| 25 | 25 | use crate::state::AppState; |
| 26 | 26 | use crate::views::parts::{PeopleList, PersonRow, SubPart, head, people_list}; |
| @@ -171,7 +171,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther> | ||
| 171 | 171 | let state = context::<AppState>(cx); |
| 172 | 172 | let back = ctx.href("/members"); |
| 173 | 173 | |
| 174 | - let Some(role) = parse_member_role(form.role.trim()) else { | |
| 174 | + let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else { | |
| 175 | 175 | return Ok(see_other(notice_href(&back, "invalid_role"))); |
| 176 | 176 | }; |
| 177 | 177 | let username = form.username.trim(); |
| @@ -207,7 +207,7 @@ async fn org_members_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOther> | ||
| 207 | 207 | id: &ctx.org.id, |
| 208 | 208 | name: &ctx.org.username, |
| 209 | 209 | }, |
| 210 | - serde_json::json!({ "user": target.username, "role": member_role_word(role) }), | |
| 210 | + serde_json::json!({ "user": target.username, "role": role.as_str() }), | |
| 211 | 211 | ) |
| 212 | 212 | .await; |
| 213 | 213 | Ok(see_other(notice_href(&back, "member_added"))) |
| @@ -222,7 +222,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe | ||
| 222 | 222 | let state = context::<AppState>(cx); |
| 223 | 223 | let back = ctx.href("/members"); |
| 224 | 224 | |
| 225 | - let Some(role) = parse_member_role(form.role.trim()) else { | |
| 225 | + let Some(role) = OrgMemberRole::parse(form.role.trim()).ok() else { | |
| 226 | 226 | return Ok(see_other(notice_href(&back, "invalid_role"))); |
| 227 | 227 | }; |
| 228 | 228 | let user_id = form.user_id.trim(); |
| @@ -255,7 +255,7 @@ async fn org_members_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOthe | ||
| 255 | 255 | id: &ctx.org.id, |
| 256 | 256 | name: &ctx.org.username, |
| 257 | 257 | }, |
| 258 | - serde_json::json!({ "user": user_id, "role": member_role_word(role) }), | |
| 258 | + serde_json::json!({ "user": user_id, "role": role.as_str() }), | |
| 259 | 259 | ) |
| 260 | 260 | .await; |
| 261 | 261 | Ok(see_other(notice_href(&back, "role_updated"))) |
crates/forge-web-account/src/pages/org_new.rsmodified+2 -3
| @@ -17,12 +17,11 @@ use crate::auth::{require_csrf, require_user}; | ||
| 17 | 17 | use crate::i18n::orgs::{self as g, K}; |
| 18 | 18 | use crate::i18n::{self, Lang}; |
| 19 | 19 | use crate::live::Topic; |
| 20 | +use crate::pages::org_ctx::MAX_DESCRIPTION_CHARS; | |
| 20 | 21 | use crate::state::AppState; |
| 21 | 22 | use crate::views::parts::head; |
| 22 | 23 | use crate::views::{alert, csrf_field, shell, user_facing_message}; |
| 23 | 24 | |
| 24 | -const MAX_DESCRIPTION_CHARS: usize = 2000; | |
| 25 | - | |
| 26 | 25 | #[derive(Deserialize)] |
| 27 | 26 | struct NewOrgForm { |
| 28 | 27 | #[serde(default)] |
| @@ -53,7 +52,7 @@ async fn new_org_form( | ||
| 53 | 52 | ) -> Result<impl View> { |
| 54 | 53 | Ok(view! { |
| 55 | 54 | head(title: g::t(lang, K::NewOrganization), sub: Vec::new()) |
| 56 | - crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: "organizations".to_owned()) | |
| 55 | + crate::pages::profile::own_profile_tabs(lang: lang, username: username, current: crate::pages::profile::Tab::Organizations) | |
| 57 | 56 | <div class="sheet fit"> |
| 58 | 57 | if let Some(message) = error { |
| 59 | 58 | alert(message: message.as_str()) |
crates/forge-web-account/src/pages/org_settings.rsmodified+2 -4
| @@ -22,8 +22,8 @@ use crate::i18n::orgs::{self as g, K}; | ||
| 22 | 22 | use crate::i18n::{self, Key, Lang, t}; |
| 23 | 23 | use crate::live::Topic; |
| 24 | 24 | 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, | |
| 27 | 27 | }; |
| 28 | 28 | use crate::pages::settings_profile::store_avatar; |
| 29 | 29 | use crate::state::AppState; |
| @@ -32,8 +32,6 @@ use crate::views::{avatar_url, shell, user_facing_message}; | ||
| 32 | 32 | |
| 33 | 33 | path_param!(org); |
| 34 | 34 | |
| 35 | -const MAX_DESCRIPTION_CHARS: usize = 2000; | |
| 36 | - | |
| 37 | 35 | #[derive(Deserialize)] |
| 38 | 36 | struct SettingsForm { |
| 39 | 37 | #[serde(default)] |
crates/forge-web-account/src/pages/org_teams.rsmodified+0 -12
| @@ -782,18 +782,6 @@ mod tests { | ||
| 782 | 782 | assert_eq!(parse_team_role(""), None); |
| 783 | 783 | } |
| 784 | 784 | |
| 785 | - #[test] | |
| 786 | - fn coverage_reads_in_words() { | |
| 787 | - assert_eq!( | |
| 788 | - g::coverage_text(Lang::En, "write", true), | |
| 789 | - "write on all repositories" | |
| 790 | - ); | |
| 791 | - assert_eq!( | |
| 792 | - g::coverage_text(Lang::En, "read", false), | |
| 793 | - "read on linked repositories" | |
| 794 | - ); | |
| 795 | - } | |
| 796 | - | |
| 797 | 785 | #[test] |
| 798 | 786 | fn duplicate_and_bad_names_get_their_own_notices() { |
| 799 | 787 | let dup = forge_core::Error::Conflict("taken".into()); |
crates/forge-web-account/src/pages/profile.rsmodified+87 -181
| @@ -1,11 +1,3 @@ | ||
| 1 | -//! Page: public profile at `/{username}`. Avatar, about (rendered markdown) and local time, then | |
| 2 | -//! the tabs: `overview` (pinned repos, or the most recently active ones when nothing is pinned, | |
| 3 | -//! plus a person's contribution calendar, or an organization's members and teams), `repositories`, | |
| 4 | -//! `snippets` (people only), `stars`, `packages` and `organizations` (the viewer's own only). The | |
| 5 | -//! repo tabs list what the viewer is allowed to read, 10 per page, so a page fits the screen,, with a name filter and three | |
| 6 | -//! sort orders; the filtering, sorting and paging run in the database. Fixed single-segment routes | |
| 7 | -//! are registered statically, so they win over this parameter route. | |
| 8 | - | |
| 9 | 1 | use forge_core::authz::{Action, authorize}; |
| 10 | 2 | use forge_core::store::RepoSort; |
| 11 | 3 | use forge_core::store::orgs::OrgMemberRole; |
| @@ -47,47 +39,35 @@ use crate::views::{ | ||
| 47 | 39 | |
| 48 | 40 | path_param!(username); |
| 49 | 41 | |
| 50 | -/// Repos per page on the repositories and stars tabs. | |
| 51 | 42 | const PER_PAGE: u64 = 10; |
| 52 | -/// What the pin menu needs: shown to whoever may edit the pins, on the overview. | |
| 43 | +const BATCH: u64 = 100; | |
| 53 | 44 | struct PinsMenu { |
| 54 | 45 | action: String, |
| 55 | 46 | csrf: String, |
| 56 | 47 | options: Vec<PinOption>, |
| 57 | 48 | } |
| 58 | 49 | |
| 59 | -/// Repos the overview shows when the owner has no visible pins. | |
| 60 | 50 | const POPULAR_COUNT: usize = 6; |
| 61 | -/// Members an organization's overview lists; a longer list links to the members page. | |
| 62 | 51 | const ORG_MEMBERS_SHOWN: usize = 12; |
| 63 | -/// Repos the name filter reads at once. The filter runs in Rust, so it covers every repo in scope. | |
| 64 | -const SEARCH_CAP: u64 = 5000; | |
| 65 | 52 | |
| 66 | 53 | #[query_params(error = bad_request)] |
| 67 | 54 | struct ProfileQuery { |
| 68 | 55 | tab: Option<String>, |
| 69 | 56 | q: Option<String>, |
| 70 | - /// Set when the filter asks for the text as typed, as one piece. | |
| 71 | 57 | exact: Option<String>, |
| 72 | - /// Set when the filter keeps upper and lower case apart. | |
| 73 | 58 | case: Option<String>, |
| 74 | 59 | sort: Option<String>, |
| 75 | 60 | page: Option<String>, |
| 76 | - /// A calendar day whose contributions to list under the calendar on the overview. | |
| 77 | 61 | day: Option<String>, |
| 78 | - /// `too_many` after a save with more pins than the limit. | |
| 79 | 62 | pins: Option<String>, |
| 80 | 63 | } |
| 81 | 64 | |
| 82 | -/// Sort keys of the repo tabs in the order their chips are shown, with the label of each. The | |
| 83 | -/// first one is the default. | |
| 84 | 65 | const SORTS: [(&str, K); 3] = [ |
| 85 | 66 | ("updated", K::SortRecentlyUpdated), |
| 86 | 67 | ("name", K::Name), |
| 87 | 68 | ("stars", K::SortMostStars), |
| 88 | 69 | ]; |
| 89 | 70 | |
| 90 | -/// Maps the `sort` query value to a key from `SORTS`; anything unknown means the default. | |
| 91 | 71 | fn sort_key(raw: Option<&str>) -> &'static str { |
| 92 | 72 | SORTS |
| 93 | 73 | .iter() |
| @@ -96,6 +76,40 @@ fn sort_key(raw: Option<&str>) -> &'static str { | ||
| 96 | 76 | .unwrap_or(SORTS[0].0) |
| 97 | 77 | } |
| 98 | 78 | |
| 79 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 80 | +pub enum Tab { | |
| 81 | + Overview, | |
| 82 | + Repositories, | |
| 83 | + Snippets, | |
| 84 | + Stars, | |
| 85 | + Packages, | |
| 86 | + Organizations, | |
| 87 | +} | |
| 88 | + | |
| 89 | +impl Tab { | |
| 90 | + fn from_query(raw: Option<&str>) -> Self { | |
| 91 | + match raw { | |
| 92 | + Some("repositories") => Self::Repositories, | |
| 93 | + Some("snippets") => Self::Snippets, | |
| 94 | + Some("stars") => Self::Stars, | |
| 95 | + Some("packages") => Self::Packages, | |
| 96 | + Some("organizations") => Self::Organizations, | |
| 97 | + _ => Self::Overview, | |
| 98 | + } | |
| 99 | + } | |
| 100 | + | |
| 101 | + fn key(self) -> &'static str { | |
| 102 | + match self { | |
| 103 | + Self::Overview => "overview", | |
| 104 | + Self::Repositories => "repositories", | |
| 105 | + Self::Snippets => "snippets", | |
| 106 | + Self::Stars => "stars", | |
| 107 | + Self::Packages => "packages", | |
| 108 | + Self::Organizations => "organizations", | |
| 109 | + } | |
| 110 | + } | |
| 111 | +} | |
| 112 | + | |
| 99 | 113 | #[page("/{username}")] |
| 100 | 114 | async fn profile_page(cx: &Cx) -> Result<impl View> { |
| 101 | 115 | let name = username(cx); |
| @@ -117,15 +131,12 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 117 | 131 | |
| 118 | 132 | let actor = viewer.as_ref().map(|(u, _)| u); |
| 119 | 133 | let lang = i18n::lang(cx, actor); |
| 120 | - // Whether the viewer is this person. Only the person sees their Organizations tab and edit links. | |
| 121 | 134 | 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) | |
| 127 | 138 | { |
| 128 | - "overview" | |
| 139 | + Tab::Overview | |
| 129 | 140 | } else { |
| 130 | 141 | tab |
| 131 | 142 | }; |
| @@ -137,17 +148,14 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 137 | 148 | let page = page_number(query.page.as_deref()); |
| 138 | 149 | let sort = sort_key(query.sort.as_deref()); |
| 139 | 150 | |
| 140 | - // The tab labels count what the viewer may read, with no filter. | |
| 141 | 151 | let owned = RepoScope::OwnedBy(&user.id); |
| 142 | 152 | let starred = RepoScope::StarredBy(&user.id); |
| 143 | 153 | let repo_total = state.store.count_visible_repos(owned, actor).await?; |
| 144 | 154 | let star_total = state.store.count_visible_repos(starred, actor).await?; |
| 145 | 155 | |
| 146 | - // The overview shows the owner's pins that the viewer may read. With none visible, it shows | |
| 147 | - // the most recently active repos instead. | |
| 148 | 156 | let mut cards = Vec::new(); |
| 149 | 157 | let mut from_pins = true; |
| 150 | - if tab == "overview" { | |
| 158 | + if tab == Tab::Overview { | |
| 151 | 159 | let mut shown = readable( |
| 152 | 160 | state, |
| 153 | 161 | actor, |
| @@ -171,7 +179,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 171 | 179 | } |
| 172 | 180 | } |
| 173 | 181 | |
| 174 | - // The viewer's role in an organization, looked up once for the header, the tabs and the pins. | |
| 175 | 182 | let org_role = match actor { |
| 176 | 183 | Some(u) if user.is_org() => state.store.org_member_role(&user.id, &u.id).await?, |
| 177 | 184 | _ => None, |
| @@ -185,14 +192,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 185 | 192 | _ => false, |
| 186 | 193 | }; |
| 187 | 194 | |
| 188 | - // An organization's pins are edited by its owners, a user's by the user. | |
| 189 | 195 | let can_edit_pins = match actor { |
| 190 | 196 | Some(_) if user.is_org() => org_owner, |
| 191 | 197 | Some(u) => u.id == user.id, |
| 192 | 198 | None => false, |
| 193 | 199 | }; |
| 194 | 200 | let mut pins_menu_data = None; |
| 195 | - if can_edit_pins && tab == "overview" { | |
| 201 | + if can_edit_pins && tab == Tab::Overview { | |
| 196 | 202 | let options = pin_options(&state.store, &user.id).await?; |
| 197 | 203 | if let (false, Some((_, session))) = (options.is_empty(), viewer.as_ref()) { |
| 198 | 204 | let action = if user.is_org() { |
| @@ -209,15 +215,12 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 209 | 215 | } |
| 210 | 216 | let pins_error = can_edit_pins && query.pins.as_deref() == Some("too_many"); |
| 211 | 217 | |
| 212 | - // The contribution calendar on the overview, for a person only. Its counts and day links 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() { | |
| 215 | 219 | Some(load_calendar(state, &user, query.day.as_deref()).await?) |
| 216 | 220 | } else { |
| 217 | 221 | None |
| 218 | 222 | }; |
| 219 | 223 | |
| 220 | - // The Snippets tab lists the person's snippets the viewer may read. An organization keeps none. | |
| 221 | 224 | let snippets: Vec<ListRow> = if user.is_org() { |
| 222 | 225 | Vec::new() |
| 223 | 226 | } else { |
| @@ -229,18 +232,11 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 229 | 232 | .map(|summary| list_row(lang, summary)) |
| 230 | 233 | .collect() |
| 231 | 234 | }; |
| 232 | - // Snippets page like the repo tabs, so the tab fits the screen however many there are. | |
| 233 | 235 | let snippet_total = snippets.len() as u64; |
| 234 | 236 | let snippet_pages = snippet_total.div_ceil(PER_PAGE).max(1); |
| 235 | 237 | let snippet_page = page.min(snippet_pages); |
| 236 | 238 | 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) | |
| 244 | 240 | }); |
| 245 | 241 | let snippets: Vec<ListRow> = snippets |
| 246 | 242 | .into_iter() |
| @@ -248,10 +244,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 248 | 244 | .take(PER_PAGE as usize) |
| 249 | 245 | .collect(); |
| 250 | 246 | |
| 251 | - // The viewer's Organizations tab lists the organizations they belong to, and whether the | |
| 252 | - // instance lets them create one. | |
| 253 | 247 | let (orgs, org_create_allowed) = match actor { |
| 254 | - Some(viewer_user) if tab == "organizations" => { | |
| 248 | + Some(viewer_user) if tab == Tab::Organizations => { | |
| 255 | 249 | let mut cards = Vec::new(); |
| 256 | 250 | for (org, role) in state.store.orgs_for_user(&user.id).await? { |
| 257 | 251 | let hash = state.store.avatar_hash(&org.id).await?; |
| @@ -276,8 +270,8 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 276 | 270 | }; |
| 277 | 271 | |
| 278 | 272 | 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 }; | |
| 281 | 275 | let sort_kind = match sort { |
| 282 | 276 | "stars" => RepoSort::MostStars, |
| 283 | 277 | "name" => RepoSort::Name, |
| @@ -289,12 +283,20 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 289 | 283 | .list_visible_repos(scope, actor, None, sort_kind, page, PER_PAGE) |
| 290 | 284 | .await? |
| 291 | 285 | } 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 | + } | |
| 298 | 300 | let matching: Vec<_> = all |
| 299 | 301 | .into_iter() |
| 300 | 302 | .filter(|(repo, _, _)| { |
| @@ -302,6 +304,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 302 | 304 | }) |
| 303 | 305 | .collect(); |
| 304 | 306 | let total = matching.len() as u64; |
| 307 | + let page = page.min(total.div_ceil(PER_PAGE).max(1)); | |
| 305 | 308 | let shown = matching |
| 306 | 309 | .into_iter() |
| 307 | 310 | .skip(((page - 1) * PER_PAGE) as usize) |
| @@ -313,10 +316,10 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 313 | 316 | let now = now_unix(); |
| 314 | 317 | let empty = match (tab, finder.is_empty()) { |
| 315 | 318 | (_, false) => g::t(lang, K::NoReposMatch), |
| 316 | - ("stars", true) => g::t(lang, K::NoVisibleStarred), | |
| 319 | + (Tab::Stars, true) => g::t(lang, K::NoVisibleStarred), | |
| 317 | 320 | _ => g::t(lang, K::NoVisibleRepos), |
| 318 | 321 | }; |
| 319 | - let count_text = if tab == "stars" { | |
| 322 | + let count_text = if tab == Tab::Stars { | |
| 320 | 323 | g::starred_count(lang, total) |
| 321 | 324 | } else { |
| 322 | 325 | g::repo_count(lang, total) |
| @@ -331,13 +334,13 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 331 | 334 | page, |
| 332 | 335 | pages, |
| 333 | 336 | pager: pager_links(page, pages, |n| { |
| 334 | - profile_href(&user.username, tab, &finder, sort, n) | |
| 337 | + profile_href(&user.username, tab.key(), &finder, sort, n) | |
| 335 | 338 | }), |
| 336 | 339 | sort_links: SORTS |
| 337 | 340 | .iter() |
| 338 | 341 | .map(|(key, label)| SortLink { |
| 339 | 342 | label: g::t(lang, *label), |
| 340 | - href: profile_href(&user.username, tab, &finder, key, 1), | |
| 343 | + href: profile_href(&user.username, tab.key(), &finder, key, 1), | |
| 341 | 344 | current: *key == sort, |
| 342 | 345 | }) |
| 343 | 346 | .collect(), |
| @@ -348,8 +351,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 348 | 351 | _ => Listing::default(), |
| 349 | 352 | }; |
| 350 | 353 | |
| 351 | - // An organization shows its members (the first few, with their avatars) and how many teams it | |
| 352 | - // has. Its `about` is its description. | |
| 353 | 354 | let org = if user.is_org() { |
| 354 | 355 | let members = state.store.org_members(&user.id).await?; |
| 355 | 356 | let teams = state.store.teams_for_org(&user.id).await?.len(); |
| @@ -369,18 +370,16 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 369 | 370 | None |
| 370 | 371 | }; |
| 371 | 372 | |
| 372 | - // The Packages tab lists the registry's packages the viewer may see. | |
| 373 | 373 | let package_rows = packages::package_rows(state, actor, &user).await?; |
| 374 | - let packages_on = tab == "packages"; | |
| 374 | + let packages_on = tab == Tab::Packages; | |
| 375 | 375 | |
| 376 | - // A repo deleted just before this redirect here shows its one-line notice once. | |
| 377 | 376 | let notice = take_notice(cx); |
| 378 | 377 | let title = user.username.clone(); |
| 379 | 378 | Ok(view! { |
| 380 | 379 | shell(title: title.as_str(), viewer: viewer.as_ref(), |
| 381 | 380 | notice_banner_for(lang: lang, title: notice) |
| 382 | 381 | profile_card(user: user, avatar: avatar, about_html: about_html, local_time: local_time, |
| 383 | - org: org, lang: lang, tab: tab.to_owned(), finder: finder, sort: sort, repo_total: repo_total, | |
| 382 | + org: org, lang: lang, tab: tab, finder: finder, sort: sort, repo_total: repo_total, | |
| 384 | 383 | star_total: star_total, cards: cards, from_pins: from_pins, |
| 385 | 384 | pins_menu_data: pins_menu_data, pins_error: pins_error, edit_profile: own, listing: listing, |
| 386 | 385 | packages_on: packages_on, package_rows: package_rows, |
| @@ -391,9 +390,6 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 391 | 390 | }) |
| 392 | 391 | } |
| 393 | 392 | |
| 394 | -/// The profile's change stream. It follows the user's topic: repos created, changed or starred, | |
| 395 | -/// pins, and pushes by the user. The stream is keyed by the username in the URL, but the viewer | |
| 396 | -/// comes from the session, so what it sends is what that viewer may read. An unknown name is 404. | |
| 397 | 393 | #[route(GET "/users/{username}/events")] |
| 398 | 394 | async fn profile_events(cx: &Cx) -> Result<Response> { |
| 399 | 395 | let name = username(cx); |
| @@ -412,8 +408,6 @@ async fn profile_events(cx: &Cx) -> Result<Response> { | ||
| 412 | 408 | .await |
| 413 | 409 | } |
| 414 | 410 | |
| 415 | -/// The state the profile shows: the tab counts, the pins with their stars, and the first page of | |
| 416 | -/// the owner's repos as the default tab lists them. | |
| 417 | 411 | async fn profile_fingerprint( |
| 418 | 412 | state: &AppState, |
| 419 | 413 | user: &User, |
| @@ -433,7 +427,6 @@ async fn profile_fingerprint( | ||
| 433 | 427 | .await? |
| 434 | 428 | .to_string(), |
| 435 | 429 | ]; |
| 436 | - // The header's about text and avatar, read fresh: the stream's `user` is a snapshot from connect. | |
| 437 | 430 | let about = state |
| 438 | 431 | .store |
| 439 | 432 | .user_by_id(&user.id) |
| @@ -445,13 +438,11 @@ async fn profile_fingerprint( | ||
| 445 | 438 | "avatar {}", |
| 446 | 439 | state.store.avatar_hash(&user.id).await?.unwrap_or_default() |
| 447 | 440 | )); |
| 448 | - // An organization's page shows its member and team counts. | |
| 449 | 441 | if user.is_org() { |
| 450 | 442 | let members = state.store.org_members(&user.id).await?.len(); |
| 451 | 443 | let teams = state.store.teams_for_org(&user.id).await?.len(); |
| 452 | 444 | lines.push(format!("org {members} {teams}")); |
| 453 | 445 | } else { |
| 454 | - // The overview shows a person's calendar, so its total moves with each one. | |
| 455 | 446 | let total: u64 = state |
| 456 | 447 | .store |
| 457 | 448 | .contribution_counts(&user.id, &calendar_since(), &user.timezone) |
| @@ -485,38 +476,30 @@ async fn profile_fingerprint( | ||
| 485 | 476 | Ok(lines.join("\n")) |
| 486 | 477 | } |
| 487 | 478 | |
| 488 | -/// What an organization's profile adds: its member count, the first members to list, and its team | |
| 489 | -/// count. | |
| 490 | 479 | struct OrgSummary { |
| 491 | 480 | total: usize, |
| 492 | 481 | members: Vec<OrgMember>, |
| 493 | 482 | teams: usize, |
| 494 | 483 | } |
| 495 | 484 | |
| 496 | -/// A member on an organization's overview: the login name and the avatar URL. | |
| 497 | 485 | struct OrgMember { |
| 498 | 486 | username: String, |
| 499 | 487 | avatar: String, |
| 500 | 488 | } |
| 501 | 489 | |
| 502 | -/// A repo card on the overview: the repo and its star count. | |
| 503 | 490 | struct PinCard { |
| 504 | 491 | repo: Repo, |
| 505 | 492 | stars: u64, |
| 506 | 493 | } |
| 507 | 494 | |
| 508 | -/// One organization on the viewer's own Organizations tab, with its strings ready for the view. | |
| 509 | 495 | struct OrgCard { |
| 510 | 496 | href: String, |
| 511 | 497 | avatar: String, |
| 512 | 498 | name: String, |
| 513 | - /// Empty when the organization has no display name. | |
| 514 | 499 | display_name: String, |
| 515 | 500 | role: &'static str, |
| 516 | 501 | } |
| 517 | 502 | |
| 518 | -/// One page of a repo tab: the rows, the pager, the sort chips, the match count text and the | |
| 519 | -/// empty-list text. | |
| 520 | 503 | #[derive(Default)] |
| 521 | 504 | struct Listing { |
| 522 | 505 | rows: Vec<RepoRow>, |
| @@ -528,25 +511,10 @@ struct Listing { | ||
| 528 | 511 | empty: &'static str, |
| 529 | 512 | } |
| 530 | 513 | |
| 531 | -/// The profile tabs, by their `?tab=` key. Anything unknown is the overview. | |
| 532 | -fn tab_key(raw: Option<&str>) -> &'static str { | |
| 533 | - match raw { | |
| 534 | - Some("repositories") => "repositories", | |
| 535 | - Some("snippets") => "snippets", | |
| 536 | - Some("stars") => "stars", | |
| 537 | - Some("packages") => "packages", | |
| 538 | - Some("organizations") => "organizations", | |
| 539 | - _ => "overview", | |
| 540 | - } | |
| 541 | -} | |
| 542 | - | |
| 543 | -/// The `?page=` value, 1-based. Anything unreadable is page 1. | |
| 544 | 514 | fn page_number(raw: Option<&str>) -> u64 { |
| 545 | 515 | raw.and_then(|p| p.parse::<u64>().ok()).unwrap_or(1).max(1) |
| 546 | 516 | } |
| 547 | 517 | |
| 548 | -/// The profile URL for a tab, with the name filter, a sort other than the default and the page | |
| 549 | -/// when they are set. | |
| 550 | 518 | fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) -> String { |
| 551 | 519 | let mut href = format!("/{}?tab={tab}", enc(name)); |
| 552 | 520 | if !finder.is_empty() { |
| @@ -567,9 +535,6 @@ fn profile_href(name: &str, tab: &str, finder: &Finder, sort: &str, page: u64) - | ||
| 567 | 535 | href |
| 568 | 536 | } |
| 569 | 537 | |
| 570 | -/// Whether the viewer may read `repo`. Public repos, and repos the viewer owns or administers, | |
| 571 | -/// need no role lookup. Other private repos get their collaborator and org roles, and `authorize` | |
| 572 | -/// makes the final call either way. | |
| 573 | 538 | async fn may_read(state: &AppState, actor: Option<&User>, repo: &Repo) -> Result<bool> { |
| 574 | 539 | let open = repo.visibility == Visibility::Public |
| 575 | 540 | || actor.is_some_and(|u| u.is_admin || u.id == repo.owner_id); |
| @@ -586,7 +551,6 @@ async fn may_read(state: &AppState, actor: Option<&User>, repo: &Repo) -> Result | ||
| 586 | 551 | Ok(authorize(actor, repo, role, org_role, Action::Read).is_ok()) |
| 587 | 552 | } |
| 588 | 553 | |
| 589 | -/// The first `limit` repos of `repos` that the viewer may read, in their order. | |
| 590 | 554 | async fn readable( |
| 591 | 555 | state: &AppState, |
| 592 | 556 | actor: Option<&User>, |
| @@ -614,7 +578,7 @@ async fn profile_card( | ||
| 614 | 578 | local_time: String, |
| 615 | 579 | org: Option<OrgSummary>, |
| 616 | 580 | lang: Lang, |
| 617 | - tab: String, | |
| 581 | + tab: Tab, | |
| 618 | 582 | finder: Finder, |
| 619 | 583 | sort: &'static str, |
| 620 | 584 | repo_total: u64, |
| @@ -640,16 +604,14 @@ async fn profile_card( | ||
| 640 | 604 | ) -> Result<impl View> { |
| 641 | 605 | let has_snippets = !snippets.is_empty(); |
| 642 | 606 | 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; | |
| 645 | 609 | let has_orgs = !orgs.is_empty(); |
| 646 | 610 | let packages_events = packages::events_href(&user.username); |
| 647 | 611 | let has_packages = !package_rows.is_empty(); |
| 648 | 612 | let src = avatar_url(&user.username, avatar.as_deref()); |
| 649 | 613 | let has_about = !about_html.is_empty(); |
| 650 | 614 | let is_org = user.is_org(); |
| 651 | - // An organization's header avatar is smaller. The tab bar comes from the shared list, with the | |
| 652 | - // counts that go on its labels. | |
| 653 | 615 | let avatar_px = if is_org { "96" } else { "256" }; |
| 654 | 616 | let avatar_class = if is_org { |
| 655 | 617 | "profile-avatar org-avatar" |
| @@ -665,9 +627,9 @@ async fn profile_card( | ||
| 665 | 627 | ("packages", package_rows.len().to_string()), |
| 666 | 628 | ]; |
| 667 | 629 | 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; | |
| 671 | 633 | let list_on = repos_on || stars_on; |
| 672 | 634 | let pinned_heading = if from_pins { |
| 673 | 635 | g::t(lang, K::Pinned) |
| @@ -677,7 +639,6 @@ async fn profile_card( | ||
| 677 | 639 | let has_cards = !cards.is_empty(); |
| 678 | 640 | let edit_label = mi::t(lang, MK::EditProfile); |
| 679 | 641 | let org_edit_label = mi::t(lang, MK::EditOrganization); |
| 680 | - // The display name is the heading when set; the username then moves under it. | |
| 681 | 642 | let has_name = user.display_name.is_some(); |
| 682 | 643 | let heading = user |
| 683 | 644 | .display_name |
| @@ -700,8 +661,6 @@ async fn profile_card( | ||
| 700 | 661 | let members_more = org |
| 701 | 662 | .as_ref() |
| 702 | 663 | .is_some_and(|summary| org_member && summary.total > summary.members.len()); |
| 703 | - // The sub line: the username under a display name, then whether this is an organization or the | |
| 704 | - // person's local time. | |
| 705 | 664 | let mut sub = Vec::new(); |
| 706 | 665 | if has_name { |
| 707 | 666 | sub.push(SubPart::text(user.username.as_str())); |
| @@ -734,7 +693,7 @@ async fn profile_card( | ||
| 734 | 693 | <a class="button" href="/org/new">(g::t(lang, K::NewOrganization))</a> |
| 735 | 694 | } |
| 736 | 695 | ) |
| 737 | - profile_tabs(username: user.username.clone(), items: tab_items, current: tab.clone(), counts: tab_counts) | |
| 696 | + profile_tabs(username: user.username.clone(), items: tab_items, current: tab, counts: tab_counts) | |
| 738 | 697 | <div class="sheet" data-live=(format!("/users/{}/events", user.username))> |
| 739 | 698 | if has_about { |
| 740 | 699 | <section class="sec profile-about markdown-body">(Unescaped::new_unchecked(about_html))</section> |
| @@ -806,7 +765,7 @@ async fn profile_card( | ||
| 806 | 765 | <div class="sheet-tools"> |
| 807 | 766 | <strong>(count_text.as_str())</strong> |
| 808 | 767 | <form method="get" action=(base.as_str()) role="search"> |
| 809 | - <input type="hidden" name="tab" value=(tab.as_str())> | |
| 768 | + <input type="hidden" name="tab" value=(tab.key())> | |
| 810 | 769 | <input type="hidden" name="sort" value=(sort)> |
| 811 | 770 | finder_field(lang: lang, finder: finder, placeholder: filter_label, id: Some("profile-q")) |
| 812 | 771 | </form> |
| @@ -879,14 +838,12 @@ async fn profile_card( | ||
| 879 | 838 | }) |
| 880 | 839 | } |
| 881 | 840 | |
| 882 | -/// The viewer's own profile tabs on a page that makes something of theirs (a repository, a | |
| 883 | -/// snippet, an organization): the same tabs and counts as their profile, with `current` marked. | |
| 884 | 841 | #[component] |
| 885 | 842 | pub async fn own_profile_tabs( |
| 886 | 843 | cx: &Cx, |
| 887 | 844 | lang: Lang, |
| 888 | 845 | username: String, |
| 889 | - current: String, | |
| 846 | + current: Tab, | |
| 890 | 847 | ) -> Result<impl View> { |
| 891 | 848 | let items = crate::views::profile_items(lang, &username, false, true, false); |
| 892 | 849 | let mut counts = Vec::new(); |
| @@ -920,53 +877,34 @@ pub async fn own_profile_tabs( | ||
| 920 | 877 | }) |
| 921 | 878 | } |
| 922 | 879 | |
| 923 | -/// The profile tab bar: one link per item, the current tab marked, and a count after the label of | |
| 924 | -/// each tab that has one in `counts`, by the item's key. A person's, an organization's and an | |
| 925 | -/// organization's member pages all render it. | |
| 926 | 880 | #[component] |
| 927 | 881 | pub async fn profile_tabs( |
| 928 | 882 | cx: &Cx, |
| 929 | 883 | username: String, |
| 930 | 884 | items: Vec<NavItem>, |
| 931 | - current: String, | |
| 885 | + current: Tab, | |
| 932 | 886 | counts: Vec<(&'static str, String)>, |
| 933 | 887 | ) -> Result<impl View> { |
| 934 | - let rows: Vec<(String, String, bool, String, bool)> = items | |
| 888 | + let rows: Vec<(String, String, bool, Option<String>)> = items | |
| 935 | 889 | .into_iter() |
| 936 | 890 | .map(|item| { |
| 937 | - let on = item.key == current; | |
| 891 | + let on = item.key == current.key(); | |
| 938 | 892 | let count = counts |
| 939 | 893 | .iter() |
| 940 | 894 | .find(|(key, _)| *key == item.key) |
| 941 | 895 | .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) | |
| 950 | 897 | }) |
| 951 | 898 | .collect(); |
| 952 | 899 | Ok(view! { |
| 953 | 900 | <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> | |
| 970 | 908 | } |
| 971 | 909 | </nav> |
| 972 | 910 | }) |
| @@ -1003,7 +941,6 @@ mod tests { | ||
| 1003 | 941 | } |
| 1004 | 942 | } |
| 1005 | 943 | |
| 1006 | - /// Creates a session for `user_id` and returns the cookie header value. | |
| 1007 | 944 | async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { |
| 1008 | 945 | crate::test_support::create_session(store, user_id, token, CSRF).await; |
| 1009 | 946 | format!("__Host-{SESSION_COOKIE}={token}") |
| @@ -1020,7 +957,6 @@ mod tests { | ||
| 1020 | 957 | (status, String::from_utf8_lossy(&bytes).into_owned()) |
| 1021 | 958 | } |
| 1022 | 959 | |
| 1023 | - /// Tahinli has a public repo, a private repo and a private repo that carol collaborates on. | |
| 1024 | 960 | async fn seeded() -> Site { |
| 1025 | 961 | let site = site().await; |
| 1026 | 962 | let tahinli = site |
| @@ -1061,14 +997,10 @@ mod tests { | ||
| 1061 | 997 | site |
| 1062 | 998 | } |
| 1063 | 999 | |
| 1064 | - /// One seeded site covers the repo list for each kind of viewer, the about text, the | |
| 1065 | - /// edit button, the unknown-user 404 and the fixed routes. Each signed-in viewer gets its | |
| 1066 | - /// own session token. | |
| 1067 | 1000 | #[tokio::test] |
| 1068 | 1001 | async fn profile_visibility_routing_and_edit_button() { |
| 1069 | 1002 | let site = seeded().await; |
| 1070 | 1003 | |
| 1071 | - // About is rendered and sanitized. | |
| 1072 | 1004 | let (status, anon) = get(&site.router, "/tahinli", None).await; |
| 1073 | 1005 | assert_eq!(status, 200, "about"); |
| 1074 | 1006 | assert!(anon.contains("<h1"), "about: heading rendered: {anon}"); |
| @@ -1080,7 +1012,6 @@ mod tests { | ||
| 1080 | 1012 | assert!(!anon.contains("<script>"), "about: script stripped: {anon}"); |
| 1081 | 1013 | assert!(!anon.contains("alert(1)"), "about: script body stripped"); |
| 1082 | 1014 | |
| 1083 | - // Anonymous visitors see only public repos and no edit button. | |
| 1084 | 1015 | assert!(anon.contains("tahinli/open-repo"), "anonymous: public repo"); |
| 1085 | 1016 | assert!( |
| 1086 | 1017 | !anon.contains("tahinli/secret-repo"), |
| @@ -1095,7 +1026,6 @@ mod tests { | ||
| 1095 | 1026 | "anonymous: edit button" |
| 1096 | 1027 | ); |
| 1097 | 1028 | |
| 1098 | - // Another user sees the same public-only list and no edit button. | |
| 1099 | 1029 | let bob = site |
| 1100 | 1030 | .store |
| 1101 | 1031 | .create_user("bob", None, "not-a-real-hash", false) |
| @@ -1120,7 +1050,6 @@ mod tests { | ||
| 1120 | 1050 | "other user: edit button" |
| 1121 | 1051 | ); |
| 1122 | 1052 | |
| 1123 | - // The owner sees every repo and the edit button. | |
| 1124 | 1053 | let tahinli = user_id(&site.store, "tahinli").await; |
| 1125 | 1054 | let cookie = sign_in(&site.store, &tahinli, "visibility-owner-token").await; |
| 1126 | 1055 | let (_, owner) = get(&site.router, "/tahinli", Some(&cookie)).await; |
| @@ -1131,7 +1060,6 @@ mod tests { | ||
| 1131 | 1060 | "owner: edit button" |
| 1132 | 1061 | ); |
| 1133 | 1062 | |
| 1134 | - // A collaborator sees the repo they were added to, not the private one. | |
| 1135 | 1063 | let carol = user_id(&site.store, "carol").await; |
| 1136 | 1064 | let cookie = sign_in(&site.store, &carol, "visibility-carol-token").await; |
| 1137 | 1065 | let (_, collab) = get(&site.router, "/tahinli", Some(&cookie)).await; |
| @@ -1144,14 +1072,12 @@ mod tests { | ||
| 1144 | 1072 | "collaborator: private repo" |
| 1145 | 1073 | ); |
| 1146 | 1074 | |
| 1147 | - // Unknown users 404, and the lookup ignores case. | |
| 1148 | 1075 | let (status, _) = get(&site.router, "/nobody-here", None).await; |
| 1149 | 1076 | assert_eq!(status, 404, "unknown user"); |
| 1150 | 1077 | let (status, body) = get(&site.router, "/TAHINLI", None).await; |
| 1151 | 1078 | assert_eq!(status, 200, "case-insensitive lookup"); |
| 1152 | 1079 | assert!(body.contains("tahinli"), "case-insensitive lookup"); |
| 1153 | 1080 | |
| 1154 | - // Fixed routes are not shadowed by the profile. | |
| 1155 | 1081 | for uri in [ |
| 1156 | 1082 | "/new", |
| 1157 | 1083 | "/login", |
| @@ -1170,11 +1096,9 @@ mod tests { | ||
| 1170 | 1096 | "{uri} was served by the profile page" |
| 1171 | 1097 | ); |
| 1172 | 1098 | } |
| 1173 | - // The fixed login page still renders its form, not a profile. | |
| 1174 | 1099 | let (status, body) = get(&site.router, "/login", None).await; |
| 1175 | 1100 | assert_eq!(status, 200, "fixed login page"); |
| 1176 | 1101 | assert!(body.contains("<form"), "fixed login page renders its form"); |
| 1177 | - // Two-segment repo routes keep working and still 404 for a missing repo. | |
| 1178 | 1102 | let (status, body) = get(&site.router, "/tahinli/missing", None).await; |
| 1179 | 1103 | assert_eq!(status, 404, "missing repo"); |
| 1180 | 1104 | assert!( |
| @@ -1183,14 +1107,11 @@ mod tests { | ||
| 1183 | 1107 | ); |
| 1184 | 1108 | } |
| 1185 | 1109 | |
| 1186 | - /// Stars, the org sidebar and org pins, on one seeded site. The org scenarios use their | |
| 1187 | - /// own org names and session tokens. | |
| 1188 | 1110 | #[tokio::test] |
| 1189 | 1111 | async fn stars_org_sidebar_and_org_pins() { |
| 1190 | 1112 | let site = seeded().await; |
| 1191 | 1113 | let tahinli = user_id(&site.store, "tahinli").await; |
| 1192 | 1114 | |
| 1193 | - // The stars tab lists only starred repos the viewer may read. | |
| 1194 | 1115 | let mira = site |
| 1195 | 1116 | .store |
| 1196 | 1117 | .create_user("mira", None, "not-a-real-hash", false) |
| @@ -1212,8 +1133,6 @@ mod tests { | ||
| 1212 | 1133 | "stars: private starred repo" |
| 1213 | 1134 | ); |
| 1214 | 1135 | |
| 1215 | - // Members and teams pages have no sidebar; their tab bar leads to both, and a member gets no | |
| 1216 | - // settings link. Owners edit the organization from its profile. | |
| 1217 | 1136 | let kaan = site |
| 1218 | 1137 | .store |
| 1219 | 1138 | .create_user("kaan", None, "not-a-real-hash", false) |
| @@ -1255,7 +1174,6 @@ mod tests { | ||
| 1255 | 1174 | !member_profile.contains("href=\"/org/forge-org/settings\""), |
| 1256 | 1175 | "org profile: member has no edit button" |
| 1257 | 1176 | ); |
| 1258 | - // Settings keeps a sidebar of its own pages, and its back link goes to the profile. | |
| 1259 | 1177 | let (_, settings) = get(&site.router, "/org/forge-org/settings", Some(&owner_cookie)).await; |
| 1260 | 1178 | assert!( |
| 1261 | 1179 | !settings.contains("/org/forge-org/settings/pins"), |
| @@ -1270,7 +1188,6 @@ mod tests { | ||
| 1270 | 1188 | "org settings: Overview tab goes to the profile" |
| 1271 | 1189 | ); |
| 1272 | 1190 | |
| 1273 | - // Org pins show on the org profile, with an edit link for owners only. | |
| 1274 | 1191 | let acme = site.store.create_org("acme", &tahinli).await.unwrap(); |
| 1275 | 1192 | let lib = site |
| 1276 | 1193 | .store |
| @@ -1306,8 +1223,6 @@ mod tests { | ||
| 1306 | 1223 | ); |
| 1307 | 1224 | } |
| 1308 | 1225 | |
| 1309 | - /// Pins, the popular-repos fallback and the display name, on one seeded site. The | |
| 1310 | - /// scenarios run in order, and each one sets the pins or name the next one reads. | |
| 1311 | 1226 | #[tokio::test] |
| 1312 | 1227 | async fn pins_fallback_and_display_name() { |
| 1313 | 1228 | let site = seeded().await; |
| @@ -1317,7 +1232,6 @@ mod tests { | ||
| 1317 | 1232 | let open = id_of("open-repo"); |
| 1318 | 1233 | let secret = id_of("secret-repo"); |
| 1319 | 1234 | |
| 1320 | - // Pins: anonymous visitors see the public pin only; the owner sees both. | |
| 1321 | 1235 | site.store |
| 1322 | 1236 | .set_profile_pins(&tahinli, &[open, secret.clone()]) |
| 1323 | 1237 | .await |
| @@ -1359,7 +1273,6 @@ mod tests { | ||
| 1359 | 1273 | "pins: owner edits them on the profile" |
| 1360 | 1274 | ); |
| 1361 | 1275 | |
| 1362 | - // Fallback: with no visible pin, the overview shows popular repos instead. | |
| 1363 | 1276 | site.store |
| 1364 | 1277 | .set_profile_pins(&tahinli, &[secret]) |
| 1365 | 1278 | .await |
| @@ -1372,7 +1285,6 @@ mod tests { | ||
| 1372 | 1285 | "fallback: private repo hidden" |
| 1373 | 1286 | ); |
| 1374 | 1287 | |
| 1375 | - // Display name: the heading uses it with the username below; a blank name falls back. | |
| 1376 | 1288 | site.store |
| 1377 | 1289 | .set_display_name(&tahinli, "Ahmet Kaan Gümüş") |
| 1378 | 1290 | .await |
| @@ -1400,7 +1312,6 @@ mod tests { | ||
| 1400 | 1312 | ); |
| 1401 | 1313 | } |
| 1402 | 1314 | |
| 1403 | - /// The calendar sits on the overview. An old `?tab=contributions` link falls through to it. | |
| 1404 | 1315 | #[tokio::test] |
| 1405 | 1316 | async fn overview_holds_the_calendar() { |
| 1406 | 1317 | let site = seeded().await; |
| @@ -1416,7 +1327,6 @@ mod tests { | ||
| 1416 | 1327 | assert!(day.contains("class=\"heat\""), "day link: calendar"); |
| 1417 | 1328 | } |
| 1418 | 1329 | |
| 1419 | - /// The calendar's stream is the profile's own: an unknown name is 404. | |
| 1420 | 1330 | #[tokio::test] |
| 1421 | 1331 | async fn profile_events_is_404_for_an_unknown_user() { |
| 1422 | 1332 | let site = seeded().await; |
| @@ -1428,7 +1338,6 @@ mod tests { | ||
| 1428 | 1338 | body.matches(needle).count() |
| 1429 | 1339 | } |
| 1430 | 1340 | |
| 1431 | - /// A user with 35 public repos, `bulk-00` to `bulk-34`. | |
| 1432 | 1341 | async fn bulk_site() -> Site { |
| 1433 | 1342 | let site = site().await; |
| 1434 | 1343 | let tahinli = site |
| @@ -1455,12 +1364,10 @@ mod tests { | ||
| 1455 | 1364 | store.user_by_username(name).await.unwrap().unwrap().id |
| 1456 | 1365 | } |
| 1457 | 1366 | |
| 1458 | - /// Pagination and the name filter on one 35-repo site. | |
| 1459 | 1367 | #[tokio::test] |
| 1460 | 1368 | async fn repositories_tab_paging_and_name_filter() { |
| 1461 | 1369 | let site = bulk_site().await; |
| 1462 | 1370 | |
| 1463 | - // Ten repos per page, the last five on page four. | |
| 1464 | 1371 | let (status, first) = get(&site.router, "/tahinli?tab=repositories&sort=name", None).await; |
| 1465 | 1372 | assert_eq!(status, 200, "paging: first page"); |
| 1466 | 1373 | assert_eq!( |
| @@ -1490,7 +1397,6 @@ mod tests { | ||
| 1490 | 1397 | "paging: first repo not on page two" |
| 1491 | 1398 | ); |
| 1492 | 1399 | |
| 1493 | - // The name filter is a case-insensitive substring match. | |
| 1494 | 1400 | let (_, body) = get(&site.router, "/tahinli?tab=repositories&q=BULK-1", None).await; |
| 1495 | 1401 | assert_eq!( |
| 1496 | 1402 | count(&body, "class=\"name repo-name\""), |
crates/forge-web-account/src/pages/profile_calendar.rsmodified+11 -16
| @@ -20,6 +20,14 @@ pub(crate) fn calendar_since() -> String { | ||
| 20 | 20 | forge_core::time::stamp_ago(Duration::from_secs((CALENDAR_DAYS + 1) * 86_400)) |
| 21 | 21 | } |
| 22 | 22 | |
| 23 | +fn ymd(date: civil::Date) -> (i64, i64, i64) { | |
| 24 | + ( | |
| 25 | + i64::from(date.year()), | |
| 26 | + i64::from(date.month()), | |
| 27 | + i64::from(date.day()), | |
| 28 | + ) | |
| 29 | +} | |
| 30 | + | |
| 23 | 31 | /// The day the `day` query asks for: a strict `YYYY-MM-DD` date from the calendar's first day to |
| 24 | 32 | /// today. Anything else (malformed, a future day, or before the calendar) is ignored. |
| 25 | 33 | pub(crate) fn selected_day( |
| @@ -33,12 +41,7 @@ pub(crate) fn selected_day( | ||
| 33 | 41 | if date.to_string() != text { |
| 34 | 42 | return None; |
| 35 | 43 | } |
| 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) | |
| 42 | 45 | } |
| 43 | 46 | |
| 44 | 47 | /// The contributions the user made on their local day `date`, newest first. |
| @@ -58,11 +61,7 @@ pub(crate) async fn day_detail( | ||
| 58 | 61 | .contributions_between(&user.id, &from, &to) |
| 59 | 62 | .await?; |
| 60 | 63 | 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), | |
| 66 | 65 | items, |
| 67 | 66 | })) |
| 68 | 67 | } |
| @@ -74,11 +73,7 @@ pub(crate) async fn load_calendar( | ||
| 74 | 73 | day: Option<&str>, |
| 75 | 74 | ) -> Result<(Calendar, Option<DayDetail>)> { |
| 76 | 75 | 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()); | |
| 82 | 77 | let counts = state |
| 83 | 78 | .store |
| 84 | 79 | .contribution_counts(&user.id, &calendar_since(), &user.timezone) |
crates/forge-web-account/src/pages/register.rsmodified+13 -11
| @@ -215,11 +215,10 @@ async fn create_account( | ||
| 215 | 215 | ) -> Result<std::result::Result<User, String>> { |
| 216 | 216 | let username = match validate_username(&form.username) { |
| 217 | 217 | 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 | + }, | |
| 223 | 222 | }; |
| 224 | 223 | if let Some(message) = check_new_password(lang, &form.password, &form.confirm) { |
| 225 | 224 | return Ok(Err(message)); |
| @@ -229,9 +228,10 @@ async fn create_account( | ||
| 229 | 228 | None => { |
| 230 | 229 | let address = form.email.trim().to_owned(); |
| 231 | 230 | 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 | + } | |
| 235 | 235 | } |
| 236 | 236 | address |
| 237 | 237 | } |
| @@ -423,11 +423,13 @@ async fn verify_resend(cx: &Cx, Form(form): Form<ResendForm>) -> Result<SeeOther | ||
| 423 | 423 | } |
| 424 | 424 | if let Some(address) = viewer.0.email.clone() |
| 425 | 425 | && !state.store.email_is_verified(&viewer.0.id).await? |
| 426 | - && !account::send_verify(state, &viewer.0, &address).await? | |
| 427 | 426 | { |
| 428 | - return Ok(see_other("/settings/security?saved=verify_wait")); | |
| 427 | + if !account::send_verify(state, &viewer.0, &address).await? { | |
| 428 | + return Ok(see_other("/settings/security?saved=verify_wait")); | |
| 429 | + } | |
| 430 | + return Ok(see_other("/settings/security?saved=verify_sent")); | |
| 429 | 431 | } |
| 430 | - Ok(see_other("/settings/security?saved=verify_sent")) | |
| 432 | + Ok(see_other("/settings/security")) | |
| 431 | 433 | } |
| 432 | 434 | |
| 433 | 435 | #[cfg(test)] |
crates/forge-web-account/src/pages/releases_tests.rsmodified+730 -884
| @@ -1,12 +1,11 @@ | ||
| 1 | -//! Router-level tests for releases: permissions, drafts, tags, asset upload and download, the | |
| 2 | -//! download counter, the size cap and deletion. Each test runs against a real bare repo. | |
| 3 | - | |
| 4 | 1 | use std::path::{Path, PathBuf}; |
| 5 | 2 | |
| 6 | 3 | use forge_core::releases::Release; |
| 7 | 4 | use forge_core::{Repo, Role, Store, User, Visibility}; |
| 8 | 5 | use forge_git::repo::{init_bare, repo_path}; |
| 6 | +use futures_util::StreamExt; | |
| 9 | 7 | use topcoat::router::request::Request; |
| 8 | +use topcoat::router::response::Response; | |
| 10 | 9 | use topcoat::router::{Body, HeaderMap, Router, to_bytes}; |
| 11 | 10 | |
| 12 | 11 | use crate::auth::SESSION_COOKIE; |
| @@ -15,6 +14,8 @@ use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; | ||
| 15 | 14 | use crate::test_support::{app_router, create_session, test_state}; |
| 16 | 15 | |
| 17 | 16 | const CSRF: &str = "releases-test-csrf"; |
| 17 | +const FORM_TYPE: &str = "application/x-www-form-urlencoded"; | |
| 18 | +const CHANGED: &[u8] = b"event: changed\ndata: 1\n\n"; | |
| 18 | 19 | |
| 19 | 20 | fn git(dir: &Path, args: &[&str]) -> String { |
| 20 | 21 | let out = std::process::Command::new("git") |
| @@ -89,9 +90,6 @@ fn form(pairs: &[(&str, &str)]) -> Vec<u8> { | ||
| 89 | 90 | .into_bytes() |
| 90 | 91 | } |
| 91 | 92 | |
| 92 | -const FORM_TYPE: &str = "application/x-www-form-urlencoded"; | |
| 93 | - | |
| 94 | -/// One multipart body: `csrf` first, then a `file` field with the given name and bytes. | |
| 95 | 93 | fn upload_body(file_name: &str, data: &[u8]) -> (String, Vec<u8>) { |
| 96 | 94 | crate::pages::settings_profile::tests::multipart(&[ |
| 97 | 95 | ("csrf", None, CSRF.as_bytes()), |
| @@ -111,8 +109,6 @@ struct Fixture { | ||
| 111 | 109 | bob_cookie: String, |
| 112 | 110 | } |
| 113 | 111 | |
| 114 | -/// Tahinli owns the public repo `tahinli/proj` with `main` holding one commit. Bob is a Read | |
| 115 | -/// collaborator. `max_mb` replaces the asset size limit when given. | |
| 116 | 112 | async fn fixture(max_mb: Option<u64>) -> Fixture { |
| 117 | 113 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 118 | 114 | let mut state = test_state(tmp.path()).await; |
| @@ -183,8 +179,7 @@ impl Fixture { | ||
| 183 | 179 | .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 184 | 180 | } |
| 185 | 181 | |
| 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 { | |
| 188 | 183 | self.store |
| 189 | 184 | .create_release(&forge_core::releases::NewRelease { |
| 190 | 185 | repo_id: &self.repo.id, |
| @@ -212,9 +207,20 @@ impl Fixture { | ||
| 212 | 207 | ) |
| 213 | 208 | .await |
| 214 | 209 | } |
| 210 | + | |
| 211 | + async fn download(&self, path: &str) -> Reply { | |
| 212 | + send( | |
| 213 | + &self.app, | |
| 214 | + "GET", | |
| 215 | + &format!("/tahinli/proj/releases/download/{path}"), | |
| 216 | + None, | |
| 217 | + None, | |
| 218 | + Vec::new(), | |
| 219 | + ) | |
| 220 | + .await | |
| 221 | + } | |
| 215 | 222 | } |
| 216 | 223 | |
| 217 | -/// The release's own fields, unchanged, with no tag change. | |
| 218 | 224 | fn keep(rel: &Release) -> EditRelease { |
| 219 | 225 | EditRelease { |
| 220 | 226 | title: rel.title.clone(), |
| @@ -226,7 +232,6 @@ fn keep(rel: &Release) -> EditRelease { | ||
| 226 | 232 | } |
| 227 | 233 | } |
| 228 | 234 | |
| 229 | -/// Adds a commit on top of `main` and points branch `next` at it. Returns the new commit. | |
| 230 | 235 | fn second_commit(fx: &Fixture) -> String { |
| 231 | 236 | let tree = git(&fx.bare, &["rev-parse", "refs/heads/main^{tree}"]); |
| 232 | 237 | let next = git( |
| @@ -237,771 +242,656 @@ fn second_commit(fx: &Fixture) -> String { | ||
| 237 | 242 | next |
| 238 | 243 | } |
| 239 | 244 | |
| 240 | -// Each test below builds one fixture and runs its scenarios in order. Scenarios use their own | |
| 241 | -// tags and releases so they do not interfere, and the blob-count check in the size-cap test runs | |
| 242 | -// first, before any blob exists in its fixture. | |
| 243 | - | |
| 244 | 245 | #[tokio::test] |
| 245 | 246 | async fn drafts_and_permissions_share_one_repo() { |
| 246 | 247 | let fx = fixture(None).await; |
| 247 | 248 | |
| 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) | |
| 382 | 253 | .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 | + ); | |
| 386 | 271 | |
| 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 | + ); | |
| 399 | 287 | |
| 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 | + ); | |
| 403 | 331 | |
| 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) | |
| 431 | 345 | .await |
| 432 | 346 | .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 | + ); | |
| 478 | 351 | |
| 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) | |
| 481 | 357 | .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 | + ); | |
| 489 | 361 | |
| 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 | + ); | |
| 503 | 382 | } |
| 504 | 383 | |
| 505 | 384 | #[tokio::test] |
| 506 | -async fn retagging_rules_hold_for_published_and_draft_releases() { | |
| 385 | +async fn creating_and_retagging_releases_take_tags_and_targets() { | |
| 507 | 386 | let fx = fixture(None).await; |
| 508 | 387 | |
| 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"); | |
| 536 | 453 | |
| 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 | + ); | |
| 557 | 463 | |
| 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") | |
| 578 | 496 | .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 | + ); | |
| 583 | 501 | |
| 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 | + ); | |
| 601 | 520 | |
| 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 | + ); | |
| 631 | 577 | } |
| 632 | 578 | |
| 633 | 579 | #[tokio::test] |
| 634 | 580 | async fn the_edit_page_and_its_form_follow_the_publish_state() { |
| 635 | 581 | let fx = fixture(None).await; |
| 636 | 582 | |
| 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 | + ); | |
| 672 | 615 | |
| 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 | + ); | |
| 708 | 648 | |
| 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())); | |
| 749 | 686 | } |
| 750 | 687 | |
| 751 | 688 | #[tokio::test] |
| 752 | 689 | async fn asset_upload_replace_download_delete_and_csrf_rules() { |
| 753 | 690 | let fx = fixture(None).await; |
| 754 | 691 | |
| 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 | + ); | |
| 816 | 704 | |
| 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 | |
| 825 | 735 | .store |
| 826 | 736 | .release_asset(&rel.id, "app.bin") |
| 827 | 737 | .await |
| 828 | 738 | .expect("read") |
| 829 | 739 | .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"); | |
| 870 | 741 | } |
| 871 | 742 | |
| 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) | |
| 888 | 746 | .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"); | |
| 893 | 758 | |
| 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) | |
| 931 | 761 | .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"); | |
| 934 | 786 | |
| 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) | |
| 950 | 790 | .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 | + ); | |
| 960 | 806 | |
| 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) | |
| 972 | 857 | .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 | + ); | |
| 977 | 861 | |
| 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) | |
| 986 | 866 | .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"); | |
| 1005 | 895 | } |
| 1006 | 896 | |
| 1007 | 897 | #[tokio::test] |
| @@ -1009,175 +899,131 @@ async fn the_size_cap_refuses_new_and_replacement_uploads() { | ||
| 1009 | 899 | let fx = fixture(Some(1)).await; |
| 1010 | 900 | let big = vec![7u8; 1024 * 1024 + 4096]; |
| 1011 | 901 | |
| 1012 | - // Runs first: no blob may exist yet, so the blob directory must stay empty. | |
| 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) | |
| 1058 | 917 | .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) | |
| 1070 | 929 | .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"); | |
| 1073 | 949 | } |
| 1074 | 950 | |
| 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); | |
| 1091 | 955 | } |
| 956 | + fx.app | |
| 957 | + .handle(builder.body(Body::empty()).expect("request")) | |
| 958 | + .await | |
| 959 | +} | |
| 1092 | 960 | |
| 1093 | - const CHANGED: &[u8] = b"event: changed\ndata: 1\n\n"; | |
| 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; | |
| 1127 | 964 | |
| 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 | + ); | |
| 1147 | 992 | |
| 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) | |
| 1156 | 1002 | .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 | + ); | |
| 1169 | 1014 | |
| 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 | + ); | |
| 1183 | 1029 | } |
crates/forge-web-account/src/pages/settings_appearance.rsmodified+72 -192
| @@ -1,8 +1,3 @@ | ||
| 1 | -//! Page: appearance (`/settings/appearance`). The colour theme, the language, the sound alerts, and | |
| 2 | -//! for each of the light and dark themes a background and an accent colour, all stored per user. | |
| 3 | -//! Every change saves at once, so the form has no Save button. Anonymous visitors set the theme from | |
| 4 | -//! the footer instead (see `pages/theme_cookie.rs`). Every POST checks the CSRF token first. | |
| 5 | - | |
| 6 | 1 | use std::collections::HashMap; |
| 7 | 2 | |
| 8 | 3 | use forge_core::AuditAction; |
| @@ -29,18 +24,10 @@ use crate::state::AppState; | ||
| 29 | 24 | use crate::views::parts::{SubPart, head}; |
| 30 | 25 | use crate::views::shell; |
| 31 | 26 | |
| 32 | -/// Language codes offered on the page. `auto` follows the browser. Other codes must be | |
| 33 | -/// translated in `i18n/mod.rs` before they are added here. | |
| 34 | 27 | pub const LANGUAGE_CODES: &[&str] = &["auto", "en", "tr"]; |
| 35 | 28 | |
| 36 | -/// Theme codes, in display order. | |
| 37 | -const THEME_CODES: &[&str] = &["auto", "light", "dark"]; | |
| 38 | - | |
| 39 | -/// The colour tabs, in display order: the light theme's colours, then the dark theme's. | |
| 40 | 29 | const TAB_CODES: &[&str] = &["light", "dark"]; |
| 41 | 30 | |
| 42 | -/// Reads a field that is present as a string, even an empty one. The plain `Option<String>` | |
| 43 | -/// reading would turn an empty value into `None`, which is the same as a missing field. | |
| 44 | 31 | fn present_string<'de, D: Deserializer<'de>>( |
| 45 | 32 | de: D, |
| 46 | 33 | ) -> std::result::Result<Option<String>, D::Error> { |
| @@ -55,9 +42,6 @@ struct AppearanceForm { | ||
| 55 | 42 | theme: String, |
| 56 | 43 | #[serde(default)] |
| 57 | 44 | language: String, |
| 58 | - /// The four colour fields are optional so a form loaded before a field existed still saves. | |
| 59 | - /// When a field is absent, its stored value is kept. A present but empty or unknown value | |
| 60 | - /// stays `Some("")` or an unknown id, and is rejected. | |
| 61 | 45 | #[serde(default, deserialize_with = "present_string")] |
| 62 | 46 | accent_light: Option<String>, |
| 63 | 47 | #[serde(default, deserialize_with = "present_string")] |
| @@ -68,8 +52,6 @@ struct AppearanceForm { | ||
| 68 | 52 | base_dark: Option<String>, |
| 69 | 53 | #[serde(default, deserialize_with = "present_string")] |
| 70 | 54 | sidebar_side: Option<String>, |
| 71 | - /// Present when the form that holds the sound switch was posted: an unchecked switch posts | |
| 72 | - /// nothing, so this tells off from a post that never showed the switch. | |
| 73 | 55 | #[serde(default, deserialize_with = "present_string")] |
| 74 | 56 | sound_shown: Option<String>, |
| 75 | 57 | #[serde(default, deserialize_with = "present_string")] |
| @@ -80,12 +62,9 @@ struct Choice { | ||
| 80 | 62 | value: &'static str, |
| 81 | 63 | label: &'static str, |
| 82 | 64 | selected: bool, |
| 83 | - /// The hue a preset moves the stripe knob to, as text; empty when the preset has none. | |
| 84 | 65 | hue: String, |
| 85 | 66 | } |
| 86 | 67 | |
| 87 | -/// Where a row's sliders sit: the hue, the vividness, and the hex box's colour. `custom` says the | |
| 88 | -/// stored choice is that colour, rather than a preset whose hue the knob was moved to. | |
| 89 | 68 | struct Stripe { |
| 90 | 69 | hue: u16, |
| 91 | 70 | vivid: u8, |
| @@ -93,12 +72,9 @@ struct Stripe { | ||
| 93 | 72 | hex: String, |
| 94 | 73 | } |
| 95 | 74 | |
| 96 | -/// The vividness a row starts at when its stored id gives none (a legacy `hue-N`): 50 for an accent, | |
| 97 | -/// 30 for a background. These are the defaults of `accent::custom_of`. | |
| 98 | 75 | const ACCENT_VIVID: u8 = 50; |
| 99 | 76 | const BASE_VIVID: u8 = 30; |
| 100 | 77 | |
| 101 | -/// The lightness a row's hex box uses, in one theme: the accent's, or the background's. | |
| 102 | 78 | fn row_lightness(base: bool, dark: bool) -> f64 { |
| 103 | 79 | match (base, dark) { |
| 104 | 80 | (false, true) => 0.75, |
| @@ -108,8 +84,6 @@ fn row_lightness(base: bool, dark: bool) -> f64 { | ||
| 108 | 84 | } |
| 109 | 85 | } |
| 110 | 86 | |
| 111 | -/// The `#RRGGBB` a row's hex box shows for a hue and vividness: the colour the sliders stand for, | |
| 112 | -/// at the row's lightness. The chroma is the one the stylesheet gives that vividness. | |
| 113 | 87 | fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String { |
| 114 | 88 | let v = f64::from(vivid); |
| 115 | 89 | let chroma = if base { |
| @@ -122,36 +96,14 @@ fn picker_hex(hue: u16, vivid: u8, base: bool, dark: bool) -> String { | ||
| 122 | 96 | custom_colour::colour(row_lightness(base, dark), chroma, f64::from(hue)) |
| 123 | 97 | } |
| 124 | 98 | |
| 125 | -/// The colour choices of one theme: a background and an accent, each a row of presets and the hue, | |
| 126 | -/// vividness and hex controls. `dark` picks the field names and the swatch attributes that belong to | |
| 127 | -/// the dark theme. | |
| 128 | -struct ColourGroup { | |
| 129 | - dark: bool, | |
| 130 | - background: &'static str, | |
| 131 | - accent: &'static str, | |
| 132 | - custom: &'static str, | |
| 133 | - hue: &'static str, | |
| 134 | - vividness: &'static str, | |
| 135 | - hex: &'static str, | |
| 136 | - bases: Vec<Choice>, | |
| 137 | - accents: Vec<Choice>, | |
| 138 | - base_stripe: Stripe, | |
| 139 | - accent_stripe: Stripe, | |
| 140 | -} | |
| 141 | - | |
| 142 | -/// One row of a colour panel: its presets, then the Custom choice beside the hue, vividness and hex | |
| 143 | -/// controls. `base` picks the background's chips and the accent's when false. | |
| 144 | 99 | struct ColourRow { |
| 100 | + lang: Lang, | |
| 145 | 101 | dark: bool, |
| 146 | 102 | base: bool, |
| 147 | 103 | legend: &'static str, |
| 148 | 104 | field: &'static str, |
| 149 | 105 | choices: Vec<Choice>, |
| 150 | 106 | stripe: Stripe, |
| 151 | - custom_label: &'static str, | |
| 152 | - hue_label: &'static str, | |
| 153 | - vivid_label: &'static str, | |
| 154 | - hex_label: &'static str, | |
| 155 | 107 | } |
| 156 | 108 | |
| 157 | 109 | struct AppearancePage { |
| @@ -160,16 +112,13 @@ struct AppearancePage { | ||
| 160 | 112 | theme: Vec<Choice>, |
| 161 | 113 | language: Vec<Choice>, |
| 162 | 114 | colours: &'static str, |
| 163 | - /// The tab that opens first: the light or the dark colours. | |
| 164 | 115 | tab: &'static str, |
| 165 | 116 | 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], | |
| 169 | 119 | sound_on: bool, |
| 170 | 120 | } |
| 171 | 121 | |
| 172 | -/// The label of a language code. The two native names stay as they are in every language. | |
| 173 | 122 | fn language_label(lang: Lang, code: &str) -> &'static str { |
| 174 | 123 | match code { |
| 175 | 124 | "auto" => g::t(lang, K::MatchBrowser), |
| @@ -179,8 +128,6 @@ fn language_label(lang: Lang, code: &str) -> &'static str { | ||
| 179 | 128 | } |
| 180 | 129 | } |
| 181 | 130 | |
| 182 | -/// The label of a theme code. Light is the default for everyone who has not chosen, so it is | |
| 183 | -/// marked as the default. | |
| 184 | 131 | fn theme_label(lang: Lang, code: &str) -> &'static str { |
| 185 | 132 | match code { |
| 186 | 133 | "light" => match lang { |
| @@ -208,7 +155,6 @@ fn choices( | ||
| 208 | 155 | .collect() |
| 209 | 156 | } |
| 210 | 157 | |
| 211 | -/// The label of a colour tab: the light or the dark theme. | |
| 212 | 158 | fn tab_label(lang: Lang, code: &str) -> &'static str { |
| 213 | 159 | if code == "dark" { |
| 214 | 160 | g::t(lang, K::Dark) |
| @@ -217,7 +163,6 @@ fn tab_label(lang: Lang, code: &str) -> &'static str { | ||
| 217 | 163 | } |
| 218 | 164 | } |
| 219 | 165 | |
| 220 | -/// Fills in the hue each preset moves the stripe knob to. | |
| 221 | 166 | fn with_hues(mut list: Vec<Choice>, hue: fn(&str) -> Option<u16>) -> Vec<Choice> { |
| 222 | 167 | for choice in &mut list { |
| 223 | 168 | choice.hue = hue(choice.value).map(|h| h.to_string()).unwrap_or_default(); |
| @@ -225,8 +170,6 @@ fn with_hues(mut list: Vec<Choice>, hue: fn(&str) -> Option<u16>) -> Vec<Choice> | ||
| 225 | 170 | list |
| 226 | 171 | } |
| 227 | 172 | |
| 228 | -/// The id a row shows as selected. A custom hue stays as stored; a preset is resolved, so an id | |
| 229 | -/// that is no longer offered shows the default, as the page renders it on `<html>`. | |
| 230 | 173 | fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str { |
| 231 | 174 | if hue_of(stored).is_some() { |
| 232 | 175 | stored |
| @@ -235,9 +178,6 @@ fn shown<'a>(stored: &'a str, resolved: &'static str) -> &'a str { | ||
| 235 | 178 | } |
| 236 | 179 | } |
| 237 | 180 | |
| 238 | -/// The sliders of one row. A stored custom id (`hue-H-vV`, or the legacy `hue-H`) sets the hue and | |
| 239 | -/// vividness; a preset puts the hue knob on the preset's hue at the default vividness, and nothing | |
| 240 | -/// is selected as custom. | |
| 241 | 181 | fn stripe(stored: &str, preset: Option<u16>, base: bool, dark: bool) -> Stripe { |
| 242 | 182 | let default_vivid = if base { BASE_VIVID } else { ACCENT_VIVID }; |
| 243 | 183 | let (hue, vivid, custom) = match custom_of(stored, default_vivid) { |
| @@ -252,50 +192,59 @@ fn stripe(stored: &str, preset: Option<u16>, base: bool, dark: bool) -> Stripe { | ||
| 252 | 192 | } |
| 253 | 193 | } |
| 254 | 194 | |
| 255 | -/// One theme's colour choices, with the stored background and accent selected. | |
| 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] { | |
| 257 | 196 | let base_codes: Vec<&'static str> = accent::base_ids().collect(); |
| 258 | 197 | let accent_codes: Vec<&'static str> = accent::ids().collect(); |
| 259 | 198 | let base_shown = shown(base, accent::resolve_base(base).id); |
| 260 | 199 | 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 | + ] | |
| 280 | 231 | } |
| 281 | 232 | |
| 282 | -/// One row of a colour panel: its presets as round radios, then the Custom choice, a hue slider, a | |
| 283 | -/// vividness slider and a hex box. The Custom radio carries `hue-H-vV`, and nav.js keeps it, the | |
| 284 | -/// sliders and the hex box in step while the row is used. | |
| 285 | 233 | #[component] |
| 286 | 234 | async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> { |
| 287 | 235 | let ColourRow { |
| 236 | + lang, | |
| 288 | 237 | dark, |
| 289 | 238 | base, |
| 290 | 239 | legend, |
| 291 | 240 | field, |
| 292 | 241 | choices, |
| 293 | 242 | stripe, |
| 294 | - custom_label, | |
| 295 | - hue_label, | |
| 296 | - vivid_label, | |
| 297 | - hex_label, | |
| 298 | 243 | } = row; |
| 244 | + let custom_label = g::t(lang, K::CustomLabel); | |
| 245 | + let hue_label = g::t(lang, K::HueLabel); | |
| 246 | + let vivid_label = g::t(lang, K::VividnessLabel); | |
| 247 | + let hex_label = g::t(lang, K::HexLabel); | |
| 299 | 248 | let value = custom_id(stripe.hue, stripe.vivid); |
| 300 | 249 | let hue_value = stripe.hue.to_string(); |
| 301 | 250 | let vivid_value = stripe.vivid.to_string(); |
| @@ -350,57 +299,6 @@ async fn colour_row(cx: &Cx, row: ColourRow) -> Result<impl View> { | ||
| 350 | 299 | }) |
| 351 | 300 | } |
| 352 | 301 | |
| 353 | -/// One theme's panel: a Background row and an Accent row. | |
| 354 | -#[component] | |
| 355 | -async fn colour_panel(cx: &Cx, group: ColourGroup) -> Result<impl View> { | |
| 356 | - let ColourGroup { | |
| 357 | - dark, | |
| 358 | - background, | |
| 359 | - accent, | |
| 360 | - custom, | |
| 361 | - hue, | |
| 362 | - vividness, | |
| 363 | - hex, | |
| 364 | - bases, | |
| 365 | - accents, | |
| 366 | - base_stripe, | |
| 367 | - accent_stripe, | |
| 368 | - } = group; | |
| 369 | - let base_field = if dark { "base_dark" } else { "base_light" }; | |
| 370 | - let accent_field = if dark { "accent_dark" } else { "accent_light" }; | |
| 371 | - let panel = if dark { "dark" } else { "light" }; | |
| 372 | - let base_row = ColourRow { | |
| 373 | - dark, | |
| 374 | - base: true, | |
| 375 | - legend: background, | |
| 376 | - field: base_field, | |
| 377 | - choices: bases, | |
| 378 | - stripe: base_stripe, | |
| 379 | - custom_label: custom, | |
| 380 | - hue_label: hue, | |
| 381 | - vivid_label: vividness, | |
| 382 | - hex_label: hex, | |
| 383 | - }; | |
| 384 | - let accent_row = ColourRow { | |
| 385 | - dark, | |
| 386 | - base: false, | |
| 387 | - legend: accent, | |
| 388 | - field: accent_field, | |
| 389 | - choices: accents, | |
| 390 | - stripe: accent_stripe, | |
| 391 | - custom_label: custom, | |
| 392 | - hue_label: hue, | |
| 393 | - vivid_label: vividness, | |
| 394 | - hex_label: hex, | |
| 395 | - }; | |
| 396 | - Ok(view! { | |
| 397 | - <div class="colour-panel" data-colour-panel=(panel)> | |
| 398 | - colour_row(row: base_row) | |
| 399 | - colour_row(row: accent_row) | |
| 400 | - </div> | |
| 401 | - }) | |
| 402 | -} | |
| 403 | - | |
| 404 | 302 | #[component] |
| 405 | 303 | async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> { |
| 406 | 304 | let AppearancePage { |
| @@ -411,8 +309,8 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> { | ||
| 411 | 309 | colours, |
| 412 | 310 | tab, |
| 413 | 311 | tabs, |
| 414 | - light, | |
| 415 | - dark, | |
| 312 | + light: [light_base, light_accent], | |
| 313 | + dark: [dark_base, dark_accent], | |
| 416 | 314 | sound_on, |
| 417 | 315 | } = page; |
| 418 | 316 | Ok(view! { |
| @@ -456,8 +354,14 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> { | ||
| 456 | 354 | } |
| 457 | 355 | </div> |
| 458 | 356 | </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> | |
| 461 | 365 | </fieldset> |
| 462 | 366 | </section> |
| 463 | 367 | <section class="sec"> |
| @@ -486,7 +390,6 @@ async fn appearance_body(cx: &Cx, page: AppearancePage) -> Result<impl View> { | ||
| 486 | 390 | }) |
| 487 | 391 | } |
| 488 | 392 | |
| 489 | -/// Rejects a theme or a language that is not offered. Nothing is saved for either of them. | |
| 490 | 393 | fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<()> { |
| 491 | 394 | if !THEMES.contains(&theme) { |
| 492 | 395 | return Err(CoreError::Invalid(g::t(lang, K::ChooseTheme).into())); |
| @@ -497,8 +400,6 @@ fn check_choice(lang: Lang, theme: &str, language: &str) -> forge_core::Result<( | ||
| 497 | 400 | Ok(()) |
| 498 | 401 | } |
| 499 | 402 | |
| 500 | -/// The accent a save stores for one theme. An absent field keeps the stored id. A present one | |
| 501 | -/// must be an offered accent, so an empty or unknown value is rejected. | |
| 502 | 403 | fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> { |
| 503 | 404 | match posted { |
| 504 | 405 | None => Ok(stored.to_owned()), |
| @@ -507,8 +408,6 @@ fn accent_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core:: | ||
| 507 | 408 | } |
| 508 | 409 | } |
| 509 | 410 | |
| 510 | -/// The background a save stores for one theme. An absent field keeps the stored id. A present | |
| 511 | -/// one must be an offered base, so an empty or unknown value is rejected. | |
| 512 | 411 | fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> { |
| 513 | 412 | match posted { |
| 514 | 413 | None => Ok(stored.to_owned()), |
| @@ -517,8 +416,6 @@ fn base_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Re | ||
| 517 | 416 | } |
| 518 | 417 | } |
| 519 | 418 | |
| 520 | -/// The sidebar side a save stores. An absent field keeps the stored side. A present one must be | |
| 521 | -/// `left` or `right`, so an empty or unknown value is rejected. | |
| 522 | 419 | fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core::Result<String> { |
| 523 | 420 | match posted { |
| 524 | 421 | None => Ok(stored.to_owned()), |
| @@ -527,15 +424,11 @@ fn sidebar_choice(lang: Lang, posted: Option<&str>, stored: &str) -> forge_core: | ||
| 527 | 424 | } |
| 528 | 425 | } |
| 529 | 426 | |
| 530 | -/// The side a viewer's stored value stands for. Anything but `right` is `left`, the default, which | |
| 531 | -/// is also what the shell renders on `<html>` (see `views/mod.rs`). | |
| 532 | 427 | #[cfg(test)] |
| 533 | 428 | pub fn sidebar_stored(stored: &str) -> &'static str { |
| 534 | 429 | if stored == "right" { "right" } else { "left" } |
| 535 | 430 | } |
| 536 | 431 | |
| 537 | -/// Builds the page for a viewer. Each choice shows the stored value, or the default when the | |
| 538 | -/// stored id is no longer offered, which is what the page renders on `<html>` too. | |
| 539 | 432 | fn page_for( |
| 540 | 433 | viewer: &(User, Session), |
| 541 | 434 | lang: Lang, |
| @@ -543,8 +436,6 @@ fn page_for( | ||
| 543 | 436 | ) -> AppearancePage { |
| 544 | 437 | let user = &viewer.0; |
| 545 | 438 | let sound_on = prefs.get(SOUND).is_some_and(|v| v == "on"); |
| 546 | - // The tab that opens first is the dark colours for a dark theme. The page script moves it to | |
| 547 | - // the one the viewer sees when the theme follows the system. | |
| 548 | 439 | let tab = if user.theme == "dark" { |
| 549 | 440 | "dark" |
| 550 | 441 | } else { |
| @@ -553,7 +444,7 @@ fn page_for( | ||
| 553 | 444 | AppearancePage { |
| 554 | 445 | lang, |
| 555 | 446 | csrf: viewer.1.csrf_token.clone(), |
| 556 | - theme: choices(THEME_CODES, &user.theme, |code| theme_label(lang, code)), | |
| 447 | + theme: choices(THEMES, &user.theme, |code| theme_label(lang, code)), | |
| 557 | 448 | language: choices(LANGUAGE_CODES, &user.language, |code| { |
| 558 | 449 | language_label(lang, code) |
| 559 | 450 | }), |
| @@ -566,8 +457,6 @@ fn page_for( | ||
| 566 | 457 | } |
| 567 | 458 | } |
| 568 | 459 | |
| 569 | -/// A sound value a save stores. Absent (`None`) stores nothing. A present value must | |
| 570 | -/// be one offered, so an empty or unknown value is rejected. | |
| 571 | 460 | fn pref_choice( |
| 572 | 461 | lang: Lang, |
| 573 | 462 | posted: Option<&str>, |
| @@ -612,8 +501,6 @@ async fn appearance_save(cx: &Cx, Form(form): Form<AppearanceForm>) -> Result<Se | ||
| 612 | 501 | let base_light = base_choice(lang, form.base_light.as_deref(), &user.base_light)?; |
| 613 | 502 | let base_dark = base_choice(lang, form.base_dark.as_deref(), &user.base_dark)?; |
| 614 | 503 | let sidebar_side = sidebar_choice(lang, form.sidebar_side.as_deref(), &user.sidebar_side)?; |
| 615 | - // An unchecked switch posts nothing, so a form that showed it and sent no `sound` means off. A | |
| 616 | - // post that never showed it leaves the stored sound alone. | |
| 617 | 504 | let posted_sound = match (&form.sound_shown, &form.sound) { |
| 618 | 505 | (Some(_), None) => Some("off"), |
| 619 | 506 | (_, Some(value)) => Some(value.as_str()), |
| @@ -738,7 +625,6 @@ mod tests { | ||
| 738 | 625 | "base upper case {id}" |
| 739 | 626 | ); |
| 740 | 627 | } |
| 741 | - // Removed presets, and hue values that are out of range or not canonical, are refused. | |
| 742 | 628 | for id in [ |
| 743 | 629 | "teal", |
| 744 | 630 | "moss", |
| @@ -772,7 +658,6 @@ mod tests { | ||
| 772 | 658 | ); |
| 773 | 659 | } |
| 774 | 660 | |
| 775 | - // An absent colour keeps the stored value. | |
| 776 | 661 | assert_eq!( |
| 777 | 662 | accent_choice(Lang::En, None, "plum").unwrap(), |
| 778 | 663 | "plum", |
| @@ -796,11 +681,9 @@ mod tests { | ||
| 796 | 681 | assert!(base_err.to_string().contains("background"), "{base_err}"); |
| 797 | 682 | } |
| 798 | 683 | |
| 799 | - /// The colour groups mark the stored theme, accent and base as selected. A custom hue | |
| 800 | - /// fills its stripe and checks no preset; a preset moves the knob to its own hue. | |
| 801 | 684 | #[test] |
| 802 | 685 | fn stored_colours_are_selected_and_hues_drive_the_stripes() { |
| 803 | - let options = choices(THEME_CODES, "dark", |code| theme_label(Lang::En, code)); | |
| 686 | + let options = choices(THEMES, "dark", |code| theme_label(Lang::En, code)); | |
| 804 | 687 | let selected: Vec<&str> = options |
| 805 | 688 | .iter() |
| 806 | 689 | .filter(|c| c.selected) |
| @@ -822,44 +705,42 @@ mod tests { | ||
| 822 | 705 | "accent: default first" |
| 823 | 706 | ); |
| 824 | 707 | |
| 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 | |
| 828 | 711 | .iter() |
| 829 | 712 | .filter(|c| c.selected) |
| 830 | 713 | .map(|c| c.value) |
| 831 | 714 | .collect(); |
| 832 | 715 | assert_eq!(bases, ["ink"], "base: selected"); |
| 833 | 716 | assert_eq!( |
| 834 | - group.bases[0].value, | |
| 717 | + base_row.choices[0].value, | |
| 835 | 718 | forge_web_app::accent_palette::BASE_DEFAULT, |
| 836 | 719 | "base: default first" |
| 837 | 720 | ); |
| 838 | 721 | |
| 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"); | |
| 845 | 727 | assert!( |
| 846 | - group.bases.iter().all(|c| !c.selected), | |
| 728 | + base_row.choices.iter().all(|c| !c.selected), | |
| 847 | 729 | "custom hue: no base preset checked" |
| 848 | 730 | ); |
| 849 | 731 | assert!( |
| 850 | - group.accents.iter().all(|c| !c.selected), | |
| 732 | + accent_row.choices.iter().all(|c| !c.selected), | |
| 851 | 733 | "custom hue: no accent preset checked" |
| 852 | 734 | ); |
| 853 | 735 | |
| 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"); | |
| 856 | 737 | let plum_hue = preset_accent_hue("plum").unwrap(); |
| 857 | 738 | 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(); | |
| 863 | 744 | assert!(plum.selected, "preset accent: checked"); |
| 864 | 745 | assert_eq!(plum.hue, plum_hue.to_string(), "preset accent: hue value"); |
| 865 | 746 | |
| @@ -870,11 +751,10 @@ mod tests { | ||
| 870 | 751 | assert_eq!(hue_of("sage"), None, "hue: preset id"); |
| 871 | 752 | } |
| 872 | 753 | |
| 873 | - /// A stored `hue-95-v80` fills the hue and vividness sliders, and the Custom value is that id again. | |
| 874 | 754 | #[test] |
| 875 | 755 | 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; | |
| 878 | 758 | assert_eq!((accent.hue, accent.vivid), (95, 80), "accent: sliders"); |
| 879 | 759 | assert!(accent.custom, "accent: custom"); |
| 880 | 760 | assert_eq!( |
| @@ -883,7 +763,7 @@ mod tests { | ||
| 883 | 763 | "accent: value" |
| 884 | 764 | ); |
| 885 | 765 | assert_eq!( |
| 886 | - (group.base_stripe.hue, group.base_stripe.vivid), | |
| 766 | + (base_row.stripe.hue, base_row.stripe.vivid), | |
| 887 | 767 | (95, 80), |
| 888 | 768 | "base: sliders" |
| 889 | 769 | ); |
crates/forge-web-account/src/pages/settings_export.rsmodified+9 -11
| @@ -59,6 +59,10 @@ fn signature(exports: &[DataExport]) -> String { | ||
| 59 | 59 | .join(",") |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | +fn is_building(exports: &[DataExport]) -> bool { | |
| 63 | + exports.iter().any(|e| e.state == ExportState::Building) | |
| 64 | +} | |
| 65 | + | |
| 62 | 66 | /// The rail of the Data page: the archives, and the delete-account topic. |
| 63 | 67 | fn data_rail_items(lang: Lang, delete: bool) -> Vec<RailItem> { |
| 64 | 68 | vec![ |
| @@ -85,7 +89,7 @@ async fn export_sheet( | ||
| 85 | 89 | csrf: &str, |
| 86 | 90 | exports: Vec<DataExport>, |
| 87 | 91 | ) -> Result<impl View> { |
| 88 | - let building = exports.iter().any(|e| e.state == ExportState::Building); | |
| 92 | + let building = is_building(&exports); | |
| 89 | 93 | let live = building.then(|| { |
| 90 | 94 | format!( |
| 91 | 95 | "/settings/export/events?v={}", |
| @@ -93,10 +97,6 @@ async fn export_sheet( | ||
| 93 | 97 | ) |
| 94 | 98 | }); |
| 95 | 99 | let empty = exports.is_empty(); |
| 96 | - let deletes: Vec<String> = exports | |
| 97 | - .iter() | |
| 98 | - .map(|e| format!("/settings/export/{}/delete", e.id)) | |
| 99 | - .collect(); | |
| 100 | 100 | Ok(view! { |
| 101 | 101 | <div class="sheet export-page" data-live=(live.as_deref()) data-live-state=(if building { "building" } else { "idle" })> |
| 102 | 102 | <section class="sec"> |
| @@ -104,7 +104,8 @@ async fn export_sheet( | ||
| 104 | 104 | if empty { |
| 105 | 105 | <p class="state">(g::t(lang, K::ExportNone))</p> |
| 106 | 106 | } |
| 107 | - for (export, delete) in exports.iter().zip(deletes.iter()) { | |
| 107 | + for export in exports.iter() { | |
| 108 | + let delete = format!("/settings/export/{}/delete", export.id); | |
| 108 | 109 | <div class="export-row"> |
| 109 | 110 | <div class="line"> |
| 110 | 111 | <span class="name">(g::t(lang, K::ExportRequested)) " " rel_time(lang: lang, stamp: export.created_at.as_str())</span> |
| @@ -217,7 +218,7 @@ async fn data_body( | ||
| 217 | 218 | } else { |
| 218 | 219 | g::t(lang, K::ExportTitle) |
| 219 | 220 | }; |
| 220 | - let building = exports.iter().any(|e| e.state == ExportState::Building); | |
| 221 | + let building = is_building(&exports); | |
| 221 | 222 | Ok(view! { |
| 222 | 223 | head(title: title, sub: Vec::<SubPart>::new(), |
| 223 | 224 | if !delete { |
| @@ -267,9 +268,6 @@ async fn page_view( | ||
| 267 | 268 | None => StatusCode::OK, |
| 268 | 269 | }; |
| 269 | 270 | let csrf = viewer.1.csrf_token.clone(); |
| 270 | - // `view!` expects the `cx` binding that `#[page]` and `#[component]` provide. This plain | |
| 271 | - // helper has to bind it itself. | |
| 272 | - let cx = cx; | |
| 273 | 271 | Ok(view! { |
| 274 | 272 | (status) |
| 275 | 273 | (headers) |
| @@ -349,7 +347,7 @@ async fn export_events(cx: &Cx) -> Result<Response> { | ||
| 349 | 347 | loop { |
| 350 | 348 | let exports = store.list_exports(&user_id).await.ok()?; |
| 351 | 349 | let sig = signature(&exports); |
| 352 | - let building = exports.iter().any(|e| e.state == ExportState::Building); | |
| 350 | + let building = is_building(&exports); | |
| 353 | 351 | if sig != seen { |
| 354 | 352 | seen = sig; |
| 355 | 353 | return Some((changed_event("export".to_owned()), (wake, seen, !building))); |
crates/forge-web-account/src/pages/settings_gpg.rsmodified+4 -13
| @@ -8,14 +8,14 @@ use topcoat::Result; | ||
| 8 | 8 | use topcoat::context::{Cx, context}; |
| 9 | 9 | use topcoat::router::content::Form; |
| 10 | 10 | use topcoat::router::error::{SeeOther, not_found, see_other}; |
| 11 | -use topcoat::router::{page, query_params, route}; | |
| 11 | +use topcoat::router::{page, route}; | |
| 12 | 12 | use topcoat::view::{View, component, view}; |
| 13 | 13 | |
| 14 | 14 | use crate::audit::{self, Actor, Target}; |
| 15 | -use crate::auth::{require_csrf, require_user}; | |
| 15 | +use crate::auth::require_csrf; | |
| 16 | 16 | use crate::i18n::s; |
| 17 | 17 | use crate::i18n::{self, Key, Lang, t}; |
| 18 | -use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view}; | |
| 18 | +use crate::pages::settings_keys::{KeyKind, KeysDraft, kind_page, keys_page_view}; | |
| 19 | 19 | use crate::signatures; |
| 20 | 20 | use crate::state::AppState; |
| 21 | 21 | use crate::views::parts::confirm_act; |
| @@ -86,16 +86,7 @@ pub(crate) async fn gpg_section( | ||
| 86 | 86 | |
| 87 | 87 | #[page("/settings/gpg")] |
| 88 | 88 | 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 | |
| 99 | 90 | } |
| 100 | 91 | |
| 101 | 92 | #[page(POST "/settings/gpg")] |
crates/forge-web-account/src/pages/settings_keys.rsmodified+11 -6
| @@ -19,7 +19,7 @@ use crate::i18n::{self, Key, Lang, t, unsupported_key_type}; | ||
| 19 | 19 | use crate::pages::settings_gpg::gpg_section; |
| 20 | 20 | use crate::pages::settings_tokens::tokens_section; |
| 21 | 21 | use crate::state::AppState; |
| 22 | -use crate::views::parts::{RailItem, SubPart, confirm_act, head, rail}; | |
| 22 | +use crate::views::parts::{RailItem, confirm_act, head, rail}; | |
| 23 | 23 | use crate::views::{added_status, alert, shell, user_facing_message}; |
| 24 | 24 | |
| 25 | 25 | /// Algorithms accepted for web-registered keys. `ssh-rsa` is rejected with its own message. |
| @@ -32,6 +32,7 @@ const ACCEPTED: &[&str] = &[ | ||
| 32 | 32 | "sk-ecdsa-sha2-nistp256@openssh.com", |
| 33 | 33 | ]; |
| 34 | 34 | const MAX_KEY_CHARS: usize = 16 * 1024; |
| 35 | +const MAX_TITLE_CHARS: usize = 100; | |
| 35 | 36 | |
| 36 | 37 | /// Why a pasted key line is refused. `message` says it in the viewer's language. |
| 37 | 38 | #[derive(Debug, PartialEq, Eq)] |
| @@ -221,7 +222,6 @@ pub(crate) async fn keys_page_view( | ||
| 221 | 222 | current: k == kind, |
| 222 | 223 | }) |
| 223 | 224 | .collect(); |
| 224 | - let sub = Vec::<SubPart>::new(); | |
| 225 | 225 | let add_href = format!("{}?add=1", kind.href()); |
| 226 | 226 | let add_open = draft.add |
| 227 | 227 | || draft.ssh_error.is_some() |
| @@ -231,7 +231,7 @@ pub(crate) async fn keys_page_view( | ||
| 231 | 231 | let parents = vec![(pk_title(lang).to_owned(), "/settings/keys".to_owned())]; |
| 232 | 232 | Ok(view! { |
| 233 | 233 | shell(title: kind.title(lang), viewer: Some(viewer), parents: parents, |
| 234 | - head(title: kind.title(lang), sub: sub, | |
| 234 | + head(title: kind.title(lang), | |
| 235 | 235 | <a class="button primary" href=(add_href)>(kind.add_label(lang))</a> |
| 236 | 236 | ) |
| 237 | 237 | <div class="work"> |
| @@ -301,8 +301,7 @@ async fn ssh_section( | ||
| 301 | 301 | }) |
| 302 | 302 | } |
| 303 | 303 | |
| 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> { | |
| 306 | 305 | let viewer = require_user(cx).await?; |
| 307 | 306 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 308 | 307 | let state = context::<AppState>(cx); |
| @@ -311,10 +310,15 @@ async fn keys_page(cx: &Cx) -> Result<impl View> { | ||
| 311 | 310 | ..KeysDraft::default() |
| 312 | 311 | }; |
| 313 | 312 | Ok(view! { |
| 314 | - keys_page_view(lang: lang, state: state, viewer: &viewer, kind: KeyKind::Ssh, draft: draft) | |
| 313 | + keys_page_view(lang: lang, state: state, viewer: &viewer, kind: kind, draft: draft) | |
| 315 | 314 | }) |
| 316 | 315 | } |
| 317 | 316 | |
| 317 | +#[page("/settings/keys")] | |
| 318 | +async fn keys_page(cx: &Cx) -> Result<impl View> { | |
| 319 | + kind_page(cx, KeyKind::Ssh).await | |
| 320 | +} | |
| 321 | + | |
| 318 | 322 | #[page(POST "/settings/keys")] |
| 319 | 323 | async fn keys_add(cx: &Cx, Form(form): Form<AddKeyForm>) -> Result<impl View> { |
| 320 | 324 | let viewer = require_csrf(cx, &form.csrf).await?; |
| @@ -330,6 +334,7 @@ async fn keys_add(cx: &Cx, Form(form): Form<AddKeyForm>) -> Result<impl View> { | ||
| 330 | 334 | "" => parsed.algorithm.clone(), |
| 331 | 335 | t => t.to_owned(), |
| 332 | 336 | }; |
| 337 | + let title: String = title.chars().take(MAX_TITLE_CHARS).collect(); | |
| 333 | 338 | match store |
| 334 | 339 | .add_ssh_key( |
| 335 | 340 | &viewer.0.id, |
crates/forge-web-account/src/pages/settings_live.rsmodified+18 -89
| @@ -1,26 +1,3 @@ | ||
| 1 | -//! Live settings. The signed-in user's own settings pages (`/settings/...`) follow | |
| 2 | -//! [`Topic::Account`] of their own user through `GET /settings/events`. The settings section of the | |
| 3 | -//! sidebar names that stream (see `views::section_for`), so every page under `/settings` follows it | |
| 4 | -//! without an attribute of its own. Public profile viewers follow [`Topic::User`] and never wake. | |
| 5 | -//! | |
| 6 | -//! Writes reach the topic two ways: | |
| 7 | -//! - A POST under `/settings/` (a profile, key, token, passkey, session, notification, appearance | |
| 8 | -//! or security change): [`AccountWriteLayer`] bumps the viewer's topic after the handler ran, so | |
| 9 | -//! no route calls a bump itself. A refused write bumps too: the page re-reads and agrees. | |
| 10 | -//! - Anything outside those paths that changes what the pages show: a sign-in (`auth::login`), a | |
| 11 | -//! key or token used by git, the API, SSH or a package client, and an admin action that ends | |
| 12 | -//! sessions. Those call [`bump_account`]. | |
| 13 | -//! | |
| 14 | -//! The settings stream sends `changed` on each wake and carries no data: the page re-reads itself. | |
| 15 | -//! A session revoked elsewhere is caught the same way. The re-read finds no session, so the page | |
| 16 | -//! leaves for the login page. | |
| 17 | -//! | |
| 18 | -//! Every page also holds `/-/alive` (see [`alive_response`]). That stream follows | |
| 19 | -//! [`Topic::ServerSettings`] for every viewer, anonymous included: a `settings` event when a live | |
| 20 | -//! server setting changes, so the open page re-renders. For a signed-in viewer it also sends a | |
| 21 | -//! `theme` event with the appearance attributes when they change, so a tab applies a theme, accent | |
| 22 | -//! or sidebar change made elsewhere without a reload. | |
| 23 | - | |
| 24 | 1 | use std::collections::VecDeque; |
| 25 | 2 | |
| 26 | 3 | use forge_core::server_settings::{self, FIELDS, Kind}; |
| @@ -36,8 +13,6 @@ use crate::auth::current_user; | ||
| 36 | 13 | use crate::live::{LiveHub, Topic, events_response, stream_wakes}; |
| 37 | 14 | use crate::state::AppState; |
| 38 | 15 | |
| 39 | -/// The change stream of the viewer's settings. The viewer comes from the session only, so a user | |
| 40 | -/// can follow only their own settings. Without a session: 401. | |
| 41 | 16 | #[route(GET "/settings/events")] |
| 42 | 17 | async fn settings_events(cx: &Cx) -> Result<Response> { |
| 43 | 18 | let Some((user, _)) = current_user(cx).await? else { |
| @@ -49,22 +24,16 @@ async fn settings_events(cx: &Cx) -> Result<Response> { | ||
| 49 | 24 | stream_wakes(cx, hub, &[Topic::Account(user.id)]) |
| 50 | 25 | } |
| 51 | 26 | |
| 52 | -/// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value 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> { | |
| 66 | 35 | let Some(user) = state.store.user_by_id(user_id).await? else { |
| 67 | - return Ok((String::new(), String::new(), String::new())); | |
| 36 | + return Ok(AccountState::default()); | |
| 68 | 37 | }; |
| 69 | 38 | let theme = match crate::theme::Theme::from_stored(&user.theme) { |
| 70 | 39 | crate::theme::Theme::Auto => "", |
| @@ -79,7 +48,6 @@ pub async fn account_state( | ||
| 79 | 48 | let accent_dark = crate::accent::accent_id(&user.accent_dark); |
| 80 | 49 | let base_light = crate::accent::base_id(&user.base_light); |
| 81 | 50 | let base_dark = crate::accent::base_id(&user.base_dark); |
| 82 | - // The stylesheet of the hue choices, empty when there is none (see `views::shell`). | |
| 83 | 51 | let custom_css = |
| 84 | 52 | crate::accent::custom_css_href(accent_light, accent_dark, base_light, base_dark) |
| 85 | 53 | .unwrap_or_default(); |
| @@ -97,15 +65,13 @@ pub async fn account_state( | ||
| 97 | 65 | "{}\n{avatar}\n{}\n{session_open}", |
| 98 | 66 | user.username, user.is_admin |
| 99 | 67 | ); |
| 100 | - Ok((appearance, user.language.clone(), identity)) | |
| 68 | + Ok(AccountState { | |
| 69 | + appearance, | |
| 70 | + language: user.language.clone(), | |
| 71 | + identity, | |
| 72 | + }) | |
| 101 | 73 | } |
| 102 | 74 | |
| 103 | -/// The account state the alive stream compares: appearance, language, identity (see | |
| 104 | -/// [`account_state`]). | |
| 105 | -pub type AccountState = (String, String, String); | |
| 106 | - | |
| 107 | -/// The viewer's account as the alive stream follows it: the user and session ids, the wake of its | |
| 108 | -/// topic, and the account state last sent. | |
| 109 | 75 | struct AccountFollow { |
| 110 | 76 | user_id: String, |
| 111 | 77 | session_id: String, |
| @@ -113,25 +79,19 @@ struct AccountFollow { | ||
| 113 | 79 | last: AccountState, |
| 114 | 80 | } |
| 115 | 81 | |
| 116 | -/// What the alive stream holds between events. | |
| 117 | 82 | struct Alive { |
| 118 | 83 | state: AppState, |
| 119 | - /// Present for a signed-in viewer only. | |
| 120 | 84 | account: Option<AccountFollow>, |
| 121 | 85 | server_wake: watch::Receiver<u64>, |
| 122 | - /// The server settings fingerprint last sent or seen (see [`settings_fingerprint`]). | |
| 123 | 86 | settings_last: String, |
| 124 | 87 | queue: VecDeque<Event>, |
| 125 | 88 | } |
| 126 | 89 | |
| 127 | -/// What woke the alive stream. | |
| 128 | 90 | enum Wake { |
| 129 | 91 | Account, |
| 130 | 92 | Settings, |
| 131 | 93 | } |
| 132 | 94 | |
| 133 | -/// The server settings the pages render, as one fingerprint: the values of every `Kind::Live` | |
| 134 | -/// setting, in field order. A `settings` event goes out when it differs from the last one sent. | |
| 135 | 95 | pub fn settings_fingerprint(state: &AppState) -> String { |
| 136 | 96 | let live = state.live(); |
| 137 | 97 | FIELDS |
| @@ -142,7 +102,6 @@ pub fn settings_fingerprint(state: &AppState) -> String { | ||
| 142 | 102 | .join("\n") |
| 143 | 103 | } |
| 144 | 104 | |
| 145 | -/// Waits for the viewer's account topic. A stream with no signed-in viewer waits on nothing. | |
| 146 | 105 | async fn wait_account(account: &mut Option<AccountFollow>) -> bool { |
| 147 | 106 | match account { |
| 148 | 107 | Some(follow) => follow.wake.changed().await.is_ok(), |
| @@ -150,15 +109,7 @@ async fn wait_account(account: &mut Option<AccountFollow>) -> bool { | ||
| 150 | 109 | } |
| 151 | 110 | } |
| 152 | 111 | |
| 153 | -/// The response of `GET /-/alive`, the stream every page holds. Every viewer follows the server | |
| 154 | -/// settings topic: a change to a live setting sends a `settings` event, and the page re-renders | |
| 155 | -/// (see `nav.js`). A signed-in viewer also follows their account topic: each time the appearance | |
| 156 | -/// differs from the last one sent it gets a `theme` event carrying the new attributes, a language | |
| 157 | -/// change a `language` event, and a change of the header's identity (username, avatar, admin) or a | |
| 158 | -/// revoked session an `account` event. The stream still opens with `retry`, and its open still | |
| 159 | -/// means the server is back. | |
| 160 | 112 | pub async fn alive_response(cx: &Cx) -> Result<Response> { |
| 161 | - // A router with no app state (the asset tests) has nothing to follow: the stream only stays open. | |
| 162 | 113 | let Some(state) = try_context::<AppState>(cx).cloned() else { |
| 163 | 114 | return events_response(cx, stream::pending::<Result<Event>>()); |
| 164 | 115 | }; |
| @@ -169,14 +120,10 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> { | ||
| 169 | 120 | events_response(cx, events) |
| 170 | 121 | } |
| 171 | 122 | |
| 172 | -/// The events of the alive stream for `viewer` (the user and session ids, when signed in). See | |
| 173 | -/// [`alive_response`]. The caller holds the stream slot; `pages::shell_events` merges it with the | |
| 174 | -/// shell's other streams. | |
| 175 | 123 | pub async fn alive_stream( |
| 176 | 124 | state: AppState, |
| 177 | 125 | viewer: Option<(String, String)>, |
| 178 | 126 | ) -> Result<BoxStream<'static, Result<Event>>> { |
| 179 | - // Subscribed before each baseline is read, so a change in between is not lost. | |
| 180 | 127 | let server_wake = state.live.subscribe(&Topic::ServerSettings); |
| 181 | 128 | let settings_last = settings_fingerprint(&state); |
| 182 | 129 | let account = match viewer { |
| @@ -202,8 +149,6 @@ pub async fn alive_stream( | ||
| 202 | 149 | Ok(stream::unfold(alive, next_alive_event).boxed()) |
| 203 | 150 | } |
| 204 | 151 | |
| 205 | -/// Waits for the next event of the alive stream. A wake that changes nothing the viewer sees sends | |
| 206 | -/// nothing. None when a topic is gone, which ends the stream. | |
| 207 | 152 | async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> { |
| 208 | 153 | loop { |
| 209 | 154 | if let Some(event) = alive.queue.pop_front() { |
| @@ -251,16 +196,13 @@ async fn next_alive_event(mut alive: Alive) -> Option<(Result<Event>, Alive)> { | ||
| 251 | 196 | }; |
| 252 | 197 | let last = &mut follow.last; |
| 253 | 198 | 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())); | |
| 257 | 201 | } |
| 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 { | |
| 260 | 203 | queue.push_back(Event::new().event("language").data("1")); |
| 261 | 204 | } |
| 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 { | |
| 264 | 206 | queue.push_back(Event::new().event("account").data("1")); |
| 265 | 207 | } |
| 266 | 208 | *last = now; |
| @@ -284,8 +226,6 @@ mod tests { | ||
| 284 | 226 | |
| 285 | 227 | const CSRF: &str = "settings-live-csrf"; |
| 286 | 228 | |
| 287 | - /// The settings stream needs a session, and the settings pages name it (and not the old | |
| 288 | - /// theme stream). | |
| 289 | 229 | #[tokio::test] |
| 290 | 230 | async fn the_settings_stream_needs_a_session_and_the_sidebar_names_it() { |
| 291 | 231 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -369,10 +309,6 @@ mod tests { | ||
| 369 | 309 | ); |
| 370 | 310 | } |
| 371 | 311 | |
| 372 | - /// Two live streams on one app. The settings stream sends one changed event per write to | |
| 373 | - /// the account. The alive stream sends the appearance only when it changes: a bump that | |
| 374 | - /// changes nothing sends nothing, and a theme and language change sends the theme event | |
| 375 | - /// first, then the language event. | |
| 376 | 312 | #[tokio::test] |
| 377 | 313 | async fn the_settings_stream_sends_changes_and_the_alive_stream_sends_appearance() { |
| 378 | 314 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -390,7 +326,6 @@ mod tests { | ||
| 390 | 326 | .expect("prefs"); |
| 391 | 327 | let router = app_router(state); |
| 392 | 328 | |
| 393 | - // Settings stream: a retry hint first, then one changed event per write. | |
| 394 | 329 | let request = Request::builder() |
| 395 | 330 | .method("GET") |
| 396 | 331 | .uri("/settings/events") |
| @@ -414,7 +349,6 @@ mod tests { | ||
| 414 | 349 | "settings stream: changed event" |
| 415 | 350 | ); |
| 416 | 351 | |
| 417 | - // Alive stream: no event for a bump that changes no appearance. | |
| 418 | 352 | let request = Request::builder() |
| 419 | 353 | .method("GET") |
| 420 | 354 | .uri("/-/alive") |
| @@ -427,7 +361,6 @@ mod tests { | ||
| 427 | 361 | assert!(retry.starts_with(b"retry: 1000"), "alive stream: {retry:?}"); |
| 428 | 362 | |
| 429 | 363 | live.bump(&Topic::Account(owner.id.clone())); |
| 430 | - // One change of theme and language: the theme event first, then the language event. | |
| 431 | 364 | store |
| 432 | 365 | .set_ui_prefs(&owner.id, "dark", "tr") |
| 433 | 366 | .await |
| @@ -451,8 +384,6 @@ mod tests { | ||
| 451 | 384 | ); |
| 452 | 385 | } |
| 453 | 386 | |
| 454 | - /// An anonymous page holds `/-/alive` too. A live server setting that changes, then a bump of the | |
| 455 | - /// server settings topic, sends one `settings` event. | |
| 456 | 387 | #[tokio::test] |
| 457 | 388 | async fn the_alive_stream_sends_settings_to_anonymous_viewers() { |
| 458 | 389 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -485,8 +416,6 @@ mod tests { | ||
| 485 | 416 | ); |
| 486 | 417 | } |
| 487 | 418 | |
| 488 | - /// A new avatar on the signed-in viewer's account reaches the alive stream as one `account` event, | |
| 489 | - /// so the header re-renders. | |
| 490 | 419 | #[tokio::test] |
| 491 | 420 | async fn the_alive_stream_sends_account_when_the_header_changes() { |
| 492 | 421 | let dir = tempfile::tempdir().expect("tempdir"); |
crates/forge-web-account/src/pages/settings_profile.rsmodified+9 -16
| @@ -6,7 +6,7 @@ use std::sync::{Arc, OnceLock}; | ||
| 6 | 6 | |
| 7 | 7 | use forge_core::AuditAction; |
| 8 | 8 | use forge_core::names::capitalization_change; |
| 9 | -use forge_core::store::MAX_DISPLAY_NAME_CHARS; | |
| 9 | +use forge_core::store::{MAX_ABOUT_CHARS, MAX_DISPLAY_NAME_CHARS}; | |
| 10 | 10 | use forge_core::tz::{all_timezones, validate_timezone}; |
| 11 | 11 | use forge_core::{Session, Store, User, avatar::MAX_UPLOAD_BYTES, avatar::process_avatar}; |
| 12 | 12 | use serde::Deserialize; |
| @@ -27,9 +27,6 @@ use crate::state::AppState; | ||
| 27 | 27 | use crate::views::parts::{SubPart, confirm_act, head, reveal}; |
| 28 | 28 | use crate::views::{alert, avatar_url, shell, user_facing_message}; |
| 29 | 29 | |
| 30 | -/// Longest "about" text, in characters. | |
| 31 | -pub const MAX_ABOUT_CHARS: usize = 2000; | |
| 32 | - | |
| 33 | 30 | /// Multipart framing overhead allowed on top of the image itself. |
| 34 | 31 | const MULTIPART_OVERHEAD: usize = 64 * 1024; |
| 35 | 32 | |
| @@ -210,13 +207,13 @@ async fn profile_body(cx: &Cx, page: ProfilePage) -> Result<impl View> { | ||
| 210 | 207 | } |
| 211 | 208 | |
| 212 | 209 | /// Collects what the profile page shows. `draft` fills the forms; `errors` shows under each section. |
| 213 | -async fn page_data( | |
| 210 | +fn page_data( | |
| 214 | 211 | viewer: &(User, Session), |
| 215 | 212 | lang: Lang, |
| 216 | 213 | draft: Draft, |
| 217 | 214 | errors: Errors, |
| 218 | 215 | notice: Option<&'static str>, |
| 219 | -) -> Result<ProfilePage> { | |
| 216 | +) -> ProfilePage { | |
| 220 | 217 | let hash = viewer.0.avatar_hash.clone(); |
| 221 | 218 | let zones = all_timezones() |
| 222 | 219 | .into_iter() |
| @@ -225,7 +222,7 @@ async fn page_data( | ||
| 225 | 222 | Zone { name, selected } |
| 226 | 223 | }) |
| 227 | 224 | .collect(); |
| 228 | - Ok(ProfilePage { | |
| 225 | + ProfilePage { | |
| 229 | 226 | lang, |
| 230 | 227 | csrf: viewer.1.csrf_token.clone(), |
| 231 | 228 | draft, |
| @@ -234,7 +231,7 @@ async fn page_data( | ||
| 234 | 231 | avatar_src: avatar_url(&viewer.0.username, hash.as_deref()), |
| 235 | 232 | has_avatar: hash.is_some(), |
| 236 | 233 | zones, |
| 237 | - }) | |
| 234 | + } | |
| 238 | 235 | } |
| 239 | 236 | |
| 240 | 237 | fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> { |
| @@ -330,8 +327,7 @@ async fn profile_page(cx: &Cx) -> Result<impl View> { | ||
| 330 | 327 | draft, |
| 331 | 328 | Errors::default(), |
| 332 | 329 | notice_for(lang, saved.as_deref()), |
| 333 | - ) | |
| 334 | - .await?; | |
| 330 | + ); | |
| 335 | 331 | Ok(view! { |
| 336 | 332 | shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page)) |
| 337 | 333 | }) |
| @@ -374,7 +370,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie | ||
| 374 | 370 | about, |
| 375 | 371 | timezone: form.timezone, |
| 376 | 372 | }; |
| 377 | - let page = page_data(&viewer, lang, draft, errors, None).await?; | |
| 373 | + let page = page_data(&viewer, lang, draft, errors, None); | |
| 378 | 374 | return Ok(view! { |
| 379 | 375 | shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page)) |
| 380 | 376 | }); |
| @@ -382,10 +378,7 @@ async fn profile_save(cx: &Cx, Form(form): Form<ProfileForm>) -> Result<impl Vie | ||
| 382 | 378 | }; |
| 383 | 379 | |
| 384 | 380 | 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) | |
| 389 | 382 | .await?; |
| 390 | 383 | if display != viewer.0.username { |
| 391 | 384 | store.set_username_display(&viewer.0.id, &display).await?; |
| @@ -444,7 +437,7 @@ async fn avatar_upload(cx: &Cx, mut multipart: Multipart) -> Result<impl View> { | ||
| 444 | 437 | avatar: Some(message), |
| 445 | 438 | ..Errors::default() |
| 446 | 439 | }; |
| 447 | - let page = page_data(&viewer, lang, Draft::from_user(&viewer.0), errors, None).await?; | |
| 440 | + let page = page_data(&viewer, lang, Draft::from_user(&viewer.0), errors, None); | |
| 448 | 441 | Ok(view! { |
| 449 | 442 | shell(title: t(lang, Key::Profile), viewer: Some(&viewer), profile_body(page: page)) |
| 450 | 443 | }) |
crates/forge-web-account/src/pages/settings_security.rsmodified+65 -96
| @@ -25,8 +25,9 @@ use crate::auth::{ | ||
| 25 | 25 | use crate::i18n::packages::{self as pk, K as PK}; |
| 26 | 26 | use crate::i18n::releases_ci::{self as rc, K as RC}; |
| 27 | 27 | use crate::i18n::s; |
| 28 | -use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t}; | |
| 28 | +use crate::i18n::{self, Key, Lang, t}; | |
| 29 | 29 | use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel}; |
| 30 | +use crate::pages::register::check_new_password; | |
| 30 | 31 | use crate::pages::settings_export; |
| 31 | 32 | use crate::pages::settings_sessions::session_label; |
| 32 | 33 | use crate::state::AppState; |
| @@ -34,9 +35,6 @@ use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT}; | ||
| 34 | 35 | use crate::views::parts::{RailItem, SubPart, confirm_act, head, post_act, rail}; |
| 35 | 36 | use crate::views::{added_status, alert, rel_time, shell, user_facing_message}; |
| 36 | 37 | |
| 37 | -/// Shortest and longest new passwords, in characters. | |
| 38 | -const MIN_PASSWORD_CHARS: usize = 10; | |
| 39 | -const MAX_PASSWORD_CHARS: usize = 1024; | |
| 40 | 38 | /// Recovery codes issued by each enrollment or regeneration. |
| 41 | 39 | const RECOVERY_CODE_COUNT: usize = 10; |
| 42 | 40 | /// At or below this many unused recovery codes the page warns and suggests regenerating. |
| @@ -176,12 +174,6 @@ struct SecurityPage { | ||
| 176 | 174 | email_sent: Option<String>, |
| 177 | 175 | /// Whether this server can send mail at all. The resend link shows only when it can. |
| 178 | 176 | mail_ready: bool, |
| 179 | - notice: Option<&'static str>, | |
| 180 | - password_error: Option<String>, | |
| 181 | - email_error: Option<String>, | |
| 182 | - two_factor_error: Option<String>, | |
| 183 | - two_factor_panel: TwoFactorPanel, | |
| 184 | - codes: Option<Vec<String>>, | |
| 185 | 177 | /// Secret (base32) and `otpauth://` URI while enrollment is waiting for a code. |
| 186 | 178 | pending: Option<(String, String)>, |
| 187 | 179 | /// When the password last changed, shown as a live time, when known. |
| @@ -193,8 +185,7 @@ struct SecurityPage { | ||
| 193 | 185 | sessions: Vec<Session>, |
| 194 | 186 | /// The id of the session that is viewing the page. |
| 195 | 187 | 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, | |
| 198 | 189 | } |
| 199 | 190 | |
| 200 | 191 | /// The rail's kinds of security, one per topic. `active` names the topic that is shown, or |
| @@ -258,11 +249,7 @@ pub(crate) async fn security_rail_for( | ||
| 258 | 249 | viewer: &(User, Session), |
| 259 | 250 | active: &str, |
| 260 | 251 | ) -> 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?; | |
| 266 | 253 | let passkey_count = state.store.list_passkeys(&viewer.0.id).await?.len(); |
| 267 | 254 | let session_count = state.store.list_sessions(&viewer.0.id).await?.len(); |
| 268 | 255 | Ok(security_rail_items( |
| @@ -284,20 +271,24 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | ||
| 284 | 271 | email_status, |
| 285 | 272 | email_sent, |
| 286 | 273 | mail_ready, |
| 287 | - notice, | |
| 288 | - password_error, | |
| 289 | - email_error, | |
| 290 | - two_factor_error, | |
| 291 | - two_factor_panel, | |
| 292 | - codes, | |
| 293 | 274 | pending, |
| 294 | 275 | password_changed, |
| 295 | 276 | two_factor, |
| 296 | 277 | passkeys, |
| 297 | 278 | sessions, |
| 298 | 279 | current_session_id, |
| 299 | - part, | |
| 280 | + shown, | |
| 300 | 281 | } = page; |
| 282 | + let Shown { | |
| 283 | + notice, | |
| 284 | + password_error, | |
| 285 | + email_error, | |
| 286 | + two_factor_error, | |
| 287 | + two_factor_panel, | |
| 288 | + codes, | |
| 289 | + part, | |
| 290 | + .. | |
| 291 | + } = shown; | |
| 301 | 292 | let two_factor_on = two_factor.is_some(); |
| 302 | 293 | let passkey_count = passkeys.items.len(); |
| 303 | 294 | let session_count = sessions.len(); |
| @@ -310,13 +301,11 @@ async fn security_body(cx: &Cx, page: SecurityPage, csrf: &str) -> Result<impl V | ||
| 310 | 301 | let email_open = email_error.is_some(); |
| 311 | 302 | let email_set = !email.is_empty(); |
| 312 | 303 | 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 | + }; | |
| 320 | 309 | let regenerate_open = regenerate_error.is_some(); |
| 321 | 310 | let disable_open = disable_error.is_some(); |
| 322 | 311 | // One topic shows at a time: the one with an error or fresh codes, else the one asked for. |
| @@ -629,6 +618,10 @@ async fn build_page( | ||
| 629 | 618 | } |
| 630 | 619 | status |
| 631 | 620 | }; |
| 621 | + let email = shown | |
| 622 | + .email_draft | |
| 623 | + .clone() | |
| 624 | + .unwrap_or_else(|| viewer.0.email.clone().unwrap_or_default()); | |
| 632 | 625 | Ok(SecurityPage { |
| 633 | 626 | lang, |
| 634 | 627 | passkeys: build_panel(state, &viewer.0.id).await?, |
| @@ -637,30 +630,19 @@ async fn build_page( | ||
| 637 | 630 | email_status, |
| 638 | 631 | email_sent, |
| 639 | 632 | 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, | |
| 649 | 634 | pending, |
| 650 | 635 | password_changed, |
| 651 | 636 | two_factor, |
| 652 | 637 | sessions: state.store.list_sessions(&viewer.0.id).await?, |
| 653 | 638 | current_session_id: viewer.1.id.clone(), |
| 654 | - part: shown.part, | |
| 639 | + shown, | |
| 655 | 640 | }) |
| 656 | 641 | } |
| 657 | 642 | |
| 658 | 643 | /// Renders the page. A throttled check answers 429 with `Retry-After`. |
| 659 | 644 | async fn respond(cx: &Cx, viewer: (User, Session), shown: Shown) -> Result<impl View> { |
| 660 | 645 | let state = context::<AppState>(cx); |
| 661 | - // `view!` expects the `cx` binding that `#[page]` and `#[component]` provide. This plain | |
| 662 | - // helper has to bind it itself. | |
| 663 | - let cx = cx; | |
| 664 | 646 | let mut headers = HeaderMap::new(); |
| 665 | 647 | let status = match shown.throttled { |
| 666 | 648 | Some(retry) => { |
| @@ -722,6 +704,31 @@ fn second_factor_blocked(state: &AppState, user_id: &str) -> Option<Duration> { | ||
| 722 | 704 | ) |
| 723 | 705 | } |
| 724 | 706 | |
| 707 | +async fn check_second_factor( | |
| 708 | + state: &AppState, | |
| 709 | + lang: Lang, | |
| 710 | + user_id: &str, | |
| 711 | + code: &str, | |
| 712 | +) -> forge_core::Result<std::result::Result<(), Refused>> { | |
| 713 | + if let Some(retry) = second_factor_blocked(state, user_id) { | |
| 714 | + return Ok(Err(Refused { | |
| 715 | + message: t(lang, Key::ErrThrottled), | |
| 716 | + retry: Some(retry), | |
| 717 | + })); | |
| 718 | + } | |
| 719 | + let key = throttle::two_factor_key(user_id); | |
| 720 | + if verify_second_factor(&state.store, &state.key, user_id, code).await? { | |
| 721 | + state.throttle.clear(&key); | |
| 722 | + Ok(Ok(())) | |
| 723 | + } else { | |
| 724 | + state.throttle.record_failure(&key, Instant::now()); | |
| 725 | + Ok(Err(Refused { | |
| 726 | + message: t(lang, Key::ErrWrongCode), | |
| 727 | + retry: None, | |
| 728 | + })) | |
| 729 | + } | |
| 730 | +} | |
| 731 | + | |
| 725 | 732 | /// Fresh recovery codes and their hashes. The plain codes are for display only. |
| 726 | 733 | fn new_recovery_codes() -> (Vec<String>, Vec<String>) { |
| 727 | 734 | let codes: Vec<String> = (0..RECOVERY_CODE_COUNT) |
| @@ -731,21 +738,6 @@ fn new_recovery_codes() -> (Vec<String>, Vec<String>) { | ||
| 731 | 738 | (codes, hashes) |
| 732 | 739 | } |
| 733 | 740 | |
| 734 | -/// Why a new password is refused, or `None` when it is acceptable. | |
| 735 | -fn check_new_password(lang: Lang, new: &str, confirm: &str) -> Option<String> { | |
| 736 | - let len = new.chars().count(); | |
| 737 | - if len < MIN_PASSWORD_CHARS { | |
| 738 | - return Some(password_too_short(lang, MIN_PASSWORD_CHARS)); | |
| 739 | - } | |
| 740 | - if len > MAX_PASSWORD_CHARS { | |
| 741 | - return Some(password_too_long(lang, MAX_PASSWORD_CHARS)); | |
| 742 | - } | |
| 743 | - if new != confirm { | |
| 744 | - return Some(t(lang, Key::ErrPasswordsDiffer).into()); | |
| 745 | - } | |
| 746 | - None | |
| 747 | -} | |
| 748 | - | |
| 749 | 741 | #[page("/settings/security")] |
| 750 | 742 | async fn security_page(cx: &Cx) -> Result<impl View> { |
| 751 | 743 | let viewer = require_user(cx).await?; |
| @@ -953,18 +945,11 @@ async fn two_factor_disable(cx: &Cx, Form(form): Form<DisableForm>) -> Result<im | ||
| 953 | 945 | shown.throttled = refused.retry; |
| 954 | 946 | return respond(cx, viewer, shown).await; |
| 955 | 947 | } |
| 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; | |
| 965 | 951 | return respond(cx, viewer, shown).await; |
| 966 | 952 | } |
| 967 | - state.throttle.clear(&key); | |
| 968 | 953 | state.store.disable_totp(&user_id).await?; |
| 969 | 954 | audit::record( |
| 970 | 955 | &state.store, |
| @@ -993,17 +978,10 @@ async fn account_delete(cx: &Cx, Form(form): Form<DeleteAccountForm>) -> Result< | ||
| 993 | 978 | return settings_export::respond_delete(cx, viewer, error, refused.retry).await; |
| 994 | 979 | } |
| 995 | 980 | 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; | |
| 1005 | 984 | } |
| 1006 | - state.throttle.clear(&key); | |
| 1007 | 985 | } |
| 1008 | 986 | let ghost = state.store.ensure_ghost_user().await?; |
| 1009 | 987 | match state.store.delete_user(&user_id, &ghost.id).await { |
| @@ -1051,18 +1029,11 @@ async fn two_factor_recovery(cx: &Cx, Form(form): Form<CodeForm>) -> Result<impl | ||
| 1051 | 1029 | shown.throttled = refused.retry; |
| 1052 | 1030 | return respond(cx, viewer, shown).await; |
| 1053 | 1031 | } |
| 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; | |
| 1063 | 1035 | return respond(cx, viewer, shown).await; |
| 1064 | 1036 | } |
| 1065 | - state.throttle.clear(&key); | |
| 1066 | 1037 | let (codes, hashes) = new_recovery_codes(); |
| 1067 | 1038 | state |
| 1068 | 1039 | .store |
| @@ -1291,7 +1262,7 @@ mod tests { | ||
| 1291 | 1262 | ) |
| 1292 | 1263 | .await; |
| 1293 | 1264 | assert!( |
| 1294 | - reply.body.contains("at least 10 characters"), | |
| 1265 | + reply.body.contains("at least 12 characters"), | |
| 1295 | 1266 | "short password" |
| 1296 | 1267 | ); |
| 1297 | 1268 | let mismatch = format!( |
| @@ -1586,9 +1557,8 @@ mod tests { | ||
| 1586 | 1557 | &wrong, |
| 1587 | 1558 | ) |
| 1588 | 1559 | .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"); | |
| 1592 | 1562 | let state = fx |
| 1593 | 1563 | .state |
| 1594 | 1564 | .store |
| @@ -1596,9 +1566,8 @@ mod tests { | ||
| 1596 | 1566 | .await |
| 1597 | 1567 | .unwrap() |
| 1598 | 1568 | .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"); | |
| 1602 | 1571 | |
| 1603 | 1572 | // An over-long device name is refused before the code is checked, so the code is |
| 1604 | 1573 | // not spent on it. |
crates/forge-web-account/src/pages/settings_tokens.rsmodified+4 -13
| @@ -13,17 +13,17 @@ use topcoat::context::{Cx, context}; | ||
| 13 | 13 | use topcoat::router::content::Form; |
| 14 | 14 | use topcoat::router::error::{SeeOther, see_other}; |
| 15 | 15 | use topcoat::router::response::response_headers; |
| 16 | -use topcoat::router::{page, query_params, route}; | |
| 16 | +use topcoat::router::{page, route}; | |
| 17 | 17 | use topcoat::view::{View, component, view}; |
| 18 | 18 | |
| 19 | 19 | use crate::api::packages::PACKAGES_SCOPE; |
| 20 | 20 | use crate::audit::{self, Actor, Target}; |
| 21 | -use crate::auth::{require_csrf, require_user}; | |
| 21 | +use crate::auth::require_csrf; | |
| 22 | 22 | use crate::i18n::packages::{self as pk, K as PK}; |
| 23 | 23 | use crate::i18n::releases_ci::{self as rc, K as RC}; |
| 24 | 24 | use crate::i18n::s; |
| 25 | 25 | use crate::i18n::{self, Key, Lang, t, token_name_length}; |
| 26 | -use crate::pages::settings_keys::{AddQuery, KeyKind, KeysDraft, keys_page_view}; | |
| 26 | +use crate::pages::settings_keys::{KeyKind, KeysDraft, kind_page, keys_page_view}; | |
| 27 | 27 | use crate::state::AppState; |
| 28 | 28 | use crate::views::parts::confirm_act; |
| 29 | 29 | use crate::views::{alert, rel_time, rel_time_or_never}; |
| @@ -132,16 +132,7 @@ pub(crate) async fn tokens_section( | ||
| 132 | 132 | |
| 133 | 133 | #[page("/settings/tokens")] |
| 134 | 134 | 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 | |
| 145 | 136 | } |
| 146 | 137 | |
| 147 | 138 | #[page(POST "/settings/tokens")] |
crates/forge-web-account/src/pages/setup.rsmodified+9 -7
| @@ -99,8 +99,9 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> | ||
| 99 | 99 | } |
| 100 | 100 | |
| 101 | 101 | 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), | |
| 104 | 105 | Ok(_) if form.password.chars().count() < MIN_PASSWORD_CHARS => { |
| 105 | 106 | Some(password_too_short(lang, MIN_PASSWORD_CHARS)) |
| 106 | 107 | } |
| @@ -118,7 +119,7 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> | ||
| 118 | 119 | }); |
| 119 | 120 | } |
| 120 | 121 | |
| 121 | - let (username, _) = validate_username(&form.username)?; | |
| 122 | + let (username, _) = checked?; | |
| 122 | 123 | let email = form.email.trim(); |
| 123 | 124 | let email = (!email.is_empty()).then_some(email); |
| 124 | 125 | let hash = hash_password_async(form.password.clone()).await?; |
| @@ -130,10 +131,6 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> | ||
| 130 | 131 | else { |
| 131 | 132 | return Err(not_found().into()); |
| 132 | 133 | }; |
| 133 | - if let Some(address) = email { | |
| 134 | - // The first admin confirms the address like anyone else. Nothing waits on the mail. | |
| 135 | - crate::mail::account::send_verify(state, &user, address).await?; | |
| 136 | - } | |
| 137 | 134 | audit::record( |
| 138 | 135 | &state.store, |
| 139 | 136 | Some(cx), |
| @@ -149,6 +146,11 @@ async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> | ||
| 149 | 146 | .await; |
| 150 | 147 | login(cx, &user).await?; |
| 151 | 148 | clear_pre_csrf(cx); |
| 149 | + if let Some(address) = email { | |
| 150 | + if let Err(e) = crate::mail::account::send_verify(state, &user, address).await { | |
| 151 | + tracing::warn!(error = %e, "could not queue the address check"); | |
| 152 | + } | |
| 153 | + } | |
| 152 | 154 | Err(see_other("/").into()) |
| 153 | 155 | } |
| 154 | 156 |
crates/forge-web-account/src/pages/shell_events.rsmodified+27 -3
| @@ -38,13 +38,37 @@ async fn shell_events(cx: &Cx) -> Result<Response> { | ||
| 38 | 38 | .map(|(user, session)| (user.id.clone(), session.id.clone())); |
| 39 | 39 | let mut parts: Vec<BoxStream<'static, Result<Event>>> = |
| 40 | 40 | 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)); | |
| 44 | 46 | } |
| 45 | 47 | events_response(cx, stream::select_all(parts)) |
| 46 | 48 | } |
| 47 | 49 | |
| 50 | +fn while_signed_in( | |
| 51 | + state: &AppState, | |
| 52 | + user_id: &str, | |
| 53 | + session_id: &str, | |
| 54 | + part: BoxStream<'static, Result<Event>>, | |
| 55 | +) -> BoxStream<'static, Result<Event>> { | |
| 56 | + let (state, user_id, session_id) = (state.clone(), user_id.to_owned(), session_id.to_owned()); | |
| 57 | + part.take_while(move |_| { | |
| 58 | + let (state, user_id, session_id) = (state.clone(), user_id.clone(), session_id.clone()); | |
| 59 | + async move { session_open(&state, &user_id, &session_id).await } | |
| 60 | + }) | |
| 61 | + .boxed() | |
| 62 | +} | |
| 63 | + | |
| 64 | +async fn session_open(state: &AppState, user_id: &str, session_id: &str) -> bool { | |
| 65 | + state | |
| 66 | + .store | |
| 67 | + .list_sessions(user_id) | |
| 68 | + .await | |
| 69 | + .is_ok_and(|sessions| sessions.iter().any(|session| session.id == session_id)) | |
| 70 | +} | |
| 71 | + | |
| 48 | 72 | #[cfg(test)] |
| 49 | 73 | mod tests { |
| 50 | 74 | use topcoat::router::request::Request; |
crates/forge-web-account/src/pages/snippets.rsmodified+48 -130
| @@ -1,9 +1,3 @@ | ||
| 1 | -//! Pages for snippets: `/snippets` (list), `/snippets/new`, `/snippets/{id}` (view), | |
| 2 | -//! `/snippets/{id}/edit`, `/snippets/{id}/revisions` and `POST /snippets/{id}/delete`. | |
| 3 | -//! Visibility decides who may read: a private snippet answers 404 to everyone but its owner. | |
| 4 | -//! Only the owner edits or deletes, and every save and delete is audited. Files are served on the | |
| 5 | -//! user-content origin (see `snippet_raw.rs`), and the page links to them. | |
| 6 | - | |
| 7 | 1 | use std::collections::HashMap; |
| 8 | 2 | |
| 9 | 3 | use forge_core::store::snippets::{ |
| @@ -32,22 +26,17 @@ use crate::views::{alert, empty_state, rel_time, shell, user_facing_message}; | ||
| 32 | 26 | |
| 33 | 27 | path_param!(id); |
| 34 | 28 | |
| 35 | -/// What the form shows for one file slot. | |
| 36 | 29 | struct Slot { |
| 37 | 30 | number: usize, |
| 38 | 31 | name: String, |
| 39 | 32 | content: String, |
| 40 | 33 | } |
| 41 | 34 | |
| 42 | -/// The editable state of a snippet, as typed or as saved. | |
| 43 | 35 | #[derive(Clone, Default)] |
| 44 | 36 | struct Draft { |
| 45 | 37 | title: String, |
| 46 | 38 | description: String, |
| 47 | 39 | visibility: String, |
| 48 | - /// Each file with the number of its form fields (`name_<n>`, `content_<n>`). The number stays | |
| 49 | - /// with the file when another is added or removed: the browser restores typed text by field | |
| 50 | - /// name, so a renumbered card would get the wrong text back. | |
| 51 | 40 | files: Vec<(usize, SnippetFile)>, |
| 52 | 41 | } |
| 53 | 42 | |
| @@ -68,8 +57,6 @@ impl Draft { | ||
| 68 | 57 | } |
| 69 | 58 | } |
| 70 | 59 | |
| 71 | - /// Reads the form. Every card the page rendered is kept, blank ones too, so "Add file" never | |
| 72 | - /// takes a card away; blank cards are dropped only when saving (see `saved_files`). | |
| 73 | 60 | fn from_form(form: &HashMap<String, String>) -> Self { |
| 74 | 61 | let field = |key: String| form.get(&key).cloned().unwrap_or_default(); |
| 75 | 62 | let mut files = Vec::new(); |
| @@ -89,7 +76,6 @@ impl Draft { | ||
| 89 | 76 | } |
| 90 | 77 | } |
| 91 | 78 | |
| 92 | - /// The files to save: cards with neither a name nor contents are dropped. | |
| 93 | 79 | fn saved_files(&self) -> Vec<SnippetFile> { |
| 94 | 80 | self.files |
| 95 | 81 | .iter() |
| @@ -99,17 +85,14 @@ impl Draft { | ||
| 99 | 85 | .collect() |
| 100 | 86 | } |
| 101 | 87 | |
| 102 | - /// Drops the card whose fields are `number`. Other cards keep their numbers. | |
| 103 | 88 | fn remove(&mut self, number: usize) { |
| 104 | 89 | self.files.retain(|(n, _)| *n != number); |
| 105 | 90 | } |
| 106 | 91 | |
| 107 | - /// The position of the file whose fields are `number`, if there is one. | |
| 108 | 92 | fn position(&self, number: usize) -> Option<usize> { |
| 109 | 93 | self.files.iter().position(|(n, _)| *n == number) |
| 110 | 94 | } |
| 111 | 95 | |
| 112 | - /// Adds an empty card under the lowest free field number, unless the snippet is full. | |
| 113 | 96 | fn add_blank(&mut self) { |
| 114 | 97 | if self.files.len() >= MAX_FILES { |
| 115 | 98 | return; |
| @@ -124,7 +107,6 @@ impl Draft { | ||
| 124 | 107 | } |
| 125 | 108 | } |
| 126 | 109 | |
| 127 | - /// The cards to render: one per file, or one empty card for a new snippet. | |
| 128 | 110 | fn slots(&self) -> Vec<Slot> { |
| 129 | 111 | if self.files.is_empty() { |
| 130 | 112 | return vec![Slot { |
| @@ -136,7 +118,6 @@ impl Draft { | ||
| 136 | 118 | self.files |
| 137 | 119 | .iter() |
| 138 | 120 | .map(|(number, file)| { |
| 139 | - // A browser drops one newline right after <textarea>, so keep a leading one. | |
| 140 | 121 | let content = if file.content.starts_with('\n') { |
| 141 | 122 | format!("\n{}", file.content) |
| 142 | 123 | } else { |
| @@ -152,9 +133,6 @@ impl Draft { | ||
| 152 | 133 | } |
| 153 | 134 | } |
| 154 | 135 | |
| 155 | -/// Applies an "Add file" or "Remove file" click to the draft. Returns the tab to show next, or | |
| 156 | -/// None for a save, which leaves the draft as typed. Adding shows the new last file; removing | |
| 157 | -/// shows the file before the removed one. | |
| 158 | 136 | fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option<usize> { |
| 159 | 137 | if form.get("op").map(String::as_str) == Some("add") { |
| 160 | 138 | draft.add_blank(); |
| @@ -169,7 +147,6 @@ fn apply_slot_step(draft: &mut Draft, form: &HashMap<String, String>) -> Option< | ||
| 169 | 147 | } |
| 170 | 148 | } |
| 171 | 149 | |
| 172 | -/// The tab that was checked when a save failed, so the user stays on the file they were editing. | |
| 173 | 150 | fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize { |
| 174 | 151 | form.get("tab") |
| 175 | 152 | .and_then(|tab| tab.parse().ok()) |
| @@ -177,17 +154,18 @@ fn posted_tab(draft: &Draft, form: &HashMap<String, String>) -> usize { | ||
| 177 | 154 | .unwrap_or(0) |
| 178 | 155 | } |
| 179 | 156 | |
| 180 | -/// One file as the view page shows it. `body` is trusted HTML when `markdown` or `highlighted` | |
| 181 | -/// is set, and plain text otherwise. | |
| 157 | +enum FileBody { | |
| 158 | + Markdown(String), | |
| 159 | + Highlighted(String), | |
| 160 | + Plain(String), | |
| 161 | +} | |
| 162 | + | |
| 182 | 163 | struct FileView { |
| 183 | 164 | name: String, |
| 184 | 165 | raw: String, |
| 185 | - markdown: bool, | |
| 186 | - highlighted: bool, | |
| 187 | - body: String, | |
| 166 | + body: FileBody, | |
| 188 | 167 | } |
| 189 | 168 | |
| 190 | -/// One revision as the history page shows it. | |
| 191 | 169 | struct RevisionView { |
| 192 | 170 | number: usize, |
| 193 | 171 | author: String, |
| @@ -195,18 +173,15 @@ struct RevisionView { | ||
| 195 | 173 | file_names: String, |
| 196 | 174 | } |
| 197 | 175 | |
| 198 | -/// One row of the list page and of a profile's Snippets tab. | |
| 199 | 176 | pub(crate) struct ListRow { |
| 200 | 177 | id: String, |
| 201 | 178 | title: String, |
| 202 | 179 | owner: String, |
| 203 | 180 | visibility: &'static str, |
| 204 | - /// The file count and the last update, as one line. | |
| 205 | 181 | files: String, |
| 206 | 182 | updated_at: String, |
| 207 | 183 | } |
| 208 | 184 | |
| 209 | -/// The list row for a snippet summary, with its strings ready for the view. | |
| 210 | 185 | pub(crate) fn list_row(lang: Lang, summary: SnippetSummary) -> ListRow { |
| 211 | 186 | ListRow { |
| 212 | 187 | id: summary.id, |
| @@ -233,25 +208,21 @@ fn extension(name: &str) -> String { | ||
| 233 | 208 | } |
| 234 | 209 | |
| 235 | 210 | 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)) | |
| 239 | 213 | } else { |
| 240 | 214 | 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()), | |
| 243 | 217 | } |
| 244 | 218 | }; |
| 245 | 219 | FileView { |
| 246 | 220 | name: file.name.clone(), |
| 247 | 221 | raw: snippet_raw_url(state, snippet, &file.name), |
| 248 | - markdown, | |
| 249 | - highlighted, | |
| 250 | 222 | body, |
| 251 | 223 | } |
| 252 | 224 | } |
| 253 | 225 | |
| 254 | -/// The snippet if the viewer may read it, else 404. | |
| 255 | 226 | pub(crate) async fn readable( |
| 256 | 227 | cx: &Cx, |
| 257 | 228 | viewer_id: Option<&str>, |
| @@ -264,7 +235,6 @@ pub(crate) async fn readable( | ||
| 264 | 235 | } |
| 265 | 236 | } |
| 266 | 237 | |
| 267 | -/// The snippet if the user owns it, else 404. Edits and deletes go through this check. | |
| 268 | 238 | async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> { |
| 269 | 239 | let store = &context::<AppState>(cx).store; |
| 270 | 240 | match store.get_snippet(snippet_id).await? { |
| @@ -273,7 +243,23 @@ async fn owned(cx: &Cx, user: &User, snippet_id: &str) -> Result<Snippet> { | ||
| 273 | 243 | } |
| 274 | 244 | } |
| 275 | 245 | |
| 276 | -/// The snippet rows, one linked line each: title, owner, visibility, file count and update time. | |
| 246 | +async fn record_snippet(cx: &Cx, user: &User, action: AuditAction, snippet: &Snippet) { | |
| 247 | + audit::record( | |
| 248 | + &context::<AppState>(cx).store, | |
| 249 | + Some(cx), | |
| 250 | + Actor::User(user), | |
| 251 | + action, | |
| 252 | + Target { | |
| 253 | + kind: "snippet", | |
| 254 | + id: &snippet.id, | |
| 255 | + name: &snippet.title, | |
| 256 | + }, | |
| 257 | + serde_json::Value::Null, | |
| 258 | + ) | |
| 259 | + .await; | |
| 260 | + bump_snippet(context::<AppState>(cx), &snippet.id); | |
| 261 | +} | |
| 262 | + | |
| 277 | 263 | #[component] |
| 278 | 264 | pub(crate) async fn snippet_rows(cx: &Cx, lang: Lang, rows: Vec<ListRow>) -> Result<impl View> { |
| 279 | 265 | Ok(view! { |
| @@ -312,10 +298,6 @@ async fn snippet_list_body( | ||
| 312 | 298 | }) |
| 313 | 299 | } |
| 314 | 300 | |
| 315 | -/// The files card: a tab strip with one tab per file and the "Add file" tab at its end, then one | |
| 316 | -/// panel per file. Every panel stays in the form so all fields submit; CSS shows only the panel | |
| 317 | -/// of the checked tab. A tab is a radio plus a label, so the strip works with JavaScript off. | |
| 318 | -/// The panel's remove button is shown only when there is more than one file. | |
| 319 | 301 | #[component] |
| 320 | 302 | async fn snippet_files( |
| 321 | 303 | cx: &Cx, |
| @@ -387,24 +369,22 @@ async fn snippet_files( | ||
| 387 | 369 | }) |
| 388 | 370 | } |
| 389 | 371 | |
| 390 | -/// The new and edit form. Save is the first submit button, so Enter in a field saves; "Add file" | |
| 391 | -/// and the remove buttons submit the same form with `formnovalidate` and never save. | |
| 392 | 372 | #[component] |
| 393 | 373 | async fn snippet_form( |
| 394 | 374 | cx: &Cx, |
| 395 | 375 | lang: Lang, |
| 396 | 376 | csrf: &str, |
| 397 | 377 | action: &str, |
| 398 | - title: &str, | |
| 399 | - description: &str, | |
| 400 | - visibility: &str, | |
| 401 | - slots: Vec<Slot>, | |
| 378 | + draft: &Draft, | |
| 402 | 379 | active: usize, |
| 403 | 380 | error: Option<String>, |
| 404 | 381 | ) -> 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(); | |
| 408 | 388 | let removable = slots.len() > 1; |
| 409 | 389 | let can_add = slots.len() < MAX_FILES; |
| 410 | 390 | let counter = g::files_limit( |
| @@ -480,7 +460,7 @@ async fn snippet_body( | ||
| 480 | 460 | } |
| 481 | 461 | ) |
| 482 | 462 | if is_owner { |
| 483 | - crate::pages::profile::own_profile_tabs(lang: lang, username: owner.to_owned(), current: "snippets".to_owned()) | |
| 463 | + crate::pages::profile::own_profile_tabs(lang: lang, username: owner.to_owned(), current: crate::pages::profile::Tab::Snippets) | |
| 484 | 464 | } |
| 485 | 465 | <div class="sheet" data-live=(live.as_deref())> |
| 486 | 466 | <section class="sec"> |
| @@ -488,8 +468,6 @@ async fn snippet_body( | ||
| 488 | 468 | <p>(description)</p> |
| 489 | 469 | } |
| 490 | 470 | <p class="hint">(g::updated_before(lang)) rel_time(lang: lang, stamp: updated_at) (g::updated_after(lang))</p> |
| 491 | - if !is_owner { | |
| 492 | - } | |
| 493 | 471 | </section> |
| 494 | 472 | for file in files.into_iter() { |
| 495 | 473 | <section class="sec snippet-file"> |
| @@ -497,12 +475,12 @@ async fn snippet_body( | ||
| 497 | 475 | <strong>(file.name.clone())</strong> |
| 498 | 476 | <a class="act" href=(file.raw.clone())>(g::t(lang, K::Raw))</a> |
| 499 | 477 | </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> | |
| 506 | 484 | } |
| 507 | 485 | </section> |
| 508 | 486 | } |
| @@ -527,7 +505,7 @@ async fn revisions_body( | ||
| 527 | 505 | <a class="button" href=(back)>(g::t(lang, K::BackToSnippet))</a> |
| 528 | 506 | ) |
| 529 | 507 | if let Some(owner) = owner_tabs { |
| 530 | - crate::pages::profile::own_profile_tabs(lang: lang, username: owner, current: "snippets".to_owned()) | |
| 508 | + crate::pages::profile::own_profile_tabs(lang: lang, username: owner, current: crate::pages::profile::Tab::Snippets) | |
| 531 | 509 | } |
| 532 | 510 | <div class="sheet" data-live=(live.as_deref())> |
| 533 | 511 | if revisions.is_empty() { |
| @@ -556,19 +534,14 @@ async fn snippet_form_page( | ||
| 556 | 534 | active: usize, |
| 557 | 535 | ) -> Result<impl View> { |
| 558 | 536 | let csrf = viewer.1.csrf_token.clone(); |
| 559 | - let slots = draft.slots(); | |
| 560 | - let title = draft.title.clone(); | |
| 561 | - let description = draft.description.clone(); | |
| 562 | - let visibility = draft.visibility.clone(); | |
| 563 | 537 | let tab_user = viewer.0.username.clone(); |
| 564 | 538 | Ok(view! { |
| 565 | 539 | shell(title: heading, viewer: Some(viewer), |
| 566 | 540 | head(title: heading) |
| 567 | - crate::pages::profile::own_profile_tabs(lang: lang, username: tab_user, current: "snippets".to_owned()) | |
| 541 | + crate::pages::profile::own_profile_tabs(lang: lang, username: tab_user, current: crate::pages::profile::Tab::Snippets) | |
| 568 | 542 | <div class="sheet"> |
| 569 | 543 | 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) | |
| 572 | 545 | </div> |
| 573 | 546 | ) |
| 574 | 547 | }) |
| @@ -634,20 +607,7 @@ async fn snippet_create(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R | ||
| 634 | 607 | }; |
| 635 | 608 | match saved { |
| 636 | 609 | 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; | |
| 651 | 611 | return Err(see_other(format!("/snippets/{}", snippet.id)).into()); |
| 652 | 612 | } |
| 653 | 613 | Err(message) => error = Some(message), |
| @@ -737,20 +697,7 @@ async fn snippet_update(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R | ||
| 737 | 697 | }; |
| 738 | 698 | match saved { |
| 739 | 699 | 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; | |
| 754 | 701 | return Err(see_other(format!("/snippets/{}", snippet.id)).into()); |
| 755 | 702 | } |
| 756 | 703 | Err(message) => error = Some(message), |
| @@ -774,7 +721,6 @@ async fn snippet_revisions(cx: &Cx) -> Result<impl View> { | ||
| 774 | 721 | let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user)); |
| 775 | 722 | let store = &context::<AppState>(cx).store; |
| 776 | 723 | let revisions: Vec<SnippetRevision> = store.list_snippet_revisions(&snippet.id).await?; |
| 777 | - // Stored oldest first; the page shows the newest first with its number. | |
| 778 | 724 | let rows: Vec<RevisionView> = revisions |
| 779 | 725 | .into_iter() |
| 780 | 726 | .enumerate() |
| @@ -807,20 +753,7 @@ async fn snippet_delete(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> R | ||
| 807 | 753 | let snippet = owned(cx, &user, &snippet_id).await?; |
| 808 | 754 | let store = &context::<AppState>(cx).store; |
| 809 | 755 | 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; | |
| 824 | 757 | } |
| 825 | 758 | Ok(see_other("/snippets")) |
| 826 | 759 | } |
| @@ -836,11 +769,8 @@ mod tests { | ||
| 836 | 769 | .collect() |
| 837 | 770 | } |
| 838 | 771 | |
| 839 | - /// Saving drops blank cards but editing keeps them, and a leading newline survives the | |
| 840 | - /// textarea. | |
| 841 | 772 | #[test] |
| 842 | 773 | fn draft_saves_drop_blank_cards_and_keep_leading_newlines() { |
| 843 | - // Case: every rendered card is kept while editing; a save drops the blank ones. | |
| 844 | 774 | let draft = Draft::from_form(&form(&[ |
| 845 | 775 | ("title", "t"), |
| 846 | 776 | ("visibility", "public"), |
| @@ -864,7 +794,6 @@ mod tests { | ||
| 864 | 794 | ); |
| 865 | 795 | assert_eq!(saved[1].name, "b.rs", "blank cards: the kept file"); |
| 866 | 796 | |
| 867 | - // Case: a leading newline in a file survives the textarea. | |
| 868 | 797 | let mut draft = Draft::blank(); |
| 869 | 798 | draft.files = vec![( |
| 870 | 799 | 0, |
| @@ -876,11 +805,8 @@ mod tests { | ||
| 876 | 805 | assert_eq!(draft.slots()[0].content, "\n\nx", "leading newline"); |
| 877 | 806 | } |
| 878 | 807 | |
| 879 | - /// The card steps: a new form shows one card, add and remove move the cards, the shown tab | |
| 880 | - /// follows the step, and a save or a failed save keeps the posted tab. | |
| 881 | 808 | #[test] |
| 882 | 809 | fn card_steps_add_remove_and_show_the_right_tab() { |
| 883 | - // Case: a new form shows one empty card. | |
| 884 | 810 | let draft = Draft::blank(); |
| 885 | 811 | let slots = draft.slots(); |
| 886 | 812 | assert_eq!(slots.len(), 1, "new form: one card"); |
| @@ -890,7 +816,6 @@ mod tests { | ||
| 890 | 816 | "new form: the card is empty" |
| 891 | 817 | ); |
| 892 | 818 | |
| 893 | - // Case: add appends a card until the snippet is full. | |
| 894 | 819 | let mut draft = Draft::blank(); |
| 895 | 820 | for _ in 0..MAX_FILES + 3 { |
| 896 | 821 | draft.add_blank(); |
| @@ -903,7 +828,6 @@ mod tests { | ||
| 903 | 828 | "add: numbers run from zero" |
| 904 | 829 | ); |
| 905 | 830 | |
| 906 | - // Case: removing a card keeps the other field numbers. | |
| 907 | 831 | let mut draft = Draft::blank(); |
| 908 | 832 | draft.add_blank(); |
| 909 | 833 | draft.add_blank(); |
| @@ -918,7 +842,6 @@ mod tests { | ||
| 918 | 842 | "remove: the other card's name" |
| 919 | 843 | ); |
| 920 | 844 | |
| 921 | - // Case: add and remove clicks are told apart from a save. | |
| 922 | 845 | let add = form(&[("op", "add"), ("name_0", "a")]); |
| 923 | 846 | let mut draft = Draft::from_form(&add); |
| 924 | 847 | assert_eq!(apply_slot_step(&mut draft, &add), Some(1), "add click: tab"); |
| @@ -937,7 +860,6 @@ mod tests { | ||
| 937 | 860 | "save: not a card step" |
| 938 | 861 | ); |
| 939 | 862 | |
| 940 | - // Case: add shows the new last file. | |
| 941 | 863 | let mut draft = Draft::blank(); |
| 942 | 864 | let add = form(&[("op", "add"), ("name_0", "a")]); |
| 943 | 865 | assert_eq!( |
| @@ -952,19 +874,16 @@ mod tests { | ||
| 952 | 874 | ); |
| 953 | 875 | assert_eq!(draft.slots().len(), 2, "add shows: two cards"); |
| 954 | 876 | |
| 955 | - // Case: removing a card shows the file before it, and the first one when it is first. | |
| 956 | 877 | let mut draft = Draft::blank(); |
| 957 | 878 | for _ in 0..3 { |
| 958 | 879 | draft.add_blank(); |
| 959 | 880 | } |
| 960 | - // Files 0..=2 at positions 0..=2; removing the file at position 2 shows position 1. | |
| 961 | 881 | let remove = form(&[("remove", "2")]); |
| 962 | 882 | assert_eq!( |
| 963 | 883 | apply_slot_step(&mut draft, &remove), |
| 964 | 884 | Some(1), |
| 965 | 885 | "remove shows: before" |
| 966 | 886 | ); |
| 967 | - // Removing the first file shows the new first one. | |
| 968 | 887 | let remove = form(&[("remove", "0")]); |
| 969 | 888 | assert_eq!( |
| 970 | 889 | apply_slot_step(&mut draft, &remove), |
| @@ -972,7 +891,6 @@ mod tests { | ||
| 972 | 891 | "remove shows: first" |
| 973 | 892 | ); |
| 974 | 893 | |
| 975 | - // Case: a failed save keeps the posted tab, and falls back to the first. | |
| 976 | 894 | let mut draft = Draft::blank(); |
| 977 | 895 | for _ in 0..3 { |
| 978 | 896 | draft.add_blank(); |
crates/forge-web-app/src/api/releases.rsmodified+1 -1
| @@ -264,7 +264,7 @@ async fn upload_asset(cx: &Cx, body: Body) -> topcoat::Result<Response> { | ||
| 264 | 264 | .and_then(|value| value.to_str().ok()) |
| 265 | 265 | .map(str::to_owned); |
| 266 | 266 | let max_bytes = state |
| 267 | - .config | |
| 267 | + .live() | |
| 268 | 268 | .releases |
| 269 | 269 | .max_asset_mb |
| 270 | 270 | .saturating_mul(1024 * 1024); |
crates/forge-web-app/src/live.rsmodified+10 -0
| @@ -388,6 +388,16 @@ pub fn changed_event(status: String) -> Result<Event> { | ||
| 388 | 388 | Ok(Event::new().event("changed").data(status)) |
| 389 | 389 | } |
| 390 | 390 | |
| 391 | +pub fn wake_stream( | |
| 392 | + wake: watch::Receiver<u64>, | |
| 393 | + status: &'static str, | |
| 394 | +) -> impl Stream<Item = Result<Event>> + Send + 'static { | |
| 395 | + stream::unfold(wake, move |mut wake| async move { | |
| 396 | + wake.changed().await.ok()?; | |
| 397 | + Some((changed_event(status.to_owned()), wake)) | |
| 398 | + }) | |
| 399 | +} | |
| 400 | + | |
| 391 | 401 | /// The events of a CI page, each named `name` (`changed` on a page's own stream). The first event |
| 392 | 402 | /// carries the status now. Each later one follows a wake of `wake`: with `only_on_status`, only when |
| 393 | 403 | /// the status differs from the last one sent. The stream ends after the terminal status is sent, |
crates/forge-web-app/src/package_ops.rsmodified+6 -0
| @@ -43,6 +43,12 @@ impl From<Error> for PackageError { | ||
| 43 | 43 | } |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | +impl From<PackageError> for Error { | |
| 47 | + fn from(e: PackageError) -> Self { | |
| 48 | + Self::Database(format!("{e:?}")) | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 46 | 52 | /// The user or org a registry path names. `None` when no such account exists. |
| 47 | 53 | pub async fn owner_named(state: &AppState, name: &str) -> Result<Option<User>, PackageError> { |
| 48 | 54 | Ok(state.store.user_by_username(name).await?) |
crates/forge-web-app/src/views/mod.rsmodified+11 -0
| @@ -1121,6 +1121,17 @@ pub async fn alert(cx: &Cx, message: &str) -> Result<impl View> { | ||
| 1121 | 1121 | }) |
| 1122 | 1122 | } |
| 1123 | 1123 | |
| 1124 | +#[component] | |
| 1125 | +pub async fn notice_line(cx: &Cx, text: &str, is_error: bool) -> Result<impl View> { | |
| 1126 | + Ok(view! { | |
| 1127 | + if is_error { | |
| 1128 | + alert(message: text) | |
| 1129 | + } else { | |
| 1130 | + <p class="state" role="status">(text)</p> | |
| 1131 | + } | |
| 1132 | + }) | |
| 1133 | +} | |
| 1134 | + | |
| 1124 | 1135 | /// What a list shows when it has nothing yet: one line saying so, an optional hint, and an optional |
| 1125 | 1136 | /// next step as the child (a button, a link, or a command to copy). Pages use it so every empty list |
| 1126 | 1137 | /// reads the same way. |
crates/forge-web-base/src/i18n/merge_queue.rsmodified+8 -0
| @@ -32,6 +32,8 @@ pub enum K { | ||
| 32 | 32 | ReasonPermission, |
| 33 | 33 | ReasonBlocked, |
| 34 | 34 | ReasonNoBranch, |
| 35 | + ReasonDraft, | |
| 36 | + ReasonHeadMissing, | |
| 35 | 37 | ErrQueueRequired, |
| 36 | 38 | ErrQueueAlready, |
| 37 | 39 | } |
| @@ -66,6 +68,8 @@ pub const ALL: &[K] = &[ | ||
| 66 | 68 | K::ReasonPermission, |
| 67 | 69 | K::ReasonBlocked, |
| 68 | 70 | K::ReasonNoBranch, |
| 71 | + K::ReasonDraft, | |
| 72 | + K::ReasonHeadMissing, | |
| 69 | 73 | K::ErrQueueRequired, |
| 70 | 74 | K::ErrQueueAlready, |
| 71 | 75 | ]; |
| @@ -128,6 +132,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { | ||
| 128 | 132 | (ReasonBlocked, Tr) => "bir birleştirme denetimi artık geçmiyor", |
| 129 | 133 | (ReasonNoBranch, En) => "the branch is gone", |
| 130 | 134 | (ReasonNoBranch, Tr) => "dal artık yok", |
| 135 | + (ReasonDraft, En) => "it is a draft", | |
| 136 | + (ReasonDraft, Tr) => "taslak", | |
| 137 | + (ReasonHeadMissing, En) => "the source branch is gone", | |
| 138 | + (ReasonHeadMissing, Tr) => "kaynak dal artık yok", | |
| 131 | 139 | (ErrQueueRequired, En) => { |
| 132 | 140 | "This branch requires the merge queue. Add the pull request to the queue instead." |
| 133 | 141 | } |
crates/forge-web-pages/src/pages/admin_runners.rsmodified+32 -87
| @@ -11,6 +11,7 @@ use forge_ci::proto::RunnerSample; | ||
| 11 | 11 | use forge_core::AuditAction; |
| 12 | 12 | use forge_core::ci::{ |
| 13 | 13 | CiRunner, FieldKind, JobState, RUNNER_FIELDS, RestartMode, RunnerJob, runner_field, |
| 14 | + validate_runner_field, | |
| 14 | 15 | }; |
| 15 | 16 | use forge_core::store::health::runner_is_online; |
| 16 | 17 | use serde::Deserialize; |
| @@ -31,7 +32,7 @@ use crate::ci::metrics_chart::{self, Bucket}; | ||
| 31 | 32 | use crate::ci::runner_log::Line; |
| 32 | 33 | use crate::i18n::admin::{self as g, K}; |
| 33 | 34 | use crate::i18n::releases_ci as rc; |
| 34 | -use crate::i18n::{self, Key, Lang}; | |
| 35 | +use crate::i18n::{self, Key, Lang, s}; | |
| 35 | 36 | use crate::live::events_response; |
| 36 | 37 | use crate::pages::admin_users::admin_only; |
| 37 | 38 | use crate::pages::ci_runs::{age_text, duration_text, job_href, run_href, state_text}; |
| @@ -54,14 +55,6 @@ struct RunnersQuery { | ||
| 54 | 55 | notice: Option<String>, |
| 55 | 56 | } |
| 56 | 57 | |
| 57 | -/// Picks the English or Turkish text. The runner page strings live here, not in `i18n::admin`. | |
| 58 | -fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str { | |
| 59 | - match lang { | |
| 60 | - Lang::En => en, | |
| 61 | - Lang::Tr => tr, | |
| 62 | - } | |
| 63 | -} | |
| 64 | - | |
| 65 | 58 | /// Extra notice words: (word, English, Turkish, is an error). |
| 66 | 59 | const EXTRA_NOTICES: [(&str, &str, &str, bool); 8] = [ |
| 67 | 60 | ("saved", "Saved.", "Kaydedildi.", false), |
| @@ -460,15 +453,19 @@ async fn load_meter(cx: &Cx, lang: Lang, running: u32, max: u32) -> Result<impl | ||
| 460 | 453 | let running_text = running.to_string(); |
| 461 | 454 | let meter_max = max.max(1).to_string(); |
| 462 | 455 | 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 | + }; | |
| 472 | 469 | let pips_label = match lang { |
| 473 | 470 | Lang::En => format!("{running} of {max} jobs running"), |
| 474 | 471 | Lang::Tr => format!("{running}/{max} iş çalışıyor"), |
| @@ -696,7 +693,6 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> { | ||
| 696 | 693 | .clone() |
| 697 | 694 | .or_else(|| overridden.clone()) |
| 698 | 695 | .or_else(|| reported.cloned()); |
| 699 | - // Restart fields wait for a start; a live concurrency waits for the next check-in. | |
| 700 | 696 | let pending = match (&overridden, field.kind) { |
| 701 | 697 | (Some(want), FieldKind::Restart) => reported != Some(want), |
| 702 | 698 | (Some(want), FieldKind::Live) if field.key == "concurrency" => { |
| @@ -722,10 +718,6 @@ fn field_rows(runner: &CiRunner) -> Vec<FieldRow> { | ||
| 722 | 718 | .collect() |
| 723 | 719 | } |
| 724 | 720 | |
| 725 | -fn sel(on: bool) -> Option<&'static str> { | |
| 726 | - on.then_some("selected") | |
| 727 | -} | |
| 728 | - | |
| 729 | 721 | /// The detail page tabs: slug and the config keys on it. `overview`, `jobs`, `identity` and `logs` |
| 730 | 722 | /// are read-only. |
| 731 | 723 | const TABS: [(&str, &[&str]); 8] = [ |
| @@ -942,7 +934,6 @@ fn detail_fields(lang: Lang, tab: &str, fields: &[FieldRow]) -> Vec<DetailField> | ||
| 942 | 934 | options: if choices.is_empty() { |
| 943 | 935 | Vec::new() |
| 944 | 936 | } else { |
| 945 | - // An unreported field gets a blank first option, so saving the tab leaves it alone. | |
| 946 | 937 | std::iter::once(("", s(lang, "(from runner.toml)", "(runner.toml'dan)"))) |
| 947 | 938 | .filter(|_| f.value.is_empty()) |
| 948 | 939 | .chain(choices) |
| @@ -1096,10 +1087,9 @@ async fn runner_job_rows( | ||
| 1096 | 1087 | let (running, finished): (Vec<&RunnerJob>, Vec<&RunnerJob>) = jobs |
| 1097 | 1088 | .iter() |
| 1098 | 1089 | .partition(|job| job.job.state == JobState::Running); |
| 1099 | - let to_row = |job: &RunnerJob| runner_job_row(lang, job); | |
| 1100 | 1090 | 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(), | |
| 1103 | 1093 | )) |
| 1104 | 1094 | } |
| 1105 | 1095 | |
| @@ -1175,26 +1165,6 @@ fn n(value: f64) -> String { | ||
| 1175 | 1165 | format!("{value:.1}") |
| 1176 | 1166 | } |
| 1177 | 1167 | |
| 1178 | -fn cpu_of(b: &Bucket) -> f64 { | |
| 1179 | - b.cpu | |
| 1180 | -} | |
| 1181 | - | |
| 1182 | -fn mem_of(b: &Bucket) -> f64 { | |
| 1183 | - b.mem_used | |
| 1184 | -} | |
| 1185 | - | |
| 1186 | -fn disk_of(b: &Bucket) -> f64 { | |
| 1187 | - b.disk_used | |
| 1188 | -} | |
| 1189 | - | |
| 1190 | -fn rx_of(b: &Bucket) -> f64 { | |
| 1191 | - b.rx | |
| 1192 | -} | |
| 1193 | - | |
| 1194 | -fn tx_of(b: &Bucket) -> f64 { | |
| 1195 | - b.tx | |
| 1196 | -} | |
| 1197 | - | |
| 1198 | 1168 | /// A rate in bytes per second as `80 KiB/s`, one decimal below ten units. |
| 1199 | 1169 | fn rate_text(bytes: f64) -> String { |
| 1200 | 1170 | const KIB: f64 = 1024.0; |
| @@ -1350,7 +1320,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie | ||
| 1350 | 1320 | let cpu = mx_chart( |
| 1351 | 1321 | &points, |
| 1352 | 1322 | 100.0, |
| 1353 | - &[(cpu_of, "mx-line")], | |
| 1323 | + &[(|b: &Bucket| b.cpu, "mx-line")], | |
| 1354 | 1324 | true, |
| 1355 | 1325 | &|v| format!("{v:.0}%"), |
| 1356 | 1326 | &|b| { |
| @@ -1366,7 +1336,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie | ||
| 1366 | 1336 | let mem = mx_chart( |
| 1367 | 1337 | &points, |
| 1368 | 1338 | mem_total, |
| 1369 | - &[(mem_of, "mx-line")], | |
| 1339 | + &[(|b: &Bucket| b.mem_used, "mx-line")], | |
| 1370 | 1340 | false, |
| 1371 | 1341 | &|v| bytes_text(v as u64), |
| 1372 | 1342 | &|b| vec![memory_text(lang, b.mem_used, b.mem_total)], |
| @@ -1377,7 +1347,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie | ||
| 1377 | 1347 | let disk = mx_chart( |
| 1378 | 1348 | &points, |
| 1379 | 1349 | disk_total, |
| 1380 | - &[(disk_of, "mx-line")], | |
| 1350 | + &[(|b: &Bucket| b.disk_used, "mx-line")], | |
| 1381 | 1351 | false, |
| 1382 | 1352 | &|v| bytes_text(v as u64), |
| 1383 | 1353 | &|b| vec![storage_text(lang, b.disk_used, b.disk_total)], |
| @@ -1388,7 +1358,7 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie | ||
| 1388 | 1358 | let net = mx_chart( |
| 1389 | 1359 | &points, |
| 1390 | 1360 | net_top, |
| 1391 | - &[(rx_of, "mx-line"), (tx_of, "mx-line mx-line-sent")], | |
| 1361 | + &[(|b: &Bucket| b.rx, "mx-line"), (|b: &Bucket| b.tx, "mx-line mx-line-sent")], | |
| 1392 | 1362 | false, |
| 1393 | 1363 | &rate_text, |
| 1394 | 1364 | &|b| { |
| @@ -1423,11 +1393,6 @@ fn metrics_view(lang: Lang, samples: &[RunnerSample], now_ms: i64) -> MetricsVie | ||
| 1423 | 1393 | } |
| 1424 | 1394 | } |
| 1425 | 1395 | |
| 1426 | -/// `aria-current` for the open tab of the detail page's tab row. | |
| 1427 | -fn current(on: bool) -> Option<&'static str> { | |
| 1428 | - on.then_some("page") | |
| 1429 | -} | |
| 1430 | - | |
| 1431 | 1396 | #[component] |
| 1432 | 1397 | async fn runner_detail_view( |
| 1433 | 1398 | cx: &Cx, |
| @@ -1487,8 +1452,6 @@ async fn runner_detail_view( | ||
| 1487 | 1452 | let jobs_href = format!("{}?tab=jobs", row.detail_href); |
| 1488 | 1453 | let save_action = format!("{}/settings", row.detail_href); |
| 1489 | 1454 | let reset_action = row.config_action.clone(); |
| 1490 | - // The facts under each graph's caption. Memory's total is in its caption once a sample exists, | |
| 1491 | - // so the memory facts name the total only when there is none. | |
| 1492 | 1455 | let cpu_facts = format!("{cpus} {}", s(lang, "CPUs", "CPU")); |
| 1493 | 1456 | let budget_facts = format!( |
| 1494 | 1457 | "{} {budget_text} · {} {reserved_text} · {} {free_text}", |
| @@ -1502,7 +1465,6 @@ async fn runner_detail_view( | ||
| 1502 | 1465 | budget_facts |
| 1503 | 1466 | }; |
| 1504 | 1467 | let facts = [cpu_facts, mem_facts, String::new(), String::new()]; |
| 1505 | - // A runner that has reported nothing has no figures to show, only the note below. | |
| 1506 | 1468 | let has_host = !metrics.empty || runner.reported.cpus.is_some(); |
| 1507 | 1469 | Ok(view! { |
| 1508 | 1470 | head(title: runner.name.as_str(), sub: sub, live: Some("/admin/runners/events"), |
| @@ -1523,7 +1485,7 @@ async fn runner_detail_view( | ||
| 1523 | 1485 | } |
| 1524 | 1486 | <nav class="tabs" aria-label=(s(lang, "Configuration", "Yapılandırma"))> |
| 1525 | 1487 | for (slug, _) in TABS.iter() { |
| 1526 | - <a href=(format!("{}?tab={}", row.detail_href, slug)) aria-current=(current(*slug == tab))>(tab_label(lang, slug))</a> | |
| 1488 | + <a href=(format!("{}?tab={}", row.detail_href, slug)) aria-current=((*slug == tab).then_some("page"))>(tab_label(lang, slug))</a> | |
| 1527 | 1489 | } |
| 1528 | 1490 | </nav> |
| 1529 | 1491 | <div class="sheet"> |
| @@ -1637,7 +1599,7 @@ async fn runner_detail_view( | ||
| 1637 | 1599 | if f.input == "select" { |
| 1638 | 1600 | <select id=(format!("rf-{}", f.key)) name=(f.key)> |
| 1639 | 1601 | for (value, text, on) in f.options.iter() { |
| 1640 | - <option value=(*value) selected=(sel(*on))>(*text)</option> | |
| 1602 | + <option value=(*value) selected=((*on).then_some("selected"))>(*text)</option> | |
| 1641 | 1603 | } |
| 1642 | 1604 | </select> |
| 1643 | 1605 | } else if f.input == "number" { |
| @@ -1765,8 +1727,7 @@ async fn runner_save_settings( | ||
| 1765 | 1727 | return Ok(back_to_list("missing")); |
| 1766 | 1728 | }; |
| 1767 | 1729 | let current = field_rows(&runner); |
| 1768 | - let mut saved_live = false; | |
| 1769 | - let mut saved_restart = false; | |
| 1730 | + let mut changes = Vec::new(); | |
| 1770 | 1731 | for key in tab_keys(tab) { |
| 1771 | 1732 | let (Some(field), Some(posted), Some(now)) = ( |
| 1772 | 1733 | runner_field(key), |
| @@ -1778,6 +1739,14 @@ async fn runner_save_settings( | ||
| 1778 | 1739 | if field.kind == FieldKind::ReadOnly || posted.trim() == now.value { |
| 1779 | 1740 | continue; |
| 1780 | 1741 | } |
| 1742 | + if validate_runner_field(field.key, posted).is_err() { | |
| 1743 | + return Ok(back("invalid")); | |
| 1744 | + } | |
| 1745 | + changes.push((field, posted)); | |
| 1746 | + } | |
| 1747 | + let mut saved_live = false; | |
| 1748 | + let mut saved_restart = false; | |
| 1749 | + for (field, posted) in changes { | |
| 1781 | 1750 | match state |
| 1782 | 1751 | .store |
| 1783 | 1752 | .set_runner_field(id, field.key, Some(posted.as_str())) |
| @@ -1971,7 +1940,6 @@ async fn runner_restart(cx: &Cx, Form(form): Form<RestartForm>) -> Result<SeeOth | ||
| 1971 | 1940 | Err(forge_core::Error::NotFound) => return Ok(back_to_list("missing")), |
| 1972 | 1941 | Err(e) => return Err(e.into()), |
| 1973 | 1942 | } |
| 1974 | - // Wakes a runner that is waiting on a claim, and the live runners pages. | |
| 1975 | 1943 | state.ci_waker.notify_waiters(); |
| 1976 | 1944 | state.ci_live.bump_runners(); |
| 1977 | 1945 | tracing::info!(actor_id = %viewer.0.id, runner_id = %id, mode = mode.as_str(), "ci runner restart requested"); |
| @@ -2110,13 +2078,11 @@ mod tests { | ||
| 2110 | 2078 | assert!(body.contains("event: go\ndata: /admin/runners"), "{body}"); |
| 2111 | 2079 | } |
| 2112 | 2080 | |
| 2113 | - // Scenario: the page gates, the one-time token, and labels as chips with a state badge. | |
| 2114 | 2081 | #[tokio::test] |
| 2115 | 2082 | async fn gates_token_once_and_labels_render_as_chips() { |
| 2116 | 2083 | let dir = tempfile::tempdir().expect("tempdir"); |
| 2117 | 2084 | let (store, router) = fixture(dir.path()).await; |
| 2118 | 2085 | |
| 2119 | - // Anonymous and non-admin users get 404 on every runner route. | |
| 2120 | 2086 | let (anon, _) = send(&router, "GET", "/admin/runners", None, None).await; |
| 2121 | 2087 | assert_eq!(anon, 404, "anonymous gets 404 here, not a login redirect"); |
| 2122 | 2088 | let (user, _) = send(&router, "GET", "/admin/runners", Some(USER_TOKEN), None).await; |
| @@ -2140,7 +2106,6 @@ mod tests { | ||
| 2140 | 2106 | .await; |
| 2141 | 2107 | assert_eq!(del, 404); |
| 2142 | 2108 | |
| 2143 | - // An admin post without a valid CSRF token is forbidden and changes nothing. | |
| 2144 | 2109 | let (tok, _) = send( |
| 2145 | 2110 | &router, |
| 2146 | 2111 | "POST", |
| @@ -2170,7 +2135,6 @@ mod tests { | ||
| 2170 | 2135 | assert_eq!(dis, 403); |
| 2171 | 2136 | assert!(store.list_runners().await.expect("list").is_empty()); |
| 2172 | 2137 | |
| 2173 | - // The token is shown once, in the box and in the command, and never in the list. | |
| 2174 | 2138 | let (status, created) = send( |
| 2175 | 2139 | &router, |
| 2176 | 2140 | "POST", |
| @@ -2192,12 +2156,9 @@ mod tests { | ||
| 2192 | 2156 | "token in the box and the command" |
| 2193 | 2157 | ); |
| 2194 | 2158 | let (_, list) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; |
| 2195 | - // The empty list shows the register command with a placeholder, never the token. | |
| 2196 | 2159 | assert!(!list.contains(&token), "the list never shows the token"); |
| 2197 | - // Only the hash is stored, so the list and the database hold no plain token. | |
| 2198 | 2160 | assert!(store.list_runners().await.expect("list").is_empty()); |
| 2199 | 2161 | |
| 2200 | - // Labels are one plain line joined by " · ", and the dot follows disabling. | |
| 2201 | 2162 | store |
| 2202 | 2163 | .register_runner( |
| 2203 | 2164 | &token, |
| @@ -2210,7 +2171,6 @@ mod tests { | ||
| 2210 | 2171 | assert_eq!(status, 200); |
| 2211 | 2172 | assert!(page.contains(r#"<span class="runner-labels">linux · x86_64</span>"#)); |
| 2212 | 2173 | assert!(!page.contains("linux, x86_64"), "labels are not joined"); |
| 2213 | - // Never seen, so offline; not disabled, so no disabled word. | |
| 2214 | 2174 | assert!(page.contains(r#"class="runner-dot is-offline""#)); |
| 2215 | 2175 | assert!(!page.contains(r#"<span class="val">idle · disabled</span>"#)); |
| 2216 | 2176 | |
| @@ -2224,7 +2184,6 @@ mod tests { | ||
| 2224 | 2184 | assert!(page.contains(r#"<span class="val">idle</span>"#)); |
| 2225 | 2185 | } |
| 2226 | 2186 | |
| 2227 | - // Scenario: restart is capability-gated and audited, then the runner is disabled, enabled and deleted. | |
| 2228 | 2187 | #[tokio::test] |
| 2229 | 2188 | async fn restart_then_disable_and_delete_follow_one_runner() { |
| 2230 | 2189 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -2232,7 +2191,6 @@ mod tests { | ||
| 2232 | 2191 | let runner = one_runner(&store, &router).await; |
| 2233 | 2192 | let restart = format!("/admin/runners/{}/restart", runner.id); |
| 2234 | 2193 | |
| 2235 | - // Not logged in as an admin, or a bad token, changes nothing. | |
| 2236 | 2194 | let (status, _) = send(&router, "POST", &restart, Some(USER_TOKEN), csrf_form("")).await; |
| 2237 | 2195 | assert_eq!(status, 404); |
| 2238 | 2196 | let (status, _) = send( |
| @@ -2245,7 +2203,6 @@ mod tests { | ||
| 2245 | 2203 | .await; |
| 2246 | 2204 | assert_eq!(status, 403); |
| 2247 | 2205 | |
| 2248 | - // A runner that never advertised the capability: the button is off and the post refused. | |
| 2249 | 2206 | let runner_page = format!("/admin/runners/{}", runner.id); |
| 2250 | 2207 | let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await; |
| 2251 | 2208 | assert!(list.contains("Runner too old, update it first"), "{list}"); |
| @@ -2260,7 +2217,6 @@ mod tests { | ||
| 2260 | 2217 | assert_eq!(status, 303); |
| 2261 | 2218 | assert_eq!(store.runner_restart(&runner.id).await.unwrap(), None); |
| 2262 | 2219 | |
| 2263 | - // With the capability the page offers both choices, and the post is stored and audited. | |
| 2264 | 2220 | store |
| 2265 | 2221 | .record_runner_report( |
| 2266 | 2222 | &runner.id, |
| @@ -2301,7 +2257,6 @@ mod tests { | ||
| 2301 | 2257 | && e.data.contains("drain")) |
| 2302 | 2258 | ); |
| 2303 | 2259 | |
| 2304 | - // The runner comes back with a new boot id and the pending state goes away. | |
| 2305 | 2260 | store |
| 2306 | 2261 | .record_runner_report( |
| 2307 | 2262 | &runner.id, |
| @@ -2315,7 +2270,6 @@ mod tests { | ||
| 2315 | 2270 | let (_, list) = send(&router, "GET", &runner_page, Some(ADMIN_TOKEN), None).await; |
| 2316 | 2271 | assert!(!list.contains("restart pending")); |
| 2317 | 2272 | |
| 2318 | - // Disable, then enable again. | |
| 2319 | 2273 | let disable = format!("/admin/runners/{}/disabled", runner.id); |
| 2320 | 2274 | let (status, _) = send( |
| 2321 | 2275 | &router, |
| @@ -2337,7 +2291,6 @@ mod tests { | ||
| 2337 | 2291 | .await; |
| 2338 | 2292 | assert!(!store.list_runners().await.expect("list")[0].disabled); |
| 2339 | 2293 | |
| 2340 | - // Delete it, then a second delete reports that the id is gone. | |
| 2341 | 2294 | let delete = format!("/admin/runners/{}/delete", runner.id); |
| 2342 | 2295 | let (status, _) = send(&router, "POST", &delete, Some(ADMIN_TOKEN), csrf_form("")).await; |
| 2343 | 2296 | assert_eq!(status, 303); |
| @@ -2354,8 +2307,6 @@ mod tests { | ||
| 2354 | 2307 | assert!(page.contains("No runner has that id")); |
| 2355 | 2308 | } |
| 2356 | 2309 | |
| 2357 | - // Scenario: settings save per tab and per field, concurrency and config reset, and every | |
| 2358 | - // config, settings, events and detail route is admin only. | |
| 2359 | 2310 | #[tokio::test] |
| 2360 | 2311 | async fn settings_save_per_field_reset_and_stay_admin_only() { |
| 2361 | 2312 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -2365,7 +2316,6 @@ mod tests { | ||
| 2365 | 2316 | let settings = format!("/admin/runners/{}/settings", runner.id); |
| 2366 | 2317 | let detail_uri = format!("/admin/runners/{}", runner.id); |
| 2367 | 2318 | |
| 2368 | - // Non-admins get 404 on every route, and a bad CSRF token is forbidden. | |
| 2369 | 2319 | let (status, _) = send( |
| 2370 | 2320 | &router, |
| 2371 | 2321 | "POST", |
| @@ -2409,7 +2359,6 @@ mod tests { | ||
| 2409 | 2359 | .await; |
| 2410 | 2360 | assert_eq!(status, 404); |
| 2411 | 2361 | |
| 2412 | - // One post saves the changed fields of a tab; blank fields stay unset. | |
| 2413 | 2362 | let (status, _) = send( |
| 2414 | 2363 | &router, |
| 2415 | 2364 | "POST", |
| @@ -2441,7 +2390,6 @@ mod tests { | ||
| 2441 | 2390 | ); |
| 2442 | 2391 | assert!(page.contains("Reset to runner.toml")); |
| 2443 | 2392 | |
| 2444 | - // Concurrency: set it, show it in the list and the detail page, and refuse bad values. | |
| 2445 | 2393 | let (status, _) = send( |
| 2446 | 2394 | &router, |
| 2447 | 2395 | "POST", |
| @@ -2467,7 +2415,6 @@ mod tests { | ||
| 2467 | 2415 | assert!(list.contains("Reset to runner.toml")); |
| 2468 | 2416 | assert!(list.contains(r#"data-live="/admin/runners/events""#)); |
| 2469 | 2417 | |
| 2470 | - // Out of range, wrong kind of field and a read-only field change nothing. | |
| 2471 | 2418 | for form in [ |
| 2472 | 2419 | "&key=concurrency&value=65", |
| 2473 | 2420 | "&key=concurrency&value=0", |
| @@ -2484,7 +2431,6 @@ mod tests { | ||
| 2484 | 2431 | Some(3) |
| 2485 | 2432 | ); |
| 2486 | 2433 | |
| 2487 | - // A config field saved from the detail page shows there, live. | |
| 2488 | 2434 | let (status, _) = send( |
| 2489 | 2435 | &router, |
| 2490 | 2436 | "POST", |
| @@ -2506,7 +2452,6 @@ mod tests { | ||
| 2506 | 2452 | assert!(detail.contains("Concurrency")); |
| 2507 | 2453 | assert!(detail.contains(r#"data-live="/admin/runners/events""#)); |
| 2508 | 2454 | |
| 2509 | - // Reset both overrides; the runner goes back to its runner.toml values. | |
| 2510 | 2455 | let (_, _) = send( |
| 2511 | 2456 | &router, |
| 2512 | 2457 | "POST", |
crates/forge-web-pages/src/pages/admin_users.rsmodified+29 -31
| @@ -166,6 +166,19 @@ impl UserRow { | ||
| 166 | 166 | } |
| 167 | 167 | } |
| 168 | 168 | |
| 169 | +#[component] | |
| 170 | +async fn row_body(cx: &Cx, lang: Lang, row: &UserRow) -> Result<impl View> { | |
| 171 | + Ok(view! { | |
| 172 | + <span class="name">(row.username.as_str())</span> | |
| 173 | + <span class="val"> | |
| 174 | + if !row.email.is_empty() { | |
| 175 | + (row.email.as_str()) " · " | |
| 176 | + } | |
| 177 | + (row.role.as_str()) " · " rel_time(lang: lang, stamp: row.created_at.as_str()) | |
| 178 | + </span> | |
| 179 | + }) | |
| 180 | +} | |
| 181 | + | |
| 169 | 182 | #[component] |
| 170 | 183 | async fn users_view( |
| 171 | 184 | cx: &Cx, |
| @@ -262,23 +275,11 @@ async fn users_view( | ||
| 262 | 275 | for row in rows.into_iter() { |
| 263 | 276 | if row.linkable { |
| 264 | 277 | <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) | |
| 272 | 279 | </a> |
| 273 | 280 | } else { |
| 274 | 281 | <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) | |
| 282 | 283 | </div> |
| 283 | 284 | } |
| 284 | 285 | } |
| @@ -592,21 +593,26 @@ async fn org_delete_note( | ||
| 592 | 593 | }) |
| 593 | 594 | } |
| 594 | 595 | |
| 595 | -#[page("/admin/users/{user_id}/delete")] | |
| 596 | -async fn 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 { | |
| 602 | 598 | return Err(not_found().into()); |
| 603 | 599 | }; |
| 604 | - if target.id == viewer.0.id { | |
| 600 | + if target.id == viewer.id { | |
| 605 | 601 | return Err(see_other("/settings/security").into()); |
| 606 | 602 | } |
| 607 | 603 | if is_ghost(&target) { |
| 608 | 604 | return Err(not_found().into()); |
| 609 | 605 | } |
| 606 | + Ok(target) | |
| 607 | +} | |
| 608 | + | |
| 609 | +#[page("/admin/users/{user_id}/delete")] | |
| 610 | +async fn user_delete_page(cx: &Cx) -> Result<impl View> { | |
| 611 | + let viewer = admin_only(cx).await?; | |
| 612 | + let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 613 | + let store = &context::<AppState>(cx).store; | |
| 614 | + let target_id = path_param_segment(cx, "user_id").to_owned(); | |
| 615 | + let target = delete_target(store, &viewer.0, &target_id).await?; | |
| 610 | 616 | let (repos, outcome) = review_target(store, &target, lang).await?; |
| 611 | 617 | let (impact, refusal) = match outcome { |
| 612 | 618 | Ok(impact) => (Some(impact), None), |
| @@ -637,15 +643,7 @@ async fn user_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View> | ||
| 637 | 643 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 638 | 644 | let store = &context::<AppState>(cx).store; |
| 639 | 645 | 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?; | |
| 649 | 647 | if target.is_org() { |
| 650 | 648 | // The note with its links is on the GET page: send the browser there. |
| 651 | 649 | return Err(see_other(&format!("/admin/users/{}/delete", enc(&target.id))).into()); |
crates/forge-web-pages/src/pages/ci_job.rsmodified+22 -23
| @@ -25,7 +25,6 @@ use topcoat::Result; | ||
| 25 | 25 | use topcoat::context::{Cx, context}; |
| 26 | 26 | use topcoat::router::content::sse::{Event, last_event_id}; |
| 27 | 27 | use topcoat::router::error::not_found; |
| 28 | -use topcoat::router::request::uri; | |
| 29 | 28 | use topcoat::router::response::Response; |
| 30 | 29 | use topcoat::router::{Body, HeaderName, HeaderValue, StatusCode, page, path_param, route}; |
| 31 | 30 | use topcoat::view::{View, component, view}; |
| @@ -37,8 +36,8 @@ use crate::i18n::{ | ||
| 37 | 36 | }; |
| 38 | 37 | use crate::live::{changed_event, events_response}; |
| 39 | 38 | 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, | |
| 42 | 41 | }; |
| 43 | 42 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; |
| 44 | 43 | use crate::state::AppState; |
| @@ -644,7 +643,7 @@ async fn job_events(cx: &Cx) -> Result<Response> { | ||
| 644 | 643 | let (job, _) = job_of(state, &ctx, &id).await?; |
| 645 | 644 | let offset = last_event_id(cx) |
| 646 | 645 | .and_then(|id| id.parse::<u64>().ok()) |
| 647 | - .or_else(|| from_query(cx)) | |
| 646 | + .or_else(|| query_value(cx, "from")?.parse().ok()) | |
| 648 | 647 | .unwrap_or(0); |
| 649 | 648 | // Subscribed before the first read, so a change in between is sent. |
| 650 | 649 | let wake = state.ci_live.subscribe_job(&job.id); |
| @@ -659,24 +658,13 @@ async fn job_events(cx: &Cx) -> Result<Response> { | ||
| 659 | 658 | primed: false, |
| 660 | 659 | pending_fingerprint: None, |
| 661 | 660 | 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"), | |
| 665 | 662 | viewer: ctx.viewer.as_ref().map(|(user, _)| user.clone()), |
| 666 | 663 | repo_id: ctx.repo.id.clone(), |
| 667 | 664 | }; |
| 668 | 665 | events_response(cx, job_stream(follow)) |
| 669 | 666 | } |
| 670 | 667 | |
| 671 | -/// The `from` offset of the events URL, if it is a number. | |
| 672 | -fn from_query(cx: &Cx) -> Option<u64> { | |
| 673 | - uri(cx).query().and_then(|query| { | |
| 674 | - form_urlencoded::parse(query.as_bytes()) | |
| 675 | - .find(|(key, _)| key == "from") | |
| 676 | - .and_then(|(_, value)| value.parse::<u64>().ok()) | |
| 677 | - }) | |
| 678 | -} | |
| 679 | - | |
| 680 | 668 | /// One job's stream state. Each read of the status and the log happens after a wake, and a read that |
| 681 | 669 | /// sent log bytes is followed by another read at once, so a long append drains in order. |
| 682 | 670 | struct JobFollow { |
| @@ -864,14 +852,26 @@ fn artifact_response( | ||
| 864 | 852 | let mut res = Response::new(Body::new(StreamBody::new(chunks))); |
| 865 | 853 | *res.status_mut() = StatusCode::OK; |
| 866 | 854 | let headers = res.headers_mut(); |
| 867 | - headers.insert( | |
| 868 | - CONTENT_TYPE, | |
| 869 | - HeaderValue::from_static("application/octet-stream"), | |
| 870 | - ); | |
| 871 | 855 | headers.insert(CONTENT_LENGTH, HeaderValue::from(size)); |
| 856 | + attachment_headers( | |
| 857 | + headers, | |
| 858 | + "application/octet-stream", | |
| 859 | + &artifact.name, | |
| 860 | + "private, no-cache", | |
| 861 | + ); | |
| 862 | + Ok(res) | |
| 863 | +} | |
| 864 | + | |
| 865 | +pub(crate) fn attachment_headers( | |
| 866 | + headers: &mut http::HeaderMap, | |
| 867 | + content_type: &'static str, | |
| 868 | + file_name: &str, | |
| 869 | + cache: &'static str, | |
| 870 | +) { | |
| 871 | + headers.insert(CONTENT_TYPE, HeaderValue::from_static(content_type)); | |
| 872 | 872 | if let Ok(value) = HeaderValue::from_str(&format!( |
| 873 | 873 | "attachment; filename=\"{}\"", |
| 874 | - attachment_name(&artifact.name) | |
| 874 | + attachment_name(file_name) | |
| 875 | 875 | )) { |
| 876 | 876 | headers.insert(CONTENT_DISPOSITION, value); |
| 877 | 877 | } |
| @@ -881,9 +881,8 @@ fn artifact_response( | ||
| 881 | 881 | ); |
| 882 | 882 | headers.insert( |
| 883 | 883 | HeaderName::from_static("cache-control"), |
| 884 | - HeaderValue::from_static("private, no-cache"), | |
| 884 | + HeaderValue::from_static(cache), | |
| 885 | 885 | ); |
| 886 | - Ok(res) | |
| 887 | 886 | } |
| 888 | 887 | |
| 889 | 888 | #[cfg(test)] |
crates/forge-web-pages/src/pages/ci_runs.rsmodified+12 -52
| @@ -29,7 +29,7 @@ use topcoat::router::content::sse::Event; | ||
| 29 | 29 | use topcoat::router::error::{SeeOther, forbidden, not_found, see_other}; |
| 30 | 30 | use topcoat::router::request::uri; |
| 31 | 31 | use topcoat::router::response::{IntoResponse, Response}; |
| 32 | -use topcoat::router::{HeaderValue, page, path_param, route}; | |
| 32 | +use topcoat::router::{page, path_param, route}; | |
| 33 | 33 | use topcoat::view::{View, component, view}; |
| 34 | 34 | |
| 35 | 35 | use crate::auth::{current_user, require_csrf}; |
| @@ -44,7 +44,7 @@ use crate::live::{Status, changed_event, changed_stream, events_response}; | ||
| 44 | 44 | use crate::pages::admin_runners::confirm_post; |
| 45 | 45 | use crate::pages::ci_estimate::{self, Est, Step}; |
| 46 | 46 | use crate::pages::ci_fail::{self, FailFirst, fail_first_block}; |
| 47 | -use crate::pages::ci_job::{Tail, log_from, log_tail_of}; | |
| 47 | +use crate::pages::ci_job::{Tail, attachment_headers, log_from, log_tail_of}; | |
| 48 | 48 | use crate::pages::refs::load_refs; |
| 49 | 49 | use crate::pages::repo::repo_head; |
| 50 | 50 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; |
| @@ -155,12 +155,8 @@ fn badge_info(state: &AppState, title: &str, default_branch: &str) -> BadgeInfo | ||
| 155 | 155 | BadgeInfo { image, snippet } |
| 156 | 156 | } |
| 157 | 157 | |
| 158 | -/// The notice from `?notice=<word>`. Anything else is ignored. | |
| 159 | 158 | 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")?; | |
| 164 | 160 | NOTICES |
| 165 | 161 | .iter() |
| 166 | 162 | .find(|(name, _, _)| *name == word) |
| @@ -173,13 +169,8 @@ fn notice_redirect(href: &str, word: &str) -> SeeOther { | ||
| 173 | 169 | |
| 174 | 170 | /// The page number from `?page=`. Anything unreadable or out of range is page 1. |
| 175 | 171 | 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()) | |
| 183 | 174 | .filter(|page| (1..=MAX_PAGE).contains(page)) |
| 184 | 175 | .unwrap_or(1) |
| 185 | 176 | } |
| @@ -1436,7 +1427,6 @@ fn job_steps( | ||
| 1436 | 1427 | lines |
| 1437 | 1428 | } |
| 1438 | 1429 | |
| 1439 | -/// "test OOM" for a failed run: the first failed job's message, or its name and state. | |
| 1440 | 1430 | /// One row's meta line: `#50 · e62e309 · tahinli · ` then the age, then the failure hint if any. |
| 1441 | 1431 | struct RowMeta { |
| 1442 | 1432 | head: String, |
| @@ -2131,7 +2121,7 @@ fn step_from_query(cx: &Cx) -> Option<i64> { | ||
| 2131 | 2121 | } |
| 2132 | 2122 | |
| 2133 | 2123 | /// The value of one query parameter, if the URL has it. |
| 2134 | -fn query_value(cx: &Cx, key: &str) -> Option<String> { | |
| 2124 | +pub(crate) fn query_value(cx: &Cx, key: &str) -> Option<String> { | |
| 2135 | 2125 | let query = uri(cx).query()?; |
| 2136 | 2126 | form_urlencoded::parse(query.as_bytes()) |
| 2137 | 2127 | .find(|(name, _)| name == key) |
| @@ -2213,18 +2203,12 @@ async fn runs_sheet(cx: &Cx, lang: Lang, list: &ListView) -> Result<impl View> { | ||
| 2213 | 2203 | </svg> |
| 2214 | 2204 | if let Some(est) = row.est.as_ref() { |
| 2215 | 2205 | <progress class="ci-est" max="100" value=(est.pct.as_str()) data-est="true" data-since=(row.since.as_deref()) data-expected=(est.expected.as_str())></progress> |
| 2216 | - <span class="val"><span class="ci-row-meta">(row.meta.head.as_str())<time datetime=(row.meta.at.as_str()) data-rel="true">(row.meta.age.as_str())</time>(row.meta.hint.as_str())</span> | |
| 2217 | - if !row.duration.is_empty() { | |
| 2218 | - " · " <span class="ci-row-dur" data-since=(row.since.as_deref()) data-expected=(est.expected.as_str()) data-left=(est.left.as_str()) data-over=(est.over.as_str()) data-lm=(est.minutes.as_str())>(row.duration.as_str())</span> | |
| 2219 | - } | |
| 2220 | - </span> | |
| 2221 | - } else { | |
| 2222 | - <span class="val"><span class="ci-row-meta">(row.meta.head.as_str())<time datetime=(row.meta.at.as_str()) data-rel="true">(row.meta.age.as_str())</time>(row.meta.hint.as_str())</span> | |
| 2223 | - if !row.duration.is_empty() { | |
| 2224 | - " · " <span class="ci-row-dur" data-since=(row.since.as_deref())>(row.duration.as_str())</span> | |
| 2225 | - } | |
| 2226 | - </span> | |
| 2227 | 2206 | } |
| 2207 | + <span class="val"><span class="ci-row-meta">(row.meta.head.as_str())<time datetime=(row.meta.at.as_str()) data-rel="true">(row.meta.age.as_str())</time>(row.meta.hint.as_str())</span> | |
| 2208 | + if !row.duration.is_empty() { | |
| 2209 | + " · " <span class="ci-row-dur" data-since=(row.since.as_deref()) data-expected=(row.est.as_ref().map(|est| est.expected.as_str())) data-left=(row.est.as_ref().map(|est| est.left.as_str())) data-over=(row.est.as_ref().map(|est| est.over.as_str())) data-lm=(row.est.as_ref().map(|est| est.minutes.as_str()))>(row.duration.as_str())</span> | |
| 2210 | + } | |
| 2211 | + </span> | |
| 2228 | 2212 | </a> |
| 2229 | 2213 | if let Some((action, token)) = row.rerun.as_ref() { |
| 2230 | 2214 | <form method="post" action=(action.as_str()) class="act-form ci-row-rerun-form" data-kb-rerun=""> |
| @@ -3066,32 +3050,8 @@ async fn run_artifacts_zip(cx: &Cx) -> Result<Response> { | ||
| 3066 | 3050 | .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))? |
| 3067 | 3051 | .map_err(forge_core::Error::Io)?; |
| 3068 | 3052 | let mut res = Response::new(topcoat::router::Body::from(zipped)); |
| 3069 | - let headers = res.headers_mut(); | |
| 3070 | - headers.insert( | |
| 3071 | - http::header::CONTENT_TYPE, | |
| 3072 | - HeaderValue::from_static("application/zip"), | |
| 3073 | - ); | |
| 3074 | 3053 | 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"); | |
| 3095 | 3055 | Ok(res) |
| 3096 | 3056 | } |
| 3097 | 3057 |
crates/forge-web-pages/src/pages/issue_meta.rsmodified+41 -32
| @@ -144,16 +144,7 @@ pub fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> { | ||
| 144 | 144 | /// sent to log in, a bad token is 403, and a viewer without Triage (or an archived repo) is 403. |
| 145 | 145 | pub async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<User> { |
| 146 | 146 | 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) { | |
| 157 | 148 | return Err(forbidden().into()); |
| 158 | 149 | } |
| 159 | 150 | Ok(user) |
| @@ -208,6 +199,42 @@ pub async fn action_error_at( | ||
| 208 | 199 | }) |
| 209 | 200 | } |
| 210 | 201 | |
| 202 | +pub async fn finish_write<T>( | |
| 203 | + cx: &Cx, | |
| 204 | + ctx: RepoCtx, | |
| 205 | + lang: Lang, | |
| 206 | + back: String, | |
| 207 | + result: forge_core::Result<T>, | |
| 208 | +) -> Result<impl View> { | |
| 209 | + match result { | |
| 210 | + Ok(_) => { | |
| 211 | + context::<AppState>(cx).live.bump_repo_issues(&ctx.repo.id); | |
| 212 | + Err(see_other(back).into()) | |
| 213 | + } | |
| 214 | + Err(e) => { | |
| 215 | + let message = refusal_message(e)?; | |
| 216 | + Ok(view! { | |
| 217 | + shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(), | |
| 218 | + action_error_at(lang: lang, message: message, back: back)) | |
| 219 | + }) | |
| 220 | + } | |
| 221 | + } | |
| 222 | +} | |
| 223 | + | |
| 224 | +async fn save_refused( | |
| 225 | + cx: &Cx, | |
| 226 | + ctx: RepoCtx, | |
| 227 | + lang: Lang, | |
| 228 | + back: String, | |
| 229 | + e: forge_core::Error, | |
| 230 | +) -> Result<impl View> { | |
| 231 | + let message = refusal_message(e)?; | |
| 232 | + Ok(view! { | |
| 233 | + shell(title: g::t(lang, K::CouldNotSave), viewer: ctx.viewer.as_ref(), | |
| 234 | + action_error_at(lang: lang, message: message, back: back)) | |
| 235 | + }) | |
| 236 | +} | |
| 237 | + | |
| 211 | 238 | /// Sets the labels on an item. The form repeats `label` once per label id. |
| 212 | 239 | #[page(POST "/{owner}/{repo}/issues/{number}/labels")] |
| 213 | 240 | async fn issue_labels_save(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> { |
| @@ -231,11 +258,7 @@ async fn labels_save(cx: &Cx, kind: ItemKind, fields: Vec<(String, String)>) -> | ||
| 231 | 258 | let before = item_labels(state, &item.id).await; |
| 232 | 259 | let result = state.store.set_issue_labels(&item.id, &user.id, &ids).await; |
| 233 | 260 | 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; | |
| 239 | 262 | } |
| 240 | 263 | bump_live(state, &ctx.repo.id, &item, kind); |
| 241 | 264 | let after = item_labels(state, &item.id).await; |
| @@ -279,11 +302,7 @@ async fn assignees_save( | ||
| 279 | 302 | .set_issue_assignees(&item.id, &user.id, &usernames) |
| 280 | 303 | .await; |
| 281 | 304 | 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; | |
| 287 | 306 | } |
| 288 | 307 | bump_live(state, &ctx.repo.id, &item, kind); |
| 289 | 308 | let after = assignee_names(state, &item.id).await; |
| @@ -345,13 +364,7 @@ async fn lock_save(cx: &Cx, kind: ItemKind, fields: Vec<(String, String)>) -> Re | ||
| 345 | 364 | .await; |
| 346 | 365 | let changed = match result { |
| 347 | 366 | 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, | |
| 355 | 368 | }; |
| 356 | 369 | if changed { |
| 357 | 370 | bump_live(state, &ctx.repo.id, &item, kind); |
| @@ -396,11 +409,7 @@ async fn milestone_save( | ||
| 396 | 409 | .set_issue_milestone(&item.id, &user.id, milestone) |
| 397 | 410 | .await; |
| 398 | 411 | 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; | |
| 404 | 413 | } |
| 405 | 414 | let after = match milestone { |
| 406 | 415 | Some(id) => milestone_title(state, &ctx.repo.id, id).await, |
crates/forge-web-pages/src/pages/issue_parts.rsmodified+8 -4
| @@ -52,6 +52,13 @@ impl ItemKind { | ||
| 52 | 52 | ItemKind::Pull => "pulls", |
| 53 | 53 | } |
| 54 | 54 | } |
| 55 | + | |
| 56 | + pub fn anchor(self, number: i64) -> String { | |
| 57 | + match self { | |
| 58 | + ItemKind::Issue => format!("issue-{number}"), | |
| 59 | + ItemKind::Pull => format!("pull-{number}"), | |
| 60 | + } | |
| 61 | + } | |
| 55 | 62 | } |
| 56 | 63 | |
| 57 | 64 | |
| @@ -752,10 +759,7 @@ pub async fn load_discussion( | ||
| 752 | 759 | } else { |
| 753 | 760 | item.body.as_str() |
| 754 | 761 | }; |
| 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); | |
| 759 | 763 | let opened = When::new(lang, &item.created_at, &tz, now); |
| 760 | 764 | let body_edits = state.store.edit_count(EditTarget::Issue, &[item.id.as_str()]).await?; |
| 761 | 765 | let body_history = body_edits |
crates/forge-web-pages/src/pages/issues_list.rsmodified+23 -18
| @@ -29,7 +29,7 @@ use crate::templates::{self, Template}; | ||
| 29 | 29 | use crate::views::parts::{RailItem, SubPart, rail}; |
| 30 | 30 | use crate::views::{ |
| 31 | 31 | alert, avatar_url_unknown, csrf_field, enc, iso_time, now_unix, relative_time, repo_href, |
| 32 | - shell, user_facing_message, user_link, | |
| 32 | + shell, stamp_unix, user_facing_message, user_link, | |
| 33 | 33 | }; |
| 34 | 34 | use crate::webhooks::emit::{Sender, emit_issue}; |
| 35 | 35 | |
| @@ -238,12 +238,6 @@ pub fn list_href(base: &str, params: &[(&str, &str)]) -> String { | ||
| 238 | 238 | } |
| 239 | 239 | } |
| 240 | 240 | |
| 241 | -/// Unix seconds of a stored RFC 3339 stamp. An unreadable stamp gives 0. | |
| 242 | -pub fn stamp_unix(stamp: &str) -> i64 { | |
| 243 | - time::OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339) | |
| 244 | - .map_or(0, |t| t.unix_timestamp()) | |
| 245 | -} | |
| 246 | - | |
| 247 | 241 | pub struct AssigneeView { |
| 248 | 242 | pub name: String, |
| 249 | 243 | pub avatar: String, |
| @@ -879,6 +873,22 @@ async fn new_issue_page(cx: &Cx) -> Result<impl View> { | ||
| 879 | 873 | }) |
| 880 | 874 | } |
| 881 | 875 | |
| 876 | +async fn set_picked_labels( | |
| 877 | + state: &AppState, | |
| 878 | + repo_id: &str, | |
| 879 | + issue_id: &str, | |
| 880 | + actor_id: &str, | |
| 881 | + picked: &[String], | |
| 882 | +) -> forge_core::Result<()> { | |
| 883 | + let repo_labels = state.store.list_labels(repo_id).await?; | |
| 884 | + let ids: Vec<String> = repo_labels | |
| 885 | + .iter() | |
| 886 | + .filter(|l| picked.contains(&l.id)) | |
| 887 | + .map(|l| l.id.clone()) | |
| 888 | + .collect(); | |
| 889 | + state.store.set_issue_labels(issue_id, actor_id, &ids).await | |
| 890 | +} | |
| 891 | + | |
| 882 | 892 | #[page(POST "/{owner}/{repo}/issues/new")] |
| 883 | 893 | async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> { |
| 884 | 894 | let owner = owner(cx); |
| @@ -900,17 +910,12 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> { | ||
| 900 | 910 | .store |
| 901 | 911 | .create_issue(&ctx.repo.id, &viewer.0.id, &title, &typed_body) |
| 902 | 912 | .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"); | |
| 914 | 919 | } |
| 915 | 920 | state.live.bump_issue(&ctx.repo.id, &issue.id); |
| 916 | 921 | // The author's contribution calendar counts the issue. |
crates/forge-web-pages/src/pages/notifications.rsmodified+86 -101
| @@ -158,6 +158,23 @@ impl Entry { | ||
| 158 | 158 | } |
| 159 | 159 | } |
| 160 | 160 | |
| 161 | +fn item_class(unread: bool) -> &'static str { | |
| 162 | + if unread { | |
| 163 | + "notif-row unread" | |
| 164 | + } else { | |
| 165 | + "notif-row" | |
| 166 | + } | |
| 167 | +} | |
| 168 | + | |
| 169 | +fn times(lang: Lang, updated_at: &str, tz: &str, now: i64) -> (String, String, String) { | |
| 170 | + let unix = stamp_unix(updated_at); | |
| 171 | + ( | |
| 172 | + iso_time(unix), | |
| 173 | + forge_core::tz::format_in_tz(unix, tz), | |
| 174 | + relative_time(lang, unix, now), | |
| 175 | + ) | |
| 176 | +} | |
| 177 | + | |
| 161 | 178 | /// The row for an issue or pull inbox entry. |
| 162 | 179 | fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView { |
| 163 | 180 | let (kind_label, icon_class) = match (note.is_pull, note.issue_state) { |
| @@ -170,13 +187,9 @@ fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView { | ||
| 170 | 187 | .last_actor_name |
| 171 | 188 | .as_deref() |
| 172 | 189 | .map(|name| display_name(lang, name)); |
| 173 | - let unix = stamp_unix(¬e.updated_at); | |
| 190 | + let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); | |
| 174 | 191 | RowView { |
| 175 | - item_class: if note.unread { | |
| 176 | - "notif-row unread" | |
| 177 | - } else { | |
| 178 | - "notif-row" | |
| 179 | - }, | |
| 192 | + item_class: item_class(note.unread), | |
| 180 | 193 | icon_class, |
| 181 | 194 | kind_label, |
| 182 | 195 | open_href: format!("/notifications/{}/open", percent_encode(¬e.id)), |
| @@ -187,9 +200,9 @@ fn issue_row(lang: Lang, note: &Notification, tz: &str, now: i64) -> RowView { | ||
| 187 | 200 | ), |
| 188 | 201 | reason: reason_label(lang, note.reason), |
| 189 | 202 | activity: g::activity_line(lang, activity_verb(¬e.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, | |
| 193 | 206 | unread: note.unread, |
| 194 | 207 | } |
| 195 | 208 | } |
| @@ -204,13 +217,9 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64) | ||
| 204 | 217 | .last_actor_name |
| 205 | 218 | .as_deref() |
| 206 | 219 | .map(|name| display_name(lang, name)); |
| 207 | - let unix = stamp_unix(¬e.updated_at); | |
| 220 | + let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); | |
| 208 | 221 | RowView { |
| 209 | - item_class: if note.unread { | |
| 210 | - "notif-row unread" | |
| 211 | - } else { | |
| 212 | - "notif-row" | |
| 213 | - }, | |
| 222 | + item_class: item_class(note.unread), | |
| 214 | 223 | icon_class: "notif-icon discussion", |
| 215 | 224 | kind_label: g::t(lang, K::KindDiscussion), |
| 216 | 225 | open_href: format!( |
| @@ -227,9 +236,9 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64) | ||
| 227 | 236 | ), |
| 228 | 237 | reason, |
| 229 | 238 | 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, | |
| 233 | 242 | unread: note.unread, |
| 234 | 243 | } |
| 235 | 244 | } |
| @@ -237,14 +246,10 @@ fn discussion_row(lang: Lang, note: &DiscussionNotification, tz: &str, now: i64) | ||
| 237 | 246 | /// The row for a repo's security alerts: how many alerts a scan opened since the viewer last read |
| 238 | 247 | /// the row. It links to the repo's security page through the open route. |
| 239 | 248 | fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowView { |
| 240 | - let unix = stamp_unix(¬e.updated_at); | |
| 249 | + let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); | |
| 241 | 250 | let count = note.new_alerts; |
| 242 | 251 | RowView { |
| 243 | - item_class: if note.unread { | |
| 244 | - "notif-row unread" | |
| 245 | - } else { | |
| 246 | - "notif-row" | |
| 247 | - }, | |
| 252 | + item_class: item_class(note.unread), | |
| 248 | 253 | icon_class: "notif-icon advisory", |
| 249 | 254 | kind_label: g::t(lang, K::KindSecurityAlerts), |
| 250 | 255 | open_href: format!( |
| @@ -258,9 +263,9 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie | ||
| 258 | 263 | title_line: format!("{}/{}", note.repo_owner, note.repo_name), |
| 259 | 264 | reason: g::t(lang, K::ReasonSecurity), |
| 260 | 265 | 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, | |
| 264 | 269 | unread: note.unread, |
| 265 | 270 | } |
| 266 | 271 | } |
| @@ -268,13 +273,9 @@ fn advisory_row(lang: Lang, note: &AdvisoryNotice, tz: &str, now: i64) -> RowVie | ||
| 268 | 273 | /// The row for an admin alert: the headline as the title and the explanation as the activity. It |
| 269 | 274 | /// opens the health page. |
| 270 | 275 | fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView { |
| 271 | - let unix = stamp_unix(¬e.updated_at); | |
| 276 | + let (iso, absolute, relative) = times(lang, ¬e.updated_at, tz, now); | |
| 272 | 277 | RowView { |
| 273 | - item_class: if note.unread { | |
| 274 | - "notif-row unread" | |
| 275 | - } else { | |
| 276 | - "notif-row" | |
| 277 | - }, | |
| 278 | + item_class: item_class(note.unread), | |
| 278 | 279 | icon_class: if note.resolved { |
| 279 | 280 | "notif-icon admin-resolved" |
| 280 | 281 | } else { |
| @@ -286,13 +287,29 @@ fn admin_row(lang: Lang, note: &AdminNotice, tz: &str, now: i64) -> RowView { | ||
| 286 | 287 | title_line: alert_text::title(lang, ¬e.kind, ¬e.subject, note.resolved), |
| 287 | 288 | reason: g::t(lang, K::ReasonAdmin), |
| 288 | 289 | activity: alert_text::body(lang, ¬e.kind, ¬e.subject, ¬e.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, | |
| 292 | 293 | unread: note.unread, |
| 293 | 294 | } |
| 294 | 295 | } |
| 295 | 296 | |
| 297 | +fn group_slot( | |
| 298 | + groups: &mut Vec<RepoGroup>, | |
| 299 | + index: &mut HashMap<String, usize>, | |
| 300 | + key: &str, | |
| 301 | + make: impl FnOnce() -> RepoGroup, | |
| 302 | +) -> usize { | |
| 303 | + match index.get(key) { | |
| 304 | + Some(slot) => *slot, | |
| 305 | + None => { | |
| 306 | + groups.push(make()); | |
| 307 | + index.insert(key.to_owned(), groups.len() - 1); | |
| 308 | + groups.len() - 1 | |
| 309 | + } | |
| 310 | + } | |
| 311 | +} | |
| 312 | + | |
| 296 | 313 | /// Whether the viewer may see an inbox entry: its repo must be readable, and security alerts need |
| 297 | 314 | /// the repo's managers, the same rule as the security page. `readable` caches the repo checks. |
| 298 | 315 | /// Admin alerts need no repo. |
| @@ -309,14 +326,14 @@ async fn entry_visible( | ||
| 309 | 326 | let visible = match readable.get(repo_id) { |
| 310 | 327 | Some(visible) => *visible, |
| 311 | 328 | None => { |
| 312 | - let visible = can_read(state, user, repo_id).await?; | |
| 329 | + let visible = repo_allows(state, user, repo_id, Action::Read).await?; | |
| 313 | 330 | readable.insert(repo_id.to_owned(), visible); |
| 314 | 331 | visible |
| 315 | 332 | } |
| 316 | 333 | }; |
| 317 | 334 | Ok(visible |
| 318 | 335 | && (!matches!(entry, Entry::Advisory(_)) |
| 319 | - || can_manage_alerts(state, user, repo_id).await?)) | |
| 336 | + || repo_allows(state, user, repo_id, Action::Write).await?)) | |
| 320 | 337 | } |
| 321 | 338 | #[page("/notifications")] |
| 322 | 339 | async fn inbox(cx: &Cx) -> Result<impl View> { |
| @@ -386,48 +403,30 @@ async fn inbox(cx: &Cx) -> Result<impl View> { | ||
| 386 | 403 | let mut groups: Vec<RepoGroup> = Vec::new(); |
| 387 | 404 | let mut index: HashMap<String, usize> = HashMap::new(); |
| 388 | 405 | 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)); | |
| 408 | 414 | continue; |
| 409 | 415 | } |
| 410 | 416 | if !entry_visible(state, user, &mut readable, &entry).await? { |
| 411 | 417 | hidden.push(entry); |
| 412 | 418 | continue; |
| 413 | 419 | } |
| 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 | + }); | |
| 431 | 430 | let row = match entry { |
| 432 | 431 | Entry::Issue(note) => issue_row(lang, ¬e, &tz, now), |
| 433 | 432 | Entry::Discussion(note) => discussion_row(lang, ¬e, &tz, now), |
| @@ -572,7 +571,7 @@ async fn open_notification(cx: &Cx) -> Result<SeeOther> { | ||
| 572 | 571 | }; |
| 573 | 572 | state.store.mark_read(&user.id, id).await?; |
| 574 | 573 | publish_unread(state, &user.id).await; |
| 575 | - if !can_read(state, &user, &target.repo_id).await? { | |
| 574 | + if !repo_allows(state, &user, &target.repo_id, Action::Read).await? { | |
| 576 | 575 | return Err(not_found().into()); |
| 577 | 576 | } |
| 578 | 577 | let section = if target.is_pull { "pulls" } else { "issues" }; |
| @@ -600,7 +599,7 @@ async fn open_discussion_notification(cx: &Cx) -> Result<SeeOther> { | ||
| 600 | 599 | .mark_discussion_notification_read(&user.id, id) |
| 601 | 600 | .await?; |
| 602 | 601 | publish_unread(state, &user.id).await; |
| 603 | - if !can_read(state, &user, ¬e.repo_id).await? { | |
| 602 | + if !repo_allows(state, &user, ¬e.repo_id, Action::Read).await? { | |
| 604 | 603 | return Err(not_found().into()); |
| 605 | 604 | } |
| 606 | 605 | let href = repo_href( |
| @@ -641,7 +640,7 @@ async fn open_advisory_notification(cx: &Cx) -> Result<SeeOther> { | ||
| 641 | 640 | .mark_advisory_notification_read(&user.id, repo_id) |
| 642 | 641 | .await?; |
| 643 | 642 | publish_unread(state, &user.id).await; |
| 644 | - if !can_manage_alerts(state, &user, repo_id).await? { | |
| 643 | + if !repo_allows(state, &user, repo_id, Action::Write).await? { | |
| 645 | 644 | return Err(not_found().into()); |
| 646 | 645 | } |
| 647 | 646 | Ok(see_other(repo_href( |
| @@ -673,13 +672,7 @@ async fn open_admin_notification(cx: &Cx) -> Result<SeeOther> { | ||
| 673 | 672 | let (user, _) = require_user(cx).await?; |
| 674 | 673 | let state = context::<AppState>(cx); |
| 675 | 674 | 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() { | |
| 683 | 676 | return Err(not_found().into()); |
| 684 | 677 | } |
| 685 | 678 | state.store.mark_admin_notice_read(&user.id, id).await?; |
| @@ -865,22 +858,14 @@ async fn set_watch(cx: &Cx, Form(form): Form<WatchForm>) -> Result<SeeOther> { | ||
| 865 | 858 | ))) |
| 866 | 859 | } |
| 867 | 860 | |
| 868 | -/// Whether the viewer may manage the repo's security alerts: Write on the repo, the same rule 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> { | |
| 884 | 869 | let Some(repo) = state.store.repo_by_id(repo_id).await? else { |
| 885 | 870 | return Ok(false); |
| 886 | 871 | }; |
| @@ -889,7 +874,7 @@ pub async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Result<bo | ||
| 889 | 874 | .store |
| 890 | 875 | .org_repo_role(&repo.owner_id, &user.id, &repo.id) |
| 891 | 876 | .await?; |
| 892 | - Ok(authorize(Some(user), &repo, role, org_role, Action::Read).is_ok()) | |
| 877 | + Ok(authorize(Some(user), &repo, role, org_role, action).is_ok()) | |
| 893 | 878 | } |
| 894 | 879 | |
| 895 | 880 | /// The sidebar box of an issue or pull for a signed-in viewer. Viewing the thread marks the |
crates/forge-web-pages/src/pages/packages.rsmodified+29 -45
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | //! rendered by the profile page. |
| 5 | 5 | |
| 6 | 6 | use forge_core::User; |
| 7 | -use forge_core::packages::{KIND_CARGO, KIND_OCI, Package}; | |
| 7 | +use forge_core::packages::{KIND_CARGO, KIND_OCI, Package, PackageVersion}; | |
| 8 | 8 | use futures_util::{Stream, stream}; |
| 9 | 9 | use serde::Deserialize; |
| 10 | 10 | use tokio::sync::watch; |
| @@ -70,9 +70,7 @@ pub async fn package_rows( | ||
| 70 | 70 | if summary.version_count == 0 { |
| 71 | 71 | continue; |
| 72 | 72 | } |
| 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?; | |
| 76 | 74 | if !readable { |
| 77 | 75 | continue; |
| 78 | 76 | } |
| @@ -112,8 +110,12 @@ async fn package_page(cx: &Cx) -> Result<impl View> { | ||
| 112 | 110 | }; |
| 113 | 111 | let package = match package_ops::readable_oci_package(state, actor, &owner, pkg_name).await { |
| 114 | 112 | Ok(package) => package, |
| 113 | + Err(PackageError::Internal(msg)) => return Err(forge_core::Error::Database(msg).into()), | |
| 115 | 114 | Err(_) => match package_ops::readable_package(state, actor, &owner, pkg_name).await { |
| 116 | 115 | Ok(package) => package, |
| 116 | + Err(PackageError::Internal(msg)) => { | |
| 117 | + return Err(forge_core::Error::Database(msg).into()); | |
| 118 | + } | |
| 117 | 119 | Err(_) => return Err(not_found().into()), |
| 118 | 120 | }, |
| 119 | 121 | }; |
| @@ -159,17 +161,6 @@ async fn package_page(cx: &Cx) -> Result<impl View> { | ||
| 159 | 161 | let publish_cmd = format!("cargo publish --registry {}", owner.username); |
| 160 | 162 | let login_cmd = format!("cargo login --registry {}", owner.username); |
| 161 | 163 | let versions_tab = query.tab.as_deref() == Some("versions"); |
| 162 | - let version_rows: Vec<(String, String, bool, String)> = versions | |
| 163 | - .iter() | |
| 164 | - .map(|v| { | |
| 165 | - ( | |
| 166 | - v.version.clone(), | |
| 167 | - v.created_at.clone(), | |
| 168 | - v.yanked, | |
| 169 | - v.checksum.clone(), | |
| 170 | - ) | |
| 171 | - }) | |
| 172 | - .collect(); | |
| 173 | 164 | let readme_href = format!( |
| 174 | 165 | "{}?tab=readme", |
| 175 | 166 | package_href(&owner.username, &package.name) |
| @@ -199,7 +190,7 @@ async fn package_page(cx: &Cx) -> Result<impl View> { | ||
| 199 | 190 | add_cmd, |
| 200 | 191 | publish_cmd, |
| 201 | 192 | login_cmd, |
| 202 | - version_rows, | |
| 193 | + versions, | |
| 203 | 194 | lang, |
| 204 | 195 | }; |
| 205 | 196 | Ok(view! { |
| @@ -235,7 +226,7 @@ async fn tag_delete(cx: &Cx, Form(form): Form<TagDeleteForm>) -> Result<SeeOther | ||
| 235 | 226 | }; |
| 236 | 227 | let allowed = package_ops::may_publish(state, &viewer, &owner) |
| 237 | 228 | .await |
| 238 | - .map_err(|e| forge_core::Error::Database(format!("{e:?}")))?; | |
| 229 | + .map_err(forge_core::Error::from)?; | |
| 239 | 230 | if !allowed { |
| 240 | 231 | return Err(forbidden().into()); |
| 241 | 232 | } |
| @@ -266,7 +257,7 @@ struct PackagePage { | ||
| 266 | 257 | add_cmd: String, |
| 267 | 258 | publish_cmd: String, |
| 268 | 259 | login_cmd: String, |
| 269 | - version_rows: Vec<(String, String, bool, String)>, | |
| 260 | + versions: Vec<PackageVersion>, | |
| 270 | 261 | lang: Lang, |
| 271 | 262 | } |
| 272 | 263 | |
| @@ -289,7 +280,7 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> { | ||
| 289 | 280 | add_cmd, |
| 290 | 281 | publish_cmd, |
| 291 | 282 | login_cmd, |
| 292 | - version_rows, | |
| 283 | + versions, | |
| 293 | 284 | .. |
| 294 | 285 | } = page; |
| 295 | 286 | let has_readme = !readme_html.is_empty(); |
| @@ -299,8 +290,14 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> { | ||
| 299 | 290 | let readme_on = !versions_tab; |
| 300 | 291 | let readme_current: Option<&str> = readme_on.then_some("page"); |
| 301 | 292 | let versions_current: Option<&str> = versions_tab.then_some("page"); |
| 302 | - let has_versions = !version_rows.is_empty(); | |
| 293 | + let has_versions = !versions.is_empty(); | |
| 303 | 294 | let install = pk::t(lang, K::Install); |
| 295 | + let install_cmds = [ | |
| 296 | + (pk::t(lang, K::InstallRegistryConfig), "pkg-config", config_block), | |
| 297 | + (pk::t(lang, K::InstallAdd), "pkg-add", add_cmd), | |
| 298 | + (pk::t(lang, K::InstallPublish), "pkg-publish", publish_cmd), | |
| 299 | + (pk::t(lang, K::InstallLogin), "pkg-login", login_cmd), | |
| 300 | + ]; | |
| 304 | 301 | let copy_label = pk::t(lang, K::CopyCommand); |
| 305 | 302 | let readme_label = pk::t(lang, K::Readme); |
| 306 | 303 | let versions_label = pk::t(lang, K::PackageVersions); |
| @@ -334,42 +331,29 @@ async fn package_view(cx: &Cx, page: PackagePage) -> Result<impl View> { | ||
| 334 | 331 | <p>(description.as_str())</p> |
| 335 | 332 | } |
| 336 | 333 | <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 | + } | |
| 357 | 341 | </section> |
| 358 | 342 | if versions_tab { |
| 359 | 343 | if has_versions { |
| 360 | - for (version, date, yanked, checksum) in version_rows.iter() { | |
| 344 | + for v in versions.iter() { | |
| 361 | 345 | <details class="row-open" data-kb-row=""> |
| 362 | 346 | <summary class="line"> |
| 363 | 347 | <span class="name"> |
| 364 | - (version.as_str()) | |
| 365 | - if *yanked { | |
| 348 | + (v.version.as_str()) | |
| 349 | + if v.yanked { | |
| 366 | 350 | " " <span class="badge">(pk::t(lang, K::VersionYanked))</span> |
| 367 | 351 | } |
| 368 | 352 | </span> |
| 369 | - <span class="val">rel_time(lang: lang, stamp: date.as_str())</span> | |
| 353 | + <span class="val">rel_time(lang: lang, stamp: v.created_at.as_str())</span> | |
| 370 | 354 | </summary> |
| 371 | 355 | <div class="opened"> |
| 372 | - <code class="hint">(checksum.as_str())</code> | |
| 356 | + <code class="hint">(v.checksum.as_str())</code> | |
| 373 | 357 | </div> |
| 374 | 358 | </details> |
| 375 | 359 | } |
crates/forge-web-pages/src/pages/packages_oci.rsmodified+5 -19
| @@ -39,9 +39,7 @@ pub async fn model( | ||
| 39 | 39 | ) -> forge_core::Result<OciPage> { |
| 40 | 40 | let tags = state.store.oci_tags(&package.id).await?; |
| 41 | 41 | 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?, | |
| 45 | 43 | None => false, |
| 46 | 44 | }; |
| 47 | 45 | let base = state.config.base_url.trim_end_matches('/'); |
| @@ -99,18 +97,6 @@ pub async fn oci_package_view(cx: &Cx, page: OciPage) -> Result<impl View> { | ||
| 99 | 97 | let delete_action = format!("/{}/-/packages/tags/delete", enc(&owner_name)); |
| 100 | 98 | let private = package.private; |
| 101 | 99 | let tag_count = tags.len().to_string(); |
| 102 | - let rows: Vec<(String, String, String, String, String)> = tags | |
| 103 | - .iter() | |
| 104 | - .map(|t| { | |
| 105 | - ( | |
| 106 | - t.tag.clone(), | |
| 107 | - short_digest(&t.digest), | |
| 108 | - t.digest.clone(), | |
| 109 | - human_size(lang, t.size), | |
| 110 | - t.created_at.clone(), | |
| 111 | - ) | |
| 112 | - }) | |
| 113 | - .collect(); | |
| 114 | 100 | // The head holds the name, the owner, the newest tag and the private note; the install and tag |
| 115 | 101 | // topics sit in one sheet below it. |
| 116 | 102 | let mut sub = vec![SubPart::text(format!( |
| @@ -150,13 +136,13 @@ pub async fn oci_package_view(cx: &Cx, page: OciPage) -> Result<impl View> { | ||
| 150 | 136 | <h2>(pk::t(lang, K::ContainerTags)) " " <span class="tab-count">(tag_count.as_str())</span></h2> |
| 151 | 137 | if has_tags { |
| 152 | 138 | <div> |
| 153 | - for (tag, short, full, size, created) in rows.iter() { | |
| 139 | + for t in tags.iter() { | |
| 154 | 140 | <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> | |
| 157 | 143 | if can_delete { |
| 158 | 144 | confirm_act(lang: lang, label: pk::t(lang, K::DeleteTag), action: delete_action.as_str(), csrf: csrf.as_str(), |
| 159 | - fields: vec![("package".to_owned(), package.name.clone()), ("tag".to_owned(), tag.clone())]) | |
| 145 | + fields: vec![("package".to_owned(), package.name.clone()), ("tag".to_owned(), t.tag.clone())]) | |
| 160 | 146 | } |
| 161 | 147 | </div> |
| 162 | 148 | } |
crates/forge-web-pages/src/pages/pull_reviews.rsmodified+3 -20
| @@ -80,7 +80,7 @@ pub fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> { | ||
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | /// The message for the `review_error` query value of the request, when it is a known code. |
| 83 | -fn error_from(lang: Lang, cx: &Cx) -> Option<&'static str> { | |
| 83 | +pub fn error_from(lang: Lang, cx: &Cx) -> Option<&'static str> { | |
| 84 | 84 | let request = uri(cx); |
| 85 | 85 | let query = request.query()?; |
| 86 | 86 | let (_, code) = |
| @@ -569,16 +569,7 @@ async fn review_comment_resolve(cx: &Cx, Form(form): Form<ReviewForm>) -> Result | ||
| 569 | 569 | let pr = pull_for(state, &ctx, number).await?; |
| 570 | 570 | let comment = comment_on_pull(state, &pr, &user, comment_id(cx)).await?; |
| 571 | 571 | 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() { | |
| 582 | 573 | return Err(forbidden().into()); |
| 583 | 574 | } |
| 584 | 575 | let root = root_of(&comment); |
| @@ -788,15 +779,7 @@ async fn review_dismiss(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOthe | ||
| 788 | 779 | let ctx = load_repo(cx, owner(cx), repo(cx)).await?; |
| 789 | 780 | let (user, session) = require_user(cx).await?; |
| 790 | 781 | 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() { | |
| 800 | 783 | return Err(forbidden().into()); |
| 801 | 784 | } |
| 802 | 785 | let state = context::<AppState>(cx); |
crates/forge-web-pages/src/pages/releases.rsmodified+68 -57
| @@ -152,6 +152,13 @@ fn notice_redirect(href: &str, word: &str) -> SeeOther { | ||
| 152 | 152 | see_other(format!("{href}?notice={word}")) |
| 153 | 153 | } |
| 154 | 154 | |
| 155 | +async fn csrf_token(cx: &Cx) -> Result<String> { | |
| 156 | + Ok(match crate::auth::current_user(cx).await? { | |
| 157 | + Some((_, session)) => session.csrf_token.clone(), | |
| 158 | + None => String::new(), | |
| 159 | + }) | |
| 160 | +} | |
| 161 | + | |
| 155 | 162 | /// A byte count for people: "512 B", "1.5 KiB", "3.2 MiB". |
| 156 | 163 | pub fn size_text(bytes: u64) -> String { |
| 157 | 164 | const KIB: f64 = 1024.0; |
| @@ -186,6 +193,20 @@ fn asset_link(title: &str, tag: &str, asset: &ReleaseAsset) -> AssetLink { | ||
| 186 | 193 | } |
| 187 | 194 | } |
| 188 | 195 | |
| 196 | +fn asset_links(title: &str, tag: &str, assets: &[ReleaseAsset]) -> Vec<AssetLink> { | |
| 197 | + assets | |
| 198 | + .iter() | |
| 199 | + .map(|asset| asset_link(title, tag, asset)) | |
| 200 | + .collect() | |
| 201 | +} | |
| 202 | + | |
| 203 | +fn when_of(release: &Release) -> &str { | |
| 204 | + release | |
| 205 | + .published_at | |
| 206 | + .as_deref() | |
| 207 | + .unwrap_or(&release.created_at) | |
| 208 | +} | |
| 209 | + | |
| 189 | 210 | /// One release card on the list page. |
| 190 | 211 | pub struct ReleaseCard { |
| 191 | 212 | pub title: String, |
| @@ -215,25 +236,18 @@ fn card_of( | ||
| 215 | 236 | latest_id: Option<&str>, |
| 216 | 237 | ) -> ReleaseCard { |
| 217 | 238 | let title = title_of(ctx); |
| 218 | - let when = release | |
| 219 | - .published_at | |
| 220 | - .as_deref() | |
| 221 | - .unwrap_or(&release.created_at); | |
| 222 | 239 | ReleaseCard { |
| 223 | 240 | title: release.title.clone(), |
| 224 | 241 | tag: release.tag.clone(), |
| 225 | 242 | href: tag_href(&title, &release.tag), |
| 226 | 243 | edit_href: release_edit_href(&title, &release.id), |
| 227 | 244 | body: release.body.clone(), |
| 228 | - when: When::new(ctx.lang, when, ctx.viewer_tz(), now_unix()), | |
| 245 | + when: When::new(ctx.lang, when_of(release), ctx.viewer_tz(), now_unix()), | |
| 229 | 246 | author: release.author_name.clone(), |
| 230 | 247 | draft: release.draft, |
| 231 | 248 | prerelease: release.prerelease, |
| 232 | 249 | 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), | |
| 237 | 251 | } |
| 238 | 252 | } |
| 239 | 253 | |
| @@ -250,10 +264,7 @@ pub async fn latest_release_for_home( | ||
| 250 | 264 | Ok(Some(LatestRelease { |
| 251 | 265 | tag: release.tag.clone(), |
| 252 | 266 | 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), | |
| 257 | 268 | })) |
| 258 | 269 | } |
| 259 | 270 | |
| @@ -269,6 +280,27 @@ struct FormDraft { | ||
| 269 | 280 | error: Option<String>, |
| 270 | 281 | } |
| 271 | 282 | |
| 283 | +impl FormDraft { | |
| 284 | + fn from_fields( | |
| 285 | + tag: &str, | |
| 286 | + target: &str, | |
| 287 | + title: &str, | |
| 288 | + body: &str, | |
| 289 | + prerelease: bool, | |
| 290 | + draft: bool, | |
| 291 | + ) -> Self { | |
| 292 | + Self { | |
| 293 | + tag: tag.trim().to_owned(), | |
| 294 | + target: target.trim().to_owned(), | |
| 295 | + title: title.trim().to_owned(), | |
| 296 | + body: body.trim_end().to_owned(), | |
| 297 | + prerelease, | |
| 298 | + draft, | |
| 299 | + error: None, | |
| 300 | + } | |
| 301 | + } | |
| 302 | +} | |
| 303 | + | |
| 272 | 304 | /// The new-release form fields. |
| 273 | 305 | #[derive(Deserialize)] |
| 274 | 306 | struct CreateForm { |
| @@ -636,10 +668,7 @@ async fn release_new_page(cx: &Cx) -> Result<impl View> { | ||
| 636 | 668 | require_write(&ctx)?; |
| 637 | 669 | let lang = i18n::lang(cx, viewer_user(&ctx)); |
| 638 | 670 | 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?; | |
| 643 | 672 | let draft = FormDraft { |
| 644 | 673 | target: ctx.repo.default_branch.clone(), |
| 645 | 674 | draft: false, |
| @@ -664,15 +693,14 @@ async fn release_create(cx: &Cx, Form(form): Form<CreateForm>) -> Result<impl Vi | ||
| 664 | 693 | require_write(&ctx)?; |
| 665 | 694 | let lang = i18n::lang(cx, viewer_user(&ctx)); |
| 666 | 695 | 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 | + ); | |
| 676 | 704 | match create_checked(state, &ctx, &user, &draft, lang).await? { |
| 677 | 705 | Ok(release) => { |
| 678 | 706 | let title = title_of(&ctx); |
| @@ -752,15 +780,8 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> { | ||
| 752 | 780 | } |
| 753 | 781 | let title = title_of(&ctx); |
| 754 | 782 | 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()); | |
| 764 | 785 | let body_html = render_markdown(&release.body, None); |
| 765 | 786 | let page_title = format!("{title} \u{b7} {}", release.title); |
| 766 | 787 | let archive_tar = format!("/{title}/archive/{}.tar.gz", enc(&release.tag)); |
| @@ -784,10 +805,7 @@ async fn release_tag_page(cx: &Cx) -> Result<impl View> { | ||
| 784 | 805 | let notice = notice_from_query(cx, lang); |
| 785 | 806 | let delete_href = format!("/{title}/releases/{}/delete", enc(&release.id)); |
| 786 | 807 | 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?; | |
| 791 | 809 | Ok(view! { |
| 792 | 810 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 793 | 811 | repo_head(head: head, title: Some(card.title.clone()), |
| @@ -958,10 +976,7 @@ async fn edit_parts( | ||
| 958 | 976 | ) |
| 959 | 977 | }) |
| 960 | 978 | .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); | |
| 965 | 980 | let refs = load_refs(ctx.path.clone()).await?; |
| 966 | 981 | Ok(EditParts { |
| 967 | 982 | page_title: format!("{title} \u{b7} {}", g::edit_title(lang, &release.tag)), |
| @@ -994,10 +1009,7 @@ async fn release_edit_page(cx: &Cx) -> Result<impl View> { | ||
| 994 | 1009 | if release.repo_id != ctx.repo.id { |
| 995 | 1010 | return Err(not_found().into()); |
| 996 | 1011 | } |
| 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?; | |
| 1001 | 1013 | let draft = FormDraft { |
| 1002 | 1014 | tag: release.tag.clone(), |
| 1003 | 1015 | title: release.title.clone(), |
| @@ -1032,15 +1044,14 @@ async fn release_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View | ||
| 1032 | 1044 | let Some(before) = state.store.release(&id).await? else { |
| 1033 | 1045 | return Err(not_found().into()); |
| 1034 | 1046 | }; |
| 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 | + ); | |
| 1044 | 1055 | let edit = EditRelease { |
| 1045 | 1056 | title: draft.title.clone(), |
| 1046 | 1057 | body: draft.body.clone(), |
| @@ -1135,7 +1146,7 @@ async fn asset_upload(cx: &Cx, body: Body) -> Result<Response> { | ||
| 1135 | 1146 | let state = context::<AppState>(cx); |
| 1136 | 1147 | let href = release_edit_href(&title_of(&ctx), &id); |
| 1137 | 1148 | let max_bytes = state |
| 1138 | - .config | |
| 1149 | + .live() | |
| 1139 | 1150 | .releases |
| 1140 | 1151 | .max_asset_mb |
| 1141 | 1152 | .saturating_mul(1024 * 1024); |
crates/forge-web-pages/src/pages/releases_live.rsmodified+12 -15
| @@ -36,8 +36,13 @@ pub fn tag_live_url(title: &str, tag: &str) -> String { | ||
| 36 | 36 | format!("/{title}/releases/tag/{}/events", enc(tag)) |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | -// Fingerprints. Each reads what the page shows; any change to it changes the string. `writer` | |
| 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 | +} | |
| 41 | 46 | |
| 42 | 47 | /// What the release list shows: the latest release and every release the viewer may see, with |
| 43 | 48 | /// their assets (names, sizes, download counts). |
| @@ -52,9 +57,7 @@ pub async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool) -> Res | ||
| 52 | 57 | continue; |
| 53 | 58 | } |
| 54 | 59 | 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?); | |
| 58 | 61 | } |
| 59 | 62 | Ok(lines.join("\n")) |
| 60 | 63 | } |
| @@ -74,9 +77,7 @@ pub async fn release_fingerprint( | ||
| 74 | 77 | return Ok("gone".to_owned()); |
| 75 | 78 | } |
| 76 | 79 | 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?); | |
| 80 | 81 | Ok(lines.join("\n")) |
| 81 | 82 | } |
| 82 | 83 | |
| @@ -106,16 +107,12 @@ async fn release_events(cx: &Cx) -> Result<Response> { | ||
| 106 | 107 | let ctx = load_repo(cx, owner(cx), repo(cx)).await?; |
| 107 | 108 | let state = context::<AppState>(cx); |
| 108 | 109 | 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" { | |
| 114 | 113 | return Err(not_found().into()); |
| 115 | 114 | } |
| 116 | 115 | let topic = Topic::RepoReleases(ctx.repo.id.clone()); |
| 117 | - let store = state.store.clone(); | |
| 118 | - let repo_id = ctx.repo.id.clone(); | |
| 119 | 116 | stream_changes(cx, &state.live, &[topic], move || { |
| 120 | 117 | let store = store.clone(); |
| 121 | 118 | let repo_id = repo_id.clone(); |
crates/forge-web-pages/src/pages/repo.rsmodified+1 -1
| @@ -397,7 +397,7 @@ async fn repo_page(cx: &Cx) -> Result<impl View> { | ||
| 397 | 397 | facts = Some(tree_facts(state, repo, &ctx.path, commit, &names).await?); |
| 398 | 398 | let (last, latest) = tokio::join!( |
| 399 | 399 | last_commits(state, &ctx.path, commit, "", &names), |
| 400 | - latest_bar(state, repo, &ctx.path, commit, "", lang, ctx.viewer_tz()), | |
| 400 | + latest_bar(state, repo, &ctx.path, commit, lang, ctx.viewer_tz()), | |
| 401 | 401 | ); |
| 402 | 402 | bar = latest; |
| 403 | 403 | readme = load_readme(state, repo, &ctx.path, &branch, commit, "", &entries).await?; |
crates/forge-web-pages/src/pages/repo_ctx.rsmodified+29 -49
| @@ -121,6 +121,10 @@ pub struct WatchButton { | ||
| 121 | 121 | } |
| 122 | 122 | |
| 123 | 123 | impl RepoCtx { |
| 124 | + pub fn title(&self) -> String { | |
| 125 | + format!("{}/{}", self.repo.owner_name, self.repo.name) | |
| 126 | + } | |
| 127 | + | |
| 124 | 128 | /// Whether the viewer may delete this repo: its owner or an instance admin only. |
| 125 | 129 | pub fn can_delete(&self) -> bool { |
| 126 | 130 | let actor = self.viewer.as_ref().map(|(user, _)| user); |
| @@ -138,8 +142,7 @@ impl RepoCtx { | ||
| 138 | 142 | /// Write role or higher, an org role that grants it, or the owner. Archived repos stay read-only. |
| 139 | 143 | pub fn can_write(&self) -> bool { |
| 140 | 144 | 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() | |
| 143 | 146 | } |
| 144 | 147 | |
| 145 | 148 | /// Open issue count for the Issues tab: one indexed COUNT query. |
| @@ -155,17 +158,8 @@ impl RepoCtx { | ||
| 155 | 158 | let Some(source) = state.store.repo_by_id(source_id).await? else { |
| 156 | 159 | return Ok(None); |
| 157 | 160 | }; |
| 158 | - let (role, org_role) = match &self.viewer { | |
| 159 | - Some((user, _)) => ( | |
| 160 | - state.store.collaborator_role(&source.id, &user.id).await?, | |
| 161 | - state | |
| 162 | - .store | |
| 163 | - .org_repo_role(&source.owner_id, &user.id, &source.id) | |
| 164 | - .await?, | |
| 165 | - ), | |
| 166 | - None => (None, None), | |
| 167 | - }; | |
| 168 | 161 | let actor = self.viewer.as_ref().map(|(user, _)| user); |
| 162 | + let (role, org_role) = access(&state.store, actor, &source).await?; | |
| 169 | 163 | if authorize(actor, &source, role, org_role, Action::Read).is_err() { |
| 170 | 164 | return Ok(None); |
| 171 | 165 | } |
| @@ -200,8 +194,7 @@ impl RepoCtx { | ||
| 200 | 194 | let forks = fork_count(state, &self.repo.id).await?; |
| 201 | 195 | let discussions = state.store.discussions_enabled(&self.repo.id).await?; |
| 202 | 196 | 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(); | |
| 205 | 198 | let mirror = state |
| 206 | 199 | .store |
| 207 | 200 | .pull_mirror(&self.repo.id) |
| @@ -264,12 +257,29 @@ impl RepoCtx { | ||
| 264 | 257 | } |
| 265 | 258 | } |
| 266 | 259 | |
| 267 | -/// Load `owner/name` for the current viewer, or 404. | |
| 268 | 260 | /// The number of public forks of `repo_id`. Private forks are left out (see `RepoHead::forks`). |
| 269 | 261 | pub async fn fork_count(state: &AppState, repo_id: &str) -> Result<u64> { |
| 270 | 262 | Ok(state.store.public_fork_count(repo_id).await?) |
| 271 | 263 | } |
| 272 | 264 | |
| 265 | +/// The viewer's collaborator role and organization role on `repo`; both `None` for anonymous viewers. | |
| 266 | +pub async fn access( | |
| 267 | + store: &Store, | |
| 268 | + viewer: Option<&User>, | |
| 269 | + repo: &Repo, | |
| 270 | +) -> Result<(Option<Role>, Option<Role>)> { | |
| 271 | + match viewer { | |
| 272 | + Some(user) => Ok(( | |
| 273 | + store.collaborator_role(&repo.id, &user.id).await?, | |
| 274 | + store | |
| 275 | + .org_repo_role(&repo.owner_id, &user.id, &repo.id) | |
| 276 | + .await?, | |
| 277 | + )), | |
| 278 | + None => Ok((None, None)), | |
| 279 | + } | |
| 280 | +} | |
| 281 | + | |
| 282 | +/// Load `owner/name` for the current viewer, or 404. | |
| 273 | 283 | pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> { |
| 274 | 284 | let state = context::<AppState>(cx); |
| 275 | 285 | let viewer = current_user(cx).await?; |
| @@ -280,17 +290,8 @@ pub async fn load_repo(cx: &Cx, owner: &str, name: &str) -> Result<RepoCtx> { | ||
| 280 | 290 | } |
| 281 | 291 | return Err(not_found().into()); |
| 282 | 292 | }; |
| 283 | - let (role, org_role) = match &viewer { | |
| 284 | - Some((user, _)) => ( | |
| 285 | - state.store.collaborator_role(&repo.id, &user.id).await?, | |
| 286 | - state | |
| 287 | - .store | |
| 288 | - .org_repo_role(&repo.owner_id, &user.id, &repo.id) | |
| 289 | - .await?, | |
| 290 | - ), | |
| 291 | - None => (None, None), | |
| 292 | - }; | |
| 293 | 293 | let actor = viewer.as_ref().map(|(user, _)| user); |
| 294 | + let (role, org_role) = access(&state.store, actor, &repo).await?; | |
| 294 | 295 | if authorize(actor, &repo, role, org_role, Action::Read).is_err() { |
| 295 | 296 | return Err(not_found().into()); |
| 296 | 297 | } |
| @@ -313,20 +314,8 @@ pub async fn still_readable(store: &Store, viewer: Option<&User>, repo_id: &str) | ||
| 313 | 314 | let Ok(Some(repo)) = store.repo_by_id(repo_id).await else { |
| 314 | 315 | return false; |
| 315 | 316 | }; |
| 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; | |
| 330 | 319 | }; |
| 331 | 320 | authorize(viewer, &repo, role, org_role, Action::Read).is_ok() |
| 332 | 321 | } |
| @@ -357,17 +346,8 @@ async fn moved_location( | ||
| 357 | 346 | None => return Ok(None), |
| 358 | 347 | }, |
| 359 | 348 | }; |
| 360 | - let (role, org_role) = match viewer { | |
| 361 | - Some((user, _)) => ( | |
| 362 | - state.store.collaborator_role(&target.id, &user.id).await?, | |
| 363 | - state | |
| 364 | - .store | |
| 365 | - .org_repo_role(&target.owner_id, &user.id, &target.id) | |
| 366 | - .await?, | |
| 367 | - ), | |
| 368 | - None => (None, None), | |
| 369 | - }; | |
| 370 | 349 | let actor = viewer.map(|(user, _)| user); |
| 350 | + let (role, org_role) = access(&state.store, actor, &target).await?; | |
| 371 | 351 | if authorize(actor, &target, role, org_role, Action::Read).is_err() { |
| 372 | 352 | return Ok(None); |
| 373 | 353 | } |
crates/forge-web-pages/src/pages/repo_mirrors.rsmodified+44 -37
| @@ -262,12 +262,34 @@ fn interval_text(lang: Lang, minutes: u32) -> String { | ||
| 262 | 262 | } |
| 263 | 263 | } |
| 264 | 264 | |
| 265 | -/// The last sync, as the list and the header show it: ok, failed (with the error) or not run yet. | |
| 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 { | |
| 267 | 273 | 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", | |
| 271 | 293 | } |
| 272 | 294 | } |
| 273 | 295 | |
| @@ -338,12 +360,7 @@ struct MirrorRow { | ||
| 338 | 360 | } |
| 339 | 361 | |
| 340 | 362 | 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); | |
| 347 | 364 | let (sync_prefix, sync_suffix) = match lang { |
| 348 | 365 | Lang::En => ("synced ", ""), |
| 349 | 366 | Lang::Tr => ("", " eşitlendi"), |
| @@ -370,8 +387,8 @@ fn mirror_row(lang: Lang, mirror: &Mirror, title: &str, tz: &str) -> MirrorRow { | ||
| 370 | 387 | last_sync_rel, |
| 371 | 388 | sync_prefix, |
| 372 | 389 | sync_suffix, |
| 373 | - dot_class, | |
| 374 | - status_text, | |
| 390 | + dot_class: dot_class(mirror.enabled, status), | |
| 391 | + status_text: status_label(lang, status), | |
| 375 | 392 | error: mirror.last_error.clone().unwrap_or_default(), |
| 376 | 393 | } |
| 377 | 394 | } |
| @@ -697,12 +714,7 @@ async fn mirror_create(cx: &Cx, Form(form): Form<PushForm>) -> Result<impl View> | ||
| 697 | 714 | let name = repo(cx); |
| 698 | 715 | let ctx = load_repo(cx, owner, name).await?; |
| 699 | 716 | 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)?; | |
| 706 | 718 | let state = context::<AppState>(cx); |
| 707 | 719 | let lang = lang_of(cx, &ctx); |
| 708 | 720 | let pull = form.direction == "pull"; |
| @@ -760,6 +772,16 @@ async fn mirror_create(cx: &Cx, Form(form): Form<PushForm>) -> Result<impl View> | ||
| 760 | 772 | Err(back_to_list(&title_of(&ctx), notice).into()) |
| 761 | 773 | } |
| 762 | 774 | |
| 775 | +fn require_mirror_admin(ctx: &RepoCtx) -> Result<()> { | |
| 776 | + if !ctx.can_admin() { | |
| 777 | + return Err(not_found().into()); | |
| 778 | + } | |
| 779 | + if ctx.repo.archived { | |
| 780 | + return Err(forbidden().into()); | |
| 781 | + } | |
| 782 | + Ok(()) | |
| 783 | +} | |
| 784 | + | |
| 763 | 785 | /// The mirror in the path, when it belongs to this repo. Any other mirror answers 404. |
| 764 | 786 | async fn repo_mirror(state: &AppState, ctx: &RepoCtx, id: &str) -> Result<Mirror> { |
| 765 | 787 | match state.store.mirror(id).await? { |
| @@ -881,12 +903,7 @@ async fn mirror_update(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View> | ||
| 881 | 903 | let id = mirror_id(cx); |
| 882 | 904 | let ctx = load_repo(cx, owner, name).await?; |
| 883 | 905 | 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)?; | |
| 890 | 907 | let state = context::<AppState>(cx); |
| 891 | 908 | let mirror = repo_mirror(state, &ctx, id).await?; |
| 892 | 909 | let url = if form.url.trim().is_empty() { |
| @@ -975,12 +992,7 @@ async fn mirror_sync(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | ||
| 975 | 992 | let id = mirror_id(cx); |
| 976 | 993 | let ctx = load_repo(cx, owner, name).await?; |
| 977 | 994 | 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)?; | |
| 984 | 996 | let state = context::<AppState>(cx); |
| 985 | 997 | let mirror = repo_mirror(state, &ctx, id).await?; |
| 986 | 998 | state |
| @@ -999,12 +1011,7 @@ async fn mirror_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<SeeOther | ||
| 999 | 1011 | let id = mirror_id(cx); |
| 1000 | 1012 | let ctx = load_repo(cx, owner, name).await?; |
| 1001 | 1013 | 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)?; | |
| 1008 | 1015 | let state = context::<AppState>(cx); |
| 1009 | 1016 | let mirror = repo_mirror(state, &ctx, id).await?; |
| 1010 | 1017 | let title = title_of(&ctx); |
crates/forge-web-pages/src/pages/repo_settings.rsmodified+24 -140
| @@ -1,11 +1,3 @@ | ||
| 1 | -//! Page: repo settings (`/{owner}/{repo}/settings`). The owner, an instance admin and collaborators | |
| 2 | -//! with the Admin role get the page. It shows one section at a time, chosen by `?section=`: General | |
| 3 | -//! (description, default branch, and the Features switches: discussions and wiki; the default), branch | |
| 4 | -//! protection rules (Admin), and the danger zone (rename, then transfer, visibility, archive and | |
| 5 | -//! delete). Transfer and delete need Delete: owner or instance admin only. Deleting moves the bare repo | |
| 6 | -//! into `data_dir/trash` and removes its database rows in one transaction. The repo is never erased | |
| 7 | -//! from disk, so an admin can recover it from the trash. | |
| 8 | - | |
| 9 | 1 | use std::path::Path; |
| 10 | 2 | |
| 11 | 3 | use forge_core::protection::{ |
| @@ -49,14 +41,11 @@ use crate::views::{alert, enc, shell}; | ||
| 49 | 41 | path_param!(owner); |
| 50 | 42 | path_param!(repo); |
| 51 | 43 | |
| 52 | -/// The `?section=` query of the settings page. Unknown values show General. | |
| 53 | 44 | #[query_params(error = bad_request)] |
| 54 | 45 | pub struct SectionQuery { |
| 55 | 46 | section: Option<String>, |
| 56 | 47 | } |
| 57 | 48 | |
| 58 | -/// The section to show: `branches`, or `danger` (the danger zone, for a viewer who may admin the | |
| 59 | -/// repo, which the page requires). Anything else, including the old `discussions`, is `general`. | |
| 60 | 49 | fn pick_section(raw: Option<&str>) -> &'static str { |
| 61 | 50 | match raw { |
| 62 | 51 | Some("branches") => "branches", |
| @@ -65,14 +54,10 @@ fn pick_section(raw: Option<&str>) -> &'static str { | ||
| 65 | 54 | } |
| 66 | 55 | } |
| 67 | 56 | |
| 68 | -/// Cookie that carries a one-shot notice (the deleted repo's `owner/name`) to the next profile page. | |
| 69 | 57 | pub const NOTICE_COOKIE: &str = "forge_notice"; |
| 70 | 58 | |
| 71 | -/// Cookie that carries a one-shot settings notice to the next settings page. Its value is one of | |
| 72 | -/// the fixed words in `SETTINGS_NOTICES`, never user text. | |
| 73 | 59 | const SETTINGS_NOTICE_COOKIE: &str = "forge_settings_notice"; |
| 74 | 60 | |
| 75 | -/// Notice words, the text each one shows, and whether it is an error (shown as an alert). | |
| 76 | 61 | const SETTINGS_NOTICES: [(&str, K, bool); 13] = [ |
| 77 | 62 | ("saved", K::BranchRuleSaved, false), |
| 78 | 63 | ("removed", K::BranchRuleRemoved, false), |
| @@ -89,7 +74,6 @@ const SETTINGS_NOTICES: [(&str, K, bool); 13] = [ | ||
| 89 | 74 | ("bad_form", K::BadForm, true), |
| 90 | 75 | ]; |
| 91 | 76 | |
| 92 | -/// Longest accepted `owner/name` in the notice cookie. | |
| 93 | 77 | const MAX_NOTICE_CHARS: usize = 256; |
| 94 | 78 | |
| 95 | 79 | #[derive(Deserialize)] |
| @@ -100,19 +84,16 @@ struct DeleteForm { | ||
| 100 | 84 | confirm: String, |
| 101 | 85 | } |
| 102 | 86 | |
| 103 | -/// The General form: description and default branch, saved together. | |
| 104 | 87 | #[derive(Deserialize)] |
| 105 | 88 | struct GeneralForm { |
| 106 | 89 | #[serde(default)] |
| 107 | 90 | csrf: String, |
| 108 | 91 | #[serde(default)] |
| 109 | 92 | description: String, |
| 110 | - /// Empty when the repo has no branches yet; the current default branch is then kept. | |
| 111 | 93 | #[serde(default)] |
| 112 | 94 | default_branch: String, |
| 113 | 95 | } |
| 114 | 96 | |
| 115 | -/// The visibility form. `understand` is the confirm popup's hidden field; a request without it is refused. | |
| 116 | 97 | #[derive(Deserialize)] |
| 117 | 98 | struct VisibilityForm { |
| 118 | 99 | #[serde(default)] |
| @@ -127,12 +108,10 @@ struct VisibilityForm { | ||
| 127 | 108 | struct ArchiveForm { |
| 128 | 109 | #[serde(default)] |
| 129 | 110 | csrf: String, |
| 130 | - /// `1` archives the repo, `0` unarchives it. | |
| 131 | 111 | #[serde(default)] |
| 132 | 112 | archived: String, |
| 133 | 113 | } |
| 134 | 114 | |
| 135 | -/// The add/update rule form. An unchecked box is absent from the body, so `Option` is `None`. | |
| 136 | 115 | #[derive(Deserialize)] |
| 137 | 116 | struct BranchForm { |
| 138 | 117 | #[serde(default)] |
| @@ -143,7 +122,6 @@ struct BranchForm { | ||
| 143 | 122 | allow_force_push: Option<String>, |
| 144 | 123 | #[serde(default)] |
| 145 | 124 | allow_deletion: Option<String>, |
| 146 | - /// Text from the number field; blank means 0. | |
| 147 | 125 | #[serde(default)] |
| 148 | 126 | required_approvals: String, |
| 149 | 127 | #[serde(default)] |
| @@ -154,11 +132,8 @@ struct BranchForm { | ||
| 154 | 132 | restrict_push: Option<String>, |
| 155 | 133 | #[serde(default)] |
| 156 | 134 | require_merge_queue: Option<String>, |
| 157 | - /// Required check contexts, separated by commas or new lines. | |
| 158 | 135 | #[serde(default)] |
| 159 | 136 | required_checks: String, |
| 160 | - /// Set by an existing rule's form, whose pattern is fixed. Without it the form adds a rule, and | |
| 161 | - /// a pattern that already has one is refused rather than overwriting it. | |
| 162 | 137 | #[serde(default)] |
| 163 | 138 | existing: Option<String>, |
| 164 | 139 | } |
| @@ -171,10 +146,9 @@ struct BranchDeleteForm { | ||
| 171 | 146 | rule_id: String, |
| 172 | 147 | } |
| 173 | 148 | |
| 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) { | |
| 176 | 150 | cookies(cx).add( |
| 177 | - Cookie::build((NOTICE_COOKIE, title.to_owned())) | |
| 151 | + Cookie::build((name, value)) | |
| 178 | 152 | .path("/") |
| 179 | 153 | .http_only(true) |
| 180 | 154 | .same_site(SameSite::Lax) |
| @@ -182,11 +156,19 @@ pub fn set_notice(cx: &Cx, title: &str) { | ||
| 182 | 156 | ); |
| 183 | 157 | } |
| 184 | 158 | |
| 185 | -/// Reads and clears the notice cookie. Anything that is not a plain `owner/name` is ignored. | |
| 186 | -pub fn take_notice(cx: &Cx) -> Option<String> { | |
| 159 | +fn take_cookie(cx: &Cx, name: &'static str) -> Option<String> { | |
| 187 | 160 | 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)?; | |
| 190 | 172 | let plain = !value.is_empty() |
| 191 | 173 | && value.chars().count() <= MAX_NOTICE_CHARS |
| 192 | 174 | && value |
| @@ -195,40 +177,26 @@ pub fn take_notice(cx: &Cx) -> Option<String> { | ||
| 195 | 177 | plain.then_some(value) |
| 196 | 178 | } |
| 197 | 179 | |
| 198 | -/// Sets the one-line notice shown on the next settings page view. | |
| 199 | 180 | 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()); | |
| 207 | 182 | } |
| 208 | 183 | |
| 209 | -/// Reads and clears the settings notice cookie. Only the fixed words are shown. The flag says | |
| 210 | -/// whether the notice is an error. | |
| 211 | 184 | 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)?; | |
| 215 | 186 | SETTINGS_NOTICES |
| 216 | 187 | .iter() |
| 217 | 188 | .find(|(word, _, _)| *word == value) |
| 218 | 189 | .map(|(_, key, is_error)| (*key, *is_error)) |
| 219 | 190 | } |
| 220 | 191 | |
| 221 | -/// Redirect back to the General section, which shows the notice set just before. | |
| 222 | 192 | fn back_to_settings(title: &str) -> SeeOther { |
| 223 | 193 | see_other(format!("/{title}/settings")) |
| 224 | 194 | } |
| 225 | 195 | |
| 226 | -/// Redirect back to one section of the settings page (its `?section=` value). | |
| 227 | 196 | fn back_to_section(title: &str, section: &str) -> SeeOther { |
| 228 | 197 | see_other(format!("/{title}/settings?section={section}")) |
| 229 | 198 | } |
| 230 | 199 | |
| 231 | -/// Drops control characters (so the text is one line) and surrounding spaces. | |
| 232 | 200 | fn clean_description(raw: &str) -> String { |
| 233 | 201 | raw.chars() |
| 234 | 202 | .filter(|c| !c.is_control()) |
| @@ -237,8 +205,6 @@ fn clean_description(raw: &str) -> String { | ||
| 237 | 205 | .to_owned() |
| 238 | 206 | } |
| 239 | 207 | |
| 240 | -/// Points git HEAD of the bare repo at `branch`. The caller has checked that the branch exists. | |
| 241 | -/// The `refs/heads/` prefix means the value can never be read as an option. | |
| 242 | 208 | async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git::Result<()> { |
| 243 | 209 | GitCommand::new(env, "symbolic-ref") |
| 244 | 210 | .git_dir(repo_path) |
| @@ -248,7 +214,6 @@ async fn point_head(env: &GitEnv, repo_path: &Path, branch: &str) -> forge_git:: | ||
| 248 | 214 | .await |
| 249 | 215 | } |
| 250 | 216 | |
| 251 | -/// Branch names of the repo. Empty for an empty repo. | |
| 252 | 217 | async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> { |
| 253 | 218 | let refs = load_refs(ctx.path.clone()).await?; |
| 254 | 219 | Ok(refs |
| @@ -258,7 +223,6 @@ async fn load_branch_names(ctx: &RepoCtx) -> Result<Vec<String>> { | ||
| 258 | 223 | .collect()) |
| 259 | 224 | } |
| 260 | 225 | |
| 261 | -/// The one-line notice on the profile page after a delete. | |
| 262 | 226 | #[component] |
| 263 | 227 | pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Result<impl View> { |
| 264 | 228 | Ok(view! { |
| @@ -270,8 +234,6 @@ pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Re | ||
| 270 | 234 | }) |
| 271 | 235 | } |
| 272 | 236 | |
| 273 | -/// What the danger zone's forms show when one came back with an error: the drafts the viewer typed and | |
| 274 | -/// the error each form got. A fresh page has the repo's own name in the rename form and nothing else. | |
| 275 | 237 | pub struct DangerForms { |
| 276 | 238 | pub rename_name: String, |
| 277 | 239 | pub rename_error: Option<String>, |
| @@ -292,7 +254,6 @@ impl DangerForms { | ||
| 292 | 254 | } |
| 293 | 255 | } |
| 294 | 256 | |
| 295 | -/// The Visibility topic: the current value as a line, and the other side behind a confirm. | |
| 296 | 257 | #[component] |
| 297 | 258 | async fn visibility_section( |
| 298 | 259 | cx: &Cx, |
| @@ -331,7 +292,6 @@ async fn visibility_section( | ||
| 331 | 292 | }) |
| 332 | 293 | } |
| 333 | 294 | |
| 334 | -/// The Archive topic: what archiving does, and the one action for the repo's state. | |
| 335 | 295 | #[component] |
| 336 | 296 | async fn archive_section( |
| 337 | 297 | cx: &Cx, |
| @@ -359,9 +319,6 @@ async fn archive_section( | ||
| 359 | 319 | }) |
| 360 | 320 | } |
| 361 | 321 | |
| 362 | -/// The danger zone, in order: Rename; Transfer, Visibility, Archive and Delete for a viewer who may | |
| 363 | -/// delete the repo (Transfer and Delete are hidden from the rest). Every topic is a `.sec` whose own | |
| 364 | -/// action is a small pill that opens its form or confirm in place. | |
| 365 | 322 | #[component] |
| 366 | 323 | async fn danger_section( |
| 367 | 324 | cx: &Cx, |
| @@ -395,7 +352,6 @@ async fn danger_section( | ||
| 395 | 352 | }) |
| 396 | 353 | } |
| 397 | 354 | |
| 398 | -/// The Delete topic: what deleting does, and the confirmation form, which opens in place. | |
| 399 | 355 | #[component] |
| 400 | 356 | async fn delete_section( |
| 401 | 357 | cx: &Cx, |
| @@ -434,10 +390,6 @@ async fn delete_section( | ||
| 434 | 390 | }) |
| 435 | 391 | } |
| 436 | 392 | |
| 437 | -/// The settings frame: the rail of settings pages beside the sheet holding the page's own content | |
| 438 | -/// (its children). Every settings page shows the same rail, one list of every page. `current` names | |
| 439 | -/// the page shown (`general`, `branches`, `webhooks`, ...) and marks its rail item. Every settings | |
| 440 | -/// page is for a repo admin, so the Danger zone is always listed. | |
| 441 | 393 | #[component] |
| 442 | 394 | pub async fn settings_frame( |
| 443 | 395 | cx: &Cx, |
| @@ -499,9 +451,6 @@ pub async fn settings_frame( | ||
| 499 | 451 | }) |
| 500 | 452 | } |
| 501 | 453 | |
| 502 | -/// The General section: description and default branch in one form, under no heading (the page's | |
| 503 | -/// head names it), then the Features topic with one switch per feature. Each form carries its own | |
| 504 | -/// CSRF token. An empty repo shows "No branches yet" and no selector. | |
| 505 | 454 | #[component] |
| 506 | 455 | async fn general_section( |
| 507 | 456 | cx: &Cx, |
| @@ -554,8 +503,6 @@ async fn general_section( | ||
| 554 | 503 | }) |
| 555 | 504 | } |
| 556 | 505 | |
| 557 | -/// Reads the rule settings from the form. Any problem is the message to show next to the form. | |
| 558 | -/// The message is for a `required_approvals` value outside 0..=20 or not a whole number. | |
| 559 | 506 | fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFlags, String> { |
| 560 | 507 | let approvals_msg = || g::t(lang, K::ApprovalsRange).to_owned(); |
| 561 | 508 | let raw = form.required_approvals.trim(); |
| @@ -583,13 +530,11 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFl | ||
| 583 | 530 | }) |
| 584 | 531 | } |
| 585 | 532 | |
| 586 | -/// One pill in a rule card's summary: its text and its classes. | |
| 587 | 533 | struct RulePill { |
| 588 | 534 | text: String, |
| 589 | 535 | class: &'static str, |
| 590 | 536 | } |
| 591 | 537 | |
| 592 | -/// The pills that describe a rule in its card summary. A rule that sets nothing gets one muted pill. | |
| 593 | 538 | fn rule_pills(lang: Lang, rule: &BranchRule) -> Vec<RulePill> { |
| 594 | 539 | let warn = "warn"; |
| 595 | 540 | let plain = ""; |
| @@ -634,7 +579,6 @@ fn pill(text: &str, class: &'static str) -> RulePill { | ||
| 634 | 579 | } |
| 635 | 580 | } |
| 636 | 581 | |
| 637 | -/// A rule as the settings page shows it: its id, its summary pills, and the form it opens with. | |
| 638 | 582 | struct RuleCard { |
| 639 | 583 | id: String, |
| 640 | 584 | pills: Vec<RulePill>, |
| @@ -642,11 +586,6 @@ struct RuleCard { | ||
| 642 | 586 | draft: RuleDraft, |
| 643 | 587 | } |
| 644 | 588 | |
| 645 | -/// The rule list: a line per rule with its summary and an Edit word. The last line is the add line: | |
| 646 | -/// when no rule covers the default branch it also names that branch as protected by default, and | |
| 647 | -/// the add line opens the add form, prefilled with the default branch. A rule opens in place with its | |
| 648 | -/// rule's values, and the rule whose draft has an error opens with the draft instead. The add line | |
| 649 | -/// opens with the draft when no rule takes it. The rows share one `name`, so opening one closes the rest. | |
| 650 | 589 | #[component] |
| 651 | 590 | async fn branch_rule_cards( |
| 652 | 591 | cx: &Cx, |
| @@ -699,11 +638,6 @@ async fn branch_rule_cards( | ||
| 699 | 638 | }) |
| 700 | 639 | } |
| 701 | 640 | |
| 702 | -/// The rule form: the pattern (a new rule only), two groups of toggles, and the approvals and checks, | |
| 703 | -/// with the actions in one row under the form. The Pull requests group hides while Only through | |
| 704 | -/// pull requests is off, unless the rule already keeps a pull request setting, so a saved setting is | |
| 705 | -/// never hidden. The actions sit outside the form and submit it by its id, because forms cannot nest; | |
| 706 | -/// an existing rule's Remove action is a confirm_act beside them, on the same row. | |
| 707 | 641 | #[component] |
| 708 | 642 | async fn branch_rule_form( |
| 709 | 643 | cx: &Cx, |
| @@ -728,7 +662,6 @@ async fn branch_rule_form( | ||
| 728 | 662 | error, |
| 729 | 663 | is_new: _, |
| 730 | 664 | } = draft; |
| 731 | - // A pull request setting that is not the default keeps its group in view while the switch is off. | |
| 732 | 665 | let pr_saved = !matches!(required_approvals.trim(), "" | "0") |
| 733 | 666 | || block_on_changes_requested |
| 734 | 667 | || require_up_to_date |
| @@ -739,7 +672,6 @@ async fn branch_rule_form( | ||
| 739 | 672 | } else { |
| 740 | 673 | "rule-pr" |
| 741 | 674 | }; |
| 742 | - // Field ids are per rule, so two open rule forms never share an id. | |
| 743 | 675 | let prefix = match &rule_id { |
| 744 | 676 | Some(id) => format!("rule-{id}"), |
| 745 | 677 | None => "rule-new".to_owned(), |
| @@ -755,8 +687,6 @@ async fn branch_rule_form( | ||
| 755 | 687 | alert(message: message.as_str()) |
| 756 | 688 | } |
| 757 | 689 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 758 | - // An existing rule's pattern is fixed: this form only changes what the rule does. A | |
| 759 | - // different pattern is a new rule, added from the Add rule line. | |
| 760 | 690 | if rule_id.is_some() { |
| 761 | 691 | <input type="hidden" name="pattern" value=(pattern.as_str())> |
| 762 | 692 | <input type="hidden" name="existing" value="1"> |
| @@ -837,7 +767,6 @@ async fn branch_rule_form( | ||
| 837 | 767 | }) |
| 838 | 768 | } |
| 839 | 769 | |
| 840 | -/// The form values to show: the pattern and checkboxes, plus any validation error. | |
| 841 | 770 | #[derive(Clone)] |
| 842 | 771 | struct RuleDraft { |
| 843 | 772 | pattern: String, |
| @@ -850,12 +779,10 @@ struct RuleDraft { | ||
| 850 | 779 | require_merge_queue: bool, |
| 851 | 780 | required_checks: String, |
| 852 | 781 | error: Option<String>, |
| 853 | - /// True for the New rule form's draft, so a refused new rule never opens an existing rule's card. | |
| 854 | 782 | is_new: bool, |
| 855 | 783 | } |
| 856 | 784 | |
| 857 | 785 | impl RuleDraft { |
| 858 | - /// The values a saved rule opens with. | |
| 859 | 786 | fn from_rule(rule: &BranchRule) -> Self { |
| 860 | 787 | Self { |
| 861 | 788 | pattern: rule.pattern.clone(), |
| @@ -872,7 +799,6 @@ impl RuleDraft { | ||
| 872 | 799 | } |
| 873 | 800 | } |
| 874 | 801 | |
| 875 | - /// The default values for the add form, with the default branch as the pattern. | |
| 876 | 802 | fn for_default_branch(default_branch: &str) -> Self { |
| 877 | 803 | Self { |
| 878 | 804 | pattern: default_branch.to_owned(), |
| @@ -890,21 +816,16 @@ impl RuleDraft { | ||
| 890 | 816 | } |
| 891 | 817 | } |
| 892 | 818 | |
| 893 | -/// Everything the settings page shows besides the repo header. | |
| 894 | 819 | struct SettingsView { |
| 895 | 820 | rules: Vec<BranchRule>, |
| 896 | - /// A settings notice: its text and whether it is an error. | |
| 897 | 821 | notice: Option<(K, bool)>, |
| 898 | 822 | draft: RuleDraft, |
| 899 | 823 | danger: DangerForms, |
| 900 | 824 | transfer: TransferStatus, |
| 901 | 825 | wiki_on: bool, |
| 902 | - /// Recently reported status contexts, offered as required-check suggestions. | |
| 903 | 826 | contexts: Vec<String>, |
| 904 | 827 | } |
| 905 | 828 | |
| 906 | -/// What a settings page shows: its section, a notice, a rule draft and the danger zone's forms. A | |
| 907 | -/// page drawn again after a refused POST passes what the viewer had typed. | |
| 908 | 829 | pub struct Shown { |
| 909 | 830 | section: &'static str, |
| 910 | 831 | notice: Option<(K, bool)>, |
| @@ -913,7 +834,6 @@ pub struct Shown { | ||
| 913 | 834 | } |
| 914 | 835 | |
| 915 | 836 | impl Shown { |
| 916 | - /// The danger zone, with its forms as they came back. | |
| 917 | 837 | pub fn danger(danger: DangerForms) -> Self { |
| 918 | 838 | Self { |
| 919 | 839 | section: "danger", |
| @@ -924,8 +844,6 @@ impl Shown { | ||
| 924 | 844 | } |
| 925 | 845 | } |
| 926 | 846 | |
| 927 | -/// Draws the settings page at `shown.section`. The page and every POST that is refused draw through | |
| 928 | -/// here, so a refused form comes back as the same page with its message. | |
| 929 | 847 | pub async fn render_settings( |
| 930 | 848 | cx: &Cx, |
| 931 | 849 | ctx: RepoCtx, |
| @@ -965,8 +883,6 @@ pub async fn render_settings( | ||
| 965 | 883 | }) |
| 966 | 884 | } |
| 967 | 885 | |
| 968 | -/// The settings body: the repo header with Settings active, then the rail and one section (`section`: | |
| 969 | -/// general, branches or danger) in the sheet. | |
| 970 | 886 | #[component] |
| 971 | 887 | async fn settings_body( |
| 972 | 888 | cx: &Cx, |
| @@ -996,8 +912,6 @@ async fn settings_body( | ||
| 996 | 912 | wiki_on, |
| 997 | 913 | contexts, |
| 998 | 914 | } = page; |
| 999 | - // A card takes the draft when the draft has an error and the pattern is its rule's pattern. | |
| 1000 | - // Every other card opens with its saved values. A draft no card takes goes to the New rule card. | |
| 1001 | 915 | let mut draft = Some(draft); |
| 1002 | 916 | let mut cards = Vec::with_capacity(rules.len()); |
| 1003 | 917 | for rule in rules { |
| @@ -1016,9 +930,7 @@ async fn settings_body( | ||
| 1016 | 930 | }); |
| 1017 | 931 | } |
| 1018 | 932 | let new_draft = draft.unwrap_or_else(|| RuleDraft::for_default_branch(&default_branch)); |
| 1019 | - // The New rule form stays collapsed unless its draft was rejected with an error. | |
| 1020 | 933 | let mut new_open = new_draft.error.is_some(); |
| 1021 | - // The editor pane is never blank on arrival: the first rule, or the new rule if there is none. | |
| 1022 | 934 | if !new_open && !cards.iter().any(|card| card.open) { |
| 1023 | 935 | match cards.first_mut() { |
| 1024 | 936 | Some(first) => first.open = true, |
| @@ -1033,7 +945,6 @@ async fn settings_body( | ||
| 1033 | 945 | "danger" => g::t(lang, K::DangerZone), |
| 1034 | 946 | _ => g::t(lang, K::General), |
| 1035 | 947 | }; |
| 1036 | - // Only one section is rendered. | |
| 1037 | 948 | Ok(view! { |
| 1038 | 949 | repo_head(head: head, title: Some(section_name.to_owned())) |
| 1039 | 950 | settings_frame(lang: lang, title: title.clone(), current: section, |
| @@ -1065,7 +976,6 @@ async fn settings_body( | ||
| 1065 | 976 | }) |
| 1066 | 977 | } |
| 1067 | 978 | |
| 1068 | -/// The repo fields the settings page shows, read once from the repo context. | |
| 1069 | 979 | struct SettingsFrame { |
| 1070 | 980 | page_title: String, |
| 1071 | 981 | default_branch: String, |
| @@ -1077,7 +987,7 @@ struct SettingsFrame { | ||
| 1077 | 987 | |
| 1078 | 988 | impl SettingsFrame { |
| 1079 | 989 | async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> { |
| 1080 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 990 | + let title = ctx.title(); | |
| 1081 | 991 | Ok(Self { |
| 1082 | 992 | page_title: g::settings_page_title(lang, &title), |
| 1083 | 993 | default_branch: ctx.repo.default_branch.clone(), |
| @@ -1089,8 +999,6 @@ impl SettingsFrame { | ||
| 1089 | 999 | } |
| 1090 | 1000 | } |
| 1091 | 1001 | |
| 1092 | -/// Gets the settings page. Hidden repos are 404 (checked in `load_repo`), anonymous viewers of | |
| 1093 | -/// visible repos go to login, and signed-in viewers who may not manage the repo get 403. | |
| 1094 | 1002 | #[page("/{owner}/{repo}/settings")] |
| 1095 | 1003 | async fn settings_page(cx: &Cx) -> Result<impl View> { |
| 1096 | 1004 | let owner = owner(cx); |
| @@ -1111,9 +1019,6 @@ async fn settings_page(cx: &Cx) -> Result<impl View> { | ||
| 1111 | 1019 | render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await |
| 1112 | 1020 | } |
| 1113 | 1021 | |
| 1114 | -/// Saves the description and the default branch together. The form is checked for CSRF and | |
| 1115 | -/// `Action::Admin` first. The branch must be an existing branch: git HEAD is pointed at it first, | |
| 1116 | -/// and the database changes only when that succeeds. A failed database write puts HEAD back. | |
| 1117 | 1022 | #[route(POST "/{owner}/{repo}/settings/general")] |
| 1118 | 1023 | async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result<SeeOther> { |
| 1119 | 1024 | let owner = owner(cx); |
| @@ -1123,7 +1028,7 @@ async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result | ||
| 1123 | 1028 | if !ctx.can_admin() { |
| 1124 | 1029 | return Err(forbidden().into()); |
| 1125 | 1030 | } |
| 1126 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 1031 | + let title = ctx.title(); | |
| 1127 | 1032 | let state = context::<AppState>(cx); |
| 1128 | 1033 | |
| 1129 | 1034 | let description = clean_description(&form.description); |
| @@ -1181,8 +1086,6 @@ async fn settings_general_save(cx: &Cx, Form(form): Form<GeneralForm>) -> Result | ||
| 1181 | 1086 | Ok(back_to_settings(&title)) |
| 1182 | 1087 | } |
| 1183 | 1088 | |
| 1184 | -/// Changes the visibility. Changing it needs `understand`, which only the confirm popup sends. Picking the current value | |
| 1185 | -/// changes nothing. | |
| 1186 | 1089 | #[route(POST "/{owner}/{repo}/settings/visibility")] |
| 1187 | 1090 | async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) -> Result<SeeOther> { |
| 1188 | 1091 | let owner = owner(cx); |
| @@ -1192,7 +1095,7 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) -> | ||
| 1192 | 1095 | if !ctx.can_admin() { |
| 1193 | 1096 | return Err(forbidden().into()); |
| 1194 | 1097 | } |
| 1195 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 1098 | + let title = ctx.title(); | |
| 1196 | 1099 | let Ok(target) = form.visibility.parse::<Visibility>() else { |
| 1197 | 1100 | set_settings_notice(cx, "bad_form"); |
| 1198 | 1101 | return Ok(back_to_section(&title, "danger")); |
| @@ -1233,8 +1136,6 @@ async fn settings_visibility_save(cx: &Cx, Form(form): Form<VisibilityForm>) -> | ||
| 1233 | 1136 | Ok(back_to_section(&title, "danger")) |
| 1234 | 1137 | } |
| 1235 | 1138 | |
| 1236 | -/// Archives (`archived=1`) or unarchives (`archived=0`) the repo. Archiving is an Admin action, and | |
| 1237 | -/// the archived flag does not block Admin. | |
| 1238 | 1139 | #[route(POST "/{owner}/{repo}/settings/archive")] |
| 1239 | 1140 | async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result<SeeOther> { |
| 1240 | 1141 | let owner = owner(cx); |
| @@ -1244,7 +1145,7 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result | ||
| 1244 | 1145 | if !ctx.can_admin() { |
| 1245 | 1146 | return Err(forbidden().into()); |
| 1246 | 1147 | } |
| 1247 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 1148 | + let title = ctx.title(); | |
| 1248 | 1149 | let archived = match form.archived.as_str() { |
| 1249 | 1150 | "1" => true, |
| 1250 | 1151 | "0" => false, |
| @@ -1288,10 +1189,6 @@ async fn settings_archive_save(cx: &Cx, Form(form): Form<ArchiveForm>) -> Result | ||
| 1288 | 1189 | Ok(back_to_section(&title, "danger")) |
| 1289 | 1190 | } |
| 1290 | 1191 | |
| 1291 | -/// Deletes the repo when the viewer may delete it, the CSRF token is valid and the confirmation | |
| 1292 | -/// is exactly `owner/name`. On success the repo is moved to trash, its rows are deleted, and the | |
| 1293 | -/// viewer is redirected to the owner's repositories tab with a notice. If the database delete fails the directory goes back. | |
| 1294 | -/// A wrong confirmation re-renders the page with an error and changes nothing. | |
| 1295 | 1192 | #[page(POST "/{owner}/{repo}/settings/delete")] |
| 1296 | 1193 | async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl View> { |
| 1297 | 1194 | let owner = owner(cx); |
| @@ -1302,7 +1199,7 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V | ||
| 1302 | 1199 | return Err(forbidden().into()); |
| 1303 | 1200 | } |
| 1304 | 1201 | let lang = i18n::lang(cx, Some(&user)); |
| 1305 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 1202 | + let title = ctx.title(); | |
| 1306 | 1203 | let error = if form.confirm.trim() == title { |
| 1307 | 1204 | None |
| 1308 | 1205 | } else { |
| @@ -1313,8 +1210,7 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V | ||
| 1313 | 1210 | let state = context::<AppState>(cx); |
| 1314 | 1211 | let repo: &RepoRow = &ctx.repo; |
| 1315 | 1212 | let data_dir = &state.config.data_dir; |
| 1316 | - // A missing directory (already removed by hand) has nothing to trash, so only the rows go. | |
| 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?; | |
| 1318 | 1214 | let trash_path = if repo_dir_missing(data_dir, &repo.id).map_err(forge_core::Error::from)? { |
| 1319 | 1215 | tracing::warn!(repo_id = %repo.id, "repo dir missing, deleting DB rows only"); |
| 1320 | 1216 | None |
| @@ -1325,7 +1221,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V | ||
| 1325 | 1221 | .map_err(forge_core::Error::from)?, |
| 1326 | 1222 | ) |
| 1327 | 1223 | }; |
| 1328 | - // The wiki goes to the trash with the repo. A failure here puts the repo back first. | |
| 1329 | 1224 | let wiki_trash = match move_wiki_to_trash(data_dir, &repo.id).await { |
| 1330 | 1225 | Ok(path) => path, |
| 1331 | 1226 | Err(e) => { |
| @@ -1338,8 +1233,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V | ||
| 1338 | 1233 | return Err(forge_core::Error::from(e).into()); |
| 1339 | 1234 | } |
| 1340 | 1235 | }; |
| 1341 | - // Release assets: their rows go with the repo, so their blob ids are read first. | |
| 1342 | - let release_assets = state.store.repo_release_asset_ids(&repo.id).await?; | |
| 1343 | 1236 | let deleted = state.store.delete_repo(&repo.id).await; |
| 1344 | 1237 | state.live.bump_repo(&repo.owner_id, &repo.id); |
| 1345 | 1238 | if let Err(e) = deleted { |
| @@ -1393,11 +1286,9 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V | ||
| 1393 | 1286 | ) |
| 1394 | 1287 | .await; |
| 1395 | 1288 | set_notice(cx, &title); |
| 1396 | - // The owner's profile repository list shows the notice (the profile reads the cookie). | |
| 1397 | 1289 | return Err(see_other(format!("/{}?tab=repositories", enc(&ctx.repo.owner_name))).into()); |
| 1398 | 1290 | } |
| 1399 | 1291 | |
| 1400 | - // The delete form lives in the danger zone, so a failed confirmation draws that section again. | |
| 1401 | 1292 | let shown = Shown { |
| 1402 | 1293 | section: "danger", |
| 1403 | 1294 | notice: None, |
| @@ -1410,8 +1301,6 @@ async fn settings_delete(cx: &Cx, Form(form): Form<DeleteForm>) -> Result<impl V | ||
| 1410 | 1301 | render_settings(cx, ctx, user, session.csrf_token.clone(), lang, shown).await |
| 1411 | 1302 | } |
| 1412 | 1303 | |
| 1413 | -/// Adds a branch rule or updates the one with the same pattern. The form is checked for CSRF and | |
| 1414 | -/// `Action::Admin` first. An invalid pattern re-renders the page with the error next to the form. | |
| 1415 | 1304 | #[page(POST "/{owner}/{repo}/settings/branches")] |
| 1416 | 1305 | async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<impl View> { |
| 1417 | 1306 | let owner = owner(cx); |
| @@ -1423,7 +1312,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i | ||
| 1423 | 1312 | } |
| 1424 | 1313 | let lang = i18n::lang(cx, Some(&user)); |
| 1425 | 1314 | let pattern = form.pattern.trim().to_owned(); |
| 1426 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 1315 | + let title = ctx.title(); | |
| 1427 | 1316 | |
| 1428 | 1317 | let is_new = form.existing.is_none(); |
| 1429 | 1318 | let taken = is_new |
| @@ -1491,7 +1380,6 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i | ||
| 1491 | 1380 | Err(back_to_section(&title, "branches").into()) |
| 1492 | 1381 | } |
| 1493 | 1382 | |
| 1494 | -/// Removes a branch rule by id, scoped to this repo. Same checks as the save form. | |
| 1495 | 1383 | #[route(POST "/{owner}/{repo}/settings/branches/delete")] |
| 1496 | 1384 | async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) -> Result<SeeOther> { |
| 1497 | 1385 | let owner = owner(cx); |
| @@ -1520,7 +1408,7 @@ async fn settings_branch_delete(cx: &Cx, Form(form): Form<BranchDeleteForm>) -> | ||
| 1520 | 1408 | ) |
| 1521 | 1409 | .await; |
| 1522 | 1410 | set_settings_notice(cx, "removed"); |
| 1523 | - let title = format!("{}/{}", ctx.repo.owner_name, ctx.repo.name); | |
| 1411 | + let title = ctx.title(); | |
| 1524 | 1412 | Ok(back_to_section(&title, "branches")) |
| 1525 | 1413 | } |
| 1526 | 1414 | |
| @@ -1536,7 +1424,6 @@ mod tests { | ||
| 1536 | 1424 | |
| 1537 | 1425 | const CSRF: &str = "settings-test-csrf"; |
| 1538 | 1426 | |
| 1539 | - /// Posts the branch form as `tahinli` and returns the status and body. | |
| 1540 | 1427 | async fn post_rule(app: &Router, cookie: &str, fields: &[(&str, &str)]) -> (u16, String) { |
| 1541 | 1428 | let mut form = form_urlencoded::Serializer::new(String::new()); |
| 1542 | 1429 | form.append_pair("csrf", CSRF); |
| @@ -1600,7 +1487,6 @@ mod tests { | ||
| 1600 | 1487 | assert!(rule.restrict_push); |
| 1601 | 1488 | assert!(!rule.allow_force_push && !rule.allow_deletion); |
| 1602 | 1489 | |
| 1603 | - // A blank count means 0 and unchecked boxes are off. | |
| 1604 | 1490 | let (status, _) = post_rule( |
| 1605 | 1491 | &app, |
| 1606 | 1492 | &cookie, |
| @@ -1618,7 +1504,6 @@ mod tests { | ||
| 1618 | 1504 | !rule.block_on_changes_requested && !rule.require_up_to_date && !rule.restrict_push |
| 1619 | 1505 | ); |
| 1620 | 1506 | |
| 1621 | - // Out of range re-renders the form with the error and saves nothing. | |
| 1622 | 1507 | let (status, body) = post_rule( |
| 1623 | 1508 | &app, |
| 1624 | 1509 | &cookie, |
| @@ -1639,7 +1524,6 @@ mod tests { | ||
| 1639 | 1524 | assert_eq!(rule.required_approvals, 0); |
| 1640 | 1525 | assert!(!rule.restrict_push); |
| 1641 | 1526 | |
| 1642 | - // Not a number is refused the same way. | |
| 1643 | 1527 | let (status, body) = post_rule( |
| 1644 | 1528 | &app, |
| 1645 | 1529 | &cookie, |
crates/forge-web-pages/src/pages/tree.rsmodified+3 -6
| @@ -125,21 +125,18 @@ pub struct LatestBar { | ||
| 125 | 125 | pub author: String, |
| 126 | 126 | } |
| 127 | 127 | |
| 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. | |
| 130 | 129 | pub async fn latest_bar( |
| 131 | 130 | state: &AppState, |
| 132 | 131 | repo: &RepoRow, |
| 133 | 132 | path: &Path, |
| 134 | 133 | commit: &str, |
| 135 | - dir: &str, | |
| 136 | 134 | lang: Lang, |
| 137 | 135 | tz: &str, |
| 138 | 136 | ) -> Option<LatestBar> { |
| 139 | - let filter = (!dir.is_empty()).then_some(dir); | |
| 140 | 137 | let log = tokio::time::timeout( |
| 141 | 138 | LAST_COMMIT_TIMEOUT, |
| 142 | - history::log(&state.git, path, commit, filter, 0, 1), | |
| 139 | + history::log(&state.git, path, commit, None, 0, 1), | |
| 143 | 140 | ) |
| 144 | 141 | .await; |
| 145 | 142 | let info = match log { |
| @@ -476,7 +473,7 @@ async fn tree_page(cx: &Cx) -> Result<impl View> { | ||
| 476 | 473 | }; |
| 477 | 474 | let (last, bar, strip, runs) = tokio::join!( |
| 478 | 475 | last_commits(state, &ctx.path, &commit, &dir, &names), |
| 479 | - latest_bar(state, repo, &ctx.path, &commit, "", lang, ctx.viewer_tz()), | |
| 476 | + latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()), | |
| 480 | 477 | commit_strip(state, repo, &ctx.path, &commit), |
| 481 | 478 | run_rows(state, lang, repo), |
| 482 | 479 | ); |
crates/forge-web-pages/src/pages/wiki.rsmodified+7 -14
| @@ -364,16 +364,6 @@ async fn wiki_edit_body( | ||
| 364 | 364 | }) |
| 365 | 365 | } |
| 366 | 366 | |
| 367 | -/// Reads the page `name` and the wiki head in one blocking call. | |
| 368 | -async fn load_page(dir: PathBuf, name: String) -> Result<(Option<String>, Option<String>)> { | |
| 369 | - blocking(move || { | |
| 370 | - let head = wiki::head_commit(&dir)?; | |
| 371 | - let text = wiki::read_page(&dir, &name)?; | |
| 372 | - Ok((head, text)) | |
| 373 | - }) | |
| 374 | - .await | |
| 375 | -} | |
| 376 | - | |
| 377 | 367 | #[page("/{owner}/{repo}/wiki")] |
| 378 | 368 | async fn wiki_home(cx: &Cx) -> Result<impl View> { |
| 379 | 369 | let owner = owner(cx); |
| @@ -383,7 +373,7 @@ async fn wiki_home(cx: &Cx) -> Result<impl View> { | ||
| 383 | 373 | ensure_enabled(state, &ctx).await?; |
| 384 | 374 | let dir = wiki_dir(state, &ctx)?; |
| 385 | 375 | let names = page_names(dir.clone()).await?; |
| 386 | - let (_, home) = load_page(dir, "Home".to_owned()).await?; | |
| 376 | + let home = blocking(move || wiki::read_page(&dir, "Home")).await?; | |
| 387 | 377 | let can_write = ctx.can_write(); |
| 388 | 378 | let owner_name = ctx.repo.owner_name.clone(); |
| 389 | 379 | let repo_name = ctx.repo.name.clone(); |
| @@ -469,7 +459,8 @@ async fn wiki_page_view(cx: &Cx) -> Result<impl View> { | ||
| 469 | 459 | } |
| 470 | 460 | let dir = wiki_dir(state, &ctx)?; |
| 471 | 461 | let names = page_names(dir.clone()).await?; |
| 472 | - let (_, text) = load_page(dir, page_name.clone()).await?; | |
| 462 | + let name = page_name.clone(); | |
| 463 | + let text = blocking(move || wiki::read_page(&dir, &name)).await?; | |
| 473 | 464 | let Some(text) = text else { |
| 474 | 465 | return Err(not_found().into()); |
| 475 | 466 | }; |
| @@ -646,7 +637,8 @@ async fn wiki_edit_page(cx: &Cx) -> Result<impl View> { | ||
| 646 | 637 | return Err(not_found().into()); |
| 647 | 638 | } |
| 648 | 639 | let dir = wiki_dir(state, &ctx)?; |
| 649 | - let (_, text) = load_page(dir, page_name.clone()).await?; | |
| 640 | + let name = page_name.clone(); | |
| 641 | + let text = blocking(move || wiki::read_page(&dir, &name)).await?; | |
| 650 | 642 | edit_screen(cx, ctx, page_name, false, text.unwrap_or_default(), None).await |
| 651 | 643 | } |
| 652 | 644 | |
| @@ -667,7 +659,8 @@ async fn wiki_new_post(cx: &Cx, Form(form): Form<EditForm>) -> Result<impl View> | ||
| 667 | 659 | Some(g::t(lang, K::PageNameRules).to_owned()) |
| 668 | 660 | } else { |
| 669 | 661 | let dir = wiki_dir(state, &ctx)?; |
| 670 | - let (_, existing) = load_page(dir, name.clone()).await?; | |
| 662 | + let check = name.clone(); | |
| 663 | + let existing = blocking(move || wiki::read_page(&dir, &check)).await?; | |
| 671 | 664 | if existing.is_some() { |
| 672 | 665 | Some(g::t(lang, K::PageExists).to_owned()) |
| 673 | 666 | } else { |
crates/forge-web-repo/src/pages/authoring.rsmodified+7 -43
| @@ -29,7 +29,7 @@ use crate::api; | ||
| 29 | 29 | use crate::auth::{current_user, require_csrf}; |
| 30 | 30 | use crate::blobs::attachment_key; |
| 31 | 31 | use crate::pages::issue_parts::{ItemKind, comment_for, item_for, may_change, parse_number}; |
| 32 | -use crate::pages::repo_ctx::load_repo; | |
| 32 | +use crate::pages::repo_ctx::{access, load_repo}; | |
| 33 | 33 | use crate::render::markdown::{set_task, task_progress}; |
| 34 | 34 | use crate::state::AppState; |
| 35 | 35 | |
| @@ -86,33 +86,6 @@ pub fn clean_name(raw: &str) -> String { | ||
| 86 | 86 | out |
| 87 | 87 | } |
| 88 | 88 | |
| 89 | -/// Decodes `%XX` escapes and `+` in a query value; invalid escapes are kept as typed. | |
| 90 | -fn percent_decode(input: &str) -> String { | |
| 91 | - let bytes = input.as_bytes(); | |
| 92 | - let mut out = Vec::with_capacity(bytes.len()); | |
| 93 | - let mut i = 0; | |
| 94 | - while i < bytes.len() { | |
| 95 | - match bytes[i] { | |
| 96 | - b'+' => out.push(b' '), | |
| 97 | - b'%' if i + 2 < bytes.len() => { | |
| 98 | - let hex = std::str::from_utf8(&bytes[i + 1..i + 3]) | |
| 99 | - .ok() | |
| 100 | - .and_then(|h| u8::from_str_radix(h, 16).ok()); | |
| 101 | - match hex { | |
| 102 | - Some(b) => { | |
| 103 | - out.push(b); | |
| 104 | - i += 2; | |
| 105 | - } | |
| 106 | - None => out.push(b'%'), | |
| 107 | - } | |
| 108 | - } | |
| 109 | - b => out.push(b), | |
| 110 | - } | |
| 111 | - i += 1; | |
| 112 | - } | |
| 113 | - String::from_utf8_lossy(&out).into_owned() | |
| 114 | -} | |
| 115 | - | |
| 116 | 89 | fn fail(status: StatusCode, message: &str) -> Response { |
| 117 | 90 | api::error(status, message) |
| 118 | 91 | } |
| @@ -239,17 +212,8 @@ async fn download(cx: &Cx) -> Result<Response> { | ||
| 239 | 212 | return Err(not_found().into()); |
| 240 | 213 | }; |
| 241 | 214 | let viewer = current_user(cx).await?; |
| 242 | - let (role, org_role) = match &viewer { | |
| 243 | - Some((user, _)) => ( | |
| 244 | - state.store.collaborator_role(&repo.id, &user.id).await?, | |
| 245 | - state | |
| 246 | - .store | |
| 247 | - .org_repo_role(&repo.owner_id, &user.id, &repo.id) | |
| 248 | - .await?, | |
| 249 | - ), | |
| 250 | - None => (None, None), | |
| 251 | - }; | |
| 252 | 215 | let actor = viewer.as_ref().map(|(user, _)| user); |
| 216 | + let (role, org_role) = access(&state.store, actor, &repo).await?; | |
| 253 | 217 | if authorize(actor, &repo, role, org_role, Action::Read).is_err() { |
| 254 | 218 | return Err(not_found().into()); |
| 255 | 219 | } |
| @@ -296,11 +260,11 @@ async fn suggest(cx: &Cx) -> Result<Response> { | ||
| 296 | 260 | } |
| 297 | 261 | let mut kind = ""; |
| 298 | 262 | 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 | + _ => {} | |
| 304 | 268 | } |
| 305 | 269 | } |
| 306 | 270 | let q: String = q.chars().take(60).collect(); |
crates/forge-web-repo/src/pages/blame.rsmodified+4 -21
| @@ -16,7 +16,7 @@ use crate::i18n::browse as b; | ||
| 16 | 16 | use crate::i18n::code::{self as g, K}; |
| 17 | 17 | use crate::i18n::s; |
| 18 | 18 | use crate::i18n::{self, Lang}; |
| 19 | -use crate::pages::blob::{Line, text_lines}; | |
| 19 | +use crate::pages::blob::{Line, file_href, is_markdown, text_lines}; | |
| 20 | 20 | use crate::pages::ref_live; |
| 21 | 21 | use crate::pages::repo::repo_head; |
| 22 | 22 | use crate::pages::repo_ctx::load_repo; |
| @@ -191,31 +191,14 @@ async fn blame_page(cx: &Cx) -> Result<impl View> { | ||
| 191 | 191 | } |
| 192 | 192 | } |
| 193 | 193 | |
| 194 | - let blob_href = repo_href( | |
| 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); | |
| 200 | 195 | // 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) { | |
| 209 | 197 | format!("{blob_href}?plain=1") |
| 210 | 198 | } else { |
| 211 | 199 | blob_href.clone() |
| 212 | 200 | }; |
| 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); | |
| 219 | 202 | let title = format!( |
| 220 | 203 | "{}/{} \u{b7} {} \u{b7} {file}", |
| 221 | 204 | repo.owner_name, |
crates/forge-web-repo/src/pages/blob.rsmodified+49 -81
| @@ -45,21 +45,25 @@ struct BlobQuery { | ||
| 45 | 45 | } |
| 46 | 46 | |
| 47 | 47 | /// One line of a text file. `highlighted` is true when `code` is trusted highlighter output. |
| 48 | +#[derive(Clone)] | |
| 48 | 49 | pub struct Line { |
| 49 | 50 | pub num: String, |
| 50 | 51 | pub code: String, |
| 51 | 52 | pub highlighted: bool, |
| 52 | 53 | } |
| 53 | 54 | |
| 54 | -/// What the page shows for the file. `kind` is one of: image, submodule, symlink, binary, | |
| 55 | -/// 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 | + | |
| 56 | 65 | 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, | |
| 63 | 67 | truncated: bool, |
| 64 | 68 | } |
| 65 | 69 | |
| @@ -69,6 +73,14 @@ fn extension(name: &str) -> String { | ||
| 69 | 73 | .unwrap_or_default() |
| 70 | 74 | } |
| 71 | 75 | |
| 76 | +pub fn is_markdown(name: &str) -> bool { | |
| 77 | + MARKDOWN_EXTS.contains(&extension(name).as_str()) | |
| 78 | +} | |
| 79 | + | |
| 80 | +pub fn file_href(owner: &str, name: &str, verb: &str, ref_name: &str, file: &str) -> String { | |
| 81 | + repo_href(owner, name, verb, &format!("{ref_name}/{file}")) | |
| 82 | +} | |
| 83 | + | |
| 72 | 84 | pub fn text_lines(text: &str, file_name: &str) -> Vec<Line> { |
| 73 | 85 | let plain: Vec<&str> = text.lines().collect(); |
| 74 | 86 | let highlighted = highlight_lines(file_name, text).filter(|h| h.len() == plain.len()); |
| @@ -140,7 +152,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 140 | 152 | .unwrap_or("") |
| 141 | 153 | .to_owned(); |
| 142 | 154 | let ext = extension(&file_name); |
| 143 | - let is_markdown = MARKDOWN_EXTS.contains(&ext.as_str()); | |
| 155 | + let is_markdown = is_markdown(&file_name); | |
| 144 | 156 | |
| 145 | 157 | // A Git LFS pointer is a small text blob that names an object the forge stores. |
| 146 | 158 | let pointer = match blob.kind { |
| @@ -158,7 +170,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 158 | 170 | Ok(None) => (Some(g::lfs_missing(lang, &size)), None), |
| 159 | 171 | Err(e) => { |
| 160 | 172 | tracing::warn!(error = %e, "blob: LFS object link lookup failed"); |
| 161 | - (Some(g::lfs_stored(lang, &size)), None) | |
| 173 | + (None, None) | |
| 162 | 174 | } |
| 163 | 175 | } |
| 164 | 176 | } |
| @@ -167,38 +179,23 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 167 | 179 | |
| 168 | 180 | let viewer = match blob.kind { |
| 169 | 181 | 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()), | |
| 174 | 183 | truncated: false, |
| 175 | 184 | }, |
| 176 | 185 | 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()), | |
| 181 | 187 | truncated: false, |
| 182 | 188 | }, |
| 183 | 189 | _ 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()), | |
| 188 | 191 | truncated: false, |
| 189 | 192 | }, |
| 190 | 193 | _ 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, | |
| 195 | 195 | truncated: blob.truncated, |
| 196 | 196 | }, |
| 197 | 197 | _ 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)), | |
| 202 | 199 | truncated: false, |
| 203 | 200 | }, |
| 204 | 201 | _ => { |
| @@ -206,18 +203,12 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 206 | 203 | if is_markdown && !plain { |
| 207 | 204 | let link_ctx = link_context(state, repo, &ref_name, &dir); |
| 208 | 205 | 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))), | |
| 213 | 207 | truncated: blob.truncated, |
| 214 | 208 | } |
| 215 | 209 | } else { |
| 216 | 210 | 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)), | |
| 221 | 212 | truncated: blob.truncated, |
| 222 | 213 | } |
| 223 | 214 | } |
| @@ -225,38 +216,17 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 225 | 216 | }; |
| 226 | 217 | |
| 227 | 218 | 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); | |
| 246 | 222 | // 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); | |
| 253 | 224 | let finder_owner = repo.owner_name.clone(); |
| 254 | 225 | let finder_repo = repo.name.clone(); |
| 255 | 226 | let finder_ref = ref_name.clone(); |
| 256 | 227 | let title = format!("{}/{} \u{b7} {file}", repo.owner_name, repo.name); |
| 257 | 228 | |
| 258 | - let kind = viewer.kind; | |
| 259 | - let is_text = kind == "text"; | |
| 229 | + let is_text = matches!(viewer.kind, ViewerKind::Text(_)); | |
| 260 | 230 | // The ways to read the file, one switch with the current one marked, the same on every view of |
| 261 | 231 | // it: Rendered and Source for markdown, Source alone otherwise, and Blame for any text. |
| 262 | 232 | let mut views: Vec<(&'static str, String, bool)> = Vec::new(); |
| @@ -274,9 +244,6 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 274 | 244 | if can_blame { |
| 275 | 245 | views.push((b::t(lang, b::K::BlameLink), blame.clone(), false)); |
| 276 | 246 | } |
| 277 | - let note = viewer.note; | |
| 278 | - let html = viewer.html; | |
| 279 | - let lines = viewer.lines; | |
| 280 | 247 | let truncated = viewer.truncated; |
| 281 | 248 | let image_alt = file_name.clone(); |
| 282 | 249 | let download_name = file_name.clone(); |
| @@ -301,7 +268,7 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 301 | 268 | }; |
| 302 | 269 | let (last, bar, strip, runs) = tokio::join!( |
| 303 | 270 | last_commits(state, &ctx.path, &commit, &dir, &names), |
| 304 | - latest_bar(state, repo, &ctx.path, &commit, "", lang, ctx.viewer_tz()), | |
| 271 | + latest_bar(state, repo, &ctx.path, &commit, lang, ctx.viewer_tz()), | |
| 305 | 272 | commit_strip(state, repo, &ctx.path, &commit), |
| 306 | 273 | run_rows(state, lang, repo), |
| 307 | 274 | ); |
| @@ -325,10 +292,11 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 325 | 292 | let mut header = ctx.head(state, "code").await?; |
| 326 | 293 | header.live = live_url(&repo.owner_name, &repo.name, &refs, &ref_name); |
| 327 | 294 | 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, | |
| 332 | 300 | }; |
| 333 | 301 | Ok(view! { |
| 334 | 302 | shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), |
| @@ -363,27 +331,27 @@ async fn blob_page(cx: &Cx) -> Result<impl View> { | ||
| 363 | 331 | } |
| 364 | 332 | </div> |
| 365 | 333 | <section class="file" data-lines="" data-permalink=(permalink.as_str())> |
| 366 | - if kind == "image" { | |
| 334 | + if let ViewerKind::Image = &viewer.kind { | |
| 367 | 335 | <div class="file-image"> |
| 368 | 336 | <img src=(raw.clone()) alt=(image_alt)> |
| 369 | 337 | </div> |
| 370 | 338 | } |
| 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> | |
| 373 | 341 | } |
| 374 | - if kind == "text" { | |
| 375 | - file_table(lines: lines) | |
| 342 | + if let ViewerKind::Text(lines) = &viewer.kind { | |
| 343 | + file_table(lines: lines.clone()) | |
| 376 | 344 | } |
| 377 | - if kind == "lfs" { | |
| 345 | + if let ViewerKind::Lfs(note) = &viewer.kind { | |
| 378 | 346 | <p class="state">(note.clone())</p> |
| 379 | 347 | } |
| 380 | - if kind == "binary" { | |
| 348 | + if let ViewerKind::Binary(note) = &viewer.kind { | |
| 381 | 349 | <p class="state">(note.clone())</p> |
| 382 | 350 | } |
| 383 | - if kind == "symlink" { | |
| 351 | + if let ViewerKind::Symlink(note) = &viewer.kind { | |
| 384 | 352 | <p class="state">(g::t(lang, K::SymlinkPrefix)) <code>(note.clone())</code></p> |
| 385 | 353 | } |
| 386 | - if kind == "submodule" { | |
| 354 | + if let ViewerKind::Submodule(note) = &viewer.kind { | |
| 387 | 355 | <p class="state">(g::t(lang, K::SubmodulePrefix)) <code>(note.clone())</code> (g::t(lang, K::SubmoduleSuffix))</p> |
| 388 | 356 | } |
| 389 | 357 | if truncated { |
crates/forge-web-repo/src/pages/browse_tests.rsmodified+20 -43
| @@ -1,6 +1,3 @@ | ||
| 1 | -//! Page tests for the code-browsing upgrades: diff toolbar, whitespace and split views, patch and | |
| 2 | -//! diff downloads, the file list endpoint, the branches page and the default-branch setting. | |
| 3 | - | |
| 4 | 1 | use forge_core::Visibility; |
| 5 | 2 | use forge_core::protection::RuleFlags; |
| 6 | 3 | use topcoat::router::request::Request; |
| @@ -49,7 +46,6 @@ async fn send( | ||
| 49 | 46 | ) |
| 50 | 47 | } |
| 51 | 48 | |
| 52 | -/// A commit whose changes are a whitespace-only edit of `a.txt` and a real edit of `ws.txt`. | |
| 53 | 49 | fn whitespace_commit(fx: &Fixture) -> String { |
| 54 | 50 | std::fs::write(fx.work.join("ws.txt"), "x\ny\n").unwrap(); |
| 55 | 51 | git(&fx.work, &["add", "-A"]); |
| @@ -71,7 +67,6 @@ fn whitespace_commit(fx: &Fixture) -> String { | ||
| 71 | 67 | oid |
| 72 | 68 | } |
| 73 | 69 | |
| 74 | -/// The commit toolbar, and the whitespace toggle that hides whitespace-only files. | |
| 75 | 70 | async fn scenario_whitespace_toolbar(fx: &Fixture) { |
| 76 | 71 | let oid = whitespace_commit(fx); |
| 77 | 72 | let base = format!("/{OWNER}/{REPO}/commit/{oid}"); |
| @@ -84,7 +79,6 @@ async fn scenario_whitespace_toolbar(fx: &Fixture) { | ||
| 84 | 79 | assert!(html.contains(&format!("{base}.diff"))); |
| 85 | 80 | assert!(html.contains("a.txt")); |
| 86 | 81 | assert!(html.contains("ws.txt")); |
| 87 | - // The toggle links to the same page with w=1. | |
| 88 | 82 | assert!(html.contains("w=1")); |
| 89 | 83 | |
| 90 | 84 | let (_, _, body) = get(&fx.router, &format!("{base}?w=1")).await; |
| @@ -98,7 +92,6 @@ async fn scenario_whitespace_toolbar(fx: &Fixture) { | ||
| 98 | 92 | assert!(main.contains("aria-pressed=\"true\"")); |
| 99 | 93 | } |
| 100 | 94 | |
| 101 | -/// The split view renders two sides and is remembered in a cookie. | |
| 102 | 95 | async fn scenario_split_view(fx: &Fixture) { |
| 103 | 96 | let uri = format!("/{OWNER}/{REPO}/commit/{}?view=split", fx.modified); |
| 104 | 97 | |
| @@ -107,7 +100,6 @@ async fn scenario_split_view(fx: &Fixture) { | ||
| 107 | 100 | let html = String::from_utf8(body).unwrap(); |
| 108 | 101 | assert!(html.contains("diff-split")); |
| 109 | 102 | assert!(html.contains("diff-split-row")); |
| 110 | - // The deleted "two" and the added "TWO" sit in one row. | |
| 111 | 103 | let row = html |
| 112 | 104 | .split("diff-split-row") |
| 113 | 105 | .find(|r| r.contains("-two") && r.contains("+TWO")) |
| @@ -121,7 +113,6 @@ async fn scenario_split_view(fx: &Fixture) { | ||
| 121 | 113 | .expect("view cookie"); |
| 122 | 114 | assert!(cookie.starts_with("forge_diff=split")); |
| 123 | 115 | |
| 124 | - // With the cookie and no query, the page is split; ?view=unified switches back. | |
| 125 | 116 | let plain = format!("/{OWNER}/{REPO}/commit/{}", fx.modified); |
| 126 | 117 | let req = Request::builder() |
| 127 | 118 | .method("GET") |
| @@ -136,7 +127,6 @@ async fn scenario_split_view(fx: &Fixture) { | ||
| 136 | 127 | assert!(!String::from_utf8(body).unwrap().contains("diff-split-row")); |
| 137 | 128 | } |
| 138 | 129 | |
| 139 | -/// Patch and diff downloads for a commit and a root commit, and 404s for bad or private ones. | |
| 140 | 130 | async fn scenario_patch_and_diff(fx: &Fixture) { |
| 141 | 131 | let base = format!("/{OWNER}/{REPO}/commit/{}", fx.modified); |
| 142 | 132 | |
| @@ -159,7 +149,6 @@ async fn scenario_patch_and_diff(fx: &Fixture) { | ||
| 159 | 149 | assert!(text.starts_with("diff --git a/a.txt b/a.txt")); |
| 160 | 150 | assert!(!text.contains("Subject:")); |
| 161 | 151 | |
| 162 | - // Root commits work. | |
| 163 | 152 | let (status, _, _) = get( |
| 164 | 153 | &fx.router, |
| 165 | 154 | &format!("/{OWNER}/{REPO}/commit/{}.patch", fx.root), |
| @@ -170,7 +159,6 @@ async fn scenario_patch_and_diff(fx: &Fixture) { | ||
| 170 | 159 | assert_eq!(status, 404); |
| 171 | 160 | } |
| 172 | 161 | |
| 173 | -/// Compare lists the commits on the head side, as a patch and as a diff. | |
| 174 | 162 | async fn scenario_compare(fx: &Fixture) { |
| 175 | 163 | git(&fx.work, &["checkout", "-q", "-b", "topic", &fx.root]); |
| 176 | 164 | std::fs::write(fx.work.join("topic.txt"), "topic\n").unwrap(); |
| @@ -204,14 +192,12 @@ async fn scenario_compare(fx: &Fixture) { | ||
| 204 | 192 | assert!(text.contains("+++ b/topic.txt")); |
| 205 | 193 | } |
| 206 | 194 | |
| 207 | -/// The blob page offers blame, a commit-pinned permalink and the finder. | |
| 208 | 195 | async fn scenario_blob_page(fx: &Fixture) { |
| 209 | 196 | let (status, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/blob/main/a.txt")).await; |
| 210 | 197 | assert_eq!(status, 200); |
| 211 | 198 | let html = String::from_utf8(body).unwrap(); |
| 212 | 199 | assert!(html.contains(&format!("/{OWNER}/{REPO}/blame/main/a.txt"))); |
| 213 | 200 | assert!(html.contains("data-copy-permalink")); |
| 214 | - // The permalink is pinned to a full commit oid, not the branch. | |
| 215 | 201 | let permalink = html |
| 216 | 202 | .split("data-permalink=\"") |
| 217 | 203 | .nth(1) |
| @@ -226,12 +212,10 @@ async fn scenario_blob_page(fx: &Fixture) { | ||
| 226 | 212 | assert!(html.contains("data-finder")); |
| 227 | 213 | assert!(html.contains(&format!("/{OWNER}/{REPO}/paths/main"))); |
| 228 | 214 | |
| 229 | - // The tree page has the finder too. | |
| 230 | 215 | let (_, _, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/tree/main")).await; |
| 231 | 216 | assert!(String::from_utf8(body).unwrap().contains("data-finder")); |
| 232 | 217 | } |
| 233 | 218 | |
| 234 | -/// The paths endpoint lists every file on the ref, and refuses unknown refs and subpaths. | |
| 235 | 219 | async fn scenario_paths(fx: &Fixture) { |
| 236 | 220 | let (status, headers, body) = get(&fx.router, &format!("/{OWNER}/{REPO}/paths/main")).await; |
| 237 | 221 | assert_eq!(status, 200); |
| @@ -258,7 +242,6 @@ async fn scenario_paths(fx: &Fixture) { | ||
| 258 | 242 | assert_eq!(status, 404); |
| 259 | 243 | } |
| 260 | 244 | |
| 261 | -/// The branches page shows counts, creates and deletes branches, and refuses bad input. | |
| 262 | 245 | async fn scenario_branches(fx: &Fixture, cookie: &str) { |
| 263 | 246 | git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]); |
| 264 | 247 | std::fs::write(fx.work.join("f.txt"), "f\n").unwrap(); |
| @@ -277,18 +260,15 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) { | ||
| 277 | 260 | |
| 278 | 261 | let (status, _, html) = send(&fx.router, "GET", &page, Some(cookie), &[]).await; |
| 279 | 262 | assert_eq!(status, 200); |
| 280 | - // feature is 1 ahead of and 54 behind main (the root is its base, main has 54 more commits). | |
| 281 | 263 | assert!(html.contains("1 ahead, 54 behind"), "{html}"); |
| 282 | 264 | assert!(html.contains(&format!("/{OWNER}/{REPO}/compare/main...feature"))); |
| 283 | 265 | assert!(html.contains("tahinli")); |
| 284 | 266 | let delete_form = format!("action=\"/{OWNER}/{REPO}/branches/delete\""); |
| 285 | 267 | assert!(html.contains(&delete_form), "{html}"); |
| 286 | - // Anonymous viewers get no create or delete controls. | |
| 287 | 268 | let (_, _, anon) = send(&fx.router, "GET", &page, None, &[]).await; |
| 288 | 269 | assert!(!anon.contains(&delete_form)); |
| 289 | 270 | assert!(!anon.contains("new-branch")); |
| 290 | 271 | |
| 291 | - // Create from a ref. | |
| 292 | 272 | let (status, headers, _) = send( |
| 293 | 273 | &fx.router, |
| 294 | 274 | "POST", |
| @@ -305,11 +285,25 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) { | ||
| 305 | 285 | feature_tip |
| 306 | 286 | ); |
| 307 | 287 | |
| 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 | + ), | |
| 313 | 307 | ] { |
| 314 | 308 | let (status, _, _) = send( |
| 315 | 309 | &fx.router, |
| @@ -328,13 +322,9 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) { | ||
| 328 | 322 | &[], |
| 329 | 323 | ) |
| 330 | 324 | .await; |
| 331 | - assert!( | |
| 332 | - html.contains("role=\"alert\"") || html.contains("alert"), | |
| 333 | - "{word}" | |
| 334 | - ); | |
| 325 | + assert!(html.contains(message), "{word}"); | |
| 335 | 326 | } |
| 336 | 327 | |
| 337 | - // A bad CSRF token is refused. | |
| 338 | 328 | let (status, _, _) = send( |
| 339 | 329 | &fx.router, |
| 340 | 330 | "POST", |
| @@ -345,7 +335,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) { | ||
| 345 | 335 | .await; |
| 346 | 336 | assert_eq!(status, 403); |
| 347 | 337 | |
| 348 | - // Delete: a moved branch is left alone, the right oid deletes it. | |
| 349 | 338 | let delete = format!("{page}/delete"); |
| 350 | 339 | let (status, _, _) = send( |
| 351 | 340 | &fx.router, |
| @@ -369,7 +358,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) { | ||
| 369 | 358 | let listing = git(&fx.bare, &["branch", "--list", "topic/one"]); |
| 370 | 359 | assert!(listing.is_empty(), "branch should be gone: {listing}"); |
| 371 | 360 | |
| 372 | - // The default branch can never be deleted. | |
| 373 | 361 | let main_tip = git(&fx.bare, &["rev-parse", "refs/heads/main"]); |
| 374 | 362 | send( |
| 375 | 363 | &fx.router, |
| @@ -382,7 +370,6 @@ async fn scenario_branches(fx: &Fixture, cookie: &str) { | ||
| 382 | 370 | git(&fx.bare, &["rev-parse", "--verify", "refs/heads/main"]); |
| 383 | 371 | } |
| 384 | 372 | |
| 385 | -/// A branch rule blocks deleting the branches it matches. | |
| 386 | 373 | async fn scenario_protection(fx: &Fixture, cookie: &str) { |
| 387 | 374 | git(&fx.bare, &["branch", "release/1", "main"]); |
| 388 | 375 | git(&fx.bare, &["branch", "scratch", "main"]); |
| @@ -420,7 +407,6 @@ async fn scenario_protection(fx: &Fixture, cookie: &str) { | ||
| 420 | 407 | assert!(git(&fx.bare, &["branch", "--list", "scratch"]).is_empty()); |
| 421 | 408 | } |
| 422 | 409 | |
| 423 | -/// Changing the default branch moves HEAD and the record; a missing branch changes nothing. | |
| 424 | 410 | async fn scenario_default_branch(fx: &Fixture, cookie: &str) { |
| 425 | 411 | git(&fx.bare, &["branch", "trunk", "main"]); |
| 426 | 412 | let settings = format!("/{OWNER}/{REPO}/settings/general"); |
| @@ -448,7 +434,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) { | ||
| 448 | 434 | assert_eq!(repo.default_branch, "trunk"); |
| 449 | 435 | assert_eq!(repo.description, "demo"); |
| 450 | 436 | |
| 451 | - // A branch that does not exist changes nothing. | |
| 452 | 437 | send( |
| 453 | 438 | &fx.router, |
| 454 | 439 | "POST", |
| @@ -470,7 +455,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) { | ||
| 470 | 455 | .unwrap(); |
| 471 | 456 | assert_eq!(repo.default_branch, "trunk"); |
| 472 | 457 | |
| 473 | - // The settings page offers the branches and marks the current one. | |
| 474 | 458 | let (_, _, html) = send( |
| 475 | 459 | &fx.router, |
| 476 | 460 | "GET", |
| @@ -482,8 +466,6 @@ async fn scenario_default_branch(fx: &Fixture, cookie: &str) { | ||
| 482 | 466 | assert!(html.contains("name=\"default_branch\"")); |
| 483 | 467 | } |
| 484 | 468 | |
| 485 | -/// Paths, patch and diff, split view and blob page, on one public repo. These pin the file set | |
| 486 | -/// and the commit count, so they run before any commit is added. | |
| 487 | 469 | #[tokio::test] |
| 488 | 470 | async fn public_repo_pages_and_downloads() { |
| 489 | 471 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -493,8 +475,6 @@ async fn public_repo_pages_and_downloads() { | ||
| 493 | 475 | scenario_blob_page(&fx).await; |
| 494 | 476 | } |
| 495 | 477 | |
| 496 | -/// The commit toolbar, then compare. The whitespace scenario adds commits to main, and compare | |
| 497 | -/// moves the working checkout to a topic branch, so compare runs last. | |
| 498 | 478 | #[tokio::test] |
| 499 | 479 | async fn public_repo_commit_views_and_compare() { |
| 500 | 480 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -502,8 +482,6 @@ async fn public_repo_commit_views_and_compare() { | ||
| 502 | 482 | scenario_compare(&fx).await; |
| 503 | 483 | } |
| 504 | 484 | |
| 505 | -/// Branches, branch rules and the default branch on one fixture. The branch counts assume main | |
| 506 | -/// has not moved, and the default-branch change runs last. | |
| 507 | 485 | #[tokio::test] |
| 508 | 486 | async fn public_repo_branches_rules_and_default_branch() { |
| 509 | 487 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -513,7 +491,6 @@ async fn public_repo_branches_rules_and_default_branch() { | ||
| 513 | 491 | scenario_default_branch(&fx, &cookie).await; |
| 514 | 492 | } |
| 515 | 493 | |
| 516 | -/// A private repo hides its patch download and its file list from anonymous viewers. | |
| 517 | 494 | #[tokio::test] |
| 518 | 495 | async fn private_repo_hides_downloads_and_paths() { |
| 519 | 496 | let private = Fixture::new(Visibility::Private).await; |
crates/forge-web-repo/src/pages/ci_badge.rsmodified+5 -5
| @@ -37,7 +37,7 @@ const GREY: &str = "#9f9f9f"; | ||
| 37 | 37 | |
| 38 | 38 | /// What the right-hand half of the badge says. |
| 39 | 39 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 40 | -pub enum BadgeStatus { | |
| 40 | +enum BadgeStatus { | |
| 41 | 41 | Passing, |
| 42 | 42 | Failing, |
| 43 | 43 | Error, |
| @@ -76,7 +76,7 @@ impl BadgeStatus { | ||
| 76 | 76 | } |
| 77 | 77 | |
| 78 | 78 | /// The badge status of a run. Waiting for approval shows as pending. |
| 79 | -pub fn status_of_run(state: RunState) -> BadgeStatus { | |
| 79 | +fn status_of_run(state: RunState) -> BadgeStatus { | |
| 80 | 80 | match state { |
| 81 | 81 | RunState::Success => BadgeStatus::Passing, |
| 82 | 82 | RunState::Failure => BadgeStatus::Failing, |
| @@ -88,7 +88,7 @@ pub fn status_of_run(state: RunState) -> BadgeStatus { | ||
| 88 | 88 | } |
| 89 | 89 | |
| 90 | 90 | /// The badge status of one job. |
| 91 | -pub fn status_of_job(state: JobState) -> BadgeStatus { | |
| 91 | +fn status_of_job(state: JobState) -> BadgeStatus { | |
| 92 | 92 | match state { |
| 93 | 93 | JobState::Success => BadgeStatus::Passing, |
| 94 | 94 | JobState::Failure => BadgeStatus::Failing, |
| @@ -101,7 +101,7 @@ pub fn status_of_job(state: JobState) -> BadgeStatus { | ||
| 101 | 101 | |
| 102 | 102 | /// Escapes text for XML element content and attribute values. Control characters, which XML |
| 103 | 103 | /// does not allow, become spaces. |
| 104 | -pub fn escape_xml(text: &str) -> String { | |
| 104 | +fn escape_xml(text: &str) -> String { | |
| 105 | 105 | let mut out = String::with_capacity(text.len()); |
| 106 | 106 | for c in text.chars() { |
| 107 | 107 | match c { |
| @@ -124,7 +124,7 @@ fn text_box(text: &str) -> u32 { | ||
| 124 | 124 | } |
| 125 | 125 | |
| 126 | 126 | /// Renders the flat badge: a grey label half and a coloured status half. |
| 127 | -pub fn render_badge(label: &str, status: BadgeStatus) -> String { | |
| 127 | +fn render_badge(label: &str, status: BadgeStatus) -> String { | |
| 128 | 128 | let label: String = label.chars().take(MAX_LABEL_CHARS).collect(); |
| 129 | 129 | let status_text = status.text(); |
| 130 | 130 | let label_w = text_box(&label); |
crates/forge-web-repo/src/pages/ci_tests.rsmodified+9 -78
| @@ -1,6 +1,3 @@ | ||
| 1 | -//! Route tests for the CI run and job pages. The fixture: tahinli owns the private repo `proj`, bob | |
| 2 | -//! has Write, dave has Read, and carol is outside the repo. | |
| 3 | - | |
| 4 | 1 | use std::io::Write; |
| 5 | 2 | use std::path::{Path, PathBuf}; |
| 6 | 3 | use std::sync::Arc; |
| @@ -18,7 +15,6 @@ use crate::ci::{CiLive, artifact_key, log_path}; | ||
| 18 | 15 | use crate::test_support::{app_router, create_session, test_state}; |
| 19 | 16 | |
| 20 | 17 | const CSRF: &str = "ci-test-csrf"; |
| 21 | -/// A hash no ref reaches, standing in for a commit that was overwritten. | |
| 22 | 18 | const SHA: &str = "0123456789abcdef0123456789abcdef01234567"; |
| 23 | 19 | const SPEC: &str = r#"{"runs_on":[]}"#; |
| 24 | 20 | const RUN_BASE: &str = "/tahinli/proj/ci"; |
| @@ -29,7 +25,6 @@ struct Fixture { | ||
| 29 | 25 | live: Arc<CiLive>, |
| 30 | 26 | repo: forge_core::Repo, |
| 31 | 27 | tahinli: String, |
| 32 | - /// The commit `main` points at in `proj`. | |
| 33 | 28 | head: String, |
| 34 | 29 | data_dir: PathBuf, |
| 35 | 30 | blobs: BlobStore, |
| @@ -90,7 +85,6 @@ async fn fixture(dir: &Path) -> Fixture { | ||
| 90 | 85 | } |
| 91 | 86 | } |
| 92 | 87 | |
| 93 | -/// Puts one empty commit on `main` and returns its hash. | |
| 94 | 88 | fn commit_main(bare: &Path) -> String { |
| 95 | 89 | let git = |args: &[&str]| { |
| 96 | 90 | let out = std::process::Command::new("git") |
| @@ -113,7 +107,6 @@ fn cookie_for(token: &str) -> String { | ||
| 113 | 107 | format!("__Host-{SESSION_COOKIE}={token}") |
| 114 | 108 | } |
| 115 | 109 | |
| 116 | -/// A response: status, headers and the whole body. | |
| 117 | 110 | struct Reply { |
| 118 | 111 | status: u16, |
| 119 | 112 | headers: HeaderMap, |
| @@ -150,7 +143,6 @@ async fn get(app: &Router, uri: &str, cookie: Option<&str>) -> Reply { | ||
| 150 | 143 | collect(app.handle(req).await).await |
| 151 | 144 | } |
| 152 | 145 | |
| 153 | -/// A POST with the CSRF token and the given form fields. | |
| 154 | 146 | async fn post(app: &Router, uri: &str, cookie: &str, fields: &[(&str, &str)]) -> Reply { |
| 155 | 147 | let mut form = form_urlencoded::Serializer::new(String::new()); |
| 156 | 148 | form.append_pair("csrf", CSRF); |
| @@ -178,7 +170,6 @@ async fn collect(res: topcoat::router::response::Response) -> Reply { | ||
| 178 | 170 | } |
| 179 | 171 | } |
| 180 | 172 | |
| 181 | -/// Creates a run on `main` with one job per name. Jobs wait for approval when `needs_approval`. | |
| 182 | 173 | async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun { |
| 183 | 174 | let needs: &[String] = &[]; |
| 184 | 175 | let specs: Vec<NewJob<'_>> = jobs |
| @@ -207,7 +198,6 @@ async fn run_with(fx: &Fixture, jobs: &[&str], needs_approval: bool) -> CiRun { | ||
| 207 | 198 | .expect("run") |
| 208 | 199 | } |
| 209 | 200 | |
| 210 | -/// Claims the one queued job with a fresh runner and finishes it as a success. | |
| 211 | 201 | async fn finish_job(fx: &Fixture) -> CiJob { |
| 212 | 202 | let token = fx |
| 213 | 203 | .store |
| @@ -232,6 +222,10 @@ async fn finish_job(fx: &Fixture) -> CiJob { | ||
| 232 | 222 | job |
| 233 | 223 | } |
| 234 | 224 | |
| 225 | +async fn run_now(fx: &Fixture, id: &str) -> CiRun { | |
| 226 | + fx.store.run_by_id(id).await.expect("run").expect("run") | |
| 227 | +} | |
| 228 | + | |
| 235 | 229 | async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob { |
| 236 | 230 | fx.store |
| 237 | 231 | .jobs_for_run(&run.id) |
| @@ -242,7 +236,6 @@ async fn job_of(fx: &Fixture, run: &CiRun) -> CiJob { | ||
| 242 | 236 | .expect("a job") |
| 243 | 237 | } |
| 244 | 238 | |
| 245 | -/// Access follows the repo's role on every route: anonymous and outsider requests are 404, readers see the pages and streams, and only writers see or use the controls. Each scenario makes its own run. | |
| 246 | 239 | #[tokio::test] |
| 247 | 240 | async fn access_follows_the_repo_role_on_every_route() { |
| 248 | 241 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -298,12 +291,7 @@ async fn access_follows_the_repo_role_on_every_route() { | ||
| 298 | 291 | ) |
| 299 | 292 | .await; |
| 300 | 293 | 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; | |
| 307 | 295 | assert_eq!(still.state, RunState::Queued); |
| 308 | 296 | } |
| 309 | 297 | |
| @@ -326,7 +314,6 @@ async fn access_follows_the_repo_role_on_every_route() { | ||
| 326 | 314 | } |
| 327 | 315 | } |
| 328 | 316 | |
| 329 | -/// The run list pages 25 at a time and is live on page 1 only. Thirty runs make two pages; page 2 is a fixed slice, so it carries no live marker. | |
| 330 | 317 | #[tokio::test] |
| 331 | 318 | async fn run_list_pages_and_its_live_marker() { |
| 332 | 319 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -337,7 +324,6 @@ async fn run_list_pages_and_its_live_marker() { | ||
| 337 | 324 | } |
| 338 | 325 | let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; |
| 339 | 326 | let text = first.text(); |
| 340 | - // The topbar's live strip links the viewer's own running runs too; only the list counts. | |
| 341 | 327 | let list = text |
| 342 | 328 | .split_once("</header>") |
| 343 | 329 | .map_or(text.as_str(), |(_, rest)| rest); |
| @@ -395,7 +381,6 @@ async fn run_list_pages_and_its_live_marker() { | ||
| 395 | 381 | } |
| 396 | 382 | } |
| 397 | 383 | |
| 398 | -/// Opens an event stream without reading it. The response head carries the status. | |
| 399 | 384 | async fn open( |
| 400 | 385 | app: &Router, |
| 401 | 386 | uri: &str, |
| @@ -409,7 +394,6 @@ async fn open( | ||
| 409 | 394 | .await |
| 410 | 395 | } |
| 411 | 396 | |
| 412 | -/// The next frame of an event stream, or None once the stream has ended. Fails after five seconds. | |
| 413 | 397 | async fn next_frame<S, E>(frames: &mut S) -> Option<Vec<u8>> |
| 414 | 398 | where |
| 415 | 399 | S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Unpin, |
| @@ -430,7 +414,6 @@ where | ||
| 430 | 414 | { |
| 431 | 415 | use futures_util::StreamExt; |
| 432 | 416 | |
| 433 | - // Every stream opens with its `retry` field (one frame): skip it, the tests want the events. | |
| 434 | 417 | loop { |
| 435 | 418 | let frame = tokio::time::timeout(Duration::from_secs(5), frames.next()) |
| 436 | 419 | .await |
| @@ -442,7 +425,6 @@ where | ||
| 442 | 425 | } |
| 443 | 426 | } |
| 444 | 427 | |
| 445 | -/// The pages no longer reload themselves, and a job's live streams end with the job. Each scenario finishes its own job first, since `finish_job` claims the oldest queued job. | |
| 446 | 428 | #[tokio::test] |
| 447 | 429 | async fn live_pages_and_streams_follow_a_job_to_its_end() { |
| 448 | 430 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -455,7 +437,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | ||
| 455 | 437 | let url = format!("/tahinli/proj/ci/jobs/{}", job.id); |
| 456 | 438 | let run_url = format!("{RUN_BASE}/runs/{}", run.number); |
| 457 | 439 | let job_marker = format!("data-live=\"{url}/events\""); |
| 458 | - // The split view is live on page 1 through the repo stream, whatever the run's state. | |
| 459 | 440 | let run_marker = format!("data-live=\"{RUN_BASE}/events\""); |
| 460 | 441 | |
| 461 | 442 | let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; |
| @@ -474,7 +455,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | ||
| 474 | 455 | |
| 475 | 456 | finish_job(&fx).await; |
| 476 | 457 | let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; |
| 477 | - // A finished job stays live: a retention purge can still take its artifacts and log. | |
| 478 | 458 | assert!( |
| 479 | 459 | done.text().contains(&job_marker), |
| 480 | 460 | "job still live when finished" |
| @@ -518,26 +498,18 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | ||
| 518 | 498 | format!("event: changed\ndata: {}||nolog\n\n", job.state.as_str()).into_bytes() |
| 519 | 499 | ); |
| 520 | 500 | |
| 521 | - // A bump with no new log bytes and no status change sends nothing. | |
| 522 | 501 | fx.live.bump_job(&job.id); |
| 523 | 502 | let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await; |
| 524 | 503 | assert!(quiet.is_err(), "a log append sends no status event"); |
| 525 | 504 | |
| 526 | - // The run stream sends its status on every bump of the run. | |
| 527 | 505 | fx.live.bump_run(&run.id); |
| 528 | 506 | 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; | |
| 535 | 508 | assert_eq!( |
| 536 | 509 | bumped, |
| 537 | 510 | format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes() |
| 538 | 511 | ); |
| 539 | 512 | |
| 540 | - // The job finishes: its final status is sent, then the stream ends. | |
| 541 | 513 | finish_job(&fx).await; |
| 542 | 514 | fx.live.close_job(&job.id); |
| 543 | 515 | let last = next_event(&mut job_frames).await.expect("the final status"); |
| @@ -553,7 +525,6 @@ async fn live_pages_and_streams_follow_a_job_to_its_end() { | ||
| 553 | 525 | } |
| 554 | 526 | } |
| 555 | 527 | |
| 556 | -/// The href of the list row marked as current, from the markup of the runs page. | |
| 557 | 528 | fn current_href(html: &str) -> Option<&str> { |
| 558 | 529 | let mark = html.find("aria-current=\"true\"")?; |
| 559 | 530 | let start = html[..mark].rfind("<a ")?; |
| @@ -562,8 +533,6 @@ fn current_href(html: &str) -> Option<&str> { | ||
| 562 | 533 | link[at..].split('"').next() |
| 563 | 534 | } |
| 564 | 535 | |
| 565 | -/// `/ci` is the run list alone, each row opening its run; `/ci/runs/n` draws run n. A run that is not | |
| 566 | -/// on the list page is still drawn, and no row of the list is marked for it. | |
| 567 | 536 | #[tokio::test] |
| 568 | 537 | async fn split_view_draws_the_newest_run_or_the_one_named() { |
| 569 | 538 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -585,8 +554,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() { | ||
| 585 | 554 | .await |
| 586 | 555 | .text(); |
| 587 | 556 | assert!(named.contains(&format!("data-run=\"{}\"", first.number))); |
| 588 | - // The run page is the run alone: the All runs link goes back to the list, and a one-job run has | |
| 589 | - // no job list to mark. | |
| 590 | 557 | assert!( |
| 591 | 558 | named.contains(&format!("href=\"{RUN_BASE}\"")), |
| 592 | 559 | "All runs link" |
| @@ -594,7 +561,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() { | ||
| 594 | 561 | assert!(!named.contains("ci-run-list")); |
| 595 | 562 | assert_eq!(named.matches("aria-current=\"true\"").count(), 0); |
| 596 | 563 | |
| 597 | - // Thirty runs make two pages. Run 1 is on page 2, so page 1 marks no row and draws run 1. | |
| 598 | 564 | for _ in 0..28 { |
| 599 | 565 | run_with(&fx, &["build"], false).await; |
| 600 | 566 | } |
| @@ -606,7 +572,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() { | ||
| 606 | 572 | .await |
| 607 | 573 | .text(); |
| 608 | 574 | assert!(off_page.contains(&format!("data-run=\"{}\"", first.number))); |
| 609 | - // A run off the list's first page opens all the same. | |
| 610 | 575 | assert!(off_page.contains(&format!("data-live=\"{RUN_BASE}/events\""))); |
| 611 | 576 | let rows = get(&fx.app, &format!("{RUN_BASE}?page=2"), tahinli.as_deref()) |
| 612 | 577 | .await |
| @@ -617,7 +582,6 @@ async fn split_view_draws_the_newest_run_or_the_one_named() { | ||
| 617 | 582 | ); |
| 618 | 583 | } |
| 619 | 584 | |
| 620 | -/// The list stream sends nothing on connect, then one `changed` event per change of the repo. | |
| 621 | 585 | #[tokio::test] |
| 622 | 586 | async fn run_list_events_follow_repo_changes() { |
| 623 | 587 | use futures_util::StreamExt; |
| @@ -633,7 +597,6 @@ async fn run_list_events_follow_repo_changes() { | ||
| 633 | 597 | .into_body() |
| 634 | 598 | .into_data_stream(); |
| 635 | 599 | |
| 636 | - // The retry field comes first; after it nothing is sent until a change. | |
| 637 | 600 | let retry = next_frame(&mut frames).await.expect("the retry field"); |
| 638 | 601 | assert!(retry.starts_with(b"retry: "), "{retry:?}"); |
| 639 | 602 | let quiet = tokio::time::timeout(Duration::from_millis(200), frames.next()).await; |
| @@ -645,7 +608,6 @@ async fn run_list_events_follow_repo_changes() { | ||
| 645 | 608 | assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec()); |
| 646 | 609 | } |
| 647 | 610 | |
| 648 | -/// The job's log stream: each append is a `log` event with its bytes, the id is the offset past them, bytes before `?from=` are not sent again, a long append is split into 64 KiB events, and a reconnect resumes after `Last-Event-ID`. | |
| 649 | 611 | #[tokio::test] |
| 650 | 612 | async fn job_log_events() { |
| 651 | 613 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -750,7 +712,6 @@ async fn job_log_events() { | ||
| 750 | 712 | } |
| 751 | 713 | } |
| 752 | 714 | |
| 753 | -/// The job page's log tail says where its text ends, tails the last 512 KiB, and a cut log starts at its own line number. | |
| 754 | 715 | #[tokio::test] |
| 755 | 716 | async fn job_page_log_tail() { |
| 756 | 717 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -814,7 +775,6 @@ async fn job_page_log_tail() { | ||
| 814 | 775 | let path = log_path(&fx.data_dir, &job.id); |
| 815 | 776 | std::fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 816 | 777 | let mut file = std::fs::File::create(&path).unwrap(); |
| 817 | - // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000. | |
| 818 | 778 | for n in 0..11_000 { |
| 819 | 779 | writeln!(file, "{n:0>98}").unwrap(); |
| 820 | 780 | } |
| @@ -840,7 +800,6 @@ async fn job_page_log_tail() { | ||
| 840 | 800 | } |
| 841 | 801 | } |
| 842 | 802 | |
| 843 | -/// The next chunk a follower sends. Fails the test when none comes within five seconds. | |
| 844 | 803 | async fn next_chunk( |
| 845 | 804 | chunks: &mut tokio::sync::mpsc::UnboundedReceiver<bytes::Bytes>, |
| 846 | 805 | ) -> Option<bytes::Bytes> { |
| @@ -849,7 +808,6 @@ async fn next_chunk( | ||
| 849 | 808 | .expect("a chunk within five seconds") |
| 850 | 809 | } |
| 851 | 810 | |
| 852 | -/// `log.txt` is the full file of a finished job, and a log follower is woken by bumps and ends once the job is terminal. | |
| 853 | 811 | #[tokio::test] |
| 854 | 812 | async fn log_txt_and_log_follower() { |
| 855 | 813 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -933,7 +891,6 @@ async fn log_txt_and_log_follower() { | ||
| 933 | 891 | } |
| 934 | 892 | } |
| 935 | 893 | |
| 936 | -/// Artifact downloads send attachment headers, and a run's artifacts list and zip for readers only. | |
| 937 | 894 | #[tokio::test] |
| 938 | 895 | async fn artifact_downloads_and_zip() { |
| 939 | 896 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -1069,12 +1026,7 @@ async fn approve_only_works_while_waiting_for_approval() { | ||
| 1069 | 1026 | ) |
| 1070 | 1027 | .await; |
| 1071 | 1028 | 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; | |
| 1078 | 1030 | assert_eq!(now.state, RunState::Queued); |
| 1079 | 1031 | let page = get(&fx.app, &run_url, Some(&cookie_for("bob-token"))).await; |
| 1080 | 1032 | assert!( |
| @@ -1090,12 +1042,7 @@ async fn approve_only_works_while_waiting_for_approval() { | ||
| 1090 | 1042 | ) |
| 1091 | 1043 | .await; |
| 1092 | 1044 | 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; | |
| 1099 | 1046 | assert_eq!(still.state, RunState::Queued); |
| 1100 | 1047 | } |
| 1101 | 1048 | |
| @@ -1113,12 +1060,7 @@ async fn cancel_and_rerun_post_and_redirect() { | ||
| 1113 | 1060 | ) |
| 1114 | 1061 | .await; |
| 1115 | 1062 | 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; | |
| 1122 | 1064 | assert_eq!(now.state, RunState::Cancelled); |
| 1123 | 1065 | let finished = post( |
| 1124 | 1066 | &fx.app, |
| @@ -1171,7 +1113,6 @@ async fn manual_run_refuses_an_unknown_branch() { | ||
| 1171 | 1113 | assert_eq!(reader.status, 403, "reader cannot start a manual run"); |
| 1172 | 1114 | } |
| 1173 | 1115 | |
| 1174 | -/// The badge follows read access, and a repo with no run answers 200 with "no status". It runs before any run exists on the private repo. | |
| 1175 | 1116 | #[tokio::test] |
| 1176 | 1117 | async fn badge_follows_read_access_and_has_no_run_before_one_exists() { |
| 1177 | 1118 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -1202,7 +1143,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() { | ||
| 1202 | 1143 | .expect("public repo"); |
| 1203 | 1144 | let svg_path = "/tahinli/proj/badge.svg"; |
| 1204 | 1145 | |
| 1205 | - // The private repo: a run exists, but only readers see its badge. | |
| 1206 | 1146 | run_with(&fx, &["build"], false).await; |
| 1207 | 1147 | finish_job(&fx).await; |
| 1208 | 1148 | assert_eq!(get(&fx.app, svg_path, None).await.status, 404, "anonymous"); |
| @@ -1226,7 +1166,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() { | ||
| 1226 | 1166 | Some("no-cache, max-age=0") |
| 1227 | 1167 | ); |
| 1228 | 1168 | |
| 1229 | - // The public repo: anyone sees the badge. Unknown branches and jobs have no status. | |
| 1230 | 1169 | let needs: &[String] = &[]; |
| 1231 | 1170 | let specs = [NewJob { |
| 1232 | 1171 | name: "build", |
| @@ -1266,7 +1205,6 @@ async fn badge_follows_read_access_and_has_no_run_before_one_exists() { | ||
| 1266 | 1205 | } |
| 1267 | 1206 | } |
| 1268 | 1207 | |
| 1269 | -/// Writes `.forge/ci.toml` with `text` into a new commit of the bare repo and returns its id. | |
| 1270 | 1208 | fn commit_ci_toml(bare: &Path, text: &str) -> String { |
| 1271 | 1209 | fn git(bare: &Path, args: &[&str], stdin: &str) -> String { |
| 1272 | 1210 | let mut child = std::process::Command::new("git") |
| @@ -1305,7 +1243,6 @@ fn commit_ci_toml(bare: &Path, text: &str) -> String { | ||
| 1305 | 1243 | git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], "") |
| 1306 | 1244 | } |
| 1307 | 1245 | |
| 1308 | -/// Creates a queued run of one job `build` at `commit` on `main`. | |
| 1309 | 1246 | async fn run_at(fx: &Fixture, commit: &str) { |
| 1310 | 1247 | let needs: &[String] = &[]; |
| 1311 | 1248 | let specs = [NewJob { |
| @@ -1331,7 +1268,6 @@ async fn run_at(fx: &Fixture, commit: &str) { | ||
| 1331 | 1268 | .expect("run"); |
| 1332 | 1269 | } |
| 1333 | 1270 | |
| 1334 | -/// The badge label comes from `?label=`, the job or the workflow name, trimmed and escaped, with "build" as the fallback. Each scenario finishes its own run, so the latest run is the one it made. | |
| 1335 | 1271 | #[tokio::test] |
| 1336 | 1272 | async fn badge_label_comes_from_the_query_job_or_name() { |
| 1337 | 1273 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -1414,7 +1350,6 @@ async fn badge_label_comes_from_the_query_job_or_name() { | ||
| 1414 | 1350 | |
| 1415 | 1351 | { |
| 1416 | 1352 | let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); |
| 1417 | - // A run whose config has an empty name: the name is ignored. | |
| 1418 | 1353 | let commit = commit_ci_toml( |
| 1419 | 1354 | &bare, |
| 1420 | 1355 | "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", |
| @@ -1429,7 +1364,6 @@ async fn badge_label_comes_from_the_query_job_or_name() { | ||
| 1429 | 1364 | } |
| 1430 | 1365 | } |
| 1431 | 1366 | |
| 1432 | -/// The pages say whether a run is counting. A running run carries the start of each counting duration, and the run page previews each job's last log line and opens a failed job. | |
| 1433 | 1367 | #[tokio::test] |
| 1434 | 1368 | async fn running_runs_and_run_page_previews() { |
| 1435 | 1369 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -1474,7 +1408,6 @@ async fn running_runs_and_run_page_previews() { | ||
| 1474 | 1408 | html.contains("data-tick=\"rest\""), |
| 1475 | 1409 | "the hatched remainder follows the clock" |
| 1476 | 1410 | ); |
| 1477 | - // The timeline is on the run's own page. | |
| 1478 | 1411 | let html = get(&fx.app, &format!("{RUN_BASE}/runs/1"), Some(&cookie)) |
| 1479 | 1412 | .await |
| 1480 | 1413 | .text() |
| @@ -1570,7 +1503,6 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() { | ||
| 1570 | 1503 | let run_url = format!("{RUN_BASE}/runs/{}", run.number); |
| 1571 | 1504 | let writer = cookie_for("bob-token"); |
| 1572 | 1505 | |
| 1573 | - // A live run offers neither control and refuses the request. | |
| 1574 | 1506 | let page = get(&fx.app, &run_url, Some(&writer)).await.text(); |
| 1575 | 1507 | assert!(!page.contains("Re-run failed jobs")); |
| 1576 | 1508 | let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; |
| @@ -1604,7 +1536,6 @@ async fn rerun_failed_and_rerun_job_start_partial_runs() { | ||
| 1604 | 1536 | .unwrap(); |
| 1605 | 1537 | assert_eq!(fx.store.jobs_for_run(&second.id).await.unwrap().len(), 2); |
| 1606 | 1538 | |
| 1607 | - // One job: it must have finished, and the request needs Write. | |
| 1608 | 1539 | let job = job_of(&fx, &run).await; |
| 1609 | 1540 | let single = post( |
| 1610 | 1541 | &fx.app, |
crates/forge-web-repo/src/pages/commit.rsmodified+24 -24
| @@ -8,12 +8,12 @@ use topcoat::Result; | ||
| 8 | 8 | use topcoat::context::{Cx, context}; |
| 9 | 9 | use topcoat::router::error::{content_too_large, not_found}; |
| 10 | 10 | use topcoat::router::{page, path_param, route}; |
| 11 | -use topcoat::view::{View, view}; | |
| 11 | +use topcoat::view::{View, component, view}; | |
| 12 | 12 | |
| 13 | 13 | use crate::i18n::code::{self as g, K}; |
| 14 | 14 | use crate::i18n::{self}; |
| 15 | 15 | use crate::layers::RawDownload; |
| 16 | -use crate::pages::commits::{SigBadgeView, blocking, iso_time, now_secs, short_oid}; | |
| 16 | +use crate::pages::commits::{SigBadgeView, blocking}; | |
| 17 | 17 | use crate::pages::ref_live; |
| 18 | 18 | use crate::pages::repo::repo_head; |
| 19 | 19 | use crate::pages::repo_ctx::load_repo; |
| @@ -24,7 +24,9 @@ use crate::state::AppState; | ||
| 24 | 24 | use crate::views::commit_status::{StatusLang, StatusSummary, checks_summary}; |
| 25 | 25 | use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; |
| 26 | 26 | use crate::views::shell; |
| 27 | -use crate::views::{avatar_url, display_name, relative_time, user_href}; | |
| 27 | +use crate::views::{ | |
| 28 | + avatar_url, display_name, iso_time, now_unix, relative_time, short_oid, user_href, | |
| 29 | +}; | |
| 28 | 30 | |
| 29 | 31 | path_param!(owner); |
| 30 | 32 | path_param!(repo); |
| @@ -54,6 +56,22 @@ struct CoAuthorView { | ||
| 54 | 56 | sep: bool, |
| 55 | 57 | } |
| 56 | 58 | |
| 59 | +#[component] | |
| 60 | +async fn coauthor_link(cx: &Cx, c: &CoAuthorView) -> Result<impl View> { | |
| 61 | + Ok(view! { | |
| 62 | + if let Some(href) = c.href.as_ref() { | |
| 63 | + <a class="coauthor" href=(href.as_str())> | |
| 64 | + if let Some(src) = c.avatar.as_ref() { | |
| 65 | + <img class="avatar coauthor-avatar" src=(src.as_str()) alt="" width="16" height="16"> | |
| 66 | + } | |
| 67 | + (c.name.as_str()) | |
| 68 | + </a> | |
| 69 | + } else { | |
| 70 | + <span class="coauthor" title=(c.email.as_str())>(c.name.as_str())</span> | |
| 71 | + } | |
| 72 | + }) | |
| 73 | +} | |
| 74 | + | |
| 57 | 75 | fn is_hex_prefix(s: &str) -> bool { |
| 58 | 76 | (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit()) |
| 59 | 77 | } |
| @@ -146,7 +164,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> { | ||
| 146 | 164 | let tz = ctx.viewer_tz().to_owned(); |
| 147 | 165 | let parent = info.parents.first().cloned(); |
| 148 | 166 | |
| 149 | - let now = now_secs(); | |
| 167 | + let now = now_unix(); | |
| 150 | 168 | let author = Person { |
| 151 | 169 | name: info.author_name.clone(), |
| 152 | 170 | email: info.author_email.clone(), |
| @@ -277,16 +295,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> { | ||
| 277 | 295 | (g::t(lang, K::CoAuthorAnd)) |
| 278 | 296 | for c in coauthors.iter() { |
| 279 | 297 | 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) | |
| 290 | 299 | } |
| 291 | 300 | if folded { |
| 292 | 301 | ", " |
| @@ -295,16 +304,7 @@ async fn commit_page(cx: &Cx) -> Result<impl View> { | ||
| 295 | 304 | <ul class="coauthors-list" aria-label=(coauthors_label)> |
| 296 | 305 | for c in rest.iter() { |
| 297 | 306 | <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) | |
| 308 | 308 | </li> |
| 309 | 309 | } |
| 310 | 310 | </ul> |
crates/forge-web-repo/src/pages/commits.rsmodified+2 -47
| @@ -1,8 +1,6 @@ | ||
| 1 | 1 | //! Page: commit history for a ref and optional path, at `/{owner}/{repo}/commits/{*rest}`. |
| 2 | 2 | //! Also home of the helpers shared by the commit and archive pages. |
| 3 | 3 | |
| 4 | -use std::time::{SystemTime, UNIX_EPOCH}; | |
| 5 | - | |
| 6 | 4 | use std::collections::HashMap; |
| 7 | 5 | |
| 8 | 6 | use forge_core::store::commit_status::CommitStatus; |
| @@ -28,7 +26,7 @@ use crate::signatures::{self, SigBadge}; | ||
| 28 | 26 | use crate::state::AppState; |
| 29 | 27 | use crate::views::commit_line::commit_line; |
| 30 | 28 | use crate::views::commit_status::{StatusLang, StatusSummary, commit_status, status_list}; |
| 31 | -use crate::views::{enc, shell}; | |
| 29 | +use crate::views::{enc, iso_time, now_unix, shell, short_oid}; | |
| 32 | 30 | |
| 33 | 31 | path_param!(owner); |
| 34 | 32 | path_param!(repo); |
| @@ -53,46 +51,6 @@ where | ||
| 53 | 51 | Ok(tokio::task::spawn_blocking(f).await??) |
| 54 | 52 | } |
| 55 | 53 | |
| 56 | -/// Current Unix time in seconds. | |
| 57 | -pub(crate) fn now_secs() -> i64 { | |
| 58 | - SystemTime::now() | |
| 59 | - .duration_since(UNIX_EPOCH) | |
| 60 | - .ok() | |
| 61 | - .and_then(|d| i64::try_from(d.as_secs()).ok()) | |
| 62 | - .unwrap_or(0) | |
| 63 | -} | |
| 64 | - | |
| 65 | -/// Days since the Unix epoch to a proleptic Gregorian `(year, month, day)`. | |
| 66 | -fn civil_from_days(days: i64) -> (i64, u32, u32) { | |
| 67 | - let z = days + 719_468; | |
| 68 | - let era = z.div_euclid(146_097); | |
| 69 | - let doe = z - era * 146_097; | |
| 70 | - let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; | |
| 71 | - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); | |
| 72 | - let mp = (5 * doy + 2) / 153; | |
| 73 | - let day = doy - (153 * mp + 2) / 5 + 1; | |
| 74 | - let month = if mp < 10 { mp + 3 } else { mp - 9 }; | |
| 75 | - let year = yoe + era * 400 + i64::from(month <= 2); | |
| 76 | - (year, month as u32, day as u32) | |
| 77 | -} | |
| 78 | - | |
| 79 | -/// RFC 3339 UTC stamp for the `datetime` attribute. | |
| 80 | -pub(crate) fn iso_time(at: i64) -> String { | |
| 81 | - let (y, m, d) = civil_from_days(at.div_euclid(86_400)); | |
| 82 | - let secs = at.rem_euclid(86_400); | |
| 83 | - format!( | |
| 84 | - "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", | |
| 85 | - secs / 3600, | |
| 86 | - secs % 3600 / 60, | |
| 87 | - secs % 60 | |
| 88 | - ) | |
| 89 | -} | |
| 90 | - | |
| 91 | -/// Seven-character abbreviation, as shown in lists. | |
| 92 | -pub(crate) fn short_oid(oid: &str) -> &str { | |
| 93 | - oid.get(..7).unwrap_or(oid) | |
| 94 | -} | |
| 95 | - | |
| 96 | 54 | /// One commit as shown in the history list. |
| 97 | 55 | pub(crate) struct CommitRow { |
| 98 | 56 | /// The full oid: the row's `data-arrive` value. |
| @@ -279,7 +237,7 @@ async fn commits_page(cx: &Cx) -> Result<impl View> { | ||
| 279 | 237 | let older_href = href_for(page_no + 1); |
| 280 | 238 | let has_newer = page_no > 1; |
| 281 | 239 | |
| 282 | - let now = now_secs(); | |
| 240 | + let now = now_unix(); | |
| 283 | 241 | let tz = ctx.viewer_tz().to_owned(); |
| 284 | 242 | let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect(); |
| 285 | 243 | let statuses = state |
| @@ -403,7 +361,6 @@ async fn commits_page(cx: &Cx) -> Result<impl View> { | ||
| 403 | 361 | mod tests { |
| 404 | 362 | use forge_core::Visibility; |
| 405 | 363 | |
| 406 | - use super::iso_time; | |
| 407 | 364 | use crate::i18n::Lang; |
| 408 | 365 | use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git}; |
| 409 | 366 | use crate::views::relative_time; |
| @@ -411,8 +368,6 @@ mod tests { | ||
| 411 | 368 | |
| 412 | 369 | #[test] |
| 413 | 370 | fn dates_and_relative_units_format() { |
| 414 | - assert_eq!(iso_time(0), "1970-01-01T00:00:00Z"); | |
| 415 | - assert_eq!(iso_time(1_700_000_000), "2023-11-14T22:13:20Z"); | |
| 416 | 371 | assert_eq!(relative_time(Lang::En, 990, 1000), "just now"); |
| 417 | 372 | assert_eq!( |
| 418 | 373 | relative_time(Lang::En, 10_000 - 3 * 86_400, 10_000), |
crates/forge-web-repo/src/pages/compare.rsmodified+8 -30
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | |
| 12 | 12 | use std::path::PathBuf; |
| 13 | 13 | |
| 14 | -use forge_core::{Action, Repo as RepoRecord, Session, authorize, validate_body, validate_title}; | |
| 14 | +use forge_core::{Action, Repo as RepoRecord, authorize, validate_body, validate_title}; | |
| 15 | 15 | use forge_git::browse::{self, CommitInfo, RefKind}; |
| 16 | 16 | use forge_git::command::ObjectSource; |
| 17 | 17 | use forge_git::history; |
| @@ -21,16 +21,18 @@ use serde::Deserialize; | ||
| 21 | 21 | use topcoat::Result; |
| 22 | 22 | use topcoat::context::{Cx, context}; |
| 23 | 23 | use topcoat::router::content::Form; |
| 24 | -use topcoat::router::error::{bad_request, forbidden, not_found, see_other}; | |
| 24 | +use topcoat::router::error::{bad_request, not_found, see_other}; | |
| 25 | 25 | use topcoat::router::{page, path_param, query_params}; |
| 26 | 26 | use topcoat::view::{View, view}; |
| 27 | 27 | |
| 28 | -use crate::auth::{check_csrf, require_user}; | |
| 28 | +use crate::auth::require_user; | |
| 29 | 29 | use crate::i18n; |
| 30 | 30 | use crate::i18n::pulls::{self as g, K}; |
| 31 | 31 | use crate::notify::{self, Activity}; |
| 32 | 32 | use crate::pages::commit::Download; |
| 33 | -use crate::pages::commits::{CommitRow, blocking, now_secs, short_oid}; | |
| 33 | +use crate::pages::commits::{CommitRow, blocking}; | |
| 34 | +use crate::pages::issue_parts::{check_write, csrf_of}; | |
| 35 | +use crate::pages::pull_flow::pull_href; | |
| 34 | 36 | use crate::pages::ref_live; |
| 35 | 37 | use crate::pages::repo::repo_head; |
| 36 | 38 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| @@ -39,7 +41,7 @@ use crate::templates; | ||
| 39 | 41 | use crate::views::commit_line::commit_line; |
| 40 | 42 | use crate::views::diff::{DiffLang, DiffOpts, LIMITS, diff_section}; |
| 41 | 43 | use crate::views::parts::reveal; |
| 42 | -use crate::views::{alert, enc, repo_href, shell, user_facing_message}; | |
| 44 | +use crate::views::{alert, enc, now_unix, repo_href, shell, short_oid, user_facing_message}; | |
| 43 | 45 | use crate::webhooks::emit::{Sender, emit_pull}; |
| 44 | 46 | |
| 45 | 47 | path_param!(owner); |
| @@ -195,30 +197,6 @@ async fn resolve_comparison( | ||
| 195 | 197 | })) |
| 196 | 198 | } |
| 197 | 199 | |
| 198 | -fn csrf_of(ctx: &RepoCtx) -> String { | |
| 199 | - ctx.viewer | |
| 200 | - .as_ref() | |
| 201 | - .map(|(_, session)| session.csrf_token.clone()) | |
| 202 | - .unwrap_or_default() | |
| 203 | -} | |
| 204 | - | |
| 205 | -/// Write requests need an unarchived repo and a matching CSRF token. | |
| 206 | -fn check_write(ctx: &RepoCtx, session: &Session, csrf: &str) -> Result<()> { | |
| 207 | - if ctx.repo.archived || !check_csrf(session, csrf) { | |
| 208 | - return Err(forbidden().into()); | |
| 209 | - } | |
| 210 | - Ok(()) | |
| 211 | -} | |
| 212 | - | |
| 213 | -fn pull_href(ctx: &RepoCtx, number: i64) -> String { | |
| 214 | - repo_href( | |
| 215 | - &ctx.repo.owner_name, | |
| 216 | - &ctx.repo.name, | |
| 217 | - "pulls", | |
| 218 | - &number.to_string(), | |
| 219 | - ) | |
| 220 | -} | |
| 221 | - | |
| 222 | 200 | /// The body the pull request form starts with: the default branch's pull request template, or |
| 223 | 201 | /// empty when there is none. |
| 224 | 202 | async fn pull_template_body(ctx: &RepoCtx) -> Result<String> { |
| @@ -241,7 +219,7 @@ async fn compare_view( | ||
| 241 | 219 | let owner = ctx.repo.owner_name.clone(); |
| 242 | 220 | let name = ctx.repo.name.clone(); |
| 243 | 221 | let tz = ctx.viewer_tz().to_owned(); |
| 244 | - let now = now_secs(); | |
| 222 | + let now = now_unix(); | |
| 245 | 223 | let title = format!("{owner}/{name}"); |
| 246 | 224 | let base = cmp.base.clone(); |
| 247 | 225 | let head = head_value(&ctx, &cmp.head); |
crates/forge-web-repo/src/pages/discussion_live.rsmodified+0 -2
| @@ -54,5 +54,3 @@ async fn discussion_live(cx: &Cx) -> Result<Response> { | ||
| 54 | 54 | let discussion = discussion_by_number(state, &ctx, number(cx)).await?; |
| 55 | 55 | stream_wakes(cx, &state.live, &[Topic::Discussion(discussion.id.clone())]) |
| 56 | 56 | } |
| 57 | - | |
| 58 | -// The write layer |
crates/forge-web-repo/src/pages/fork.rsmodified+31 -4
| @@ -48,8 +48,7 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> { | ||
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | // 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? { | |
| 53 | 52 | return Ok(see_other(repo_href( |
| 54 | 53 | &existing.owner_name, |
| 55 | 54 | &existing.name, |
| @@ -59,10 +58,25 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> { | ||
| 59 | 58 | } |
| 60 | 59 | |
| 61 | 60 | let fork_name = free_name(state, &viewer.username, &source_repo.name).await?; |
| 62 | - let fork = state | |
| 61 | + let fork = match state | |
| 63 | 62 | .store |
| 64 | 63 | .create_fork(source_repo, &viewer.id, &fork_name) |
| 65 | - .await?; | |
| 64 | + .await | |
| 65 | + { | |
| 66 | + Ok(fork) => fork, | |
| 67 | + Err(e @ forge_core::Error::Conflict(_)) => { | |
| 68 | + let Some(existing) = viewer_fork(state, &source_repo.id, &viewer.id).await? else { | |
| 69 | + return Err(e.into()); | |
| 70 | + }; | |
| 71 | + return Ok(see_other(repo_href( | |
| 72 | + &existing.owner_name, | |
| 73 | + &existing.name, | |
| 74 | + "", | |
| 75 | + "", | |
| 76 | + ))); | |
| 77 | + } | |
| 78 | + Err(e) => return Err(e.into()), | |
| 79 | + }; | |
| 66 | 80 | let dst = repo_path(&state.config.data_dir, &fork.id)?; |
| 67 | 81 | if let Err(e) = fork_bare(&state.git, &source.path, &dst).await { |
| 68 | 82 | // Without the directory the row would point at nothing, so drop it again. |
| @@ -107,6 +121,19 @@ async fn fork_post(cx: &Cx, Form(form): Form<ForkForm>) -> Result<SeeOther> { | ||
| 107 | 121 | Ok(see_other(repo_href(&fork.owner_name, &fork.name, "", ""))) |
| 108 | 122 | } |
| 109 | 123 | |
| 124 | +async fn viewer_fork( | |
| 125 | + state: &AppState, | |
| 126 | + source_id: &str, | |
| 127 | + viewer_id: &str, | |
| 128 | +) -> Result<Option<forge_core::Repo>> { | |
| 129 | + Ok(state | |
| 130 | + .store | |
| 131 | + .list_forks(source_id) | |
| 132 | + .await? | |
| 133 | + .into_iter() | |
| 134 | + .find(|fork| fork.owner_id == viewer_id)) | |
| 135 | +} | |
| 136 | + | |
| 110 | 137 | /// `base` when `owner` has no repo of that name, else the first of `base-1`, `base-2`, ... that is |
| 111 | 138 | /// free. |
| 112 | 139 | async fn free_name(state: &AppState, owner: &str, base: &str) -> Result<String> { |
crates/forge-web-repo/src/pages/labels_css.rsmodified+2 -6
| @@ -32,12 +32,8 @@ fn parse_hex(color: &str) -> Option<(u8, u8, u8)> { | ||
| 32 | 32 | if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 33 | 33 | return None; |
| 34 | 34 | } |
| 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)) | |
| 41 | 37 | } |
| 42 | 38 | |
| 43 | 39 | /// Label ids go into a CSS class name, so only plain identifier characters are kept. |
crates/forge-web-repo/src/pages/labels_page.rsmodified+14 -61
| @@ -8,18 +8,15 @@ use serde::Deserialize; | ||
| 8 | 8 | use topcoat::Result; |
| 9 | 9 | use topcoat::context::{Cx, context}; |
| 10 | 10 | use topcoat::router::content::Form; |
| 11 | -use topcoat::router::error::see_other; | |
| 12 | 11 | use topcoat::router::{page, path_param, query_params}; |
| 13 | 12 | use topcoat::view::{View, component, view}; |
| 14 | 13 | |
| 15 | 14 | use crate::i18n::issues::{self as g, K}; |
| 16 | 15 | 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}; | |
| 20 | 17 | use crate::pages::issues_live::list_live_url; |
| 21 | 18 | use crate::pages::repo::repo_head; |
| 22 | -use crate::pages::repo_ctx::load_repo; | |
| 19 | +use crate::pages::repo_ctx::{RepoCtx, load_repo}; | |
| 23 | 20 | use crate::state::AppState; |
| 24 | 21 | use crate::views::parts::{confirm_act, post_act, reveal}; |
| 25 | 22 | use crate::views::repo_list::{PageLink, pager, pager_links}; |
| @@ -77,6 +74,10 @@ fn labels_href(title: &str) -> String { | ||
| 77 | 74 | format!("/{title}/labels") |
| 78 | 75 | } |
| 79 | 76 | |
| 77 | +fn labels_back(ctx: &RepoCtx) -> String { | |
| 78 | + labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)) | |
| 79 | +} | |
| 80 | + | |
| 80 | 81 | /// The header, the label list and, for triage holders, the forms. |
| 81 | 82 | #[component] |
| 82 | 83 | async fn labels_body( |
| @@ -249,24 +250,12 @@ async fn label_create(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View> | ||
| 249 | 250 | let ctx = load_repo(cx, owner, name).await?; |
| 250 | 251 | triage_guard(cx, &ctx, &form.csrf).await?; |
| 251 | 252 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u)); |
| 252 | - let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)); | |
| 253 | + let back = labels_back(&ctx); | |
| 253 | 254 | let result = context::<AppState>(cx) |
| 254 | 255 | .store |
| 255 | 256 | .create_label(&ctx.repo.id, &form.name, &form.color, &form.description) |
| 256 | 257 | .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 | |
| 270 | 259 | } |
| 271 | 260 | |
| 272 | 261 | /// Updates a label's name, color and description. |
| @@ -278,24 +267,12 @@ async fn label_update(cx: &Cx, Form(form): Form<LabelForm>) -> Result<impl View> | ||
| 278 | 267 | let ctx = load_repo(cx, owner, name).await?; |
| 279 | 268 | triage_guard(cx, &ctx, &form.csrf).await?; |
| 280 | 269 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u)); |
| 281 | - let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)); | |
| 270 | + let back = labels_back(&ctx); | |
| 282 | 271 | let result = context::<AppState>(cx) |
| 283 | 272 | .store |
| 284 | 273 | .update_label(&ctx.repo.id, id, &form.name, &form.color, &form.description) |
| 285 | 274 | .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 | |
| 299 | 276 | } |
| 300 | 277 | |
| 301 | 278 | /// Adds the default labels to a repo that has none. Triage holders only; labels that already |
| @@ -307,24 +284,12 @@ async fn label_defaults(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View | ||
| 307 | 284 | let ctx = load_repo(cx, owner, name).await?; |
| 308 | 285 | triage_guard(cx, &ctx, &form.csrf).await?; |
| 309 | 286 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u)); |
| 310 | - let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)); | |
| 287 | + let back = labels_back(&ctx); | |
| 311 | 288 | let result = context::<AppState>(cx) |
| 312 | 289 | .store |
| 313 | 290 | .create_default_labels(&ctx.repo.id) |
| 314 | 291 | .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 | |
| 328 | 293 | } |
| 329 | 294 | |
| 330 | 295 | /// Deletes a label and its links to issues. |
| @@ -336,24 +301,12 @@ async fn label_delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<impl View> | ||
| 336 | 301 | let ctx = load_repo(cx, owner, name).await?; |
| 337 | 302 | triage_guard(cx, &ctx, &form.csrf).await?; |
| 338 | 303 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u)); |
| 339 | - let back = labels_href(&format!("{}/{}", ctx.repo.owner_name, ctx.repo.name)); | |
| 304 | + let back = labels_back(&ctx); | |
| 340 | 305 | let result = context::<AppState>(cx) |
| 341 | 306 | .store |
| 342 | 307 | .delete_label(&ctx.repo.id, id) |
| 343 | 308 | .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 | |
| 357 | 310 | } |
| 358 | 311 | |
| 359 | 312 | #[cfg(test)] |
crates/forge-web-repo/src/pages/merge_queue.rsmodified+28 -66
| @@ -13,13 +13,10 @@ use std::collections::HashMap; | ||
| 13 | 13 | |
| 14 | 14 | use forge_core::merge_queue::{QueueEntry, QueueState}; |
| 15 | 15 | use forge_core::{Action, MergeStyle, PullRequest, authorize}; |
| 16 | -use futures_util::{Stream, stream}; | |
| 17 | 16 | use serde::Deserialize; |
| 18 | -use tokio::sync::watch; | |
| 19 | 17 | use topcoat::Result; |
| 20 | 18 | use topcoat::context::{Cx, context}; |
| 21 | 19 | use topcoat::router::content::Form; |
| 22 | -use topcoat::router::content::sse::Event; | |
| 23 | 20 | use topcoat::router::error::{bad_request, forbidden, not_found, see_other}; |
| 24 | 21 | use topcoat::router::response::Response; |
| 25 | 22 | use topcoat::router::{page, path_param, query_params, route}; |
| @@ -28,10 +25,11 @@ use topcoat::view::{View, component, view}; | ||
| 28 | 25 | use crate::auth::require_csrf; |
| 29 | 26 | use crate::i18n::merge_queue::{self as g, K}; |
| 30 | 27 | use crate::i18n::{self, Lang}; |
| 31 | -use crate::live::{changed_event, events_response}; | |
| 28 | +use crate::live::{events_response, wake_stream}; | |
| 32 | 29 | use crate::merge::ERR_NOT_OPEN; |
| 33 | 30 | use crate::merge_queue as queue; |
| 34 | 31 | use crate::pages::issue_parts::parse_number; |
| 32 | +use crate::pages::pull_flow::pull_href; | |
| 35 | 33 | use crate::pages::repo::repo_head; |
| 36 | 34 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 37 | 35 | use crate::state::AppState; |
| @@ -55,15 +53,6 @@ struct QueueQuery { | ||
| 55 | 53 | show: Option<String>, |
| 56 | 54 | } |
| 57 | 55 | |
| 58 | -fn pull_href(ctx: &RepoCtx, number: i64) -> String { | |
| 59 | - repo_href( | |
| 60 | - &ctx.repo.owner_name, | |
| 61 | - &ctx.repo.name, | |
| 62 | - "pulls", | |
| 63 | - &number.to_string(), | |
| 64 | - ) | |
| 65 | -} | |
| 66 | - | |
| 67 | 56 | fn queue_href(ctx: &RepoCtx) -> String { |
| 68 | 57 | repo_href(&ctx.repo.owner_name, &ctx.repo.name, "merge-queue", "") |
| 69 | 58 | } |
| @@ -323,6 +312,8 @@ fn reason_label(lang: Lang, reason: &str) -> String { | ||
| 323 | 312 | "permission" => K::ReasonPermission, |
| 324 | 313 | "blocked" => K::ReasonBlocked, |
| 325 | 314 | "no_branch" => K::ReasonNoBranch, |
| 315 | + "draft" => K::ReasonDraft, | |
| 316 | + "head_missing" => K::ReasonHeadMissing, | |
| 326 | 317 | _ => return reason.to_owned(), |
| 327 | 318 | }; |
| 328 | 319 | g::t(lang, key).to_owned() |
| @@ -335,14 +326,7 @@ async fn queue_events(cx: &Cx) -> Result<Response> { | ||
| 335 | 326 | let ctx = load_repo(cx, owner(cx), repo(cx)).await?; |
| 336 | 327 | let state = context::<AppState>(cx); |
| 337 | 328 | 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")) | |
| 346 | 330 | } |
| 347 | 331 | |
| 348 | 332 | #[component] |
| @@ -378,52 +362,30 @@ async fn queue_body( | ||
| 378 | 362 | } |
| 379 | 363 | } else { |
| 380 | 364 | 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 { | |
| 402 | 386 | confirm_act(lang: lang, label: remove_label, action: row.remove_action.as_str(), csrf: csrf.as_str(), note: Some(remove_note.clone())) |
| 403 | - </div> | |
| 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> | |
| 427 | 389 | } |
| 428 | 390 | } |
| 429 | 391 | </div> |
crates/forge-web-repo/src/pages/pull_branch.rsmodified+33 -21
| @@ -100,13 +100,7 @@ async fn branch_post(cx: &Cx, csrf: &str, op: Op) -> Result<Response> { | ||
| 100 | 100 | let head = head_repo(state, &pr).await?; |
| 101 | 101 | match &head { |
| 102 | 102 | 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? { | |
| 110 | 104 | return Err(forbidden().into()); |
| 111 | 105 | } |
| 112 | 106 | } |
| @@ -149,6 +143,29 @@ fn finished(pr: &PullRequest) -> bool { | ||
| 149 | 143 | pr.merged_at.is_some() || pr.issue.state != IssueState::Open |
| 150 | 144 | } |
| 151 | 145 | |
| 146 | +async fn head_writable( | |
| 147 | + state: &AppState, | |
| 148 | + head: &forge_core::Repo, | |
| 149 | + user: &User, | |
| 150 | +) -> forge_core::Result<bool> { | |
| 151 | + let role = state.store.collaborator_role(&head.id, &user.id).await?; | |
| 152 | + let org_role = state | |
| 153 | + .store | |
| 154 | + .org_repo_role(&head.owner_id, &user.id, &head.id) | |
| 155 | + .await?; | |
| 156 | + Ok(!head.archived && authorize(Some(user), head, role, org_role, Action::Write).is_ok()) | |
| 157 | +} | |
| 158 | + | |
| 159 | +fn cas_refusal( | |
| 160 | + result: forge_git::error::Result<()>, | |
| 161 | +) -> forge_core::Result<Option<&'static str>> { | |
| 162 | + match result { | |
| 163 | + Ok(()) => Ok(None), | |
| 164 | + Err(forge_git::error::Error::RefMoved(_)) => Ok(Some(ERR_MOVED)), | |
| 165 | + Err(e) => Err(e.into()), | |
| 166 | + } | |
| 167 | +} | |
| 168 | + | |
| 152 | 169 | /// The head repo of `pr` when it still exists. |
| 153 | 170 | async fn head_repo( |
| 154 | 171 | state: &AppState, |
| @@ -177,10 +194,10 @@ async fn delete_branch( | ||
| 177 | 194 | Some(tip) if tip != pr.head_oid => return Ok(Some(ERR_MOVED)), |
| 178 | 195 | Some(_) => {} |
| 179 | 196 | } |
| 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)); | |
| 184 | 201 | } |
| 185 | 202 | record_ref_change(state, head, user, &refname, &pr.head_oid, ZERO_OID).await; |
| 186 | 203 | state |
| @@ -214,10 +231,10 @@ async fn restore_branch( | ||
| 214 | 231 | if read_commit(&path, &pr.head_oid)?.is_none() { |
| 215 | 232 | return Ok(Some(ERR_MISSING)); |
| 216 | 233 | } |
| 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)); | |
| 221 | 238 | } |
| 222 | 239 | record_ref_change(state, head, user, &refname, ZERO_OID, &pr.head_oid).await; |
| 223 | 240 | state |
| @@ -304,12 +321,7 @@ pub(crate) async fn branch_action( | ||
| 304 | 321 | let Some(head) = head_repo(state, pr).await? else { |
| 305 | 322 | return Ok(None); |
| 306 | 323 | }; |
| 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? { | |
| 313 | 325 | return Ok(None); |
| 314 | 326 | } |
| 315 | 327 | let path = repo_path(&state.git.data_dir, &head.id)?; |
crates/forge-web-repo/src/pages/pull_files.rsmodified+12 -108
| @@ -1,9 +1,3 @@ | ||
| 1 | -//! The Files changed tab of a pull request, `/{owner}/{repo}/pulls/{n}/files`. Each diff line has | |
| 2 | -//! an anchor and a "+" link (`?comment=<file>:<old|new>:<line>`), which opens an inline comment | |
| 3 | -//! form under that line. Existing review threads render under their lines. Signed-in viewers see | |
| 4 | -//! the decision pill under the diff. The header and tabs come from `pull_view`. The review POST | |
| 5 | -//! routes are in `pull_reviews`. | |
| 6 | - | |
| 7 | 1 | use std::collections::{HashMap, HashSet}; |
| 8 | 2 | use std::sync::Arc; |
| 9 | 3 | |
| @@ -27,7 +21,7 @@ use crate::i18n::pulls::{self as g, K}; | ||
| 27 | 21 | use crate::i18n::{self, Lang}; |
| 28 | 22 | use crate::pages::edit_history::thread_edit_counts; |
| 29 | 23 | use crate::pages::issue_parts::{check_write, csrf_of, may_converse, parse_number, triage, viewer}; |
| 30 | -use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states}; | |
| 24 | +use crate::pages::pull_reviews::{error_from, pull_diff, suggest_states}; | |
| 31 | 25 | use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header}; |
| 32 | 26 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 33 | 27 | use crate::pages::tree::link_context; |
| @@ -41,7 +35,6 @@ path_param!(owner); | ||
| 41 | 35 | path_param!(repo); |
| 42 | 36 | path_param!(number); |
| 43 | 37 | |
| 44 | -/// Parses a non-empty run of ASCII digits. `str::parse` alone would also accept a leading `+`. | |
| 45 | 38 | fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> { |
| 46 | 39 | if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) { |
| 47 | 40 | return None; |
| @@ -49,7 +42,6 @@ fn digits<T: std::str::FromStr>(raw: &str) -> Option<T> { | ||
| 49 | 42 | raw.parse().ok() |
| 50 | 43 | } |
| 51 | 44 | |
| 52 | -/// The `comment=<file>:<old|new>:<line>` target of an inline form. Anything else is ignored. | |
| 53 | 45 | fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> { |
| 54 | 46 | let request = uri(cx); |
| 55 | 47 | let query = request.query()?; |
| @@ -61,24 +53,12 @@ fn comment_target(cx: &Cx) -> Option<(usize, Side, u32)> { | ||
| 61 | 53 | parts.next().is_none().then_some((index, side, line)) |
| 62 | 54 | } |
| 63 | 55 | |
| 64 | -/// The message for the `review_error` query value of the request, when it is a known code. The | |
| 65 | -/// codes and their messages are shared with the review routes (`pull_reviews::error_text`). | |
| 66 | -fn review_error_from(lang: Lang, cx: &Cx) -> Option<String> { | |
| 67 | - let request = uri(cx); | |
| 68 | - let query = request.query()?; | |
| 69 | - let (_, code) = | |
| 70 | - form_urlencoded::parse(query.as_bytes()).find(|(key, _)| *key == "review_error")?; | |
| 71 | - error_text_in(lang, &code).map(str::to_owned) | |
| 72 | -} | |
| 73 | - | |
| 74 | -/// Index of the diff file a thread's path names, matched on either side of a rename. | |
| 75 | 56 | fn file_index(diff: &CommitDiff, path: &str) -> Option<usize> { |
| 76 | 57 | diff.files |
| 77 | 58 | .iter() |
| 78 | 59 | .position(|f| f.new_path.as_deref() == Some(path) || f.old_path.as_deref() == Some(path)) |
| 79 | 60 | } |
| 80 | 61 | |
| 81 | -/// The path a file's Viewed mark is kept under: its new path, or the old one when it was deleted. | |
| 82 | 62 | fn mark_path(file: &FileDiff) -> Option<&str> { |
| 83 | 63 | if file.status == DiffStatus::Deleted { |
| 84 | 64 | file.old_path.as_deref() |
| @@ -87,7 +67,6 @@ fn mark_path(file: &FileDiff) -> Option<&str> { | ||
| 87 | 67 | } |
| 88 | 68 | } |
| 89 | 69 | |
| 90 | -/// The file's heading in the diff, as `diff_section` writes it: `old → new` for a rename. | |
| 91 | 70 | fn file_label(file: &FileDiff) -> String { |
| 92 | 71 | match (&file.old_path, &file.new_path) { |
| 93 | 72 | (Some(old), Some(new)) if old != new => format!("{old} → {new}"), |
| @@ -97,12 +76,9 @@ fn file_label(file: &FileDiff) -> String { | ||
| 97 | 76 | } |
| 98 | 77 | } |
| 99 | 78 | |
| 100 | -/// Where a file's mark stands for the viewer. | |
| 101 | 79 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 102 | 80 | enum MarkState { |
| 103 | - /// Marked at the file's current blob. | |
| 104 | 81 | Viewed, |
| 105 | - /// Marked at an older blob: the file changed since. | |
| 106 | 82 | Changed, |
| 107 | 83 | Unviewed, |
| 108 | 84 | } |
| @@ -117,29 +93,16 @@ impl MarkState { | ||
| 117 | 93 | } |
| 118 | 94 | } |
| 119 | 95 | |
| 120 | -/// One file of the full diff, as the Files pane lists it. | |
| 121 | 96 | struct FileRow { |
| 122 | 97 | path: String, |
| 123 | - /// The heading `diff_section` gives the file, to find its section on the page. | |
| 124 | 98 | label: String, |
| 125 | 99 | state: MarkState, |
| 126 | 100 | additions: u32, |
| 127 | 101 | deletions: u32, |
| 128 | - /// The file's index in the diff the page shows, when that diff lists it. | |
| 129 | 102 | index: Option<usize>, |
| 130 | - /// A thread on this file is still open. | |
| 131 | 103 | commented: bool, |
| 132 | 104 | } |
| 133 | 105 | |
| 134 | -/// Where the viewed checkboxes post, for a signed-in viewer. | |
| 135 | -struct ViewedControls { | |
| 136 | - pr_href: String, | |
| 137 | - csrf: String, | |
| 138 | -} | |
| 139 | - | |
| 140 | -/// One row per file of the full diff. A mark counts only while its blob is the file's blob at the | |
| 141 | -/// head, so a file a later push changed shows as changed. `marks` is `None` for a signed-out | |
| 142 | -/// viewer, whose rows carry no marks and so no blob reads. | |
| 143 | 106 | async fn file_rows( |
| 144 | 107 | state: &AppState, |
| 145 | 108 | ctx: &RepoCtx, |
| @@ -179,14 +142,12 @@ async fn file_rows( | ||
| 179 | 142 | Ok(rows) |
| 180 | 143 | } |
| 181 | 144 | |
| 182 | -/// One segment of the strip above the diff: one file, its size among the files, and its state. | |
| 183 | 145 | struct SegView { |
| 184 | 146 | class: String, |
| 185 | 147 | href: String, |
| 186 | 148 | label: String, |
| 187 | 149 | } |
| 188 | 150 | |
| 189 | -/// One row of the Files rail, with its tick and counts worked out. | |
| 190 | 151 | struct RailFile { |
| 191 | 152 | class: String, |
| 192 | 153 | tick: String, |
| @@ -198,9 +159,6 @@ struct RailFile { | ||
| 198 | 159 | counts: String, |
| 199 | 160 | } |
| 200 | 161 | |
| 201 | -/// The Files rail: one row per file of the full diff, with its viewed tick, its name and its | |
| 202 | -/// counts. A row links to its file in the diff. For a signed-in viewer the tick is the Viewed | |
| 203 | -/// toggle, and a changed file says so. | |
| 204 | 162 | #[component] |
| 205 | 163 | async fn files_rail( |
| 206 | 164 | cx: &Cx, |
| @@ -248,7 +206,6 @@ async fn files_rail( | ||
| 248 | 206 | }) |
| 249 | 207 | } |
| 250 | 208 | |
| 251 | -/// The diff pane's top row: Unified or Split, and whitespace. Its links are the toolbar's own. | |
| 252 | 209 | #[component] |
| 253 | 210 | async fn diff_top( |
| 254 | 211 | cx: &Cx, |
| @@ -271,7 +228,6 @@ async fn diff_top( | ||
| 271 | 228 | }) |
| 272 | 229 | } |
| 273 | 230 | |
| 274 | -/// The Viewed form body: `viewed` is `1` to mark the file, anything else clears the mark. | |
| 275 | 231 | #[derive(Deserialize)] |
| 276 | 232 | struct ViewedForm { |
| 277 | 233 | csrf: String, |
| @@ -279,10 +235,6 @@ struct ViewedForm { | ||
| 279 | 235 | viewed: String, |
| 280 | 236 | } |
| 281 | 237 | |
| 282 | -/// Marks or clears the viewer's Viewed mark on one file. The blob is read from the head here, never | |
| 283 | -/// taken from the form, so a mark always names the file as it is now. A path that is not a file of | |
| 284 | -/// the pull request changes nothing. The repo and pull lookups match the Files page, so an | |
| 285 | -/// unreadable repo answers with the same not-found. | |
| 286 | 238 | #[route(POST "/{owner}/{repo}/pulls/{number}/viewed")] |
| 287 | 239 | async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther> { |
| 288 | 240 | let number = parse_number(number(cx))?; |
| @@ -328,9 +280,6 @@ async fn viewed_post(cx: &Cx, Form(form): Form<ViewedForm>) -> Result<SeeOther> | ||
| 328 | 280 | Ok(see_other(files)) |
| 329 | 281 | } |
| 330 | 282 | |
| 331 | -/// The decision pill under the diff: the viewed count, the open threads, the next unviewed file and | |
| 332 | -/// Finish review. Finish review opens the review form in a panel above the pill. Approve and | |
| 333 | -/// Request changes in the pull's head submit the same form. | |
| 334 | 283 | #[component] |
| 335 | 284 | async fn review_bar( |
| 336 | 285 | cx: &Cx, |
| @@ -381,7 +330,6 @@ async fn review_bar( | ||
| 381 | 330 | <label for="review-body">(summary)</label> |
| 382 | 331 | <textarea id="review-body" name="body" rows="3"></textarea> |
| 383 | 332 | </div> |
| 384 | - // An author cannot approve or block their own pull, so they only comment. | |
| 385 | 333 | if !is_author { |
| 386 | 334 | <label class="opt"><input type="radio" name="state" value="approve"><span>(approve)</span></label> |
| 387 | 335 | <label class="opt"><input type="radio" name="state" value="request_changes"><span>(changes)</span></label> |
| @@ -403,7 +351,6 @@ async fn review_bar( | ||
| 403 | 351 | }) |
| 404 | 352 | } |
| 405 | 353 | |
| 406 | -/// The `file=<index>` param: the diff file the Files pane marks as current. | |
| 407 | 354 | fn file_param(cx: &Cx) -> Option<usize> { |
| 408 | 355 | let request = uri(cx); |
| 409 | 356 | let query = request.query()?; |
| @@ -411,6 +358,10 @@ fn file_param(cx: &Cx) -> Option<usize> { | ||
| 411 | 358 | digits::<usize>(&raw) |
| 412 | 359 | } |
| 413 | 360 | |
| 361 | +fn file_href(i: usize) -> String { | |
| 362 | + format!("?file={i}#file-{}", i + 1) | |
| 363 | +} | |
| 364 | + | |
| 414 | 365 | #[page("/{owner}/{repo}/pulls/{number}/files")] |
| 415 | 366 | async fn pull_files(cx: &Cx) -> Result<impl View> { |
| 416 | 367 | let number = parse_number(number(cx))?; |
| @@ -429,8 +380,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 429 | 380 | (add + file.additions, del + file.deletions) |
| 430 | 381 | })); |
| 431 | 382 | let opts = DiffOpts::from_cx(cx, None).await?; |
| 432 | - // The Files pane lists the full diff. Its marks are read here, and its rows are built once the | |
| 433 | - // shown diff is known, since a whitespace-ignoring view may list fewer files. | |
| 434 | 383 | let viewer_user = viewer(&ctx); |
| 435 | 384 | let marks = match &viewer_user { |
| 436 | 385 | Some(user) => Some( |
| @@ -441,12 +390,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 441 | 390 | ), |
| 442 | 391 | None => None, |
| 443 | 392 | }; |
| 444 | - let controls = viewer_user.as_ref().map(|_| ViewedControls { | |
| 445 | - pr_href: frame.href.clone(), | |
| 446 | - csrf: csrf_of(&ctx), | |
| 447 | - }); | |
| 448 | - // With whitespace ignored the file list can shrink, so file indexes differ from the comment | |
| 449 | - // routes' view. Existing threads still show; new inline comments wait for the full diff. | |
| 450 | 393 | let shown_ws = if opts.ignore_ws { |
| 451 | 394 | Some( |
| 452 | 395 | range_diff_files_ws( |
| @@ -484,14 +427,11 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 484 | 427 | Action::Write, |
| 485 | 428 | ) |
| 486 | 429 | .is_ok(); |
| 487 | - // Comments and replies stay open on a closed pull request; new reviews do not. | |
| 488 | 430 | let can_review = can_comment && open; |
| 489 | - // Approve and request changes are offered to every viewer who may review but did not open it. | |
| 490 | 431 | let href = frame.href.clone(); |
| 491 | 432 | let csrf = csrf_of(&ctx); |
| 433 | + let panel = signed_in.then(|| (format!("{href}/viewed"), csrf.clone())); | |
| 492 | 434 | |
| 493 | - // The viewer's own pending comments are included by `review_threads`. Outdated threads are | |
| 494 | - // left out of the Files tab; they still show in the Conversation. | |
| 495 | 435 | let threads = state |
| 496 | 436 | .store |
| 497 | 437 | .review_threads(&pr.issue.id, viewer_id.as_deref()) |
| @@ -521,7 +461,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 521 | 461 | } |
| 522 | 462 | } |
| 523 | 463 | |
| 524 | - // The view owns the diff it shows, so the shown diff moves here once every borrow of it is done. | |
| 525 | 464 | let diff = shown_ws.unwrap_or(full_diff); |
| 526 | 465 | |
| 527 | 466 | let link = link_context(state, &ctx.repo, &ctx.repo.default_branch, ""); |
| @@ -547,7 +486,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 547 | 486 | ctx: thread_ctx, |
| 548 | 487 | }; |
| 549 | 488 | |
| 550 | - // The diff pane has its own top row, so the section's toolbar is left off. | |
| 551 | 489 | let mut section_opts = opts.clone(); |
| 552 | 490 | section_opts.enabled = false; |
| 553 | 491 | section_opts.only = selected; |
| @@ -557,21 +495,13 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 557 | 495 | let split_on = opts.split; |
| 558 | 496 | let ws_on = opts.ignore_ws; |
| 559 | 497 | |
| 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); | |
| 562 | 499 | let live = format!("{href}/events"); |
| 563 | 500 | let owner = ctx.repo.owner_name.clone(); |
| 564 | 501 | let name = ctx.repo.name.clone(); |
| 565 | 502 | let parent = pr.merge_base.clone(); |
| 566 | 503 | 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(); | |
| 575 | 505 | |
| 576 | 506 | let done = rows |
| 577 | 507 | .iter() |
| @@ -596,7 +526,6 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 596 | 526 | let current_path = current.map(|row| row.path.clone()).unwrap_or_default(); |
| 597 | 527 | let current_viewed = current.is_some_and(|row| row.state == MarkState::Viewed); |
| 598 | 528 | let mark_shown = signed_in && !archived && current.is_some(); |
| 599 | - // The next file after the current one that is not viewed, wrapping round. | |
| 600 | 529 | let next = { |
| 601 | 530 | let start = rows |
| 602 | 531 | .iter() |
| @@ -610,9 +539,8 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 610 | 539 | row.index.is_some() && row.index != selected && row.state != MarkState::Viewed |
| 611 | 540 | }) |
| 612 | 541 | .and_then(|row| row.index) |
| 613 | - .map(|i| format!("?file={i}#file-{}", i + 1)) | |
| 542 | + .map(file_href) | |
| 614 | 543 | }; |
| 615 | - // The strip above the diff: one segment per file, sized by its changed lines. | |
| 616 | 544 | let segs: Vec<SegView> = rows |
| 617 | 545 | .iter() |
| 618 | 546 | .map(|row| { |
| @@ -630,9 +558,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 630 | 558 | }; |
| 631 | 559 | SegView { |
| 632 | 560 | 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), | |
| 636 | 562 | label: row.path.clone(), |
| 637 | 563 | } |
| 638 | 564 | }) |
| @@ -656,7 +582,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 656 | 582 | } |
| 657 | 583 | .to_owned(), |
| 658 | 584 | tick, |
| 659 | - href: row.index.map(|i| format!("?file={i}#file-{}", i + 1)), | |
| 585 | + href: row.index.map(file_href), | |
| 660 | 586 | path: row.path, |
| 661 | 587 | label: row.label, |
| 662 | 588 | state: row.state, |
| @@ -675,7 +601,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> { | ||
| 675 | 601 | } |
| 676 | 602 | </div> |
| 677 | 603 | if let Some(message) = error { |
| 678 | - alert(message: message.as_str()) | |
| 604 | + alert(message: message) | |
| 679 | 605 | } |
| 680 | 606 | <div class="work" data-live=(live.as_str()) data-viewed-panel="" data-action=(panel_action.as_str()) data-csrf=(panel_csrf.as_str())> |
| 681 | 607 | files_rail(lang: lang, rows: rail, done_text: viewed_text.clone(), signed_in: signed_in, archived: archived) |
| @@ -719,8 +645,6 @@ mod tests { | ||
| 719 | 645 | format!("__Host-{SESSION_COOKIE}={token}") |
| 720 | 646 | } |
| 721 | 647 | |
| 722 | - /// The page's own `<main>` element. The shell's header echoes the request URL (theme | |
| 723 | - /// form `back` field), so the body checks are scoped to `<main>`. | |
| 724 | 648 | fn page_main(body: &str) -> &str { |
| 725 | 649 | body.split_once("<main tabindex=\"-1\"") |
| 726 | 650 | .and_then(|(_, rest)| rest.split_once('>')) |
| @@ -729,7 +653,6 @@ mod tests { | ||
| 729 | 653 | .expect("page has a <main> element") |
| 730 | 654 | } |
| 731 | 655 | |
| 732 | - /// Sends one GET through the router and returns `(status, body)`. | |
| 733 | 656 | async fn get(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) { |
| 734 | 657 | let mut req = Request::builder().method("GET").uri(uri); |
| 735 | 658 | if let Some(token) = token { |
| @@ -741,7 +664,6 @@ mod tests { | ||
| 741 | 664 | (status, String::from_utf8_lossy(&bytes).into_owned()) |
| 742 | 665 | } |
| 743 | 666 | |
| 744 | - /// A user with a session whose CSRF token is `{token}-csrf`. | |
| 745 | 667 | async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User { |
| 746 | 668 | let user = fx |
| 747 | 669 | .store |
| @@ -753,14 +675,11 @@ mod tests { | ||
| 753 | 675 | user |
| 754 | 676 | } |
| 755 | 677 | |
| 756 | - /// The repo owner, signed in with token `tahinli`. | |
| 757 | 678 | async fn owner_session(fx: &Fixture) { |
| 758 | 679 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 759 | 680 | crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await; |
| 760 | 681 | } |
| 761 | 682 | |
| 762 | - /// Pushes a `feature` branch (one commit adding `feat.txt` with the line `feature`) and opens | |
| 763 | - /// a pull request for it against `main`. Returns the pull request number. | |
| 764 | 683 | async fn open_pull(fx: &Fixture) -> i64 { |
| 765 | 684 | let base_oid = git(&fx.work, &["rev-parse", "HEAD"]); |
| 766 | 685 | git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]); |
| @@ -810,7 +729,6 @@ mod tests { | ||
| 810 | 729 | pr.issue.number |
| 811 | 730 | } |
| 812 | 731 | |
| 813 | - /// The pull request's issue id and head commit. | |
| 814 | 732 | async fn pull_ids(fx: &Fixture, number: i64) -> (String, String) { |
| 815 | 733 | let repo = fx |
| 816 | 734 | .store |
| @@ -831,9 +749,6 @@ mod tests { | ||
| 831 | 749 | format!("/{OWNER}/{REPO}/pulls/{number}/files{query}") |
| 832 | 750 | } |
| 833 | 751 | |
| 834 | - /// Every Files tab scenario for one open pull request. The pull is opened once. Each | |
| 835 | - /// scenario adds only what it needs, and the scenarios that add comments run last in an | |
| 836 | - /// order where no later scenario is confused by an earlier comment. | |
| 837 | 752 | #[tokio::test] |
| 838 | 753 | async fn files_tab_scenarios_on_one_open_pull() { |
| 839 | 754 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -844,7 +759,6 @@ mod tests { | ||
| 844 | 759 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 845 | 760 | let uri = files_uri(number, ""); |
| 846 | 761 | |
| 847 | - // Turkish viewers get the translated review bar. | |
| 848 | 762 | let req = Request::builder() |
| 849 | 763 | .method("GET") |
| 850 | 764 | .uri(uri.as_str()) |
| @@ -856,13 +770,11 @@ mod tests { | ||
| 856 | 770 | let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); |
| 857 | 771 | let body = String::from_utf8_lossy(&bytes).into_owned(); |
| 858 | 772 | assert!(body.contains("İncelemeyi tamamla"), "turkish bar: {body}"); |
| 859 | - // With nothing pending there is nothing to discard. | |
| 860 | 773 | assert!( |
| 861 | 774 | !body.contains("Bekleyen yorumları sil"), |
| 862 | 775 | "turkish bar: {body}" |
| 863 | 776 | ); |
| 864 | 777 | |
| 865 | - // Signed-in viewer: line anchors and plus links. | |
| 866 | 778 | let (status, body) = get(&fx.router, &uri, Some("tahinli")).await; |
| 867 | 779 | assert_eq!(status, 200, "anchors"); |
| 868 | 780 | assert!(body.contains("id=\"L-0-new-1\""), "anchors: {body}"); |
| @@ -872,7 +784,6 @@ mod tests { | ||
| 872 | 784 | ); |
| 873 | 785 | assert!(body.contains("id=\"review-form\""), "review bar: {body}"); |
| 874 | 786 | |
| 875 | - // A well-formed `comment` param opens the form under its line. | |
| 876 | 787 | let (status, body) = get( |
| 877 | 788 | &fx.router, |
| 878 | 789 | &files_uri(number, "?comment=0:new:1"), |
| @@ -896,7 +807,6 @@ mod tests { | ||
| 896 | 807 | let form = body.find("name=\"file_index\"").unwrap(); |
| 897 | 808 | assert!(form > line, "the form sits after its line"); |
| 898 | 809 | |
| 899 | - // Malformed `comment` params are ignored. | |
| 900 | 810 | for query in [ |
| 901 | 811 | "?comment=abc", |
| 902 | 812 | "?comment=0:bogus:1", |
| @@ -911,7 +821,6 @@ mod tests { | ||
| 911 | 821 | assert!(!body.contains("name=\"file_index\""), "garbage {query}"); |
| 912 | 822 | } |
| 913 | 823 | |
| 914 | - // The review bar hides approve from the pull's author only. | |
| 915 | 824 | let (_, author) = get(&fx.router, &uri, Some("tahinli")).await; |
| 916 | 825 | assert!(author.contains("value=\"comment\""), "author bar: {author}"); |
| 917 | 826 | assert!( |
| @@ -929,7 +838,6 @@ mod tests { | ||
| 929 | 838 | "reader bar: {other}" |
| 930 | 839 | ); |
| 931 | 840 | |
| 932 | - // Anonymous viewers get no comment controls at all. | |
| 933 | 841 | let (status, body) = get(&fx.router, &files_uri(number, "?comment=0:new:1"), None).await; |
| 934 | 842 | assert_eq!(status, 200, "anonymous"); |
| 935 | 843 | assert!(!page_main(&body).contains("?comment="), "anonymous: {body}"); |
| @@ -938,7 +846,6 @@ mod tests { | ||
| 938 | 846 | assert!(!body.contains("id=\"review-form\""), "anonymous: {body}"); |
| 939 | 847 | assert!(!body.contains("class=\"diff-plus\""), "anonymous: {body}"); |
| 940 | 848 | |
| 941 | - // A known review error shows its message, an unknown code shows nothing. | |
| 942 | 849 | let (_, known) = get( |
| 943 | 850 | &fx.router, |
| 944 | 851 | &files_uri(number, "?review_error=own_pr"), |
| @@ -959,7 +866,6 @@ mod tests { | ||
| 959 | 866 | ); |
| 960 | 867 | assert!(!unknown.contains("<b>hi</b>"), "unknown error: {unknown}"); |
| 961 | 868 | |
| 962 | - // An outdated thread is hidden. Only the outdated comment exists at this point. | |
| 963 | 869 | let comment = fx |
| 964 | 870 | .store |
| 965 | 871 | .add_review_comment( |
| @@ -987,7 +893,6 @@ mod tests { | ||
| 987 | 893 | "outdated: {body}" |
| 988 | 894 | ); |
| 989 | 895 | |
| 990 | - // A pending comment is visible only to its author. | |
| 991 | 896 | fx.store |
| 992 | 897 | .add_review_comment( |
| 993 | 898 | &issue_id, |
| @@ -1014,7 +919,6 @@ mod tests { | ||
| 1014 | 919 | "pending author: {author}" |
| 1015 | 920 | ); |
| 1016 | 921 | |
| 1017 | - // A submitted thread renders under its line. | |
| 1018 | 922 | fx.store |
| 1019 | 923 | .add_review_comment( |
| 1020 | 924 | &issue_id, |
crates/forge-web-repo/src/pages/pull_flow.rsmodified+5 -9
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | //! or approvals that can still arrive. All of them answer with a redirect back to the pull |
| 11 | 11 | //! request (the soft-nav script follows it without a reload). |
| 12 | 12 | |
| 13 | -use forge_core::{Action, IssueState, MergeStyle, PullRequest, authorize}; | |
| 13 | +use forge_core::{IssueState, MergeStyle, PullRequest}; | |
| 14 | 14 | use serde::Deserialize; |
| 15 | 15 | use topcoat::Result; |
| 16 | 16 | use topcoat::context::{Cx, context}; |
| @@ -40,7 +40,7 @@ struct FlowForm { | ||
| 40 | 40 | style: String, |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | -fn pull_href(ctx: &RepoCtx, number: i64) -> String { | |
| 43 | +pub(crate) fn pull_href(ctx: &RepoCtx, number: i64) -> String { | |
| 44 | 44 | repo_href( |
| 45 | 45 | &ctx.repo.owner_name, |
| 46 | 46 | &ctx.repo.name, |
| @@ -49,10 +49,6 @@ fn pull_href(ctx: &RepoCtx, number: i64) -> String { | ||
| 49 | 49 | ) |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | -fn can_write(ctx: &RepoCtx, user: &forge_core::User) -> bool { | |
| 53 | - authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok() | |
| 54 | -} | |
| 55 | - | |
| 56 | 52 | async fn load(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> { |
| 57 | 53 | let state = context::<AppState>(cx); |
| 58 | 54 | match state.store.pull_by_number(&ctx.repo.id, number).await? { |
| @@ -77,7 +73,7 @@ async fn set_draft(cx: &Cx, csrf: &str, draft: bool) -> Result<Response> { | ||
| 77 | 73 | let (user, _) = require_csrf(cx, csrf).await?; |
| 78 | 74 | let state = context::<AppState>(cx); |
| 79 | 75 | let pr = load(cx, &ctx, number).await?; |
| 80 | - if ctx.repo.archived || !(can_write(&ctx, &user) || user.id == pr.issue.author_id) { | |
| 76 | + if ctx.repo.archived || !(ctx.can_write() || user.id == pr.issue.author_id) { | |
| 81 | 77 | return Err(forbidden().into()); |
| 82 | 78 | } |
| 83 | 79 | let href = pull_href(&ctx, number); |
| @@ -121,7 +117,7 @@ async fn auto_merge_enable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Respon | ||
| 121 | 117 | let number = parse_number(number(cx))?; |
| 122 | 118 | let ctx = load_repo(cx, owner(cx), repo(cx)).await?; |
| 123 | 119 | let (user, _) = require_csrf(cx, &form.csrf).await?; |
| 124 | - if ctx.repo.archived || !can_write(&ctx, &user) { | |
| 120 | + if !ctx.can_write() { | |
| 125 | 121 | return Err(forbidden().into()); |
| 126 | 122 | } |
| 127 | 123 | let state = context::<AppState>(cx); |
| @@ -152,7 +148,7 @@ async fn auto_merge_disable(cx: &Cx, Form(form): Form<FlowForm>) -> Result<Respo | ||
| 152 | 148 | let number = parse_number(number(cx))?; |
| 153 | 149 | let ctx = load_repo(cx, owner(cx), repo(cx)).await?; |
| 154 | 150 | let (user, _) = require_csrf(cx, &form.csrf).await?; |
| 155 | - if ctx.repo.archived || !can_write(&ctx, &user) { | |
| 151 | + if !ctx.can_write() { | |
| 156 | 152 | return Err(forbidden().into()); |
| 157 | 153 | } |
| 158 | 154 | let state = context::<AppState>(cx); |
crates/forge-web-repo/src/pages/pull_view.rsmodified+29 -38
| @@ -29,7 +29,7 @@ use crate::merge::{ | ||
| 29 | 29 | ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, |
| 30 | 30 | merge_gate, |
| 31 | 31 | }; |
| 32 | -use crate::pages::commits::{CommitRow, now_secs}; | |
| 32 | +use crate::pages::commits::CommitRow; | |
| 33 | 33 | use crate::pages::issue_meta::item_href; |
| 34 | 34 | use crate::pages::issue_parts::{ |
| 35 | 35 | CommentForm, ItemKind, Posted, check_write, comment_form, csrf_of, discussion_timeline, |
| @@ -38,7 +38,7 @@ use crate::pages::issue_parts::{ | ||
| 38 | 38 | }; |
| 39 | 39 | use crate::pages::notifications::notify_box_for; |
| 40 | 40 | use crate::pages::pull_branch::{self, branch_box, branch_error_from}; |
| 41 | -use crate::pages::pull_reviews::error_text_in; | |
| 41 | +use crate::pages::pull_reviews::error_from; | |
| 42 | 42 | use crate::pages::repo_ctx::{RepoCtx, load_repo}; |
| 43 | 43 | use crate::pages::review_requests::{load_reviewers, reviewers_box}; |
| 44 | 44 | use crate::state::AppState; |
| @@ -315,6 +315,20 @@ struct FlowView { | ||
| 315 | 315 | queue_add: Option<String>, |
| 316 | 316 | } |
| 317 | 317 | |
| 318 | +#[component] | |
| 319 | +async fn style_select(cx: &Cx, id: &str, lang: Lang) -> Result<impl View> { | |
| 320 | + let merge = g::t(lang, K::StyleMergeCommit).trim(); | |
| 321 | + let squash = g::t(lang, K::StyleSquash).trim(); | |
| 322 | + let rebase = g::t(lang, K::StyleRebase).trim(); | |
| 323 | + Ok(view! { | |
| 324 | + <select id=(id) name="style"> | |
| 325 | + <option value="merge">(merge)</option> | |
| 326 | + <option value="squash">(squash)</option> | |
| 327 | + <option value="rebase">(rebase)</option> | |
| 328 | + </select> | |
| 329 | + }) | |
| 330 | +} | |
| 331 | + | |
| 318 | 332 | /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of |
| 319 | 333 | /// `ok`, `bad` or `muted` and picks the box colors. |
| 320 | 334 | #[component] |
| @@ -335,8 +349,6 @@ async fn merge_box( | ||
| 335 | 349 | let class = format!("sec merge-{tone}"); |
| 336 | 350 | let required_heading = g::t(lang, K::RequiredChecksHeading); |
| 337 | 351 | let style_rebase = g::t(lang, K::StyleRebase); |
| 338 | - let style_merge_option = g::t(lang, K::StyleMergeCommit); | |
| 339 | - let style_squash_option = g::t(lang, K::StyleSquash); | |
| 340 | 352 | let enable_auto = g::t(lang, K::EnableAutoMerge); |
| 341 | 353 | let disable_auto = g::t(lang, K::DisableAutoMerge); |
| 342 | 354 | let FlowView { |
| @@ -425,11 +437,7 @@ async fn merge_box( | ||
| 425 | 437 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 426 | 438 | <div class="field"> |
| 427 | 439 | <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) | |
| 433 | 441 | </div> |
| 434 | 442 | <button type="submit" class="primary">(queue_add_label)</button> |
| 435 | 443 | </form> |
| @@ -445,11 +453,7 @@ async fn merge_box( | ||
| 445 | 453 | <input type="hidden" name="csrf" value=(flow_csrf.as_str())> |
| 446 | 454 | <div class="field"> |
| 447 | 455 | <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) | |
| 453 | 457 | </div> |
| 454 | 458 | <button type="submit" class="primary">(enable_auto)</button> |
| 455 | 459 | </form> |
| @@ -693,19 +697,15 @@ async fn pull_conversation( | ||
| 693 | 697 | // outdated head does not block it. |
| 694 | 698 | let queue_required = |
| 695 | 699 | 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); | |
| 709 | 709 | let approvals = gate |
| 710 | 710 | .as_ref() |
| 711 | 711 | .filter(|gate| gate.rule.required_approvals > 0) |
| @@ -857,7 +857,7 @@ async fn pull_conversation( | ||
| 857 | 857 | .then(|| format!("/{owner}/{name}/commit/{oid}")), |
| 858 | 858 | }; |
| 859 | 859 | |
| 860 | - let review_error = review_error_from(lang, cx); | |
| 860 | + let review_error = error_from(lang, cx); | |
| 861 | 861 | let summary = state.store.review_summary(&pr.issue.id).await?; |
| 862 | 862 | // Approvals of an earlier head no longer count for the merge rules (see `merge_gate`), so |
| 863 | 863 | // they are listed apart from the current ones. |
| @@ -990,15 +990,6 @@ fn merge_error_from(lang: Lang, cx: &Cx) -> Option<String> { | ||
| 990 | 990 | merge_error_text(lang, &code).map(str::to_owned) |
| 991 | 991 | } |
| 992 | 992 | |
| 993 | -/// The message for the `review_error` query value of the request, when it is a known code. | |
| 994 | -fn review_error_from(lang: Lang, cx: &Cx) -> Option<&'static str> { | |
| 995 | - let request = uri(cx); | |
| 996 | - let query = request.query()?; | |
| 997 | - let (_, code) = | |
| 998 | - form_urlencoded::parse(query.as_bytes()).find(|(key, _)| *key == "review_error")?; | |
| 999 | - error_text_in(lang, &code) | |
| 1000 | -} | |
| 1001 | - | |
| 1002 | 993 | #[page("/{owner}/{repo}/pulls/{number}")] |
| 1003 | 994 | async fn pull_show(cx: &Cx) -> Result<impl View> { |
| 1004 | 995 | let (ctx, pr) = load_pull(cx).await?; |
| @@ -1019,7 +1010,7 @@ async fn pull_commits(cx: &Cx) -> Result<impl View> { | ||
| 1019 | 1010 | let owner = ctx.repo.owner_name.clone(); |
| 1020 | 1011 | let name = ctx.repo.name.clone(); |
| 1021 | 1012 | let tz = ctx.viewer_tz().to_owned(); |
| 1022 | - let now = now_secs(); | |
| 1013 | + let now = now_unix(); | |
| 1023 | 1014 | let oids: Vec<&str> = commits.iter().map(|info| info.oid.as_str()).collect(); |
| 1024 | 1015 | let statuses = state |
| 1025 | 1016 | .store |
crates/forge-web-repo/src/pages/pulls_list.rsmodified+3 -2
| @@ -17,14 +17,15 @@ use crate::i18n::pulls::{self as g, K}; | ||
| 17 | 17 | use crate::i18n::s; |
| 18 | 18 | use crate::i18n::{self, Lang}; |
| 19 | 19 | use crate::pages::issues_list::{ |
| 20 | - AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href, stamp_unix, | |
| 20 | + AssigneeView, LabelView, ListQuery, MilestoneView, Selection, SortOption, list_href, | |
| 21 | 21 | }; |
| 22 | 22 | use crate::pages::repo::repo_head; |
| 23 | 23 | use crate::pages::repo_ctx::load_repo; |
| 24 | 24 | use crate::state::AppState; |
| 25 | 25 | use crate::views::parts::{RailItem, SubPart, rail}; |
| 26 | 26 | use crate::views::{ |
| 27 | - avatar_url_unknown, iso_time, now_unix, relative_time, repo_href, shell, user_link, | |
| 27 | + avatar_url_unknown, iso_time, now_unix, relative_time, repo_href, shell, stamp_unix, | |
| 28 | + user_link, | |
| 28 | 29 | }; |
| 29 | 30 | |
| 30 | 31 | path_param!(owner); |
crates/forge-web-repo/src/pages/reactions.rsmodified+1 -5
| @@ -66,11 +66,7 @@ async fn react(cx: &Cx, kind: ItemKind, form: ReactionForm) -> Result<SeeOther> | ||
| 66 | 66 | if form.target_id != item.id { |
| 67 | 67 | return Err(not_found().into()); |
| 68 | 68 | } |
| 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)) | |
| 74 | 70 | } |
| 75 | 71 | "comment" => { |
| 76 | 72 | let comment = comment_for(state, &item, &form.target_id).await?; |
crates/forge-web-repo/src/pages/repo_collaborators.rsmodified+6 -15
| @@ -31,7 +31,7 @@ use crate::pages::repo_settings::settings_frame; | ||
| 31 | 31 | use crate::pages::repo_settings_live::settings_head; |
| 32 | 32 | use crate::state::AppState; |
| 33 | 33 | use crate::views::parts::{PeopleList, PersonRow, people_list}; |
| 34 | -use crate::views::{alert, avatar_url, display_name, shell}; | |
| 34 | +use crate::views::{avatar_url, display_name, notice_line, shell}; | |
| 35 | 35 | |
| 36 | 36 | path_param!(owner); |
| 37 | 37 | path_param!(repo); |
| @@ -128,11 +128,6 @@ async fn owns_repo_org(state: &AppState, ctx: &RepoCtx, actor: &User) -> Result< | ||
| 128 | 128 | )) |
| 129 | 129 | } |
| 130 | 130 | |
| 131 | -/// `Owner/name` for redirects and form actions. | |
| 132 | -fn title_of(ctx: &RepoCtx) -> String { | |
| 133 | - format!("{}/{}", ctx.repo.owner_name, ctx.repo.name) | |
| 134 | -} | |
| 135 | - | |
| 136 | 131 | fn collaborators_redirect(title: &str) -> SeeOther { |
| 137 | 132 | see_other(format!("/{title}/settings/collaborators")) |
| 138 | 133 | } |
| @@ -146,7 +141,7 @@ struct FrameData { | ||
| 146 | 141 | |
| 147 | 142 | impl FrameData { |
| 148 | 143 | async fn new(ctx: &RepoCtx, state: &AppState, lang: Lang) -> Result<Self> { |
| 149 | - let title = title_of(ctx); | |
| 144 | + let title = ctx.title(); | |
| 150 | 145 | Ok(Self { |
| 151 | 146 | page_title: g::collaborators_page_title(lang, &title), |
| 152 | 147 | title, |
| @@ -215,11 +210,7 @@ async fn collaborators_body( | ||
| 215 | 210 | repo_head(head: header, title: Some(section_name)) |
| 216 | 211 | settings_frame(lang: lang, title: nav_title, current: "collaborators", |
| 217 | 212 | 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) | |
| 223 | 214 | } |
| 224 | 215 | people_list(list: list) |
| 225 | 216 | ) |
| @@ -282,7 +273,7 @@ async fn collaborators_add(cx: &Cx, Form(form): Form<AddForm>) -> Result<SeeOthe | ||
| 282 | 273 | if !ctx.can_admin() { |
| 283 | 274 | return Err(forbidden().into()); |
| 284 | 275 | } |
| 285 | - let title = title_of(&ctx); | |
| 276 | + let title = ctx.title(); | |
| 286 | 277 | let state = context::<AppState>(cx); |
| 287 | 278 | |
| 288 | 279 | let Ok(role) = form.role.trim().parse::<Role>() else { |
| @@ -368,7 +359,7 @@ async fn collaborators_role(cx: &Cx, Form(form): Form<RoleForm>) -> Result<SeeOt | ||
| 368 | 359 | if !ctx.can_admin() { |
| 369 | 360 | return Err(forbidden().into()); |
| 370 | 361 | } |
| 371 | - let title = title_of(&ctx); | |
| 362 | + let title = ctx.title(); | |
| 372 | 363 | let state = context::<AppState>(cx); |
| 373 | 364 | |
| 374 | 365 | let Ok(role) = form.role.trim().parse::<Role>() else { |
| @@ -429,7 +420,7 @@ async fn collaborators_remove(cx: &Cx, Form(form): Form<RemoveForm>) -> Result<S | ||
| 429 | 420 | if !ctx.can_admin() { |
| 430 | 421 | return Err(forbidden().into()); |
| 431 | 422 | } |
| 432 | - let title = title_of(&ctx); | |
| 423 | + let title = ctx.title(); | |
| 433 | 424 | let state = context::<AppState>(cx); |
| 434 | 425 | let target_id = form.user_id.trim(); |
| 435 | 426 | let self_removal = target_id == actor.id; |
crates/forge-web-repo/src/pages/repo_secrets.rsmodified+8 -27
| @@ -30,7 +30,7 @@ path_param!(owner); | ||
| 30 | 30 | path_param!(repo); |
| 31 | 31 | |
| 32 | 32 | /// Longest secret value accepted, in bytes. |
| 33 | -pub const MAX_VALUE_BYTES: usize = 48 * 1024; | |
| 33 | +const MAX_VALUE_BYTES: usize = 48 * 1024; | |
| 34 | 34 | /// Longest secret name accepted, in characters. |
| 35 | 35 | const MAX_NAME_CHARS: usize = 64; |
| 36 | 36 | |
| @@ -60,7 +60,7 @@ struct DeleteForm { | ||
| 60 | 60 | } |
| 61 | 61 | |
| 62 | 62 | /// `^[A-Z_][A-Z0-9_]{0,63}$`, checked by hand so no regex engine is needed. |
| 63 | -pub fn valid_name(name: &str) -> bool { | |
| 63 | +fn valid_name(name: &str) -> bool { | |
| 64 | 64 | let bytes = name.as_bytes(); |
| 65 | 65 | let Some((first, rest)) = bytes.split_first() else { |
| 66 | 66 | return false; |
| @@ -231,19 +231,14 @@ async fn secrets_body( | ||
| 231 | 231 | } |
| 232 | 232 | <div> |
| 233 | 233 | 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 { | |
| 243 | 238 | confirm_act(lang: lang, label: g::t(lang, K::Delete), action: delete_action.as_str(), csrf: csrf.as_str(), |
| 244 | 239 | fields: vec![("name".to_owned(), row.name.clone())]) |
| 245 | - </div> | |
| 246 | - } | |
| 240 | + } | |
| 241 | + </div> | |
| 247 | 242 | } |
| 248 | 243 | </div> |
| 249 | 244 | </section> |
| @@ -615,20 +610,6 @@ mod tests { | ||
| 615 | 610 | async fn bad_name_and_bad_value_are_rejected() { |
| 616 | 611 | let dir = tempfile::tempdir().expect("tempdir"); |
| 617 | 612 | let (store, app, repo) = fixture(dir.path()).await; |
| 618 | - let too_long = format!("A{}", "1".repeat(64)); | |
| 619 | - for name in ["", "lower", "1NUM", "A-B", too_long.as_str()] { | |
| 620 | - let (status, _, body) = send( | |
| 621 | - &app, | |
| 622 | - "POST", | |
| 623 | - PAGE, | |
| 624 | - Some("tahinli-token"), | |
| 625 | - &[("name", name), ("value", "v")], | |
| 626 | - None, | |
| 627 | - ) | |
| 628 | - .await; | |
| 629 | - assert_eq!(status, 200, "{name:?} re-renders the form"); | |
| 630 | - assert!(body.contains("Names are 1 to 64 characters"), "{name:?}"); | |
| 631 | - } | |
| 632 | 613 | let (_, _, body) = send( |
| 633 | 614 | &app, |
| 634 | 615 | "POST", |
crates/forge-web-repo/src/pages/repo_webhooks.rsmodified+25 -58
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | //! and response. A hook's secret is sealed with the instance key and is never shown again: a blank |
| 5 | 5 | //! secret on edit keeps the stored one. Archived repos show everything but change nothing. |
| 6 | 6 | |
| 7 | +use std::collections::HashMap; | |
| 8 | + | |
| 7 | 9 | use forge_core::AuditAction; |
| 8 | 10 | use forge_core::secret; |
| 9 | 11 | use forge_core::tz::format_in_tz; |
| @@ -69,7 +71,6 @@ const EVENT_CHOICES: [(WebhookEvent, K); 8] = [ | ||
| 69 | 71 | (WebhookEvent::Release, K::EvRelease), |
| 70 | 72 | ]; |
| 71 | 73 | |
| 72 | -/// The hook form. Unticked boxes are absent from the body, so each event has an `Option`. | |
| 73 | 74 | #[derive(Deserialize)] |
| 74 | 75 | struct HookForm { |
| 75 | 76 | #[serde(default)] |
| @@ -81,44 +82,18 @@ struct HookForm { | ||
| 81 | 82 | secret: String, |
| 82 | 83 | #[serde(default)] |
| 83 | 84 | 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>, | |
| 100 | 87 | } |
| 101 | 88 | |
| 102 | 89 | impl HookForm { |
| 103 | 90 | /// The ticked events, in the form's order. |
| 104 | 91 | 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() | |
| 122 | 97 | } |
| 123 | 98 | } |
| 124 | 99 | |
| @@ -339,15 +314,17 @@ fn hook_row( | ||
| 339 | 314 | tz: &str, |
| 340 | 315 | title: &str, |
| 341 | 316 | hook: Webhook, |
| 342 | - last: Option<(&'static str, &'static str)>, | |
| 317 | + last: Option<DeliveryState>, | |
| 343 | 318 | last_stamp: &str, |
| 344 | 319 | ) -> 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", | |
| 350 | 326 | }; |
| 327 | + let dot_text = last.map_or(g::t(lang, K::NoneYet), |state| state_label(lang, state).1); | |
| 351 | 328 | let (last_text, last_rel) = match (last, last_stamp) { |
| 352 | 329 | (Some(_), stamp) if !stamp.is_empty() => { |
| 353 | 330 | let rel = OffsetDateTime::parse(stamp, &Rfc3339) |
| @@ -381,8 +358,8 @@ fn hook_row( | ||
| 381 | 358 | last_full: local_stamp(last_stamp, tz), |
| 382 | 359 | last_rel, |
| 383 | 360 | problem: match last { |
| 384 | - Some(("ok", _)) | None => "", | |
| 385 | - Some((_, text)) => text, | |
| 361 | + None | Some(DeliveryState::Ok) => "", | |
| 362 | + Some(state) => state_label(lang, state).1, | |
| 386 | 363 | }, |
| 387 | 364 | inactive_text: match lang { |
| 388 | 365 | Lang::En => "inactive", |
| @@ -750,19 +727,7 @@ async fn hooks_list_page(cx: &Cx) -> Result<impl View> { | ||
| 750 | 727 | let tz = ctx.viewer_tz(); |
| 751 | 728 | let mut rows: Vec<HookRow> = Vec::with_capacity(hooks.len()); |
| 752 | 729 | 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)); | |
| 766 | 731 | rows.push(hook_row(lang, tz, &frame.title, hook, last, &last_stamp)); |
| 767 | 732 | } |
| 768 | 733 | let notice = notice_from_query(cx, lang); |
| @@ -816,9 +781,11 @@ async fn hook_new_body( | ||
| 816 | 781 | <a class="act quiet" href=(back.as_str())>(g::t(lang, K::BackToWebhooks))</a> |
| 817 | 782 | </div> |
| 818 | 783 | </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 | + } | |
| 822 | 789 | ) |
| 823 | 790 | }) |
| 824 | 791 | } |
crates/forge-web-repo/src/pages/review_requests.rsmodified+33 -29
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | //! clears the reviewer's own request in the store. |
| 6 | 6 | |
| 7 | 7 | use forge_core::authz::{Action, authorize}; |
| 8 | +use forge_core::{Repo, User}; | |
| 8 | 9 | use serde::Deserialize; |
| 9 | 10 | use topcoat::Result; |
| 10 | 11 | use topcoat::context::{Cx, context}; |
| @@ -99,16 +100,7 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt | ||
| 99 | 100 | if target.id == pull.author_id { |
| 100 | 101 | return Ok(refusal("author", &href)); |
| 101 | 102 | } |
| 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? { | |
| 112 | 104 | return Ok(refusal("access", &href)); |
| 113 | 105 | } |
| 114 | 106 | if state |
| @@ -124,6 +116,15 @@ async fn reviewers_save(cx: &Cx, Form(form): Form<ReviewerForm>) -> Result<SeeOt | ||
| 124 | 116 | Ok(see_other(format!("{href}#reviewers"))) |
| 125 | 117 | } |
| 126 | 118 | |
| 119 | +async fn can_read_repo(state: &AppState, viewer: &User, repo: &Repo) -> Result<bool> { | |
| 120 | + let role = state.store.collaborator_role(&repo.id, &viewer.id).await?; | |
| 121 | + let org_role = state | |
| 122 | + .store | |
| 123 | + .org_repo_role(&repo.owner_id, &viewer.id, &repo.id) | |
| 124 | + .await?; | |
| 125 | + Ok(authorize(Some(viewer), repo, role, org_role, Action::Read).is_ok()) | |
| 126 | +} | |
| 127 | + | |
| 127 | 128 | /// What the Reviewers box shows. |
| 128 | 129 | pub(crate) struct ReviewersView { |
| 129 | 130 | pub(crate) action: String, |
| @@ -227,6 +228,14 @@ pub(crate) async fn reviewers_box( | ||
| 227 | 228 | }) |
| 228 | 229 | } |
| 229 | 230 | |
| 231 | +struct ReviewRow { | |
| 232 | + repo_full: String, | |
| 233 | + href: String, | |
| 234 | + title: String, | |
| 235 | + requested_by: String, | |
| 236 | + created_at: String, | |
| 237 | +} | |
| 238 | + | |
| 230 | 239 | /// The open pull requests waiting for the viewer's review, newest request first. |
| 231 | 240 | #[page("/review-requests")] |
| 232 | 241 | async fn review_requests(cx: &Cx) -> Result<impl View> { |
| @@ -245,26 +254,21 @@ async fn review_requests(cx: &Cx) -> Result<impl View> { | ||
| 245 | 254 | else { |
| 246 | 255 | continue; |
| 247 | 256 | }; |
| 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? { | |
| 254 | 258 | continue; |
| 255 | 259 | } |
| 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( | |
| 259 | 263 | &item.repo_owner, |
| 260 | 264 | &item.repo_name, |
| 261 | - "pulls", | |
| 265 | + ItemKind::Pull.segment(), | |
| 262 | 266 | &item.number.to_string(), |
| 263 | 267 | ), |
| 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 | + }); | |
| 268 | 272 | } |
| 269 | 273 | let heading = ga::t(lang, AK::ReviewRequests); |
| 270 | 274 | let empty = rows.is_empty(); |
| @@ -280,11 +284,11 @@ async fn review_requests(cx: &Cx) -> Result<impl View> { | ||
| 280 | 284 | <p class="state">(ga::t(lang, AK::NoReviewRequests))</p> |
| 281 | 285 | } |
| 282 | 286 | 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> | |
| 288 | 292 | </a> |
| 289 | 293 | } |
| 290 | 294 | </div> |
crates/forge-web/src/admin_cli.rsmodified+3 -7
| @@ -40,13 +40,13 @@ const TEMPORARY_PASSWORD_CHARS: usize = 20; | ||
| 40 | 40 | |
| 41 | 41 | const MIN_PASSWORD_CHARS: usize = 12; |
| 42 | 42 | |
| 43 | -/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty. | |
| 44 | 43 | /// Refusal text for admin commands that would give a login to an organization. |
| 45 | 44 | const ORG_NO_LOGIN: &str = |
| 46 | 45 | "an organization cannot sign in, so it has no password or login name here"; |
| 47 | 46 | /// Refusal text for `create-user` on a name that an organization already holds. |
| 48 | 47 | const ORG_NAME_TAKEN: &str = "that name belongs to an organization"; |
| 49 | 48 | |
| 49 | +/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty. | |
| 50 | 50 | pub async fn create_user( |
| 51 | 51 | config_path: &Path, |
| 52 | 52 | username: &str, |
| @@ -74,8 +74,6 @@ pub async fn create_user( | ||
| 74 | 74 | } |
| 75 | 75 | |
| 76 | 76 | let hash = hash_password_async(pw).await?; |
| 77 | - // The first user is always an admin. The insert is atomic, so a concurrent creator falls | |
| 78 | - // through to the ordinary path instead of racing into a second admin. | |
| 79 | 77 | let user = match store.create_first_admin(&username, None, &hash).await? { |
| 80 | 78 | Some(user) => user, |
| 81 | 79 | None => { |
| @@ -117,7 +115,6 @@ pub async fn create_user( | ||
| 117 | 115 | pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> { |
| 118 | 116 | let config = Config::load(config_path)?; |
| 119 | 117 | let store = Store::open(&config.database).await?; |
| 120 | - // The id is gone once the account is deleted, so it is read first. | |
| 121 | 118 | let user_id = store.user_by_username(username).await?.map(|u| u.id); |
| 122 | 119 | let report = delete_user_in(&store, username, yes).await?; |
| 123 | 120 | if let Some(id) = user_id { |
| @@ -134,7 +131,7 @@ pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge | ||
| 134 | 131 | /// The store-level part of [`delete_user`]. Returns the report of what was (or, with `yes` |
| 135 | 132 | /// unset, would be) done. Without `yes` nothing is written and an error is returned, so the |
| 136 | 133 | /// command exits nonzero. The ghost account is not created by a dry run. |
| 137 | -pub async fn delete_user_in( | |
| 134 | +async fn delete_user_in( | |
| 138 | 135 | store: &Store, |
| 139 | 136 | username: &str, |
| 140 | 137 | yes: bool, |
| @@ -258,7 +255,7 @@ pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::R | ||
| 258 | 255 | } |
| 259 | 256 | |
| 260 | 257 | /// The store-level part of [`reset_password`]. Returns the new password and the display name. |
| 261 | -pub async fn reset_password_in( | |
| 258 | +async fn reset_password_in( | |
| 262 | 259 | store: &Store, |
| 263 | 260 | username: &str, |
| 264 | 261 | ) -> forge_core::Result<(String, String)> { |
| @@ -574,7 +571,6 @@ pub async fn backup_verify(path: &Path) -> forge_core::Result<()> { | ||
| 574 | 571 | .parent() |
| 575 | 572 | .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))? |
| 576 | 573 | .to_path_buf(); |
| 577 | - // Git runs with the set's parent as its HOME, so no user gitconfig is read. | |
| 578 | 574 | let git = GitEnv { |
| 579 | 575 | git_bin: find_git(), |
| 580 | 576 | data_dir: parent, |
crates/forge-web/src/boot.rsmodified+7 -0
| @@ -47,6 +47,13 @@ pub async fn serve( | ||
| 47 | 47 | // The data dir holds the instance key and the internal socket. Keep it private to this user. |
| 48 | 48 | std::fs::set_permissions(&config.data_dir, std::fs::Permissions::from_mode(0o700))?; |
| 49 | 49 | let data_dir = config.data_dir.canonicalize()?; |
| 50 | + let data_lock = std::fs::File::create(data_dir.join("forge.lock"))?; | |
| 51 | + data_lock.try_lock().map_err(|e| { | |
| 52 | + forge_core::Error::Config(format!( | |
| 53 | + "another forge server already uses {}: {e}", | |
| 54 | + data_dir.display() | |
| 55 | + )) | |
| 56 | + })?; | |
| 50 | 57 | |
| 51 | 58 | let key = Arc::new(secret::load_or_create_key(&data_dir.join("forge.key"))?); |
| 52 | 59 | let store = Store::open(&config.database).await?; |
crates/forge-web/src/importer_route_tests.rsmodified+22 -13
| @@ -24,6 +24,14 @@ use crate::test_support::{app_router, create_session, test_state}; | ||
| 24 | 24 | |
| 25 | 25 | const TOKEN: &str = "ghp_supersecret_token_value"; |
| 26 | 26 | |
| 27 | +fn all_issues() -> IssueFilter { | |
| 28 | + IssueFilter { | |
| 29 | + state: None, | |
| 30 | + per_page: 100, | |
| 31 | + ..IssueFilter::default() | |
| 32 | + } | |
| 33 | +} | |
| 34 | + | |
| 27 | 35 | #[derive(Default)] |
| 28 | 36 | struct Fake { |
| 29 | 37 | labels: Vec<ExtLabel>, |
| @@ -343,12 +351,10 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() { | ||
| 343 | 351 | let job = store.import_job(&job.id).await.unwrap().unwrap(); |
| 344 | 352 | assert_eq!(job.state, ImportState::Done, "{:?}", job.error); |
| 345 | 353 | |
| 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(); | |
| 352 | 358 | assert_eq!(total, 2); |
| 353 | 359 | let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); |
| 354 | 360 | assert_eq!(issue.issue.state, IssueState::Closed); |
| @@ -407,7 +413,10 @@ async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() { | ||
| 407 | 413 | .await; |
| 408 | 414 | let again = store.import_job(&again.id).await.unwrap().unwrap(); |
| 409 | 415 | assert_eq!(again.state, ImportState::Done, "{:?}", again.error); |
| 410 | - let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); | |
| 416 | + let (items, total) = store | |
| 417 | + .list_issues(&fx.repo.id, &all_issues()) | |
| 418 | + .await | |
| 419 | + .unwrap(); | |
| 411 | 420 | assert_eq!(total, 2); |
| 412 | 421 | let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); |
| 413 | 422 | assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1); |
| @@ -456,12 +465,12 @@ async fn a_rate_limit_fails_the_job_clearly_and_a_retry_finishes_it() { | ||
| 456 | 465 | let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); |
| 457 | 466 | assert_eq!(done.state, ImportState::Done, "{:?}", done.error); |
| 458 | 467 | 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(); | |
| 465 | 474 | assert_eq!(total, 2); |
| 466 | 475 | } |
| 467 | 476 |
crates/forge-web/src/main.rsmodified+11 -25
| @@ -94,25 +94,11 @@ fn parse_args( | ||
| 94 | 94 | /// the binary, never the unit, so the server sets it itself: `serve` re-runs itself once with the |
| 95 | 95 | /// variable set (same PID, so systemd is unaffected). An explicit value is left alone, and |
| 96 | 96 | /// short-lived commands such as `hook` skip the extra exec. |
| 97 | -fn reexec_with_allocator_env(raw: &[std::ffi::OsString]) { | |
| 97 | +fn reexec_with_allocator_env(raw: &[std::ffi::OsString], command: Option<&str>) { | |
| 98 | 98 | const VAR: &str = "MIMALLOC_ALLOW_THP"; |
| 99 | 99 | if std::env::var_os(VAR).is_some() { |
| 100 | 100 | return; |
| 101 | 101 | } |
| 102 | - let mut words = raw.iter(); | |
| 103 | - let mut command = None; | |
| 104 | - while let Some(arg) = words.next() { | |
| 105 | - match arg.to_str() { | |
| 106 | - Some("--config") => { | |
| 107 | - words.next(); | |
| 108 | - } | |
| 109 | - Some("--admin") => {} | |
| 110 | - _ => { | |
| 111 | - command = Some(arg); | |
| 112 | - break; | |
| 113 | - } | |
| 114 | - } | |
| 115 | - } | |
| 116 | 102 | if command.is_some_and(|c| c != "serve") { |
| 117 | 103 | return; |
| 118 | 104 | } |
| @@ -157,7 +143,14 @@ fn main() -> ExitCode { | ||
| 157 | 143 | if let Err(e) = nix::sys::prctl::set_thp_disable(true) { |
| 158 | 144 | eprintln!("forge: cannot disable transparent huge pages: {e}"); |
| 159 | 145 | } |
| 160 | - reexec_with_allocator_env(&raw); | |
| 146 | + let (flag_config, admin, positional) = match parse_args(std::env::args().skip(1)) { | |
| 147 | + Ok(parsed) => parsed, | |
| 148 | + Err(e) => { | |
| 149 | + eprintln!("forge: {e}\n{USAGE}"); | |
| 150 | + return ExitCode::from(2); | |
| 151 | + } | |
| 152 | + }; | |
| 153 | + reexec_with_allocator_env(&raw, positional.first().map(String::as_str)); | |
| 161 | 154 | let runtime = match tokio::runtime::Builder::new_multi_thread() |
| 162 | 155 | .enable_all() |
| 163 | 156 | .build() |
| @@ -168,10 +161,10 @@ fn main() -> ExitCode { | ||
| 168 | 161 | return ExitCode::FAILURE; |
| 169 | 162 | } |
| 170 | 163 | }; |
| 171 | - runtime.block_on(real_main()) | |
| 164 | + runtime.block_on(real_main(flag_config, admin, positional)) | |
| 172 | 165 | } |
| 173 | 166 | |
| 174 | -async fn real_main() -> ExitCode { | |
| 167 | +async fn real_main(flag_config: Option<PathBuf>, admin: bool, positional: Vec<String>) -> ExitCode { | |
| 175 | 168 | // Logs go to stderr: the hook stages write protocol output to stdout. |
| 176 | 169 | let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); |
| 177 | 170 | tracing_subscriber::fmt() |
| @@ -179,13 +172,6 @@ async fn real_main() -> ExitCode { | ||
| 179 | 172 | .with_writer(std::io::stderr) |
| 180 | 173 | .init(); |
| 181 | 174 | |
| 182 | - let (flag_config, admin, positional) = match parse_args(std::env::args().skip(1)) { | |
| 183 | - Ok(parsed) => parsed, | |
| 184 | - Err(e) => { | |
| 185 | - eprintln!("forge: {e}\n{USAGE}"); | |
| 186 | - return ExitCode::from(2); | |
| 187 | - } | |
| 188 | - }; | |
| 189 | 175 | let config_path = flag_config |
| 190 | 176 | .or_else(|| std::env::var_os("FORGE_CONFIG").map(PathBuf::from)) |
| 191 | 177 | .unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG)); |
crates/forge-web/src/page_route_tests/edit_history.rsmodified+0 -10
| @@ -5,7 +5,6 @@ use topcoat::router::{Body, Router, to_bytes}; | ||
| 5 | 5 | use crate::auth::SESSION_COOKIE; |
| 6 | 6 | use crate::test_support::fixture::{Fixture, OWNER, REPO}; |
| 7 | 7 | |
| 8 | -/// Sends one request and returns `(status, body)`. | |
| 9 | 8 | async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) { |
| 10 | 9 | let mut req = Request::builder().method("GET").uri(uri); |
| 11 | 10 | if let Some(token) = token { |
| @@ -17,7 +16,6 @@ async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) | ||
| 17 | 16 | (status, String::from_utf8_lossy(&bytes).into_owned()) |
| 18 | 17 | } |
| 19 | 18 | |
| 20 | -/// The repo owner with a session whose token is `tahinli`. | |
| 21 | 19 | async fn tahinli(fx: &Fixture) -> forge_core::User { |
| 22 | 20 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 23 | 21 | crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await; |
| @@ -37,15 +35,12 @@ fn hex_oid(c: char) -> String { | ||
| 37 | 35 | std::iter::repeat_n(c, 40).collect() |
| 38 | 36 | } |
| 39 | 37 | |
| 40 | -/// Every scenario on the public repo shares one fixture. Each makes its own issue or pull and | |
| 41 | -/// reads its numbers from the store, so no scenario depends on another's data. | |
| 42 | 38 | #[tokio::test] |
| 43 | 39 | async fn public_histories_show_diffs_markers_and_refusals() { |
| 44 | 40 | let fx = Fixture::new(Visibility::Public).await; |
| 45 | 41 | let owner = tahinli(&fx).await; |
| 46 | 42 | let id = repo_id(&fx).await; |
| 47 | 43 | |
| 48 | - // A comment edited twice: a marker on the item page and two versions with diffs. | |
| 49 | 44 | let issue = fx |
| 50 | 45 | .store |
| 51 | 46 | .create_issue(&id, &owner.id, "bug", "body") |
| @@ -97,7 +92,6 @@ async fn public_histories_show_diffs_markers_and_refusals() { | ||
| 97 | 92 | "edited comment: editor {history}" |
| 98 | 93 | ); |
| 99 | 94 | |
| 100 | - // A comment that was never edited has no marker. | |
| 101 | 95 | let plain = fx |
| 102 | 96 | .store |
| 103 | 97 | .create_issue(&id, &owner.id, "plain", "body") |
| @@ -119,7 +113,6 @@ async fn public_histories_show_diffs_markers_and_refusals() { | ||
| 119 | 113 | "unedited comment: no marker {page}" |
| 120 | 114 | ); |
| 121 | 115 | |
| 122 | - // An issue body and title edit: the old title and the changed lines show. | |
| 123 | 116 | let titled = fx |
| 124 | 117 | .store |
| 125 | 118 | .create_issue(&id, &owner.id, "old title", "a\nb\nc") |
| @@ -153,7 +146,6 @@ async fn public_histories_show_diffs_markers_and_refusals() { | ||
| 153 | 146 | assert!(history.contains("-b"), "body edit: -b {history}"); |
| 154 | 147 | assert!(history.contains("+B"), "body edit: +B {history}"); |
| 155 | 148 | |
| 156 | - // A comment on one issue is not found under another issue's URL. | |
| 157 | 149 | let other = fx |
| 158 | 150 | .store |
| 159 | 151 | .create_issue(&id, &owner.id, "second", "body") |
| @@ -189,7 +181,6 @@ async fn public_histories_show_diffs_markers_and_refusals() { | ||
| 189 | 181 | .await; |
| 190 | 182 | assert_eq!(status, 200, "right item: found"); |
| 191 | 183 | |
| 192 | - // An unknown kind and a missing target are both not found. | |
| 193 | 184 | let (status, _) = send( |
| 194 | 185 | &fx.router, |
| 195 | 186 | &format!( |
| @@ -211,7 +202,6 @@ async fn public_histories_show_diffs_markers_and_refusals() { | ||
| 211 | 202 | .await; |
| 212 | 203 | assert_eq!(status, 404, "missing target"); |
| 213 | 204 | |
| 214 | - // Review comment history on a pull request, and not under the issue URL of the same number. | |
| 215 | 205 | let pr = fx |
| 216 | 206 | .store |
| 217 | 207 | .create_pull( |
crates/forge-web/src/page_route_tests/notifications.rsmodified+0 -15
| @@ -34,7 +34,6 @@ async fn site() -> Site { | ||
| 34 | 34 | } |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | -/// Signs `user_id` in with `token` and returns the cookie header value. | |
| 38 | 37 | async fn sign_in(store: &Store, user_id: &str, token: &str) -> String { |
| 39 | 38 | crate::test_support::create_session(store, user_id, token, CSRF).await; |
| 40 | 39 | format!("__Host-{SESSION_COOKIE}={token}") |
| @@ -91,7 +90,6 @@ async fn post(site: &Site, uri: &str, cookie: &str, extra: &str) -> Reply { | ||
| 91 | 90 | .await |
| 92 | 91 | } |
| 93 | 92 | |
| 94 | -/// Tahinli owns `demo` with one issue (#1), and Bob has a notification row for it. | |
| 95 | 93 | struct World { |
| 96 | 94 | tahinli: forge_core::User, |
| 97 | 95 | bob: forge_core::User, |
| @@ -185,8 +183,6 @@ async fn unread_inbox_lists_unread_rows_grouped_by_repo() { | ||
| 185 | 183 | assert!(page.body.contains("Mark all as read")); |
| 186 | 184 | } |
| 187 | 185 | |
| 188 | -/// Another user cannot open or mark read a row that is not theirs. The owner's open redirects | |
| 189 | -/// to the issue and marks the row read. | |
| 190 | 186 | #[tokio::test] |
| 191 | 187 | async fn another_users_notification_is_404_and_the_owner_opens_it() { |
| 192 | 188 | let site = site().await; |
| @@ -215,7 +211,6 @@ async fn another_users_notification_is_404_and_the_owner_opens_it() { | ||
| 215 | 211 | assert_eq!(read.status, 303); |
| 216 | 212 | assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1); |
| 217 | 213 | |
| 218 | - // Bob opens his own row: it redirects to the issue and marks the row read. | |
| 219 | 214 | let res = get( |
| 220 | 215 | &site, |
| 221 | 216 | &format!("/notifications/{id}/open"), |
| @@ -261,13 +256,11 @@ async fn the_stream_sends_the_count_then_each_change() { | ||
| 261 | 256 | assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no"); |
| 262 | 257 | |
| 263 | 258 | let mut frames = res.into_body().into_data_stream(); |
| 264 | - // The stream opens with its retry field, then the count. | |
| 265 | 259 | let retry = frames.next().await.expect("a frame").expect("data"); |
| 266 | 260 | assert!(retry.starts_with(b"retry: 1000"), "{retry:?}"); |
| 267 | 261 | let first = frames.next().await.expect("a frame").expect("data"); |
| 268 | 262 | assert_eq!(&first[..], b"event: unread\ndata: 1\n\n"); |
| 269 | 263 | |
| 270 | - // Marking the row read pushes the new count to the open stream. | |
| 271 | 264 | let read = post(&site, "/notifications/mark_all_read", &cookie, "").await; |
| 272 | 265 | assert_eq!(read.status, 303); |
| 273 | 266 | let next = frames.next().await.expect("a frame").expect("data"); |
| @@ -328,7 +321,6 @@ async fn subscription_toggles_on_an_issue_and_unknown_pull_is_404() { | ||
| 328 | 321 | .expect("sub"); |
| 329 | 322 | assert_eq!(sub, Some((SubState::Ignored, Reason::Subscribed))); |
| 330 | 323 | |
| 331 | - // A pull request number that does not exist is a 404 on the pulls subscription. | |
| 332 | 324 | let res = post( |
| 333 | 325 | &site, |
| 334 | 326 | "/tahinli/demo/pulls/1/subscription", |
| @@ -355,7 +347,6 @@ async fn watch_form_sets_the_level() { | ||
| 355 | 347 | WatchLevel::Watching |
| 356 | 348 | ); |
| 357 | 349 | |
| 358 | - // The watch menu sits in the repo head on the code tab, which reads the repository. | |
| 359 | 350 | let bare = forge_git::repo::repo_path(&site.git.data_dir, &w.repo.id).expect("repo path"); |
| 360 | 351 | forge_git::repo::init_bare(&site.git, &bare, "main") |
| 361 | 352 | .await |
| @@ -364,7 +355,6 @@ async fn watch_form_sets_the_level() { | ||
| 364 | 355 | assert!(header.body.contains("action=\"/tahinli/demo/watch\"")); |
| 365 | 356 | assert!(header.body.contains("<details class=\"menu watch-menu\">")); |
| 366 | 357 | assert!(!header.body.contains("<select")); |
| 367 | - // One form per level, and only the watched level is marked current. | |
| 368 | 358 | assert_eq!(header.body.matches("name=\"level\"").count(), 3); |
| 369 | 359 | assert_eq!( |
| 370 | 360 | header |
| @@ -417,7 +407,6 @@ async fn row_for_a_repo_the_viewer_lost_access_to_is_hidden() { | ||
| 417 | 407 | async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() { |
| 418 | 408 | let site = site().await; |
| 419 | 409 | let w = world(&site, Visibility::Public).await; |
| 420 | - // The world's issue takes number 1, so the discussion is #2. | |
| 421 | 410 | let discussion = site |
| 422 | 411 | .store |
| 423 | 412 | .create_discussion( |
| @@ -446,7 +435,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() { | ||
| 446 | 435 | 1 |
| 447 | 436 | ); |
| 448 | 437 | |
| 449 | - // Bob has no row for the discussion, so he cannot open it. | |
| 450 | 438 | let other = get(&site, &open, Some(&bob)).await; |
| 451 | 439 | assert_eq!(other.status, 404); |
| 452 | 440 | |
| @@ -458,7 +446,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() { | ||
| 458 | 446 | 0 |
| 459 | 447 | ); |
| 460 | 448 | |
| 461 | - // A second discussion, cleared by mark all read. | |
| 462 | 449 | let discussion = site |
| 463 | 450 | .store |
| 464 | 451 | .create_discussion( |
| @@ -491,7 +478,6 @@ async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() { | ||
| 491 | 478 | async fn advisory_alerts_show_for_managers_and_open_marks_read() { |
| 492 | 479 | let site = site().await; |
| 493 | 480 | let w = world(&site, Visibility::Public).await; |
| 494 | - // Tahinli owns the repo, so she manages its alerts. Bob is a reader with a stale row. | |
| 495 | 481 | site.store |
| 496 | 482 | .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2) |
| 497 | 483 | .await |
| @@ -514,7 +500,6 @@ async fn advisory_alerts_show_for_managers_and_open_marks_read() { | ||
| 514 | 500 | 1 |
| 515 | 501 | ); |
| 516 | 502 | |
| 517 | - // Bob cannot manage the alerts: his row is hidden and marked read, as lost-access rows are. | |
| 518 | 503 | let bob_page = get(&site, "/notifications", Some(&bob)).await; |
| 519 | 504 | assert_eq!(bob_page.status, 200); |
| 520 | 505 | assert!(!bob_page.body.contains(&open)); |
crates/forge-web/src/page_route_tests/pull_reviews.rsmodified+48 -95
| @@ -11,7 +11,6 @@ fn cookie(token: &str) -> String { | ||
| 11 | 11 | format!("__Host-{SESSION_COOKIE}={token}") |
| 12 | 12 | } |
| 13 | 13 | |
| 14 | -/// Sends one request through the router and returns `(status, location, body)`. | |
| 15 | 14 | async fn send( |
| 16 | 15 | router: &Router, |
| 17 | 16 | method: &str, |
| @@ -44,7 +43,6 @@ async fn send( | ||
| 44 | 43 | ) |
| 45 | 44 | } |
| 46 | 45 | |
| 47 | -/// A user with a session whose CSRF token is `{token}-csrf`. | |
| 48 | 46 | async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User { |
| 49 | 47 | let user = fx |
| 50 | 48 | .store |
| @@ -55,7 +53,6 @@ async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User { | ||
| 55 | 53 | user |
| 56 | 54 | } |
| 57 | 55 | |
| 58 | -/// The repo owner, signed in with token `tahinli` (CSRF `tahinli-csrf`). | |
| 59 | 56 | async fn owner_session(fx: &Fixture) { |
| 60 | 57 | let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 61 | 58 | crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await; |
| @@ -69,6 +66,22 @@ fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String { | ||
| 69 | 66 | form |
| 70 | 67 | } |
| 71 | 68 | |
| 69 | +async fn post_form( | |
| 70 | + fx: &Fixture, | |
| 71 | + uri: &str, | |
| 72 | + token: &str, | |
| 73 | + pairs: &[(&str, &str)], | |
| 74 | +) -> (u16, Option<String>, String) { | |
| 75 | + send( | |
| 76 | + &fx.router, | |
| 77 | + "POST", | |
| 78 | + uri, | |
| 79 | + Some(token), | |
| 80 | + Some(csrf_form(token, pairs)), | |
| 81 | + ) | |
| 82 | + .await | |
| 83 | +} | |
| 84 | + | |
| 72 | 85 | async fn pull(fx: &Fixture, number: i64) -> PullRequest { |
| 73 | 86 | let repo = fx |
| 74 | 87 | .store |
| @@ -83,8 +96,6 @@ async fn pull(fx: &Fixture, number: i64) -> PullRequest { | ||
| 83 | 96 | .unwrap() |
| 84 | 97 | } |
| 85 | 98 | |
| 86 | -/// Pushes a `feature` branch from the root that changes `a.txt` (`two` becomes `changed`) and | |
| 87 | -/// opens a pull request for it against `main`. Returns the pull request number. | |
| 88 | 99 | async fn open_pull(fx: &Fixture) -> i64 { |
| 89 | 100 | let base_oid = git(&fx.work, &["rev-parse", "HEAD"]); |
| 90 | 101 | git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]); |
| @@ -126,12 +137,10 @@ async fn open_pull(fx: &Fixture) -> i64 { | ||
| 126 | 137 | pr.issue.number |
| 127 | 138 | } |
| 128 | 139 | |
| 129 | -/// The pull request's current head, for the `head_oid` field of a comment form. | |
| 130 | 140 | async fn head_of(fx: &Fixture, number: i64) -> String { |
| 131 | 141 | pull(fx, number).await.head_oid |
| 132 | 142 | } |
| 133 | 143 | |
| 134 | -/// Posts a single line comment on line `line` of the new side of `a.txt` (file index 0). | |
| 135 | 144 | async fn comment_on( |
| 136 | 145 | fx: &Fixture, |
| 137 | 146 | number: i64, |
| @@ -140,7 +149,9 @@ async fn comment_on( | ||
| 140 | 149 | body: &str, |
| 141 | 150 | ) -> (u16, Option<String>) { |
| 142 | 151 | let head = head_of(fx, number).await; |
| 143 | - let form = csrf_form( | |
| 152 | + let (status, location, _) = post_form( | |
| 153 | + fx, | |
| 154 | + &format!("/tahinli/demo/pulls/{number}/review_comments"), | |
| 144 | 155 | token, |
| 145 | 156 | &[ |
| 146 | 157 | ("file_index", "0"), |
| @@ -150,19 +161,11 @@ async fn comment_on( | ||
| 150 | 161 | ("action", "single"), |
| 151 | 162 | ("body", body), |
| 152 | 163 | ], |
| 153 | - ); | |
| 154 | - let (status, location, _) = send( | |
| 155 | - &fx.router, | |
| 156 | - "POST", | |
| 157 | - &format!("/tahinli/demo/pulls/{number}/review_comments"), | |
| 158 | - Some(token), | |
| 159 | - Some(form), | |
| 160 | 164 | ) |
| 161 | 165 | .await; |
| 162 | 166 | (status, location) |
| 163 | 167 | } |
| 164 | 168 | |
| 165 | -/// The id of the thread at `index` (in creation order) on the pull request. | |
| 166 | 169 | async fn root_at(fx: &Fixture, number: i64, index: usize) -> String { |
| 167 | 170 | let pr = pull(fx, number).await; |
| 168 | 171 | fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index] |
| @@ -171,26 +174,22 @@ async fn root_at(fx: &Fixture, number: i64, index: usize) -> String { | ||
| 171 | 174 | .clone() |
| 172 | 175 | } |
| 173 | 176 | |
| 174 | -/// The comment body that proposes replacing line 2 of `a.txt` with `text`. | |
| 175 | 177 | fn suggestion(text: &str) -> String { |
| 176 | 178 | format!("Try this:\n```suggestion\n{text}\n```") |
| 177 | 179 | } |
| 178 | 180 | |
| 179 | -/// Posts the apply form for suggestion block 0 of comment `comment_id`. | |
| 180 | 181 | async fn apply_as( |
| 181 | 182 | fx: &Fixture, |
| 182 | 183 | number: i64, |
| 183 | 184 | token: &str, |
| 184 | 185 | comment_id: &str, |
| 185 | 186 | ) -> (u16, Option<String>) { |
| 186 | - let form = csrf_form(token, &[("block", "0"), ("return", "files")]); | |
| 187 | 187 | let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply"); |
| 188 | - let (status, location, _) = send(&fx.router, "POST", &uri, Some(token), Some(form)).await; | |
| 188 | + let (status, location, _) = | |
| 189 | + post_form(fx, &uri, token, &[("block", "0"), ("return", "files")]).await; | |
| 189 | 190 | (status, location) |
| 190 | 191 | } |
| 191 | 192 | |
| 192 | -/// Comment posting rules and a pending review, on one open pull. Scenarios run in order: | |
| 193 | -/// the rejected posts first (no thread), then the first thread, then the pending review. | |
| 194 | 193 | #[tokio::test] |
| 195 | 194 | async fn comment_rules_and_pending_review_on_one_pull() { |
| 196 | 195 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -198,7 +197,6 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 198 | 197 | let number = open_pull(&fx).await; |
| 199 | 198 | let pr = pull(&fx, number).await; |
| 200 | 199 | |
| 201 | - // A line outside the diff is rejected and leaves no thread. | |
| 202 | 200 | let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await; |
| 203 | 201 | assert_eq!(status, 303, "outside diff"); |
| 204 | 202 | assert!( |
| @@ -214,9 +212,10 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 214 | 212 | "outside diff left a thread" |
| 215 | 213 | ); |
| 216 | 214 | |
| 217 | - // A head that is not the pull's current head is rejected. | |
| 218 | 215 | let zero = "0".repeat(40); |
| 219 | - let form = csrf_form( | |
| 216 | + let (status, location, _) = post_form( | |
| 217 | + &fx, | |
| 218 | + &format!("/tahinli/demo/pulls/{number}/review_comments"), | |
| 220 | 219 | "tahinli", |
| 221 | 220 | &[ |
| 222 | 221 | ("file_index", "0"), |
| @@ -226,13 +225,6 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 226 | 225 | ("action", "single"), |
| 227 | 226 | ("body", "Stale"), |
| 228 | 227 | ], |
| 229 | - ); | |
| 230 | - let (status, location, _) = send( | |
| 231 | - &fx.router, | |
| 232 | - "POST", | |
| 233 | - &format!("/tahinli/demo/pulls/{number}/review_comments"), | |
| 234 | - Some("tahinli"), | |
| 235 | - Some(form), | |
| 236 | 228 | ) |
| 237 | 229 | .await; |
| 238 | 230 | assert_eq!(status, 303, "stale head"); |
| @@ -250,7 +242,6 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 250 | 242 | "stale head left a thread" |
| 251 | 243 | ); |
| 252 | 244 | |
| 253 | - // A single comment on an added line creates a thread that carries its hunk. | |
| 254 | 245 | let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await; |
| 255 | 246 | assert_eq!(status, 303, "single comment"); |
| 256 | 247 | assert_eq!( |
| @@ -269,10 +260,11 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 269 | 260 | assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment"); |
| 270 | 261 | assert!(!root.pending, "single comment"); |
| 271 | 262 | |
| 272 | - // A pending review comment is hidden from everyone but its author until submitted. | |
| 273 | 263 | let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 274 | 264 | let head = pr.head_oid.clone(); |
| 275 | - let form = csrf_form( | |
| 265 | + let (status, _, _) = post_form( | |
| 266 | + &fx, | |
| 267 | + &format!("/tahinli/demo/pulls/{number}/review_comments"), | |
| 276 | 268 | "tahinli", |
| 277 | 269 | &[ |
| 278 | 270 | ("file_index", "0"), |
| @@ -282,13 +274,6 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 282 | 274 | ("action", "review"), |
| 283 | 275 | ("body", "Draft"), |
| 284 | 276 | ], |
| 285 | - ); | |
| 286 | - let (status, _, _) = send( | |
| 287 | - &fx.router, | |
| 288 | - "POST", | |
| 289 | - &format!("/tahinli/demo/pulls/{number}/review_comments"), | |
| 290 | - Some("tahinli"), | |
| 291 | - Some(form), | |
| 292 | 277 | ) |
| 293 | 278 | .await; |
| 294 | 279 | assert_eq!(status, 303, "pending start"); |
| @@ -326,7 +311,6 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 326 | 311 | assert_eq!(threads.len(), 2, "submitted review is public"); |
| 327 | 312 | assert!(threads.iter().all(|t| !t.root.pending), "submitted review"); |
| 328 | 313 | |
| 329 | - // Anonymous writes redirect to login, and a missing CSRF token is forbidden. | |
| 330 | 314 | let uri = format!("/tahinli/demo/pulls/{number}/review_comments"); |
| 331 | 315 | let form = csrf_form( |
| 332 | 316 | "tahinli", |
| @@ -347,8 +331,6 @@ async fn comment_rules_and_pending_review_on_one_pull() { | ||
| 347 | 331 | assert_eq!(status, 403, "missing csrf"); |
| 348 | 332 | } |
| 349 | 333 | |
| 350 | -/// Reply, edit, resolve and delete on the threads of one pull. Each scenario acts on its | |
| 351 | -/// own thread (the first for reply, edit and resolve, the second for delete). | |
| 352 | 334 | #[tokio::test] |
| 353 | 335 | async fn thread_reply_edit_resolve_and_delete() { |
| 354 | 336 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -359,14 +341,11 @@ async fn thread_reply_edit_resolve_and_delete() { | ||
| 359 | 341 | let pr = pull(&fx, number).await; |
| 360 | 342 | let root = root_at(&fx, number, 0).await; |
| 361 | 343 | |
| 362 | - // A reader replies into the thread and is sent back to its root. | |
| 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, | |
| 367 | 346 | &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"), |
| 368 | - Some("bob"), | |
| 369 | - Some(form), | |
| 347 | + "bob", | |
| 348 | + &[("body", "Reply")], | |
| 370 | 349 | ) |
| 371 | 350 | .await; |
| 372 | 351 | assert_eq!(status, 303, "reply"); |
| @@ -379,18 +358,15 @@ async fn thread_reply_edit_resolve_and_delete() { | ||
| 379 | 358 | assert_eq!(threads[0].replies.len(), 1, "reply"); |
| 380 | 359 | assert_eq!(threads[0].replies[0].author_name, "bob", "reply"); |
| 381 | 360 | |
| 382 | - // Only the author may open the edit form, post an edit, or resolve. | |
| 383 | 361 | let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit"); |
| 384 | 362 | let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await; |
| 385 | 363 | assert_eq!(status, 200, "edit form"); |
| 386 | 364 | assert!(body.contains("Save comment"), "edit form"); |
| 387 | 365 | let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await; |
| 388 | 366 | 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; | |
| 391 | 368 | 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; | |
| 394 | 370 | assert_eq!(status, 303, "edit"); |
| 395 | 371 | assert_eq!( |
| 396 | 372 | location.as_deref(), |
| @@ -401,32 +377,25 @@ async fn thread_reply_edit_resolve_and_delete() { | ||
| 401 | 377 | assert_eq!(threads[0].root.body, "Edited", "edit"); |
| 402 | 378 | |
| 403 | 379 | 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; | |
| 406 | 381 | 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; | |
| 409 | 383 | assert_eq!(status, 303, "resolve"); |
| 410 | 384 | let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); |
| 411 | 385 | assert!(threads[0].root.resolved, "resolve"); |
| 412 | 386 | |
| 413 | - // Delete removes only the second thread, and only for its author. | |
| 414 | 387 | comment_on(&fx, number, "tahinli", "2", "Doomed").await; |
| 415 | 388 | let doomed = root_at(&fx, number, 1).await; |
| 416 | 389 | 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; | |
| 419 | 391 | 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; | |
| 422 | 393 | assert_eq!(status, 303, "delete"); |
| 423 | 394 | let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap(); |
| 424 | 395 | assert_eq!(threads.len(), 1, "delete"); |
| 425 | 396 | assert_eq!(threads[0].root.id, root, "delete kept the other thread"); |
| 426 | 397 | } |
| 427 | 398 | |
| 428 | -/// Reviews on one pull: a reader approves, the author cannot approve their own pull, and | |
| 429 | -/// after the pull closes it takes comments but no reviews. | |
| 430 | 399 | #[tokio::test] |
| 431 | 400 | async fn reviews_approve_then_close_the_pull() { |
| 432 | 401 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -436,18 +405,14 @@ async fn reviews_approve_then_close_the_pull() { | ||
| 436 | 405 | let pr = pull(&fx, number).await; |
| 437 | 406 | let uri = format!("/tahinli/demo/pulls/{number}/reviews"); |
| 438 | 407 | |
| 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; | |
| 442 | 409 | assert_eq!(status, 303, "reader approval"); |
| 443 | 410 | assert!(location.unwrap().contains("#review-"), "reader approval"); |
| 444 | 411 | let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap(); |
| 445 | 412 | assert_eq!(reviews.len(), 1, "reader approval"); |
| 446 | 413 | assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval"); |
| 447 | 414 | |
| 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; | |
| 451 | 416 | assert_eq!(status, 303, "author approval"); |
| 452 | 417 | assert_eq!( |
| 453 | 418 | location.as_deref(), |
| @@ -460,7 +425,6 @@ async fn reviews_approve_then_close_the_pull() { | ||
| 460 | 425 | "author approval" |
| 461 | 426 | ); |
| 462 | 427 | |
| 463 | - // Once closed, comments still land but reviews are refused. | |
| 464 | 428 | let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap(); |
| 465 | 429 | fx.store |
| 466 | 430 | .set_issue_state( |
| @@ -478,8 +442,7 @@ async fn reviews_approve_then_close_the_pull() { | ||
| 478 | 442 | location.unwrap().contains("#L-0-new-2"), |
| 479 | 443 | "comment on a closed pull" |
| 480 | 444 | ); |
| 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; | |
| 483 | 446 | assert_eq!(status, 303, "review on a closed pull"); |
| 484 | 447 | assert!( |
| 485 | 448 | location.unwrap().ends_with("?review_error=closed"), |
| @@ -494,39 +457,33 @@ async fn dismiss_needs_write_and_a_reason() { | ||
| 494 | 457 | sign_in(&fx, "bob", "bob").await; |
| 495 | 458 | let number = open_pull(&fx).await; |
| 496 | 459 | 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, | |
| 501 | 462 | &format!("/tahinli/demo/pulls/{number}/reviews"), |
| 502 | - Some("bob"), | |
| 503 | - Some(form), | |
| 463 | + "bob", | |
| 464 | + &[("state", "request_changes")], | |
| 504 | 465 | ) |
| 505 | 466 | .await; |
| 467 | + assert_eq!(status, 303, "setup review"); | |
| 506 | 468 | let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0); |
| 507 | 469 | let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id); |
| 508 | 470 | |
| 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; | |
| 511 | 472 | assert_eq!(status, 403, "dismiss by a reader"); |
| 512 | 473 | |
| 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; | |
| 515 | 475 | assert_eq!(status, 303, "blank reason"); |
| 516 | 476 | assert!( |
| 517 | 477 | location.unwrap().ends_with("?review_error=empty"), |
| 518 | 478 | "blank reason" |
| 519 | 479 | ); |
| 520 | 480 | |
| 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; | |
| 523 | 482 | assert_eq!(status, 303, "dismiss"); |
| 524 | 483 | let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0); |
| 525 | 484 | assert_eq!(review.state, ReviewState::Dismissed, "dismiss"); |
| 526 | 485 | } |
| 527 | 486 | |
| 528 | -/// The apply-suggestion flow on one pull: a reader without push access sees no button, an | |
| 529 | -/// outdated suggestion is refused after the head moves, and a fresh suggestion applies. | |
| 530 | 487 | #[tokio::test] |
| 531 | 488 | async fn suggestions_reader_outdated_and_apply() { |
| 532 | 489 | let fx = Fixture::new(Visibility::Public).await; |
| @@ -537,7 +494,6 @@ async fn suggestions_reader_outdated_and_apply() { | ||
| 537 | 494 | assert_eq!(status, 303, "first suggestion"); |
| 538 | 495 | let first = root_at(&fx, number, 0).await; |
| 539 | 496 | |
| 540 | - // A reader without push access sees the diff but no apply button, and is refused. | |
| 541 | 497 | let page = get(&fx, number, "rita").await; |
| 542 | 498 | assert!(page.contains("Suggested change"), "the diff still shows"); |
| 543 | 499 | assert!( |
| @@ -551,7 +507,6 @@ async fn suggestions_reader_outdated_and_apply() { | ||
| 551 | 507 | "reader apply" |
| 552 | 508 | ); |
| 553 | 509 | |
| 554 | - // The head moves on: the first suggestion is outdated, shown without apply, and refused. | |
| 555 | 510 | let pr = pull(&fx, number).await; |
| 556 | 511 | std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap(); |
| 557 | 512 | git(&fx.work, &["commit", "-q", "-am", "Move line 2"]); |
| @@ -596,7 +551,6 @@ async fn suggestions_reader_outdated_and_apply() { | ||
| 596 | 551 | "a refused apply leaves the thread open" |
| 597 | 552 | ); |
| 598 | 553 | |
| 599 | - // A fresh suggestion against the moved head applies as a commit by the commenter. | |
| 600 | 554 | let before = pull(&fx, number).await.head_oid; |
| 601 | 555 | assert_eq!(before, moved, "the head is the moved commit"); |
| 602 | 556 | let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await; |
| @@ -639,7 +593,6 @@ async fn suggestions_reader_outdated_and_apply() { | ||
| 639 | 593 | assert!(threads[1].root.resolved, "applying resolves the thread"); |
| 640 | 594 | } |
| 641 | 595 | |
| 642 | -/// The Files tab of the pull request as `token` sees it. | |
| 643 | 596 | async fn get(fx: &Fixture, number: i64, token: &str) -> String { |
| 644 | 597 | let uri = format!("/tahinli/demo/pulls/{number}/files"); |
| 645 | 598 | let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await; |
crates/forge-web/src/page_route_tests/repo.rsmodified+0 -15
| @@ -31,7 +31,6 @@ fn git(dir: &Path, args: &[&str]) { | ||
| 31 | 31 | assert!(status.success(), "git {args:?} failed"); |
| 32 | 32 | } |
| 33 | 33 | |
| 34 | -/// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty). | |
| 35 | 34 | async fn fixture(dir: &Path) -> (Router, AppState) { |
| 36 | 35 | let state = crate::test_support::test_state(dir).await; |
| 37 | 36 | let router = crate::test_support::app_router(state.clone()); |
| @@ -87,15 +86,11 @@ async fn fixture(dir: &Path) -> (Router, AppState) { | ||
| 87 | 86 | (router, state) |
| 88 | 87 | } |
| 89 | 88 | |
| 90 | -// The read-only tests below share one fixture: they only read the demo repo, so each scenario | |
| 91 | -// sees the same pristine contents. | |
| 92 | - | |
| 93 | 89 | #[tokio::test] |
| 94 | 90 | async fn demo_pages_render_from_the_repo_contents() { |
| 95 | 91 | let dir = tempfile::tempdir().unwrap(); |
| 96 | 92 | let (router, _) = fixture(dir.path()).await; |
| 97 | 93 | |
| 98 | - // Home renders the README, the tree, the clone popover and the archive links. | |
| 99 | 94 | let (status, body) = get_as(&router, "/tahinli/demo", None).await; |
| 100 | 95 | assert_eq!(status, 200); |
| 101 | 96 | assert!(body.contains("Hello from the README"), "README rendered"); |
| @@ -117,7 +112,6 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 117 | 112 | assert!(body.contains("/tahinli/demo/branches")); |
| 118 | 113 | assert!(body.contains("data-ref-filter"), "branch switcher rendered"); |
| 119 | 114 | |
| 120 | - // Trees list their entries and link to subtrees and blobs. | |
| 121 | 115 | let (status, body) = get_as(&router, "/tahinli/demo/tree/main/src", None).await; |
| 122 | 116 | assert_eq!(status, 200); |
| 123 | 117 | assert!(body.contains("main.rs")); |
| @@ -126,7 +120,6 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 126 | 120 | assert_eq!(status, 200); |
| 127 | 121 | assert!(body.contains("/tahinli/demo/tree/main/docs")); |
| 128 | 122 | |
| 129 | - // Rust source is highlighted with line anchors. | |
| 130 | 123 | let (status, body) = get_as(&router, "/tahinli/demo/blob/main/src/main.rs", None).await; |
| 131 | 124 | assert_eq!(status, 200); |
| 132 | 125 | assert!(body.contains("id=\"L1\"")); |
| @@ -134,7 +127,6 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 134 | 127 | assert!(body.contains("<span class="), "syntax classes applied"); |
| 135 | 128 | assert!(body.contains("/assets/highlight.css?v=")); |
| 136 | 129 | |
| 137 | - // Markdown renders unless the viewer asks for the plain source. | |
| 138 | 130 | let (status, body) = get_as(&router, "/tahinli/demo/blob/main/docs/guide.md", None).await; |
| 139 | 131 | assert_eq!(status, 200); |
| 140 | 132 | assert!( |
| @@ -146,12 +138,10 @@ async fn demo_pages_render_from_the_repo_contents() { | ||
| 146 | 138 | assert!(body.contains("file-table"), "source shown as lines"); |
| 147 | 139 | assert!(!body.contains("markdown-body"), "not rendered"); |
| 148 | 140 | |
| 149 | - // Binary blobs show their size instead of content. | |
| 150 | 141 | let (status, body) = get_as(&router, "/tahinli/demo/blob/main/data.bin", None).await; |
| 151 | 142 | assert_eq!(status, 200); |
| 152 | 143 | assert!(body.contains("Binary file, 3 bytes")); |
| 153 | 144 | |
| 154 | - // Fixed segment routes win over the repo catch-all. | |
| 155 | 145 | let (status, body) = get_as(&router, "/tahinli/demo/branches", None).await; |
| 156 | 146 | assert_eq!(status, 200); |
| 157 | 147 | assert!(body.contains("default"), "default branch marked"); |
| @@ -196,7 +186,6 @@ const ZERO_OID: &str = "0000000000000000000000000000000000000000"; | ||
| 196 | 186 | const OID: &str = "1111111111111111111111111111111111111111"; |
| 197 | 187 | const BANNER: &str = "had recent pushes"; |
| 198 | 188 | |
| 199 | -/// Creates a session for `user_id` and returns the cookie header value. | |
| 200 | 189 | async fn sign_in(state: &AppState, user_id: &str, token: &str) -> String { |
| 201 | 190 | crate::test_support::create_session(&state.store, user_id, token, "csrf").await; |
| 202 | 191 | format!("__Host-{SESSION_COOKIE}={token}") |
| @@ -213,13 +202,11 @@ async fn get_as(router: &Router, uri: &str, cookie: Option<&str>) -> (u16, Strin | ||
| 213 | 202 | (status, String::from_utf8_lossy(&bytes).into_owned()) |
| 214 | 203 | } |
| 215 | 204 | |
| 216 | -/// Points `branch` at the bare repo's `main`, so the branch exists. | |
| 217 | 205 | fn make_branch(bare: &Path, branch: &str) { |
| 218 | 206 | let full = format!("refs/heads/{branch}"); |
| 219 | 207 | git(bare, &["update-ref", &full, "refs/heads/main"]); |
| 220 | 208 | } |
| 221 | 209 | |
| 222 | -/// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago. | |
| 223 | 210 | async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) { |
| 224 | 211 | let at = stamp_ago(age); |
| 225 | 212 | let full = format!("refs/heads/{branch}"); |
| @@ -439,12 +426,10 @@ async fn fork_push_links_to_parent_compare() { | ||
| 439 | 426 | .await; |
| 440 | 427 | let cookie = sign_in(&state, &bob.id, "bob-token").await; |
| 441 | 428 | |
| 442 | - // On the parent, the viewer's fork branch compares as owner:branch. | |
| 443 | 429 | let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await; |
| 444 | 430 | assert_eq!(status, 200); |
| 445 | 431 | assert!(body.contains("compare/main...bob%3Afeature"), "{body}"); |
| 446 | 432 | |
| 447 | - // On the fork itself, the link goes to the parent's compare page. | |
| 448 | 433 | let (status, body) = get_as(&router, "/bob/demo", Some(&cookie)).await; |
| 449 | 434 | assert_eq!(status, 200); |
| 450 | 435 | assert!( |
crates/forge-web/src/route_list_tests.rsmodified+0 -4
| @@ -1,7 +1,3 @@ | ||
| 1 | -//! Every route, page, layout and layer that `discover()` finds, against `routes.snap`. Moving code | |
| 2 | -//! between crates must not lose one: a crate the binary does not link drops all of its routes. | |
| 3 | -//! `FORGE_BLESS=1` rewrites the snapshot. | |
| 4 | - | |
| 5 | 1 | use topcoat::internal::inventory; |
| 6 | 2 | use topcoat::router::{Layer, Layout, Page, Route}; |
| 7 | 3 |
crates/forge-web/src/shell_route_tests.rsmodified+0 -13
| @@ -1,11 +1,8 @@ | ||
| 1 | -//! Shell tests that render pages, so they need the page routes linked in. | |
| 2 | - | |
| 3 | 1 | use topcoat::router::request::Request; |
| 4 | 2 | use topcoat::router::{Body, to_bytes}; |
| 5 | 3 | |
| 6 | 4 | use crate::views::NAV_SCRIPT_HREF; |
| 7 | 5 | |
| 8 | -/// Every `<script` tag carries a `src`: an inline script could not run under the CSP. | |
| 9 | 6 | fn assert_no_inline_scripts(html: &str) { |
| 10 | 7 | for (at, _) in html.match_indices("<script") { |
| 11 | 8 | let tag = &html[at..]; |
| @@ -54,7 +51,6 @@ async fn shell_loads_the_deferred_nav_script_without_inline_scripts() { | ||
| 54 | 51 | assert!(html.contains("<main tabindex=\"-1\" data-width=\"col\">")); |
| 55 | 52 | assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\"")); |
| 56 | 53 | |
| 57 | - // An anonymous page renders the default colours. | |
| 58 | 54 | let tag = html_tag(&html); |
| 59 | 55 | assert!(tag.contains("data-accent-light=\"sage\""), "{tag}"); |
| 60 | 56 | assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}"); |
| @@ -62,15 +58,12 @@ async fn shell_loads_the_deferred_nav_script_without_inline_scripts() { | ||
| 62 | 58 | assert!(tag.contains("data-base-dark=\"ink\""), "{tag}"); |
| 63 | 59 | } |
| 64 | 60 | |
| 65 | -/// The `<html …>` start tag of a page. | |
| 66 | 61 | fn html_tag(page: &str) -> &str { |
| 67 | 62 | let at = page.find("<html").expect("the page has an html tag"); |
| 68 | 63 | let len = page[at..].find('>').expect("the html tag closes"); |
| 69 | 64 | &page[at..at + len + 1] |
| 70 | 65 | } |
| 71 | 66 | |
| 72 | -/// The `<html>` tag of `/settings/security` for a signed-in user whose stored colours are the | |
| 73 | -/// four ids given, in the order light accent, dark accent, light base, dark base. | |
| 74 | 67 | async fn html_tag_for_colours( |
| 75 | 68 | router: &topcoat::router::Router, |
| 76 | 69 | store: &forge_core::Store, |
| @@ -101,7 +94,6 @@ async fn html_tag_for_colours( | ||
| 101 | 94 | html_tag(&String::from_utf8_lossy(&bytes)).to_owned() |
| 102 | 95 | } |
| 103 | 96 | |
| 104 | -/// Every colour case shares one fixture; each has its own user and session. | |
| 105 | 97 | #[tokio::test] |
| 106 | 98 | async fn the_html_tag_carries_the_viewers_colours() { |
| 107 | 99 | let dir = tempfile::tempdir().expect("tempdir"); |
| @@ -122,7 +114,6 @@ async fn the_html_tag_carries_the_viewers_colours() { | ||
| 122 | 114 | assert!(tag.contains("data-base-light=\"ink\""), "{tag}"); |
| 123 | 115 | assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}"); |
| 124 | 116 | assert!(!tag.contains("data-accent="), "{tag}"); |
| 125 | - // Stored ids that are no longer offered fall back to the defaults, never to nothing. | |
| 126 | 117 | let removed = html_tag_for_colours( |
| 127 | 118 | &router, |
| 128 | 119 | &store, |
| @@ -135,7 +126,6 @@ async fn the_html_tag_carries_the_viewers_colours() { | ||
| 135 | 126 | assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}"); |
| 136 | 127 | assert!(removed.contains("data-base-light=\"ink\""), "{removed}"); |
| 137 | 128 | assert!(removed.contains("data-base-dark=\"ink\""), "{removed}"); |
| 138 | - // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself. | |
| 139 | 129 | let retired = html_tag_for_colours( |
| 140 | 130 | &router, |
| 141 | 131 | &store, |
| @@ -162,7 +152,6 @@ async fn the_html_tag_carries_the_viewers_colours() { | ||
| 162 | 152 | assert!(hued.contains("data-base-dark=\"ink\""), "{hued}"); |
| 163 | 153 | } |
| 164 | 154 | |
| 165 | -/// Renders `/settings/security` (a page that uses the shell) for a freshly signed-in user. | |
| 166 | 155 | async fn menu_html( |
| 167 | 156 | router: &topcoat::router::Router, |
| 168 | 157 | store: &forge_core::Store, |
| @@ -191,8 +180,6 @@ async fn menu_html( | ||
| 191 | 180 | String::from_utf8_lossy(&bytes).into_owned() |
| 192 | 181 | } |
| 193 | 182 | |
| 194 | -/// A user sees no admin links and an admin sees the one Admin entry. Both render from one | |
| 195 | -/// fixture. | |
| 196 | 183 | #[tokio::test] |
| 197 | 184 | async fn admin_links_follow_the_role() { |
| 198 | 185 | let dir = tempfile::tempdir().expect("tempdir"); |
crates/forge-web/src/templates_route_tests.rsmodified+0 -3
| @@ -6,8 +6,6 @@ use forge_web_pages::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, s | ||
| 6 | 6 | const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n"; |
| 7 | 7 | const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n"; |
| 8 | 8 | |
| 9 | -/// A repo whose default branch gets `files` committed on top of the fixture's history. | |
| 10 | -/// Tahinli is signed in. | |
| 11 | 9 | async fn setup(files: &[(&str, &str)]) -> Fixture { |
| 12 | 10 | let fx = Fixture::new(Visibility::Public).await; |
| 13 | 11 | for (path, text) in files { |
| @@ -35,7 +33,6 @@ fn new_issue_uri(query: &str) -> String { | ||
| 35 | 33 | format!("/{OWNER}/{REPO}/issues/new{query}") |
| 36 | 34 | } |
| 37 | 35 | |
| 38 | -/// The text of the tag that starts at `needle`, up to its closing `>`. | |
| 39 | 36 | fn tag_at(html: &str, needle: &str) -> String { |
| 40 | 37 | let at = html.find(needle).expect("needle in page"); |
| 41 | 38 | let end = html[at..].find('>').expect("tag end") + at; |