diff --git a/.forge/ci.toml b/.forge/ci.toml index 12ddc82..36073a7 100644 --- a/.forge/ci.toml +++ b/.forge/ci.toml @@ -1,7 +1,11 @@ # CI for forge itself. Format: docs/ci.md, parser: crates/forge-ci/src/config.rs. # # The workflow has no branch condition, so the build job also runs for pull requests. -# A tag push matching "v*" that passes every job publishes a release with the build job's binaries and SHA256SUMS. +# test and build have no `needs` between them, so they run in parallel when runner capacity allows +# (two runners, or one runner with concurrency = 2). The build job's artifacts are still only used +# once the whole run is green: a tag push matching "v*" publishes a release with the build job's +# binaries and SHA256SUMS, and self-update deploys dist/forge, only when every job in the run, +# including test, succeeded. [on] push = ["main"] @@ -21,7 +25,6 @@ timeout_minutes = 120 [jobs.build] image = "docker.io/library/rust:1" -needs = ["test"] # Runner has a few GB RAM and 2 CPUs: rustc runs one crate at a time because a single forge-web compile needs several GB. env = { CARGO_BUILD_JOBS = "1", CARGO_INCREMENTAL = "0" } run = """ diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index f991e49..1c636cf 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -216,7 +216,7 @@ pub fn parse_config(text: &str) -> Result { // serde_ignored marks `Option` wrappers with `?`; they are not part of the key path. let path = path.to_string().replace("?.", ""); warnings.push(format!( - "unknown key `{path}` ignored \u{2014} this forge may be older than your ci.toml" + "unknown key `{path}` ignored: this forge may be older than your ci.toml" )); }) .map_err(|e| ConfigError::Toml(e.to_string()))?; @@ -715,7 +715,11 @@ artifacts = ["target/release/forge"] let cfg = parse_config(&job_toml("bogus = 1")).unwrap(); assert_eq!(cfg.warnings.len(), 1); - assert!(cfg.warnings[0].contains("`jobs.build.bogus`"), "{:?}", cfg.warnings); + assert!( + cfg.warnings[0].contains("`jobs.build.bogus`"), + "{:?}", + cfg.warnings + ); assert_eq!(cfg.jobs.len(), 1); let cfg = parse_config(&format!("{}\n[other]\nx = 1\n", job_toml(""))).unwrap(); @@ -1194,7 +1198,11 @@ artifacts = ["target/release/forge"] fn release_unknown_keys_are_ignored_with_a_warning() { let cfg = parse_config(&release_toml("bogus = 1")).unwrap(); assert_eq!(cfg.warnings.len(), 1); - assert!(cfg.warnings[0].contains("`release.bogus`"), "{:?}", cfg.warnings); + assert!( + cfg.warnings[0].contains("`release.bogus`"), + "{:?}", + cfg.warnings + ); assert!(cfg.release.is_some()); } diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index cc3e7a2..2563ecb 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -712,7 +712,8 @@ impl Store { } /// Finishes a job with a terminal state. Dependants are then unblocked or skipped, and the - /// run state is recomputed. Returns the run. `Conflict` if the job already finished. + /// run state is recomputed. A `Failure` or `Error` fails the run fast: the run's queued and + /// blocked jobs are cancelled and its running jobs get `cancel_requested`. Returns the run. `Conflict` if the job already finished. pub async fn finish_job( &self, job_id: &str, @@ -747,6 +748,23 @@ impl Store { .await .map_err(db_err)?; propagate(&tx, &job.run_id, &now).await?; + if matches!(state, JobState::Failure | JobState::Error) { + // Fail fast: the run cannot succeed any more, so stop the sibling jobs now. + tx.execute( + "UPDATE ci_jobs SET state = 'cancelled', finished_at = ?2 \ + WHERE run_id = ?1 AND state IN ('queued', 'blocked')", + (job.run_id.clone(), now.clone()), + ) + .await + .map_err(db_err)?; + tx.execute( + "UPDATE ci_jobs SET cancel_requested = 1 \ + WHERE run_id = ?1 AND state = 'running'", + (job.run_id.clone(),), + ) + .await + .map_err(db_err)?; + } recompute_run(&tx, &job.run_id, &now).await?; load_run(&tx, &job.run_id).await?.ok_or_else(missing_row) } @@ -1697,6 +1715,61 @@ mod tests { assert_eq!(done.state, RunState::Failure); } + #[tokio::test] + async fn failure_fails_fast_cancelling_running_and_queued_siblings() { + let fx = fixture().await; + let run = create( + &fx.store, + &fx.repo.id, + &fx.tahinli.id, + &[ + job("test", &[], &[]), + job("build", &[], &[]), + job("docs", &["build"], &[]), + ], + false, + ) + .await; + let runner = bare_runner(&[]); + let first = fx.store.claim_job(&runner).await.unwrap().unwrap(); + let second = fx.store.claim_job(&runner).await.unwrap().unwrap(); + let (test, build) = if first.0.name == "test" { + (first, second) + } else { + (second, first) + }; + let after = fx + .store + .finish_job(&test.0.id, JobState::Failure, Some(1), None) + .await + .unwrap(); + assert_eq!( + after.state, + RunState::Running, + "build is still winding down" + ); + let build_now = job_named(&fx.store, &run.id, "build").await; + assert!(build_now.cancel_requested); + assert!(fx.store.heartbeat(&build.0.id).await.unwrap()); + assert!( + job_named(&fx.store, &run.id, "docs") + .await + .state + .is_terminal() + ); + + let done = fx + .store + .finish_job(&build.0.id, JobState::Cancelled, None, None) + .await + .unwrap(); + assert_eq!(done.state, RunState::Failure); + assert_eq!( + job_named(&fx.store, &run.id, "build").await.state, + JobState::Cancelled + ); + } + #[tokio::test] async fn cancel_queued_and_running_jobs() { let fx = fixture().await; diff --git a/crates/forge-core/src/store/contributions.rs b/crates/forge-core/src/store/contributions.rs index e2230b2..5b8bcdf 100644 --- a/crates/forge-core/src/store/contributions.rs +++ b/crates/forge-core/src/store/contributions.rs @@ -70,7 +70,10 @@ mod tests { async fn counts_pushes_issues_pulls_and_comments_per_day() { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let tahinli = store.create_user("tahinli", None, "x", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "x", false) + .await + .unwrap(); let bob = store.create_user("bob", None, "x", false).await.unwrap(); let demo = store .create_repo(&tahinli.id, "demo", "", Visibility::Public, "main") @@ -102,12 +105,23 @@ mod tests { .unwrap(); let pull = store .create_pull( - &demo.id, &tahinli.id, "change", "", "main", &demo.id, "topic", OID, OID, + &demo.id, + &tahinli.id, + "change", + "", + "main", + &demo.id, + "topic", + OID, + OID, ) .await .unwrap(); set_created_at(&store, "issues", &pull.issue.id, day2).await; - let comment = store.add_comment(&issue.id, &tahinli.id, "hi").await.unwrap(); + let comment = store + .add_comment(&issue.id, &tahinli.id, "hi") + .await + .unwrap(); set_created_at(&store, "comments", &comment.id, day2).await; // Before `since`, and someone else's activity: left out. diff --git a/crates/forge-core/src/store/issues.rs b/crates/forge-core/src/store/issues.rs index 7ca1a23..3c0c085 100644 --- a/crates/forge-core/src/store/issues.rs +++ b/crates/forge-core/src/store/issues.rs @@ -1653,7 +1653,11 @@ mod tests { #[tokio::test] async fn usernames_by_ids_is_batched_and_skips_unknown() { let fx = fixture().await; - let ids = vec![fx.tahinli.id.clone(), fx.bob.id.clone(), "nobody".to_string()]; + let ids = vec![ + fx.tahinli.id.clone(), + fx.bob.id.clone(), + "nobody".to_string(), + ]; let map = fx.store.usernames_by_ids(&ids).await.unwrap(); assert_eq!(map.len(), 2); assert_eq!(map[&fx.tahinli.id].0, "Tahinli"); diff --git a/crates/forge-core/src/store/labels.rs b/crates/forge-core/src/store/labels.rs index 284cbfc..7cf5c81 100644 --- a/crates/forge-core/src/store/labels.rs +++ b/crates/forge-core/src/store/labels.rs @@ -1006,7 +1006,11 @@ mod tests { .unwrap(); let err = s - .set_issue_labels(&issue.id, &fx.tahinli.id, &[b.id.clone(), foreign.id.clone()]) + .set_issue_labels( + &issue.id, + &fx.tahinli.id, + &[b.id.clone(), foreign.id.clone()], + ) .await; assert!(matches!(err, Err(Error::Invalid(_)))); assert_eq!(names(&s.issue_labels(&issue.id).await.unwrap()), ["a"]); @@ -1027,7 +1031,11 @@ mod tests { .create_issue(&fx.repo.id, &fx.tahinli.id, "t", "") .await .unwrap(); - let input = ["bob".to_string(), "BOB".to_string(), " Tahinli ".to_string()]; + let input = [ + "bob".to_string(), + "BOB".to_string(), + " Tahinli ".to_string(), + ]; s.set_issue_assignees(&issue.id, &fx.tahinli.id, &input) .await .unwrap(); diff --git a/crates/forge-core/src/store/lfs.rs b/crates/forge-core/src/store/lfs.rs index ca671bf..3e3795a 100644 --- a/crates/forge-core/src/store/lfs.rs +++ b/crates/forge-core/src/store/lfs.rs @@ -60,7 +60,10 @@ mod tests { async fn repo_fixture(dir: &tempfile::TempDir) -> (Store, String, String) { let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo(&user.id, "demo", "", Visibility::Public, "main") .await diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index dd27a29..5dd403f 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -5,8 +5,8 @@ pub mod advisories; pub mod audit; pub mod backup_runs; pub mod ci; -pub mod contributions; pub mod commit_status; +pub mod contributions; pub mod discussions; pub mod edit_history_read; pub mod issues; @@ -26,6 +26,7 @@ pub mod push_recent; pub mod reactions; pub mod releases; pub mod replication; +pub mod repo_listing; pub mod reviews; pub mod signatures; pub mod snapshot; @@ -2412,7 +2413,8 @@ impl Store { /// One page of public repos, optionally filtered by `query`. The query matches the repo name /// or description, case-insensitively, as a plain substring: `%`, `_` and `\` are literal. /// Each row carries the star count and the last activity time (the latest push, or the - /// creation time). Returns the rows for `page` (1-based) and the total number of matches. + /// creation time). Returns the rows for `page` (1-based, clamped to the last page) and the + /// total number of matches. pub async fn list_public_repos( &self, query: Option<&str>, @@ -2420,10 +2422,6 @@ impl Store { page: u64, per_page: u64, ) -> Result<(Vec, u64)> { - const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \ - WHERE p.repo_id = r.id), r.created_at)"; - const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)"; - let mut clauses: Vec<&str> = vec!["r.visibility = 'public'"]; let mut params: Vec = Vec::new(); if let Some(q) = query.map(str::trim).filter(|q| !q.is_empty()) { @@ -2434,46 +2432,15 @@ impl Store { params.push(Value::Text(pattern.clone())); params.push(Value::Text(pattern)); } - let where_sql = clauses.join(" AND "); - let order = match sort { - RepoSort::RecentlyUpdated => format!("{ACTIVITY} DESC, r.name_folded ASC"), - RepoSort::MostStars => format!("{STARS} DESC, r.name_folded ASC"), - RepoSort::Name => "r.name_folded ASC".to_owned(), - }; - let per_page = per_page.clamp(1, 100); - let page = page.clamp(1, 100_000); - let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX); - - let conn = self.read_conn().await; - let total = fetch_opt( - &conn, - &format!( - "SELECT COUNT(*) FROM repos r JOIN users u ON u.id = r.owner_id WHERE {where_sql}" - ), - params.clone(), - |row| col_int(row, 0), + self.page_of_repos( + "repos r JOIN users u ON u.id = r.owner_id", + &clauses.join(" AND "), + params, + sort, + page, + per_page, ) - .await? - .unwrap_or(0); - - let mut page_params = params; - page_params.push(Value::Integer(i64::try_from(per_page).unwrap_or(100))); - page_params.push(Value::Integer(offset)); - let rows = fetch_all( - &conn, - &format!( - "SELECT {REPO_COLS}, {STARS} AS stars, {ACTIVITY} AS activity \ - FROM repos r JOIN users u ON u.id = r.owner_id \ - WHERE {where_sql} ORDER BY {order} LIMIT ? OFFSET ?" - ), - page_params, - |row| { - let stars = u64::try_from(col_int(row, 10)?).unwrap_or(0); - Ok((map_repo(row)?, stars, col_text(row, 11)?)) - }, - ) - .await?; - Ok((rows, u64::try_from(total).unwrap_or(0))) + .await } } @@ -2484,7 +2451,10 @@ mod security_tests { async fn store_with_user() -> (Store, User, tempfile::TempDir) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); (store, user, dir) } diff --git a/crates/forge-core/src/store/notifications.rs b/crates/forge-core/src/store/notifications.rs index 1c856d4..32ddc46 100644 --- a/crates/forge-core/src/store/notifications.rs +++ b/crates/forge-core/src/store/notifications.rs @@ -531,9 +531,14 @@ mod tests { async fn subscribers_lists_only_subscribed() { let fx = fixture().await; let s = &fx.store; - s.subscribe(&fx.tahinli, &fx.issue_a, SubState::Subscribed, Reason::Assign) - .await - .unwrap(); + s.subscribe( + &fx.tahinli, + &fx.issue_a, + SubState::Subscribed, + Reason::Assign, + ) + .await + .unwrap(); s.subscribe(&fx.bob, &fx.issue_a, SubState::Ignored, Reason::Subscribed) .await .unwrap(); @@ -568,7 +573,10 @@ mod tests { ) .await .unwrap(); - assert_eq!(reason_of(s, &fx.tahinli, &fx.issue_a).await, Reason::Mention); + assert_eq!( + reason_of(s, &fx.tahinli, &fx.issue_a).await, + Reason::Mention + ); assert_eq!(s.unread_count(&fx.tahinli).await.unwrap(), 1); s.mark_issue_read(&fx.tahinli, &fx.issue_a).await.unwrap(); @@ -583,7 +591,10 @@ mod tests { ) .await .unwrap(); - assert_eq!(reason_of(s, &fx.tahinli, &fx.issue_a).await, Reason::Comment); + assert_eq!( + reason_of(s, &fx.tahinli, &fx.issue_a).await, + Reason::Comment + ); assert_eq!(s.unread_count(&fx.tahinli).await.unwrap(), 1); // A stronger reason while unread still wins. @@ -806,9 +817,14 @@ mod tests { s.set_watch(&fx.tahinli, &fx.repo, WatchLevel::Watching) .await .unwrap(); - s.subscribe(&fx.tahinli, &fx.issue_a, SubState::Subscribed, Reason::Author) - .await - .unwrap(); + s.subscribe( + &fx.tahinli, + &fx.issue_a, + SubState::Subscribed, + Reason::Author, + ) + .await + .unwrap(); s.upsert_notification( &fx.tahinli, &fx.repo, @@ -859,9 +875,14 @@ mod tests { s.set_watch(&fx.tahinli, &fx.repo, WatchLevel::Watching) .await .unwrap(); - s.subscribe(&fx.tahinli, &fx.issue_a, SubState::Subscribed, Reason::Author) - .await - .unwrap(); + s.subscribe( + &fx.tahinli, + &fx.issue_a, + SubState::Subscribed, + Reason::Author, + ) + .await + .unwrap(); // Bob's inbox row whose last actor is Tahinli, and Tahinli's own inbox row. s.upsert_notification( &fx.bob, diff --git a/crates/forge-core/src/store/pinned.rs b/crates/forge-core/src/store/pinned.rs index 1439962..92df0e3 100644 --- a/crates/forge-core/src/store/pinned.rs +++ b/crates/forge-core/src/store/pinned.rs @@ -119,7 +119,10 @@ mod tests { async fn fixture() -> (Store, User, String, tempfile::TempDir) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo(&tahinli.id, "forge", "", Visibility::Public, "main") .await diff --git a/crates/forge-core/src/store/push_recent.rs b/crates/forge-core/src/store/push_recent.rs index e9b634a..7799e40 100644 --- a/crates/forge-core/src/store/push_recent.rs +++ b/crates/forge-core/src/store/push_recent.rs @@ -8,7 +8,8 @@ use crate::model::Id; /// The all-zero object ids that mark a ref deletion: SHA-1 (40 digits) and SHA-256 (64 digits). pub(super) const ZERO_OID_SHA1: &str = "0000000000000000000000000000000000000000"; -pub(super) const ZERO_OID_SHA256: &str = "0000000000000000000000000000000000000000000000000000000000000000"; +pub(super) const ZERO_OID_SHA256: &str = + "0000000000000000000000000000000000000000000000000000000000000000"; impl Store { /// Branches `pusher_id` pushed to in any of `repo_ids` at or after `since` (an RFC 3339 @@ -99,7 +100,10 @@ mod tests { async fn store_with_repos() -> (tempfile::TempDir, Store, Id, Id, Id, Id) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let tahinli = store.create_user("tahinli", None, "x", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "x", false) + .await + .unwrap(); let bob = store.create_user("bob", None, "x", false).await.unwrap(); let demo = store .create_repo(&tahinli.id, "demo", "", Visibility::Public, "main") diff --git a/crates/forge-core/src/store/repo_listing.rs b/crates/forge-core/src/store/repo_listing.rs new file mode 100644 index 0000000..dfcfccf --- /dev/null +++ b/crates/forge-core/src/store/repo_listing.rs @@ -0,0 +1,409 @@ +//! Paged repo listings filtered in SQL: the public listing (`/explore`) and the profile tabs (a +//! user's repos, a user's stars). Read access is decided in the query with the same rules as +//! `authz::authorize` for `Action::Read`, so no per-repo role lookup is needed. + +use turso::Value; + +use super::{ + ListedRepo, REPO_COLS, RepoSort, Store, col_int, col_text, fetch_all, fetch_opt, issues, + map_repo, +}; +use crate::error::Result; +use crate::model::User; + +/// Whose repos a profile tab lists. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RepoScope<'a> { + /// The repos owned by this user or organization id. + OwnedBy(&'a str), + /// The repos this user id has starred. + StarredBy(&'a str), +} + +/// The last activity time of `r`: its latest push, or its creation time. +const ACTIVITY: &str = "COALESCE((SELECT MAX(p.created_at) FROM push_events p \ + WHERE p.repo_id = r.id), r.created_at)"; +/// The star count of `r`. +const STARS: &str = "(SELECT COUNT(*) FROM stars s WHERE s.repo_id = r.id)"; + +/// The SQL condition under which a signed-in, non-admin viewer may read repo `r`, taking the +/// viewer id four times (bind it as four `?` parameters). It mirrors `authorize` for Read: +/// public repos, the viewer's own repos, repos where the viewer is a collaborator, and repos of an +/// org where the viewer's org role (`Store::org_repo_role`) is some role: an org owner, a member +/// when the default repo role is not `none`, or a member of a team covering the repo. +const READABLE_BY_VIEWER: &str = "(r.visibility = 'public' OR r.owner_id = ? \ + OR EXISTS (SELECT 1 FROM collaborators c WHERE c.repo_id = r.id AND c.user_id = ?) \ + OR EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = r.owner_id AND m.user_id = ? AND ( \ + m.role = 'owner' \ + OR EXISTS (SELECT 1 FROM org_settings os WHERE os.org_id = r.owner_id \ + AND os.default_repo_role <> 'none') \ + OR EXISTS (SELECT 1 FROM teams t JOIN team_members tm ON tm.team_id = t.id \ + WHERE t.org_id = r.owner_id AND tm.user_id = ? AND (t.all_repos = 1 \ + OR EXISTS (SELECT 1 FROM team_repos tr WHERE tr.team_id = t.id \ + AND tr.repo_id = r.id))))))"; + +impl Store { + /// One page of a profile tab: the repos in `scope` that `viewer` may read, optionally + /// filtered by `query` (a case-insensitive substring of the name; `%`, `_` and `\` are + /// literal), in `sort` order. Rows carry the star count and the last activity time. A page + /// past the end is clamped to the last page. Returns the rows and the number of matches. + pub async fn list_visible_repos( + &self, + scope: RepoScope<'_>, + viewer: Option<&User>, + query: Option<&str>, + sort: RepoSort, + page: u64, + per_page: u64, + ) -> Result<(Vec, u64)> { + let (from_sql, mut clauses, mut params) = scoped(scope, viewer); + if let Some(q) = query.map(str::trim).filter(|q| !q.is_empty()) { + clauses.push("LOWER(r.name) LIKE ? ESCAPE '\\'"); + params.push(Value::Text(issues::like_pattern(&q.to_lowercase()))); + } + self.page_of_repos( + from_sql, + &clauses.join(" AND "), + params, + sort, + page, + per_page, + ) + .await + } + + /// How many repos in `scope` the viewer may read, with no name filter (the tab counts). + pub async fn count_visible_repos( + &self, + scope: RepoScope<'_>, + viewer: Option<&User>, + ) -> Result { + let (from_sql, clauses, params) = scoped(scope, viewer); + let conn = self.read_conn().await; + let n = fetch_opt( + &conn, + &format!( + "SELECT COUNT(*) FROM {from_sql} WHERE {}", + clauses.join(" AND ") + ), + params, + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + Ok(u64::try_from(n).unwrap_or(0)) + } + + /// One page of the repos `from_sql` (which joins `repos r` and its owner `users u`) yields + /// under `where_sql`, in `sort` order, with the total match count. `page` is 1-based and is + /// clamped to the last page; `per_page` to 1..=100. + pub(super) async fn page_of_repos( + &self, + from_sql: &str, + where_sql: &str, + params: Vec, + sort: RepoSort, + page: u64, + per_page: u64, + ) -> Result<(Vec, u64)> { + let order = match sort { + RepoSort::RecentlyUpdated => format!("{ACTIVITY} DESC, r.name_folded ASC, r.id"), + RepoSort::MostStars => format!("{STARS} DESC, r.name_folded ASC, r.id"), + RepoSort::Name => "r.name_folded ASC, u.username_folded ASC, r.id".to_owned(), + }; + let per_page = per_page.clamp(1, 100); + + let conn = self.read_conn().await; + let total = fetch_opt( + &conn, + &format!("SELECT COUNT(*) FROM {from_sql} WHERE {where_sql}"), + params.clone(), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + let total = u64::try_from(total).unwrap_or(0); + let pages = total.div_ceil(per_page).max(1); + let page = page.clamp(1, pages); + let offset = i64::try_from((page - 1) * per_page).unwrap_or(i64::MAX); + + let mut page_params = params; + page_params.push(Value::Integer(i64::try_from(per_page).unwrap_or(100))); + page_params.push(Value::Integer(offset)); + let rows = fetch_all( + &conn, + &format!( + "SELECT {REPO_COLS}, {STARS} AS stars, {ACTIVITY} AS activity \ + FROM {from_sql} WHERE {where_sql} ORDER BY {order} LIMIT ? OFFSET ?" + ), + page_params, + |row| { + let stars = u64::try_from(col_int(row, 10)?).unwrap_or(0); + Ok((map_repo(row)?, stars, col_text(row, 11)?)) + }, + ) + .await?; + Ok((rows, total)) + } +} + +/// The FROM clause, the WHERE clauses and their parameters for `scope` as seen by `viewer`. +fn scoped( + scope: RepoScope<'_>, + viewer: Option<&User>, +) -> (&'static str, Vec<&'static str>, Vec) { + let (from_sql, scope_id) = match scope { + RepoScope::OwnedBy(id) => ("repos r JOIN users u ON u.id = r.owner_id", id), + RepoScope::StarredBy(id) => ( + "stars st JOIN repos r ON r.id = st.repo_id JOIN users u ON u.id = r.owner_id", + id, + ), + }; + let mut clauses = vec![match scope { + RepoScope::OwnedBy(_) => "r.owner_id = ?", + RepoScope::StarredBy(_) => "st.user_id = ?", + }]; + let mut params = vec![Value::Text(scope_id.to_owned())]; + match viewer { + // Admins read everything. + Some(user) if user.is_admin => {} + Some(user) => { + clauses.push(READABLE_BY_VIEWER); + for _ in 0..4 { + params.push(Value::Text(user.id.clone())); + } + } + None => clauses.push("r.visibility = 'public'"), + } + (from_sql, clauses, params) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{Role, Visibility}; + use crate::store::orgs::{DefaultRepoRole, OrgMemberRole, OrgSettings}; + + struct Fixture { + store: Store, + owner: User, + _dir: tempfile::TempDir, + } + + async fn names(store: &Store, scope: RepoScope<'_>, viewer: Option<&User>) -> Vec { + let (rows, total) = store + .list_visible_repos(scope, viewer, None, RepoSort::Name, 1, 100) + .await + .unwrap(); + assert_eq!(total, rows.len() as u64); + assert_eq!( + store.count_visible_repos(scope, viewer).await.unwrap(), + total + ); + rows.into_iter().map(|(repo, _, _)| repo.name).collect() + } + + /// Tahinli owns `open` (public), `closed` and `shared` (private). + async fn fixture() -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); + let owner = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); + for (name, vis) in [ + ("open", Visibility::Public), + ("closed", Visibility::Private), + ("shared", Visibility::Private), + ] { + store + .create_repo(&owner.id, name, "", vis, "main") + .await + .unwrap(); + } + Fixture { + store, + owner, + _dir: dir, + } + } + + async fn repo_id(store: &Store, owner: &str, name: &str) -> String { + store + .repo_by_owner_and_name(owner, name) + .await + .unwrap() + .unwrap() + .id + } + + #[tokio::test] + async fn strangers_and_anonymous_viewers_never_see_private_repos() { + let fx = fixture().await; + let stranger = fx + .store + .create_user("mira", None, "h", false) + .await + .unwrap(); + let scope = RepoScope::OwnedBy(&fx.owner.id); + assert_eq!(names(&fx.store, scope, None).await, ["open"]); + assert_eq!(names(&fx.store, scope, Some(&stranger)).await, ["open"]); + assert_eq!( + names(&fx.store, scope, Some(&fx.owner)).await, + ["closed", "open", "shared"] + ); + } + + #[tokio::test] + async fn a_collaborator_sees_the_private_repo_they_work_on() { + let fx = fixture().await; + let carol = fx + .store + .create_user("carol", None, "h", false) + .await + .unwrap(); + let shared = repo_id(&fx.store, "tahinli", "shared").await; + fx.store + .set_collaborator(&shared, &carol.id, Role::Read) + .await + .unwrap(); + let scope = RepoScope::OwnedBy(&fx.owner.id); + assert_eq!( + names(&fx.store, scope, Some(&carol)).await, + ["open", "shared"] + ); + } + + #[tokio::test] + async fn an_admin_sees_everything() { + let fx = fixture().await; + let admin = fx.store.create_user("root", None, "h", true).await.unwrap(); + let scope = RepoScope::OwnedBy(&fx.owner.id); + assert_eq!( + names(&fx.store, scope, Some(&admin)).await, + ["closed", "open", "shared"] + ); + } + + /// The org repos `viewer` sees are `expected`, and the SQL rule agrees with `authorize` on + /// every org repo. + async fn check_org(store: &Store, org_id: &str, viewer: User, expected: &[&str]) { + let got = names(store, RepoScope::OwnedBy(org_id), Some(&viewer)).await; + assert_eq!(got, expected, "viewer {}", viewer.username); + for repo in store.list_repos_by_owner(org_id).await.unwrap() { + let role = store.collaborator_role(&repo.id, &viewer.id).await.unwrap(); + let org_role = store + .org_repo_role(org_id, &viewer.id, &repo.id) + .await + .unwrap(); + let allowed = crate::authz::authorize( + Some(&viewer), + &repo, + role, + org_role, + crate::authz::Action::Read, + ) + .is_ok(); + assert_eq!(allowed, got.contains(&repo.name), "{}", repo.name); + } + } + + #[tokio::test] + async fn org_roles_match_org_repo_role() { + let fx = fixture().await; + let org = fx.store.create_org("acme", &fx.owner.id).await.unwrap(); + let member = fx + .store + .create_user("mira", None, "h", false) + .await + .unwrap(); + let outsider = fx.store.create_user("zed", None, "h", false).await.unwrap(); + fx.store + .add_org_member(&org.id, &member.id, OrgMemberRole::Member) + .await + .unwrap(); + for name in ["infra", "web"] { + fx.store + .create_repo(&org.id, name, "", Visibility::Private, "main") + .await + .unwrap(); + } + let check = |viewer: &User, expected: &'static [&'static str]| { + check_org(&fx.store, &org.id, viewer.clone(), expected) + }; + + // The default repo role is read: every member sees every org repo. + check(&member, &["infra", "web"]).await; + check(&outsider, &[]).await; + check(&fx.owner, &["infra", "web"]).await; + + // With no default role, a plain member sees only what a team grants. + fx.store + .set_org_settings( + &org.id, + OrgSettings { + default_repo_role: DefaultRepoRole::None, + members_can_create_repos: true, + }, + ) + .await + .unwrap(); + check(&member, &[]).await; + let team = fx + .store + .create_team(&org.id, "ops", "", Role::Read, false) + .await + .unwrap(); + fx.store + .add_team_member(&team.id, &member.id) + .await + .unwrap(); + check(&member, &[]).await; + let infra = repo_id(&fx.store, "acme", "infra").await; + fx.store.add_team_repo(&team.id, &infra).await.unwrap(); + check(&member, &["infra"]).await; + // An org owner sees every org repo whatever the default. + check(&fx.owner, &["infra", "web"]).await; + // A team membership alone, without org membership, grants nothing. + fx.store.add_team_member(&team.id, &outsider.id).await.ok(); + check(&outsider, &[]).await; + } + + #[tokio::test] + async fn stars_scope_filters_search_and_pages() { + let fx = fixture().await; + let fan = fx + .store + .create_user("mira", None, "h", false) + .await + .unwrap(); + for name in ["open", "closed"] { + let id = repo_id(&fx.store, "tahinli", name).await; + fx.store.star(&fan.id, &id).await.unwrap(); + } + let scope = RepoScope::StarredBy(&fan.id); + assert_eq!(names(&fx.store, scope, None).await, ["open"]); + assert_eq!( + names(&fx.store, scope, Some(&fx.owner)).await, + ["closed", "open"] + ); + + let owned = RepoScope::OwnedBy(&fx.owner.id); + let (rows, total) = fx + .store + .list_visible_repos(owned, Some(&fx.owner), Some("SH%"), RepoSort::Name, 1, 10) + .await + .unwrap(); + assert_eq!(total, 0, "% is literal"); + assert!(rows.is_empty()); + let (rows, total) = fx + .store + .list_visible_repos(owned, Some(&fx.owner), Some("O"), RepoSort::Name, 9, 1) + .await + .unwrap(); + // "closed" and "open" match; page 9 of 2 is clamped to the last page. + assert_eq!(total, 2); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].0.name, "open"); + } +} diff --git a/crates/forge-core/src/store/signatures.rs b/crates/forge-core/src/store/signatures.rs index 9f7ba28..6e0e369 100644 --- a/crates/forge-core/src/store/signatures.rs +++ b/crates/forge-core/src/store/signatures.rs @@ -392,7 +392,10 @@ mod tests { let got = store.cached_signatures(&repo, &oids[..1]).await.unwrap(); assert_eq!(got[&oids[0]].status, SigStatus::Unverified); - store.invalidate_signatures_for_user(&tahinli).await.unwrap(); + store + .invalidate_signatures_for_user(&tahinli) + .await + .unwrap(); let got = store.cached_signatures(&repo, &oids).await.unwrap(); // signer rows and unknown_key rows are gone; the bad row stays. assert_eq!(got.len(), 1); diff --git a/crates/forge-core/src/store/webhooks.rs b/crates/forge-core/src/store/webhooks.rs index d7d7345..42efff9 100644 --- a/crates/forge-core/src/store/webhooks.rs +++ b/crates/forge-core/src/store/webhooks.rs @@ -1234,7 +1234,12 @@ mod tests { assert_eq!(count(&store, "webhook_deliveries").await, 1); } - async fn hook_at(store: &Store, tahinli: &User, repo: &crate::model::Repo, url: &str) -> Webhook { + async fn hook_at( + store: &Store, + tahinli: &User, + repo: &crate::model::Repo, + url: &str, + ) -> Webhook { store .create_webhook( &repo.id, diff --git a/crates/forge-core/tests/stars_store.rs b/crates/forge-core/tests/stars_store.rs index 73d5dbf..9febb43 100644 --- a/crates/forge-core/tests/stars_store.rs +++ b/crates/forge-core/tests/stars_store.rs @@ -18,7 +18,10 @@ async fn open_store(path: &Path) -> Store { async fn star_and_unstar_round_trip_with_count() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let bob = store.create_user("bob", None, "h", false).await.unwrap(); let repo = store .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") @@ -46,7 +49,10 @@ async fn star_and_unstar_round_trip_with_count() { async fn delete_repo_removes_its_stars() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") .await @@ -63,7 +69,10 @@ async fn delete_repo_removes_its_stars() { async fn public_listing_hides_private_repos_and_matches_literally() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); store .create_repo(&tahinli.id, "tools", "", Visibility::Public, "main") .await @@ -126,7 +135,10 @@ async fn public_listing_hides_private_repos_and_matches_literally() { async fn listing_sorts_by_stars_and_paginates() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let bob = store.create_user("bob", None, "h", false).await.unwrap(); let quiet = store .create_repo(&tahinli.id, "aaa", "", Visibility::Public, "main") @@ -163,7 +175,10 @@ async fn listing_sorts_by_stars_and_paginates() { async fn recently_updated_uses_latest_push_over_creation() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let older = store .create_repo(&tahinli.id, "older", "", Visibility::Public, "main") .await diff --git a/crates/forge-core/tests/store_basic.rs b/crates/forge-core/tests/store_basic.rs index 9d08420..9fe11f8 100644 --- a/crates/forge-core/tests/store_basic.rs +++ b/crates/forge-core/tests/store_basic.rs @@ -84,7 +84,10 @@ async fn duplicate_username_is_conflict_case_insensitive() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - store.create_user("Tahinli", None, "h", false).await.unwrap(); + store + .create_user("Tahinli", None, "h", false) + .await + .unwrap(); let err = store .create_user("TAHINLI", None, "h", false) .await @@ -100,7 +103,10 @@ async fn duplicate_username_is_conflict_case_insensitive() { async fn sessions_respect_expiry() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let live = store .create_session( @@ -179,7 +185,10 @@ async fn sessions_respect_expiry() { async fn ssh_key_exact_blob_lookup() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let blob: Vec = vec![ 0, 0, 0, 11, b's', b's', b'h', b'-', b'e', b'd', b'2', b'5', b'5', b'1', b'9', 0, 0, 0, 32, @@ -225,7 +234,10 @@ async fn ssh_key_exact_blob_lookup() { async fn access_token_create_lookup_and_expiry() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let scopes = vec!["repo:read".to_string(), "repo:write".to_string()]; let live = store @@ -278,7 +290,10 @@ async fn access_token_create_lookup_and_expiry() { async fn repo_create_and_case_insensitive_lookup() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("Tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("Tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo( @@ -342,7 +357,10 @@ async fn repo_create_and_case_insensitive_lookup() { .unwrap(); assert_eq!(bobs.owner_name, "bob"); - assert_eq!(store.list_repos_by_owner(&tahinli.id).await.unwrap().len(), 1); + assert_eq!( + store.list_repos_by_owner(&tahinli.id).await.unwrap().len(), + 1 + ); store.set_repo_archived(&repo.id, true).await.unwrap(); assert!(store.repo_by_id(&repo.id).await.unwrap().unwrap().archived); @@ -354,7 +372,10 @@ async fn repo_create_and_case_insensitive_lookup() { async fn collaborator_role_roundtrip() { let dir = tempfile::tempdir().unwrap(); let store = open_store(&db_path(&dir)).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let bob = store.create_user("bob", None, "h", false).await.unwrap(); let repo = store .create_repo(&tahinli.id, "proj", "", Visibility::Private, "main") @@ -382,7 +403,10 @@ async fn collaborator_role_roundtrip() { Some(Role::Maintain) ); assert_eq!( - store.collaborator_role(&repo.id, &tahinli.id).await.unwrap(), + store + .collaborator_role(&repo.id, &tahinli.id) + .await + .unwrap(), None ); } @@ -392,7 +416,10 @@ async fn push_event_is_recorded() { let dir = tempfile::tempdir().unwrap(); let path = db_path(&dir); let store = open_store(&path).await; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") .await diff --git a/crates/forge-git/src/verify.rs b/crates/forge-git/src/verify.rs index 30a4ab2..8cfa694 100644 --- a/crates/forge-git/src/verify.rs +++ b/crates/forge-git/src/verify.rs @@ -409,7 +409,8 @@ mod tests { #[test] fn parses_ssh_sentences() { - let text = "Good \"git\" signature for tahinli@example.com with ED25519 key SHA256:abc+def\n"; + let text = + "Good \"git\" signature for tahinli@example.com with ED25519 key SHA256:abc+def\n"; let raw = parse_output(text, Some(SigKind::Ssh)); assert!(raw.good); assert_eq!(raw.principal.as_deref(), Some("tahinli@example.com")); diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 34e161c..f832d3a 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -414,6 +414,28 @@ load({ target: withoutHash(url), dest: url, init: GET_INIT, how: 'pop', keep: false, post: false, form: null }); }); + // Search as you type: a search field marked data-live-search refetches its GET form 250 ms after + // the last keystroke and swaps the page in place, with no history entry and the field's focus and + // caret kept. A newer request drops an older answer. The submit button stays as the no-JS path. + var searchTimer = null; + function liveSearch(input) { + var el = input.isConnected ? input : document.querySelector('[data-live-search]'); + var form = el && el.form; + var url = form ? pageUrl(form.getAttribute('action') || location.href) : null; + if (!url) { return; } + var dest = withoutHash(url); + var q = new URLSearchParams(new FormData(form)).toString(); + dest.search = q ? '?' + q : ''; + if (dest.pathname + dest.search === shown) { return; } + load({ target: dest, dest: dest, init: GET_INIT, how: 'query', keep: true, post: false, form: null }); + } + document.addEventListener('input', function (e) { + var input = e.target && e.target.closest ? e.target.closest('[data-live-search]') : null; + if (!input || !input.form) { return; } + clearTimeout(searchTimer); + searchTimer = setTimeout(function () { searchTimer = null; liveSearch(input); }, 250); + }); + // Filter controls submit their form on change. document.addEventListener('change', function (e) { var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; diff --git a/crates/forge-web/src/accent.rs b/crates/forge-web/src/accent.rs index b318a12..e372697 100644 --- a/crates/forge-web/src/accent.rs +++ b/crates/forge-web/src/accent.rs @@ -59,7 +59,7 @@ mod tests { use std::collections::HashSet; use super::*; - use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS, Tokens}; + use crate::accent_palette::{BASE_TOKEN_VARS, TOKEN_VARS}; /// WCAG relative luminance of a `#RRGGBB` colour. fn luminance(hex: &str) -> f64 { @@ -219,18 +219,4 @@ mod tests { } } } - - #[test] - fn heatmap_steps_grow_in_lightness_towards_the_strong_end() { - fn steps(t: &Tokens) -> [f64; 5] { - [t.h0, t.h1, t.h2, t.h3, t.h4].map(luminance) - } - for p in PALETTES { - // Light theme: each step is darker than the one before. Dark theme: each is lighter. - let light = steps(&p.light); - assert!(light.windows(2).all(|w| w[0] > w[1]), "{} light", p.id); - let dark = steps(&p.dark); - assert!(dark.windows(2).all(|w| w[0] < w[1]), "{} dark", p.id); - } - } } diff --git a/crates/forge-web/src/accent_palette.rs b/crates/forge-web/src/accent_palette.rs index 3b42136..2424d10 100644 --- a/crates/forge-web/src/accent_palette.rs +++ b/crates/forge-web/src/accent_palette.rs @@ -16,11 +16,6 @@ pub struct Tokens { pub note: &'static str, pub hunk_bg: &'static str, pub hunk_text: &'static str, - pub h0: &'static str, - pub h1: &'static str, - pub h2: &'static str, - pub h3: &'static str, - pub h4: &'static str, } /// One accent colour: its id (the stored value and the `data-accent` attribute), and the tokens @@ -82,30 +77,11 @@ pub const TOKEN_VARS: &[TokenVar] = &[ name: "--hunk-text", value: |t| t.hunk_text, }, - TokenVar { - name: "--h0", - value: |t| t.h0, - }, - TokenVar { - name: "--h1", - value: |t| t.h1, - }, - TokenVar { - name: "--h2", - value: |t| t.h2, - }, - TokenVar { - name: "--h3", - value: |t| t.h3, - }, - TokenVar { - name: "--h4", - value: |t| t.h4, - }, ]; -/// Every accent colour on offer, in the order the picker lists them. Heatmap steps run from -/// `h0` (nearly the background) to `h4` (strongest). +/// Every accent colour on offer, in the order the picker lists them. The heatmap levels are not +/// here: style/_heatmap.scss mixes them from `--accent`/`--accent-ink` and the base's surface, +/// so they follow every accent and base. pub const PALETTES: &[Palette] = &[ // Sage: the original forge colour. Palette { @@ -121,11 +97,6 @@ pub const PALETTES: &[Palette] = &[ note: "#4A6750", hunk_bg: "#EDF1EB", hunk_text: "#3F5F46", - h0: "#E6ECE4", - h1: "#C6D9C8", - h2: "#9DBDA2", - h3: "#6F9676", - h4: "#3F5F46", }, dark: Tokens { accent: "#9DBEA2", @@ -138,11 +109,6 @@ pub const PALETTES: &[Palette] = &[ note: "#B5D2B9", hunk_bg: "#1E2620", hunk_text: "#9DBEA2", - h0: "#1F2722", - h1: "#2D3D31", - h2: "#41604A", - h3: "#628A6C", - h4: "#9DBEA2", }, }, // Blue, clear and cool. @@ -159,11 +125,6 @@ pub const PALETTES: &[Palette] = &[ note: "#336180", hunk_bg: "#E9F1F7", hunk_text: "#2B5977", - h0: "#DFECF5", - h1: "#BED7EA", - h2: "#99BEDA", - h3: "#6692B1", - h4: "#2C5D7E", }, dark: Tokens { accent: "#86B9DD", @@ -176,11 +137,6 @@ pub const PALETTES: &[Palette] = &[ note: "#9FCBEA", hunk_bg: "#1A252E", hunk_text: "#86B9DD", - h0: "#1B262F", - h1: "#243B4C", - h2: "#375C76", - h3: "#5685A5", - h4: "#88BBDF", }, }, // Violet with a soft, muted edge. @@ -197,11 +153,6 @@ pub const PALETTES: &[Palette] = &[ note: "#645482", hunk_bg: "#F0EEF7", hunk_text: "#5C4B79", - h0: "#ECE7F6", - h1: "#D7CEEA", - h2: "#BEB1DA", - h3: "#9382B2", - h4: "#5F4D7E", }, dark: Tokens { accent: "#BBA9E0", @@ -214,11 +165,6 @@ pub const PALETTES: &[Palette] = &[ note: "#CBBCEB", hunk_bg: "#25212E", hunk_text: "#BBA9E0", - h0: "#26222F", - h1: "#3C334C", - h2: "#5D4F76", - h3: "#8674A6", - h4: "#BBA9E0", }, }, // Dusty pink, warm and quiet. @@ -235,11 +181,6 @@ pub const PALETTES: &[Palette] = &[ note: "#864958", hunk_bg: "#F7ECEE", hunk_text: "#7D4050", - h0: "#F8E4E8", - h1: "#EEC7CF", - h2: "#DFA7B3", - h3: "#B67785", - h4: "#814151", }, dark: Tokens { accent: "#E79DAD", @@ -252,11 +193,6 @@ pub const PALETTES: &[Palette] = &[ note: "#F3B2C0", hunk_bg: "#2F1E22", hunk_text: "#E79DAD", - h0: "#301F23", - h1: "#4E2D35", - h2: "#794652", - h3: "#AA6978", - h4: "#E69CAC", }, }, // Clay brown, warmer and earthier than the warning amber. @@ -273,11 +209,6 @@ pub const PALETTES: &[Palette] = &[ note: "#7A5338", hunk_bg: "#F6EEE8", hunk_text: "#724B30", - h0: "#F4E7DF", - h1: "#E6CEBE", - h2: "#D4B199", - h3: "#AB8267", - h4: "#764D30", }, dark: Tokens { accent: "#D8A98A", @@ -290,11 +221,6 @@ pub const PALETTES: &[Palette] = &[ note: "#E4BCA1", hunk_bg: "#2C211A", hunk_text: "#D8A98A", - h0: "#2D221B", - h1: "#483325", - h2: "#704F39", - h3: "#9E7458", - h4: "#D8A989", }, }, // Blue-grey graphite, nearly neutral. @@ -311,11 +237,6 @@ pub const PALETTES: &[Palette] = &[ note: "#505E6C", hunk_bg: "#EAF0F7", hunk_text: "#485563", - h0: "#E6EAEF", - h1: "#CCD4DD", - h2: "#AFBAC7", - h3: "#808E9C", - h4: "#4C5A69", }, dark: Tokens { accent: "#A4B4C4", @@ -328,11 +249,6 @@ pub const PALETTES: &[Palette] = &[ note: "#B8C6D5", hunk_bg: "#212428", hunk_text: "#A4B4C4", - h0: "#222529", - h1: "#323941", - h2: "#4E5965", - h3: "#728090", - h4: "#A6B6C7", }, }, ]; diff --git a/crates/forge-web/src/auth.rs b/crates/forge-web/src/auth.rs index 9819884..496cf20 100644 --- a/crates/forge-web/src/auth.rs +++ b/crates/forge-web/src/auth.rs @@ -415,7 +415,10 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); let key = [7u8; 32]; - let tahinli = store.create_user("tahinli", None, "h", false).await.unwrap(); + let tahinli = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let org = store.create_org("acme", &tahinli.id).await.unwrap(); let shared = forge_core::totp::new_secret(); let sealed = forge_core::secret::seal(&key, &shared).unwrap(); diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 268b5be..f2a97d7 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -136,6 +136,7 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { .cookies() .layer(crate::pages::settings_profile::avatar_body_limit()) .layer(crate::pages::repo_ctx::RepoMovedLayer) + .layer(crate::pages::not_found_page::NotFoundLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) .compression(Compression::off()) .build(); diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index bcf07ba..0581c3c 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -634,6 +634,80 @@ async fn finish_skips_dependants_on_failure() { assert_eq!(again.status, 401); } +/// Parallel `test` and `build` on a deploy-branch push: `build` finishes green first, then `test` +/// fails. Neither finish leaves the run in a state that self-update deploys. +#[tokio::test] +async fn build_green_before_test_fails_never_qualifies_for_self_update() { + let env = bare_with_self_update().await; + let (_, secret) = runner(&env, &[]).await; + let run = make_run( + &env, + "push", + None, + COMMIT, + &[job("build", spec(&[], &[])), job("test", spec(&[], &[]))], + ) + .await; + let cfg = forge_core::config::SelfUpdateConfig { + enabled: true, + repo: format!("{OWNER}/{REPO}"), + ..Default::default() + }; + let full_name = format!("{OWNER}/{REPO}"); + let qualifies = |run: &CiRun| { + crate::self_update::should_deploy(&cfg, &full_name, run, Some(run.id.as_str())) + }; + + // Both jobs are claimable at once: no `needs` between them. + let first = claim_job(&env.router, &secret).await; + let second = claim_job(&env.router, &secret).await; + let (build, test) = if first["job_name"] == "build" { + (first, second) + } else { + (second, first) + }; + assert_eq!(build["job_name"], "build"); + assert_eq!(test["job_name"], "test"); + let finish = |assignment: &Value, outcome: &'static str| { + let job_id = assignment["job_id"].as_str().unwrap().to_owned(); + let token = assignment["job_token"].as_str().unwrap().to_owned(); + let router = env.router.clone(); + async move { + send( + &router, + "POST", + &format!("/api/v1/ci/jobs/{job_id}/finish"), + &[bearer(&token)], + finish_body(outcome), + ) + .await + } + }; + + let sent = finish(&build, "success").await; + assert_eq!(sent.status, 200, "{}", sent.json()); + assert_eq!(sent.json()["state"], "running", "test is still running"); + let after_build = env.store.run_by_id(&run.id).await.unwrap().unwrap(); + assert!( + !qualifies(&after_build), + "a green build alone never deploys" + ); + + let sent = finish(&test, "failure").await; + assert_eq!(sent.status, 200, "{}", sent.json()); + assert_eq!(sent.json()["state"], "failure"); + let after_test = env.store.run_by_id(&run.id).await.unwrap().unwrap(); + assert!( + !qualifies(&after_test), + "a run with a failed job never deploys" + ); + + // Control: the same run shape with both jobs green does qualify. + let mut green = after_test.clone(); + green.state = forge_core::ci::RunState::Success; + assert!(qualifies(&green)); +} + // --------------------------------------------------------------------------------------------- // Git read with a job token // --------------------------------------------------------------------------------------------- diff --git a/crates/forge-web/src/ci/release.rs b/crates/forge-web/src/ci/release.rs index 9dfab5d..f9cdd82 100644 --- a/crates/forge-web/src/ci/release.rs +++ b/crates/forge-web/src/ci/release.rs @@ -616,6 +616,61 @@ title = "forge {tag}" assert!(release_named(&fx, "v1.0").await.is_none()); } + /// Parallel jobs: `build` finishes green while `docs` still runs, then `docs` fails. The + /// release hook runs after each finish, as `finish_job` does, and never publishes. + #[tokio::test] + async fn build_green_first_then_other_job_fails_creates_no_release() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + let run = run_of(&fx, 1).await; + let build = job_of(&fx, &run, "build").await; + let docs = job_of(&fx, &run, "docs").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; + + let after_build = fx + .state + .store + .finish_job(&build.id, JobState::Success, Some(0), None) + .await + .expect("finish build"); + assert_eq!(after_build.state, RunState::Running, "docs is still queued"); + on_run_finished(&fx.state, &after_build).await; + assert!(release_named(&fx, "v1.0").await.is_none()); + + let after_docs = fx + .state + .store + .finish_job(&docs.id, JobState::Failure, Some(1), None) + .await + .expect("finish docs"); + assert_eq!(after_docs.state, RunState::Failure); + on_run_finished(&fx.state, &after_docs).await; + assert!(release_named(&fx, "v1.0").await.is_none()); + } + + /// Fail fast: `docs` fails while `build` has not finished. `build` is cancelled at once (the + /// running-job path is covered in the store tests), the run fails, and no release is created. + #[tokio::test] + async fn failing_job_cancels_build_and_creates_no_release() { + let fx = fixture().await; + push(&fx, &[(CONFIG_PATH, RELEASE)], "refs/tags/v1.0").await; + let run = run_of(&fx, 1).await; + let build = job_of(&fx, &run, "build").await; + let docs = job_of(&fx, &run, "docs").await; + add_artifact(&fx, &build, "dist_forge-linux-x86_64", b"binary").await; + + let after_docs = fx + .state + .store + .finish_job(&docs.id, JobState::Failure, Some(1), None) + .await + .expect("finish docs"); + assert_eq!(after_docs.state, RunState::Failure); + assert_eq!(job_of(&fx, &run, "build").await.state, JobState::Cancelled); + on_run_finished(&fx.state, &after_docs).await; + assert!(release_named(&fx, "v1.0").await.is_none()); + } + #[tokio::test] async fn branch_push_run_creates_no_release() { let fx = fixture().await; @@ -665,9 +720,16 @@ title = "forge {tag}" commit_message(&fx.work, "feat: one"); let oid = commit_message(&fx.work, "fix: two"); land(&fx, &oid, "refs/tags/v1.1"); - after_ref_update(&fx.state, &fx.repo, &fx.owner.id, "refs/tags/v1.1", ZERO, &oid) - .await - .expect("post update"); + after_ref_update( + &fx.state, + &fx.repo, + &fx.owner.id, + "refs/tags/v1.1", + ZERO, + &oid, + ) + .await + .expect("post update"); finish_all(&fx, &run_of(&fx, 2).await.id, None).await; on_run_finished(&fx.state, &run_of(&fx, 2).await).await; diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index e6aaa0b..1220b33 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -721,7 +721,7 @@ run = "make" .expect("job log"); assert!( log.starts_with( - "[forge] warning: unknown key `future` ignored \u{2014} this forge may be older than your ci.toml\n" + "[forge] warning: unknown key `future` ignored: this forge may be older than your ci.toml\n" ), "log was {log:?}" ); diff --git a/crates/forge-web/src/compression.rs b/crates/forge-web/src/compression.rs index fbdd65e..9262260 100644 --- a/crates/forge-web/src/compression.rs +++ b/crates/forge-web/src/compression.rs @@ -230,13 +230,19 @@ mod tests { async fn git_smart_http_is_never_compressed() { let router = router(); assert_eq!(encoding(&router, "/tahinli/demo.git/info/refs").await, None); - assert_eq!(encoding(&router, "/tahinli/demo/git-upload-pack").await, None); + assert_eq!( + encoding(&router, "/tahinli/demo/git-upload-pack").await, + None + ); } #[tokio::test] async fn raw_and_binary_are_not_compressed() { let router = router(); - assert_eq!(encoding(&router, "/tahinli/demo/raw/main/a.txt").await, None); + assert_eq!( + encoding(&router, "/tahinli/demo/raw/main/a.txt").await, + None + ); assert_eq!(encoding(&router, "/tahinli/demo/blob.bin").await, None); } diff --git a/crates/forge-web/src/git_auth.rs b/crates/forge-web/src/git_auth.rs index 574f91d..5fd825c 100644 --- a/crates/forge-web/src/git_auth.rs +++ b/crates/forge-web/src/git_auth.rs @@ -142,7 +142,10 @@ mod tests { #[test] fn rejects_missing_colon() { - assert_eq!(parse_basic_auth(&headers_with(&basic("tahinlitoken"))), None); + assert_eq!( + parse_basic_auth(&headers_with(&basic("tahinlitoken"))), + None + ); } #[test] diff --git a/crates/forge-web/src/i18n/admin.rs b/crates/forge-web/src/i18n/admin.rs index 25d2cf6..fb2f9c2 100644 --- a/crates/forge-web/src/i18n/admin.rs +++ b/crates/forge-web/src/i18n/admin.rs @@ -605,6 +605,7 @@ pub fn healthcheck_host(lang: Lang, host: Option<&str>) -> String { /// "every 6 hours". pub fn every_hours(lang: Lang, hours: u64) -> String { match lang { + Lang::En if hours == 1 => "every hour".to_owned(), Lang::En => format!("every {hours} hours"), Lang::Tr => format!("her {hours} saatte bir"), } @@ -613,6 +614,7 @@ pub fn every_hours(lang: Lang, hours: u64) -> String { /// "every 7 days". pub fn every_days(lang: Lang, days: u64) -> String { match lang { + Lang::En if days == 1 => "every day".to_owned(), Lang::En => format!("every {days} days"), Lang::Tr => format!("her {days} günde bir"), } diff --git a/crates/forge-web/src/i18n/code.rs b/crates/forge-web/src/i18n/code.rs index 3d058ae..827413c 100644 --- a/crates/forge-web/src/i18n/code.rs +++ b/crates/forge-web/src/i18n/code.rs @@ -400,7 +400,11 @@ pub fn lfs_missing(lang: Lang, size: &str) -> String { /// The note for a binary file, with its size in bytes. pub fn binary_note(lang: Lang, bytes: impl std::fmt::Display) -> String { match lang { - Lang::En => format!("Binary file, {bytes} bytes"), + Lang::En => { + let bytes = bytes.to_string(); + let unit = if bytes == "1" { "byte" } else { "bytes" }; + format!("Binary file, {bytes} {unit}") + } Lang::Tr => format!("İkili dosya, {bytes} bayt"), } } diff --git a/crates/forge-web/src/i18n/community.rs b/crates/forge-web/src/i18n/community.rs index b48fadd..14135a3 100644 --- a/crates/forge-web/src/i18n/community.rs +++ b/crates/forge-web/src/i18n/community.rs @@ -406,7 +406,7 @@ pub fn page_too_large(lang: Lang, max: usize) -> String { } } -/// `2 file(s) · updated 3 days ago` / `2 dosya · 3 gün önce güncellendi`. +/// `2 files · updated 3 days ago` / `2 dosya · 3 gün önce güncellendi`. /// `updated 3 days ago` / `3 gün önce güncellendi`. pub fn updated_on(lang: Lang, updated: &str) -> String { match lang { @@ -417,7 +417,10 @@ pub fn updated_on(lang: Lang, updated: &str) -> String { pub fn files_updated(lang: Lang, count: u64, updated: &str) -> String { match lang { - Lang::En => format!("{count} file(s) · updated {updated}"), + Lang::En => format!( + "{count} {} · updated {updated}", + if count == 1 { "file" } else { "files" } + ), Lang::Tr => format!("{count} dosya · {updated} güncellendi"), } } @@ -570,6 +573,7 @@ mod tests { assert_eq!(comments_count(Lang::En, 3), "3 comments"); assert_eq!(comments_count(Lang::Tr, 3), "3 yorum"); assert_eq!(page_number(Lang::Tr, 2), "Sayfa 2"); - assert_eq!(files_updated(Lang::En, 2, "now"), "2 file(s) · updated now"); + assert_eq!(files_updated(Lang::En, 2, "now"), "2 files · updated now"); + assert_eq!(files_updated(Lang::En, 1, "now"), "1 file · updated now"); } } diff --git a/crates/forge-web/src/i18n/misc.rs b/crates/forge-web/src/i18n/misc.rs index 05f2d13..2e05c07 100644 --- a/crates/forge-web/src/i18n/misc.rs +++ b/crates/forge-web/src/i18n/misc.rs @@ -634,11 +634,11 @@ pub fn date_text(lang: Lang, year: i64, month: i64, day: i64) -> String { format!("{day} {} {year}", month_abbrev(lang, month)) } -/// `16 Oct 2025 to 16 Oct 2026` in English; Turkish joins the two dates with a dash. +/// `16 Oct 2025 to 16 Oct 2026` in English; Turkish uses `ile ... arası`. pub fn date_range(lang: Lang, from: &str, to: &str) -> String { match lang { Lang::En => format!("{from} to {to}"), - Lang::Tr => format!("{from} – {to}"), + Lang::Tr => format!("{from} ile {to} arası"), } } @@ -646,13 +646,13 @@ pub fn date_range(lang: Lang, from: &str, to: &str) -> String { /// streak (which counts today when `today > 0`). pub fn heatmap_motivation(lang: Lang, today: u64, streak: u64) -> String { match (lang, today > 0, streak > 0) { - (Lang::En, true, _) => format!("Nice \u{2014} that's a {streak}-day streak."), + (Lang::En, true, _) => format!("Nice, that's a {streak}-day streak!"), (Lang::En, false, true) => format!( "Keep it going: one commit today makes it a {}-day streak.", streak + 1 ), (Lang::En, false, false) => "Start a new streak today.".to_owned(), - (Lang::Tr, true, _) => format!("Harika \u{2014} {streak} günlük bir seri!"), + (Lang::Tr, true, _) => format!("Harika, {streak} günlük seri!"), (Lang::Tr, false, true) => format!( "Devam edin: bugün bir katkı, seriyi {} güne çıkarır.", streak + 1 diff --git a/crates/forge-web/src/i18n/orgs.rs b/crates/forge-web/src/i18n/orgs.rs index 59892dc..4e2a044 100644 --- a/crates/forge-web/src/i18n/orgs.rs +++ b/crates/forge-web/src/i18n/orgs.rs @@ -106,7 +106,6 @@ pub enum K { NoPublicReposMatch, // Profile. LocalTime, - AllMembers, NoMembers, NoVisibleRepos, NoVisibleStarred, @@ -339,8 +338,6 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoPublicReposMatch, Tr) => "Aramayla eşleşen herkese açık depo yok.", (LocalTime, En) => "Local time: ", (LocalTime, Tr) => "Yerel saat: ", - (AllMembers, En) => "All members", - (AllMembers, Tr) => "Tüm üyeler", (NoMembers, En) => "No members.", (NoMembers, Tr) => "Üye yok.", (NoVisibleRepos, En) => "No visible repositories.", @@ -451,19 +448,33 @@ pub fn role_for(lang: Lang, user: &str) -> String { /// The member and team counts on a profile. pub fn members_and_teams(lang: Lang, members: usize, teams: usize) -> String { match lang { - Lang::En => format!("{members} members \u{b7} {teams} teams"), + Lang::En => format!( + "{members} member{} \u{b7} {teams} team{}", + if members == 1 { "" } else { "s" }, + if teams == 1 { "" } else { "s" } + ), Lang::Tr => format!("{members} üye \u{b7} {teams} takım"), } } -/// "3 repositories", or "3 depo" in Turkish. +/// "1 repository", "3 repositories", or "3 depo" in Turkish (no plural after a number). pub fn repo_count(lang: Lang, total: u64) -> String { match lang { + Lang::En if total == 1 => "1 repository".to_owned(), Lang::En => format!("{total} repositories"), Lang::Tr => format!("{total} depo"), } } +/// "1 starred repository", "3 starred repositories", or "3 yıldızlı depo" in Turkish. +pub fn starred_count(lang: Lang, total: u64) -> String { + match lang { + Lang::En if total == 1 => "1 starred repository".to_owned(), + Lang::En => format!("{total} starred repositories"), + Lang::Tr => format!("{total} yıldızlı depo"), + } +} + /// "Page 2 of 5", or "Sayfa 2 / 5" in Turkish. pub fn page_of(lang: Lang, page: u64, pages: u64) -> String { match lang { @@ -472,11 +483,12 @@ pub fn page_of(lang: Lang, page: u64, pages: u64) -> String { } } -/// The updated note after a repository's stars: " · updated 3 days ago", or " · 3 gün önce güncellendi". -pub fn updated_text(lang: Lang, when: &str) -> String { +/// The text around the relative time in the updated note after a repository's stars, as +/// (before, after): " · updated 3 days ago", or " · 3 gün önce güncellendi". +pub fn updated_parts(lang: Lang) -> (&'static str, &'static str) { match lang { - Lang::En => format!(" \u{b7} updated {when}"), - Lang::Tr => format!(" \u{b7} {when} güncellendi"), + Lang::En => (" \u{b7} updated ", ""), + Lang::Tr => (" \u{b7} ", " güncellendi"), } } @@ -578,7 +590,6 @@ mod tests { K::SortMostStars, K::NoPublicReposMatch, K::LocalTime, - K::AllMembers, K::NoMembers, K::NoVisibleRepos, K::NoVisibleStarred, @@ -635,19 +646,16 @@ mod tests { "bağlı depolarda okuma" ); assert_eq!(page_of(Lang::En, 2, 5), "Page 2 of 5"); - assert_eq!( - updated_text(Lang::En, "3 days ago"), - " \u{b7} updated 3 days ago" - ); - assert_eq!( - updated_text(Lang::Tr, "3 gün önce"), - " \u{b7} 3 gün önce güncellendi" - ); + assert_eq!(updated_parts(Lang::En), (" \u{b7} updated ", "")); + assert_eq!(updated_parts(Lang::Tr), (" \u{b7} ", " güncellendi")); assert_eq!(repo_count(Lang::En, 3), "3 repositories"); - assert_eq!( - members_and_teams(Lang::En, 2, 1), - "2 members \u{b7} 1 teams" - ); + assert_eq!(repo_count(Lang::En, 1), "1 repository"); + assert_eq!(repo_count(Lang::Tr, 1), "1 depo"); + assert_eq!(starred_count(Lang::En, 1), "1 starred repository"); + assert_eq!(starred_count(Lang::En, 2), "2 starred repositories"); + assert_eq!(starred_count(Lang::Tr, 2), "2 yıldızlı depo"); + assert_eq!(members_and_teams(Lang::En, 2, 1), "2 members \u{b7} 1 team"); + assert_eq!(members_and_teams(Lang::En, 1, 3), "1 member \u{b7} 3 teams"); assert_eq!(type_to_confirm(Lang::En, "acme"), "Type acme to confirm"); assert_eq!( description_too_long(Lang::En, 2000), diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index cccbf2c..6d8fb80 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -392,11 +392,11 @@ pub fn page_label(lang: Lang, page: u32) -> String { } } -/// "scale: 0 — 80 min", the scale of the run list in minutes. +/// "scale: 0 to 80 min", the scale of the run list in minutes. pub fn scale_label(lang: Lang, span: &str) -> String { match lang { - Lang::En => format!("scale: 0 \u{2014} {span}"), - Lang::Tr => format!("ölçek: 0 \u{2014} {span}"), + Lang::En => format!("scale: 0 to {span}"), + Lang::Tr => format!("ölçek: 0 ile {span} arası"), } } @@ -427,6 +427,7 @@ pub fn duration_seconds(lang: Lang, secs: i64) -> String { /// "3 downloads". pub fn download_count(lang: Lang, count: u64) -> String { match lang { + Lang::En if count == 1 => "1 download".to_owned(), Lang::En => format!("{count} downloads"), Lang::Tr => format!("{count} indirme"), } @@ -594,6 +595,7 @@ mod tests { fn counted_sentences_read_in_both_languages() { assert_eq!(download_count(Lang::En, 3), "3 downloads"); assert_eq!(download_count(Lang::Tr, 3), "3 indirme"); + assert_eq!(download_count(Lang::En, 1), "1 download"); assert_eq!(duration_minutes(Lang::En, 1, 5), "1m 5s"); assert_eq!(duration_minutes(Lang::Tr, 1, 5), "1 dk 5 sn"); assert_eq!(page_label(Lang::Tr, 2), "Sayfa 2"); diff --git a/crates/forge-web/src/lfs/gc.rs b/crates/forge-web/src/lfs/gc.rs index 690d661..b9e3d15 100644 --- a/crates/forge-web/src/lfs/gc.rs +++ b/crates/forge-web/src/lfs/gc.rs @@ -186,7 +186,10 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let data = dir.path(); let store = Store::open(&data.join("forge.db")).await.unwrap(); - let user = store.create_user("tahinli", None, "h", false).await.unwrap(); + let user = store + .create_user("tahinli", None, "h", false) + .await + .unwrap(); let repo = store .create_repo(&user.id, "demo", "", Visibility::Public, "main") .await diff --git a/crates/forge-web/src/mail/smtp.rs b/crates/forge-web/src/mail/smtp.rs index 48d9372..49cb999 100644 --- a/crates/forge-web/src/mail/smtp.rs +++ b/crates/forge-web/src/mail/smtp.rs @@ -106,8 +106,8 @@ fn build_transport( #[cfg(test)] mod tests { - use forge_core::mail::MailKind; use super::*; + use forge_core::mail::MailKind; fn settings() -> MailSettings { MailSettings { diff --git a/crates/forge-web/src/mail/worker.rs b/crates/forge-web/src/mail/worker.rs index 84107e9..09306b0 100644 --- a/crates/forge-web/src/mail/worker.rs +++ b/crates/forge-web/src/mail/worker.rs @@ -174,9 +174,17 @@ mod tests { async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; - enqueue(&state, "stuck", MailKind::Notification, None, "a@example.com", "Hi", "body") - .await - .expect("queued"); + enqueue( + &state, + "stuck", + MailKind::Notification, + None, + "a@example.com", + "Hi", + "body", + ) + .await + .expect("queued"); // A pass that took the row and died before it finished: the lease is still set. let held = state .store @@ -188,7 +196,11 @@ mod tests { assert_eq!(boot(&state).await.expect("boot"), 1); tick(&state).await.expect("pass"); - assert_eq!(fake.sent().len(), 1, "the released row goes out without waiting"); + assert_eq!( + fake.sent().len(), + 1, + "the released row goes out without waiting" + ); let row = state.store.recent_mail(10).await.expect("rows").remove(0); assert_eq!(row.status(), OutboxStatus::Sent); } @@ -198,15 +210,31 @@ mod tests { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; assert!( - enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body") - .await - .expect("queued") + enqueue( + &state, + "reset:1", + MailKind::PasswordReset, + None, + "a@example.com", + "Hi", + "body" + ) + .await + .expect("queued") ); // A second enqueue with the same key is a no-op. assert!( - !enqueue(&state, "reset:1", MailKind::PasswordReset, None, "a@example.com", "Hi", "body") - .await - .expect("again") + !enqueue( + &state, + "reset:1", + MailKind::PasswordReset, + None, + "a@example.com", + "Hi", + "body" + ) + .await + .expect("again") ); tick(&state).await.expect("pass"); @@ -237,9 +265,17 @@ mod tests { }) .await .expect("off"); - enqueue(&state, "k", MailKind::Other, None, "a@example.com", "Hi", "body") - .await - .expect("queued"); + enqueue( + &state, + "k", + MailKind::Other, + None, + "a@example.com", + "Hi", + "body", + ) + .await + .expect("queued"); assert_eq!(tick(&state).await.expect("pass"), BACKSTOP); assert!(fake.sent().is_empty()); let row = state.store.recent_mail(10).await.expect("rows"); @@ -251,12 +287,28 @@ mod tests { async fn a_transient_failure_is_retried_later_and_a_permanent_one_gives_up() { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; - enqueue(&state, "retry", MailKind::Other, None, "a@example.com", "Hi", "body") - .await - .expect("queued"); - enqueue(&state, "bounce", MailKind::Other, None, "b@example.com", "Hi", "body") - .await - .expect("queued"); + enqueue( + &state, + "retry", + MailKind::Other, + None, + "a@example.com", + "Hi", + "body", + ) + .await + .expect("queued"); + enqueue( + &state, + "bounce", + MailKind::Other, + None, + "b@example.com", + "Hi", + "body", + ) + .await + .expect("queued"); fake.fail_next(MailError::Transient("timeout".into())); fake.fail_next(MailError::Permanent("550 no such user".into())); @@ -283,9 +335,17 @@ mod tests { async fn the_last_try_gives_up_and_an_earlier_one_reschedules() { let dir = tempfile::tempdir().expect("tempdir"); let (state, fake) = enabled_state(dir.path()).await; - enqueue(&state, "stubborn", MailKind::Other, None, "a@example.com", "Hi", "body") - .await - .expect("queued"); + enqueue( + &state, + "stubborn", + MailKind::Other, + None, + "a@example.com", + "Hi", + "body", + ) + .await + .expect("queued"); let row = state.store.recent_mail(10).await.expect("rows").remove(0); fake.fail_next(MailError::Transient("timeout".into())); fake.fail_next(MailError::Transient("timeout".into())); diff --git a/crates/forge-web/src/pages/admin_mail.rs b/crates/forge-web/src/pages/admin_mail.rs index b386781..15c04dc 100644 --- a/crates/forge-web/src/pages/admin_mail.rs +++ b/crates/forge-web/src/pages/admin_mail.rs @@ -8,7 +8,9 @@ //! Saving the settings and queuing a test are audited. use forge_core::config::MailTransport; -use forge_core::mail::{MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security}; +use forge_core::mail::{ + MailKind, MailSettings, MailSettingsUpdate, MailState, OutboxEntry, Security, +}; use forge_core::time::now_stamp; use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Error}; @@ -117,7 +119,11 @@ fn transport_name(transport: MailTransport) -> &'static str { } fn tab_class(on: bool) -> &'static str { - if on { "subnav-link current" } else { "subnav-link" } + if on { + "subnav-link current" + } else { + "subnav-link" + } } fn row_view(entry: &OutboxEntry, now: &str, tz: &str, lang: Lang) -> QueueRow { @@ -224,7 +230,11 @@ async fn mail_view( let settings_on = data.tab == Tab::Settings; let settings_class = tab_class(settings_on); let queue_class = tab_class(!settings_on); - let filter_param = data.queue.as_ref().map(|q| q.filter_param.clone()).unwrap_or_default(); + let filter_param = data + .queue + .as_ref() + .map(|q| q.filter_param.clone()) + .unwrap_or_default(); Ok(view! {

(g::t(lang, K::Mail))

@@ -244,7 +254,7 @@ async fn mail_view(

(g::t(lang, K::SmtpServer))

(g::t(lang, K::MailTransportNote))

(g::t(lang, K::MailTransportInUse)) " " (data.transport)

-
+ @@ -588,9 +598,8 @@ async fn queue_action(cx: &Cx, form: QueueForm, action: QueueAction) -> Result forge_core::mail::OutgoingMail { + fn outgoing( + to: &str, + subject: &str, + body: &str, + kind: MailKind, + ) -> forge_core::mail::OutgoingMail { forge_core::mail::OutgoingMail { to: to.into(), subject: subject.into(), @@ -861,9 +875,22 @@ mod tests { "https://forge.test/reset/SECRET-LINK", MailKind::PasswordReset, ); - fx.state.store.enqueue_mail("reset:1", &reset).await.expect("queued"); - let later = outgoing("b@example.com", "Queued one", "body", MailKind::Notification); - fx.state.store.enqueue_mail("notif:2", &later).await.expect("queued"); + fx.state + .store + .enqueue_mail("reset:1", &reset) + .await + .expect("queued"); + let later = outgoing( + "b@example.com", + "Queued one", + "body", + MailKind::Notification, + ); + fx.state + .store + .enqueue_mail("notif:2", &later) + .await + .expect("queued"); let failed_id = fx .state .store @@ -880,21 +907,44 @@ mod tests { .await .expect("failed"); - let (status, body) = send(&fx.router, "GET", "/admin/mail?tab=queue", Some(ADMIN_TOKEN), None).await; + let (status, body) = send( + &fx.router, + "GET", + "/admin/mail?tab=queue", + Some(ADMIN_TOKEN), + None, + ) + .await; assert_eq!(status, 200); - assert!(body.contains("data-live=\"/admin/mail/events\""), "the queue is live"); + assert!( + body.contains("data-live=\"/admin/mail/events\""), + "the queue is live" + ); assert!(body.contains("Reset your password") && body.contains("Queued one")); assert!(body.contains("550 no such user"), "the last error shows"); assert!(!body.contains("SECRET-LINK"), "a body is never rendered"); assert!(body.contains("Retry now") && body.contains("/admin/mail/queue/retry")); - let (_, failed_only) = send(&fx.router, "GET", "/admin/mail?tab=queue&state=failed", Some(ADMIN_TOKEN), None).await; + let (_, failed_only) = send( + &fx.router, + "GET", + "/admin/mail?tab=queue&state=failed", + Some(ADMIN_TOKEN), + None, + ) + .await; assert!(failed_only.contains("Reset your password")); - assert!(!failed_only.contains("Queued one"), "the filter hides queued mail"); + assert!( + !failed_only.contains("Queued one"), + "the filter hides queued mail" + ); let (_, settings) = send(&fx.router, "GET", "/admin/mail", Some(ADMIN_TOKEN), None).await; assert!(!settings.contains("data-live="), "only the queue is live"); - assert!(!settings.contains("Reset your password"), "the queue is on its own tab"); + assert!( + !settings.contains("Reset your password"), + "the queue is on its own tab" + ); } #[tokio::test] @@ -905,9 +955,23 @@ mod tests { ("POST", "/admin/mail/queue/retry"), ("POST", "/admin/mail/queue/discard"), ] { - let (anon, _) = send(&fx.router, method, uri, None, Some(format!("csrf={CSRF}&id=x"))).await; + let (anon, _) = send( + &fx.router, + method, + uri, + None, + Some(format!("csrf={CSRF}&id=x")), + ) + .await; assert_eq!(anon, 404, "{method} {uri} for anonymous"); - let (user, _) = send(&fx.router, method, uri, Some(USER_TOKEN), Some(format!("csrf={CSRF}&id=x"))).await; + let (user, _) = send( + &fx.router, + method, + uri, + Some(USER_TOKEN), + Some(format!("csrf={CSRF}&id=x")), + ) + .await; assert_eq!(user, 404, "{method} {uri} for a plain user"); } } @@ -937,7 +1001,11 @@ mod tests { let fx = fixture().await; for key in ["k1", "k2"] { let mail = outgoing("a@example.com", "Hi", "b", MailKind::Notification); - fx.state.store.enqueue_mail(key, &mail).await.expect("queued"); + fx.state + .store + .enqueue_mail(key, &mail) + .await + .expect("queued"); } let ids: Vec = fx .state @@ -949,7 +1017,11 @@ mod tests { .map(|r| r.id) .collect(); for id in &ids { - fx.state.store.mark_mail_failed(id, "550", None).await.expect("failed"); + fx.state + .store + .mark_mail_failed(id, "550", None) + .await + .expect("failed"); } let (status, _) = send( @@ -1000,7 +1072,12 @@ mod tests { .await; assert_eq!(status, 303, "refused with a notice, not an error"); assert_eq!( - fx.state.store.list_mail(Some(MailState::Queued), &now, 10).await.expect("queued").len(), + fx.state + .store + .list_mail(Some(MailState::Queued), &now, 10) + .await + .expect("queued") + .len(), 1 ); let (status, _) = send( diff --git a/crates/forge-web/src/pages/admin_runners.rs b/crates/forge-web/src/pages/admin_runners.rs index b3b6d90..28bb704 100644 --- a/crates/forge-web/src/pages/admin_runners.rs +++ b/crates/forge-web/src/pages/admin_runners.rs @@ -9,6 +9,8 @@ use forge_core::AuditAction; use forge_core::ci::CiRunner; use serde::Deserialize; +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; @@ -24,7 +26,7 @@ use crate::i18n::{self, Key, Lang}; use crate::pages::admin_users::admin_only; use crate::pages::repo_mirrors::stamp_in_tz; use crate::state::AppState; -use crate::views::{enc, shell}; +use crate::views::{enc, now_unix, relative_time, shell}; path_param!(runner_id); @@ -54,22 +56,33 @@ struct DisableForm { /// One runner row, already formatted. struct RunnerRow { name: String, - labels: String, + labels: Vec, + /// "5 minutes ago", or "never". last_seen: String, + /// The absolute time in the viewer's zone, for the `title` tooltip. Empty when never seen. + last_seen_full: String, disabled: bool, toggle_action: String, delete_action: String, } -fn runner_row(runner: &CiRunner, tz: &str, lang: Lang) -> RunnerRow { +fn runner_row(runner: &CiRunner, tz: &str, lang: Lang, now: i64) -> RunnerRow { + let (last_seen, last_seen_full) = match runner.last_seen_at.as_deref() { + Some(stamp) => { + let full = stamp_in_tz(stamp, tz); + let relative = match OffsetDateTime::parse(stamp, &Rfc3339) { + Ok(at) => relative_time(lang, at.unix_timestamp(), now), + Err(_) => full.clone(), + }; + (relative, full) + } + None => (i18n::t(lang, Key::Never).to_owned(), String::new()), + }; RunnerRow { name: runner.name.clone(), - labels: runner.labels.join(", "), - last_seen: runner - .last_seen_at - .as_deref() - .map(|stamp| stamp_in_tz(stamp, tz)) - .unwrap_or_else(|| i18n::t(lang, Key::Never).to_owned()), + labels: runner.labels.clone(), + last_seen, + last_seen_full, disabled: runner.disabled, toggle_action: format!("/admin/runners/{}/disabled", enc(&runner.id)), delete_action: format!("/admin/runners/{}/delete", enc(&runner.id)), @@ -128,22 +141,34 @@ async fn runners_view( - - - - - + + + + + for row in rows.iter() { - - - - - + + + + for user in users.into_iter() { - + - +
(g::t(lang, K::TableName))(g::t(lang, K::TableLabels))(g::t(lang, K::LastSeen))(g::t(lang, K::TableState))(g::t(lang, K::TableName))(g::t(lang, K::TableLabels))(g::t(lang, K::LastSeen))(g::t(lang, K::TableState))
(row.name.as_str())(row.labels.as_str())(row.last_seen.as_str())(if row.disabled { g::t(lang, K::Disabled) } else { g::t(lang, K::Enabled) }) -
+
(row.name.as_str()) + + for label in row.labels.iter() { + (label.as_str()) + } + + (row.last_seen.as_str()) + if row.disabled { + (g::t(lang, K::Disabled)) + } else { + (g::t(lang, K::Enabled)) + } + +
@@ -205,12 +230,13 @@ async fn runners_page(cx: &Cx) -> Result { let lang = i18n::lang(cx, Some(&viewer.0)); let state = app_context::(cx); let tz = viewer.0.timezone.clone(); + let now = now_unix(); let rows: Vec = state .store .list_runners() .await? .iter() - .map(|runner| runner_row(runner, &tz, lang)) + .map(|runner| runner_row(runner, &tz, lang, now)) .collect(); let csrf = viewer.1.csrf_token.clone(); let notice = notice_from_query(cx, lang); @@ -491,6 +517,48 @@ mod tests { assert!(store.list_runners().await.expect("list").is_empty()); } + #[tokio::test] + async fn runner_labels_are_separate_chips_and_state_is_a_badge() { + let dir = tempfile::tempdir().expect("tempdir"); + let (store, router) = fixture(dir.path()).await; + let (_, created) = send( + &router, + "POST", + "/admin/runners/tokens", + Some(ADMIN_TOKEN), + csrf_form(""), + ) + .await; + let token = created + .split("--token ") + .nth(1) + .and_then(|rest| rest.split(' ').next()) + .expect("token") + .to_owned(); + store + .register_runner( + &token, + "tahinli-box", + &["linux".to_owned(), "x86_64".to_owned()], + ) + .await + .expect("register"); + let (status, page) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert_eq!(status, 200); + assert!(page.contains(r#"linux"#)); + assert!(page.contains(r#"x86_64"#)); + assert!(!page.contains("linux, x86_64"), "labels are not joined"); + assert!(page.contains(r#"enabled"#)); + + let runner = store.list_runners().await.expect("list").remove(0); + store + .set_runner_disabled(&runner.id, true) + .await + .expect("disable"); + let (_, page) = send(&router, "GET", "/admin/runners", Some(ADMIN_TOKEN), None).await; + assert!(page.contains(r#"disabled"#)); + } + #[tokio::test] async fn disable_enable_and_delete_a_runner() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/crates/forge-web/src/pages/admin_users.rs b/crates/forge-web/src/pages/admin_users.rs index 2ebd26e..87e5f8f 100644 --- a/crates/forge-web/src/pages/admin_users.rs +++ b/crates/forge-web/src/pages/admin_users.rs @@ -2,6 +2,7 @@ use forge_core::names::{normalize_name, validate_username}; use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME}; +use forge_core::tz::format_in_tz; use forge_core::{AuditAction, Session, Store, User}; use serde::Deserialize; use topcoat::Result; @@ -15,6 +16,7 @@ use crate::audit::{self, Actor, Target}; use crate::auth::{check_csrf, current_user, hash_password_async}; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; +use crate::pages::issues_list::stamp_unix; use crate::state::AppState; use crate::views::{alert, enc, shell, user_facing_message}; @@ -54,6 +56,7 @@ async fn users_view( lang: Lang, csrf: &str, viewer_id: &str, + tz: &str, users: Vec, error: Option, ) -> Result { @@ -70,10 +73,10 @@ async fn users_view(
(user.username.clone())(user.username.clone()) (user.email.clone().unwrap_or_default()) (if user.is_org() { g::t(lang, K::RoleOrganization) } else if user.is_admin { g::t(lang, K::RoleAdmin) } else { g::t(lang, K::RoleUser) })(user.created_at.clone())(format_in_tz(stamp_unix(&user.created_at), tz)) if user.id != viewer_id && !is_ghost(&user) { (i18n::t(lang, Key::Delete)) @@ -123,7 +126,7 @@ async fn users_page(cx: &Cx) -> Result { let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Users); Ok(view! { - shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), users: users, error: None)) + shell(title: title, viewer: Some(&viewer), users_view(lang: lang, csrf: csrf.as_str(), viewer_id: viewer.0.id.as_str(), tz: viewer.0.timezone.as_str(), users: users, error: None)) }) } @@ -160,7 +163,7 @@ async fn users_create(cx: &Cx, Form(form): Form) -> Result, show_actor: bool) -> Result

(g::t(lang, K::NoEntries))

} else {
- +
@@ -111,13 +111,13 @@ async fn audit_table(lang: Lang, rows: Vec, show_actor: bool) -> Result for row in rows.into_iter() { - + if show_actor { } - + } @@ -143,17 +143,17 @@ async fn admin_audit_view(

(g::t(lang, K::AuditIntro))

- -
}) } diff --git a/crates/forge-web/src/pages/fork.rs b/crates/forge-web/src/pages/fork.rs index 83f2f74..a167a18 100644 --- a/crates/forge-web/src/pages/fork.rs +++ b/crates/forge-web/src/pages/fork.rs @@ -169,7 +169,13 @@ mod tests { .await .expect("carol"); let demo = store - .create_repo(&tahinli.id, "demo", "A demo repo", Visibility::Public, "main") + .create_repo( + &tahinli.id, + "demo", + "A demo repo", + Visibility::Public, + "main", + ) .await .expect("demo"); let secret = store diff --git a/crates/forge-web/src/pages/issue_view.rs b/crates/forge-web/src/pages/issue_view.rs index d1c5387..1f730b8 100644 --- a/crates/forge-web/src/pages/issue_view.rs +++ b/crates/forge-web/src/pages/issue_view.rs @@ -230,7 +230,7 @@ async fn edit_item_page(
- + (g::t(lang, K::Cancel))
@@ -612,7 +612,8 @@ mod tests { .unwrap() .is_none() { - crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await; + crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf") + .await; } owner } diff --git a/crates/forge-web/src/pages/labels_page.rs b/crates/forge-web/src/pages/labels_page.rs index de7c176..ebe1aca 100644 --- a/crates/forge-web/src/pages/labels_page.rs +++ b/crates/forge-web/src/pages/labels_page.rs @@ -448,11 +448,18 @@ mod tests { #[tokio::test] async fn button_shows_only_for_triage_when_no_labels() { let site = site().await; - let (status, body) = - send(&site, "GET", "/tahinli/forge/labels", Some(&site.carol), CSRF).await; + let (status, body) = send( + &site, + "GET", + "/tahinli/forge/labels", + Some(&site.carol), + CSRF, + ) + .await; assert_eq!(status, 200); assert!(body.contains("/tahinli/forge/labels/defaults")); - let (status, body) = send(&site, "GET", "/tahinli/forge/labels", Some(&site.bob), CSRF).await; + let (status, body) = + send(&site, "GET", "/tahinli/forge/labels", Some(&site.bob), CSRF).await; assert_eq!(status, 200); assert!(!body.contains("/labels/defaults")); } diff --git a/crates/forge-web/src/pages/login.rs b/crates/forge-web/src/pages/login.rs index 15268d9..9b35e40 100644 --- a/crates/forge-web/src/pages/login.rs +++ b/crates/forge-web/src/pages/login.rs @@ -492,7 +492,8 @@ mod tests { post_login(&router, from, (&token.0, &token.1), "tahinli", guess).await; post_login(&router, from, (&token.0, &token.1), "ghost", guess).await; - let (status, _) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; + let (status, _) = + post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; assert_eq!(status, 303); let tahinli = state @@ -563,12 +564,14 @@ mod tests { for _ in 0..9 { post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await; } - let (status, _) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; + let (status, _) = + post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; assert_eq!(status, 303); for _ in 0..9 { post_login(&router, from, (&token.0, &token.1), "tahinli", "wrong").await; } - let (status, _) = post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; + let (status, _) = + post_login(&router, from, (&token.0, &token.1), "tahinli", PASSWORD).await; assert_eq!(status, 303); } diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 7f98995..a682d0a 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -44,6 +44,7 @@ pub mod login; pub mod media; pub mod milestones_page; pub mod new_repo; +pub mod not_found_page; pub mod notifications; pub mod org_ctx; pub mod org_members; diff --git a/crates/forge-web/src/pages/not_found_page.rs b/crates/forge-web/src/pages/not_found_page.rs new file mode 100644 index 0000000..3619782 --- /dev/null +++ b/crates/forge-web/src/pages/not_found_page.rs @@ -0,0 +1,83 @@ +//! The styled 404 page. Topcoat answers a `not_found()` error with a bare text body, so this layer +//! swaps that body for the regular shell plus a short message, for browser requests only. + +use http::header::ACCEPT; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::error::{NotFoundError, rewrite}; +use topcoat::router::page; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, StatusCode}; +use topcoat::view::{View, component, view}; + +use crate::auth::current_user; +use crate::i18n::{self, Lang}; +use crate::views::shell; + +pub struct NotFoundLayer; + +impl Layer for NotFoundLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(styled_not_found(cx, body, next)) + } +} + +fn texts(lang: Lang) -> (&'static str, &'static str, &'static str) { + match lang { + Lang::En => ( + "Page not found", + "The page does not exist, or you do not have access to it.", + "Back to the start", + ), + Lang::Tr => ( + "Sayfa bulunamadı", + "Sayfa yok ya da erişim izniniz yok.", + "Başa dön", + ), + } +} + +#[component] +async fn not_found_body(lang: Lang) -> Result { + let (title, hint, back) = texts(lang); + Ok(view! { +
+

"404"

+

(title)

+

(hint)

+ (back) +
+ }) +} + +async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result { + let result = next.run(cx, body).await; + let is_not_found = matches!(&result, Err(e) if e.downcast_ref::().is_some()); + let wants_html = headers(cx) + .get(ACCEPT) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.contains("text/html")); + if !is_not_found || !wants_html { + return result; + } + Err(rewrite(PATH, Body::empty()).method(Method::GET).into()) +} + +/// Where the layer sends a browser's 404. The page answers with status 404 itself. +const PATH: &str = "/-/not-found"; + +#[page("/-/not-found")] +async fn not_found_page(cx: &Cx) -> Result { + let viewer = current_user(cx).await?; + let lang = i18n::lang(cx, viewer.as_ref().map(|(user, _)| user)); + let title = texts(lang).0; + Ok(view! { + (StatusCode::NOT_FOUND) + shell(title: title, viewer: viewer.as_ref(), not_found_body(lang: lang)) + }) +} diff --git a/crates/forge-web/src/pages/org_ctx.rs b/crates/forge-web/src/pages/org_ctx.rs index fbe1eed..714a26b 100644 --- a/crates/forge-web/src/pages/org_ctx.rs +++ b/crates/forge-web/src/pages/org_ctx.rs @@ -181,46 +181,18 @@ pub fn take_notice(cx: &Cx, lang: Lang) -> Option<(&'static str, bool)> { .map(|(_, key, is_error)| (g::t(lang, *key), *is_error)) } -/// The org's name, description and tabs. `active` is `members`, `teams` or `settings`. +/// The org's name and description. The members, teams and settings links live in the shell +/// sidebar (see `views::section_for`). #[component] -pub async fn org_head( - name: String, - description: String, - active: &'static str, - is_owner: bool, - lang: Lang, -) -> Result { - let members_href = format!("/org/{name}/members"); - let teams_href = format!("/org/{name}/teams"); - let settings_href = format!("/org/{name}/settings"); - let members_tab = active == "members"; - let teams_tab = active == "teams"; - let settings_tab = active == "settings"; +pub async fn org_head(name: String, description: String) -> Result { Ok(view! {
-

(name.as_str())

- if !description.is_empty() { -

(description.as_str())

- } - +
}) } diff --git a/crates/forge-web/src/pages/org_members.rs b/crates/forge-web/src/pages/org_members.rs index 00050a9..85573c0 100644 --- a/crates/forge-web/src/pages/org_members.rs +++ b/crates/forge-web/src/pages/org_members.rs @@ -82,7 +82,7 @@ async fn members_body( let remove_action = format!("{base}/members/remove"); let add_action = format!("{base}/members/add"); Ok(view! { - org_head(name: name, description: description, active: "members", is_owner: owner, lang: lang) + org_head(name: name, description: description) org_notice(notice: notice)

(g::t(lang, K::Members))

diff --git a/crates/forge-web/src/pages/org_settings.rs b/crates/forge-web/src/pages/org_settings.rs index 9c8384a..8d30a56 100644 --- a/crates/forge-web/src/pages/org_settings.rs +++ b/crates/forge-web/src/pages/org_settings.rs @@ -63,7 +63,7 @@ async fn settings_body( let delete_action = format!("{base}/settings/delete"); let confirm_label = g::type_to_confirm(lang, &name); Ok(view! { - org_head(name: name, description: description.clone(), active: "settings", is_owner: true, lang: lang) + org_head(name: name, description: description.clone()) org_notice(notice: notice)

(g::t(lang, K::Settings))

diff --git a/crates/forge-web/src/pages/org_teams.rs b/crates/forge-web/src/pages/org_teams.rs index 086dac7..0ae3220 100644 --- a/crates/forge-web/src/pages/org_teams.rs +++ b/crates/forge-web/src/pages/org_teams.rs @@ -164,7 +164,7 @@ async fn teams_body( ) -> Result { let create_action = format!("{base}/teams/new"); Ok(view! { - org_head(name: name, description: description, active: "teams", is_owner: owner, lang: lang) + org_head(name: name, description: description) org_notice(notice: notice)

(g::t(lang, K::Teams))

@@ -271,7 +271,7 @@ async fn team_body( let has_choices = !data.choices.is_empty(); let has_description = !data.team_description.is_empty(); Ok(view! { - org_head(name: data.org_name.clone(), description: data.org_description.clone(), active: "teams", is_owner: owner, lang: lang) + org_head(name: data.org_name.clone(), description: data.org_description.clone()) org_notice(notice: notice)

(data.team_name.as_str())

@@ -306,7 +306,7 @@ async fn team_body( -
+ @@ -338,7 +338,7 @@ async fn team_body( } if owner { -
+ @@ -368,7 +368,7 @@ async fn team_body( } if owner && has_choices { - + - - - -

(total_text.as_str())

- if has_rows { - - } else { -

(empty)

- } - if has_pager { - - } +
+ + + + + + + sort_chips(links: sort_links, lang: lang) +

(count_text.as_str())

+ if has_rows { + repo_rows(rows: rows, lang: lang) + } else { +

(empty)

+ } + pager(page: page, pages: pages, links: links, prev: prev, next: next, lang: lang) +
} }) @@ -600,6 +579,39 @@ mod tests { assert!(!body.contains("alert(1)")); } + #[tokio::test] + async fn org_sidebar_shows_settings_to_owners_only() { + let site = site().await; + let owner = site + .store + .create_user("tahinli", None, "not-a-real-hash", false) + .await + .unwrap(); + let member = site + .store + .create_user("kaan", None, "not-a-real-hash", false) + .await + .unwrap(); + let org = site.store.create_org("forge-org", &owner.id).await.unwrap(); + site.store + .add_org_member( + &org.id, + &member.id, + forge_core::store::orgs::OrgMemberRole::Member, + ) + .await + .unwrap(); + let owner_cookie = sign_in(&site.store, &owner.id, "owner-token").await; + let member_cookie = sign_in(&site.store, &member.id, "member-token").await; + let href = "href=\"/org/forge-org/settings\""; + let (_, as_owner) = get(&site.router, "/org/forge-org/members", Some(&owner_cookie)).await; + assert!(as_owner.contains(href), "owner sees Settings"); + let (_, as_member) = + get(&site.router, "/org/forge-org/members", Some(&member_cookie)).await; + assert!(as_member.contains("href=\"/org/forge-org/teams\"")); + assert!(!as_member.contains(href), "member does not see Settings"); + } + #[tokio::test] async fn anonymous_and_other_users_see_only_public_repos() { let site = seeded().await; @@ -689,15 +701,15 @@ mod tests { /// A user with 35 public repos, `bulk-00` to `bulk-34`. async fn bulk_site() -> Site { let site = site().await; - let mira = site + let tahinli = site .store - .create_user("mira", None, "not-a-real-hash", false) + .create_user("tahinli", None, "not-a-real-hash", false) .await .unwrap(); for i in 0..35 { site.store .create_repo( - &mira.id, + &tahinli.id, &format!("bulk-{i:02}"), "", Visibility::Public, @@ -716,24 +728,29 @@ mod tests { #[tokio::test] async fn repositories_tab_pages_thirty_at_a_time() { let site = bulk_site().await; - let (status, first) = get(&site.router, "/mira?tab=repositories", None).await; + let (status, first) = get(&site.router, "/tahinli?tab=repositories&sort=name", None).await; assert_eq!(status, 200); assert_eq!(count(&first, "class=\"repo-name\""), 30); assert!(first.contains("page=2"), "next link: {first}"); - let (_, second) = get(&site.router, "/mira?tab=repositories&page=2", None).await; + let (_, second) = get( + &site.router, + "/tahinli?tab=repositories&sort=name&page=2", + None, + ) + .await; assert_eq!(count(&second, "class=\"repo-name\""), 5); - assert!(second.contains("mira/bulk-34")); - assert!(!second.contains("mira/bulk-00")); + assert!(second.contains("tahinli/bulk-34")); + assert!(!second.contains("tahinli/bulk-00")); } #[tokio::test] async fn name_filter_is_a_case_insensitive_substring() { let site = bulk_site().await; - let (_, body) = get(&site.router, "/mira?tab=repositories&q=BULK-1", None).await; + let (_, body) = get(&site.router, "/tahinli?tab=repositories&q=BULK-1", None).await; assert_eq!(count(&body, "class=\"repo-name\""), 10); - assert!(body.contains("mira/bulk-12")); - assert!(!body.contains("mira/bulk-22")); + assert!(body.contains("tahinli/bulk-12")); + assert!(!body.contains("tahinli/bulk-22")); } #[tokio::test] diff --git a/crates/forge-web/src/pages/pull_reviews.rs b/crates/forge-web/src/pages/pull_reviews.rs index a2885cc..b9396b7 100644 --- a/crates/forge-web/src/pages/pull_reviews.rs +++ b/crates/forge-web/src/pages/pull_reviews.rs @@ -960,7 +960,8 @@ mod tests { assert_eq!(reviews[0].state, ReviewState::Approved); let form = csrf_form("tahinli", &[("state", "approve")]); - let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; + let (status, location, _) = + send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; assert_eq!(status, 303); assert_eq!( location.as_deref(), @@ -1104,7 +1105,8 @@ mod tests { assert_eq!(status, 403); let form = csrf_form("tahinli", &[("reason", " ")]); - let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; + let (status, location, _) = + send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; assert_eq!(status, 303); assert!(location.unwrap().ends_with("?review_error=empty")); diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index 65e30d3..61e6ee1 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -640,8 +640,9 @@ async fn pull_conversation( let page_title = frame.page_title.clone(); let header = ctx.head(state, "pulls").await?; + let labels_href = repo_href(&owner, &name, "labels.css", ""); Ok(view! { cx => - shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), + shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()), repo_head(head: header) pull_header(frame: frame.clone()) pull_subnav_in(lang: lang, href: href.clone(), active: "conversation".to_owned(), @@ -1151,7 +1152,8 @@ mod tests { let number = open_pull(&fx).await; let uri = format!("/tahinli/demo/pulls/{number}/comments"); let form = csrf_form("tahinli", &[("body", "Looks good to me")]); - let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; + let (status, location, _) = + send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await; assert_eq!(status, 303); assert!( location @@ -1207,7 +1209,10 @@ mod tests { assert_eq!(status, 200); assert!(body.contains("Edit pull request")); - let form = csrf_form("tahinli", &[("title", "Renamed pull"), ("body", "New text")]); + let form = csrf_form( + "tahinli", + &[("title", "Renamed pull"), ("body", "New text")], + ); let (status, location, _) = send( &fx.router, "POST", @@ -1294,7 +1299,10 @@ mod tests { assert_eq!(status, 303); assert_eq!( location, - Some(format!("/tahinli/demo/pulls/{number}#comment-{}", comment.id)) + Some(format!( + "/tahinli/demo/pulls/{number}#comment-{}", + comment.id + )) ); let saved = fx .store diff --git a/crates/forge-web/src/pages/releases.rs b/crates/forge-web/src/pages/releases.rs index e9ebed7..21c68dc 100644 --- a/crates/forge-web/src/pages/releases.rs +++ b/crates/forge-web/src/pages/releases.rs @@ -802,7 +802,7 @@ async fn release_tag_page(cx: &Cx) -> Result { }

if !body_html.is_empty() { -
(Unescaped::new_unchecked(body_html))
+
(Unescaped::new_unchecked(body_html))
}

(g::t(lang, K::Assets))

if card.assets.is_empty() { @@ -824,7 +824,7 @@ async fn release_tag_page(cx: &Cx) -> Result {
  • "zip"
  • if writer { -

    +

    (g::t(lang, K::Edit))
    @@ -834,7 +834,7 @@ async fn release_tag_page(cx: &Cx) -> Result { -

    +
    }
    ) @@ -923,7 +923,12 @@ struct EditParts { } /// Loads the edit page data for `release`. -async fn edit_parts(state: &AppState, ctx: &RepoCtx, release: &Release, lang: Lang) -> Result { +async fn edit_parts( + state: &AppState, + ctx: &RepoCtx, + release: &Release, + lang: Lang, +) -> Result { let title = title_of(ctx); let assets = state.store.list_release_assets(&release.id).await?; let delete_actions: Vec = assets diff --git a/crates/forge-web/src/pages/releases_tests.rs b/crates/forge-web/src/pages/releases_tests.rs index a16d8da..c637fe9 100644 --- a/crates/forge-web/src/pages/releases_tests.rs +++ b/crates/forge-web/src/pages/releases_tests.rs @@ -924,8 +924,14 @@ async fn the_edit_page_shows_tag_and_target_controls_and_hides_the_target_once_p .await; let html = page.text(); assert!(html.contains("name=\"tag\" value=\"v2.0\""), "{html}"); - assert!(!html.contains("name=\"target\""), "published hides the target"); - assert!(html.contains("Published releases keep their commit"), "{html}"); + assert!( + !html.contains("name=\"target\""), + "published hides the target" + ); + assert!( + html.contains("Published releases keep their commit"), + "{html}" + ); } #[tokio::test] @@ -949,12 +955,7 @@ async fn a_published_release_can_be_retagged_through_the_form_and_keeps_its_comm ) .await; assert_eq!(reply.status, 303, "body: {}", reply.text()); - assert!( - reply - .location - .unwrap_or_default() - .contains("notice=saved") - ); + assert!(reply.location.unwrap_or_default().contains("notice=saved")); let moved = fx .store .release(&published.id) @@ -963,7 +964,11 @@ async fn a_published_release_can_be_retagged_through_the_form_and_keeps_its_comm .expect("row"); assert_eq!(moved.tag, "v2.1"); assert_eq!(fx.tag_target("v2.1"), Some(fx.main_tip())); - assert_eq!(fx.tag_target("v2.0"), Some(fx.main_tip()), "old git tag kept"); + assert_eq!( + fx.tag_target("v2.0"), + Some(fx.main_tip()), + "old git tag kept" + ); } #[tokio::test] @@ -987,10 +992,18 @@ async fn a_published_target_move_is_refused_on_the_page_and_the_typed_values_sta ]), ) .await; - assert_eq!(reply.status, 200, "a refused save re-renders: {}", reply.text()); + assert_eq!( + reply.status, + 200, + "a refused save re-renders: {}", + reply.text() + ); let html = reply.text(); assert!(html.contains("pick a new tag"), "{html}"); - assert!(html.contains("Typed title"), "the typed title stays: {html}"); + assert!( + html.contains("Typed title"), + "the typed title stays: {html}" + ); assert_eq!(fx.tag_target("v2.0"), Some(fx.main_tip())); } diff --git a/crates/forge-web/src/pages/repo.rs b/crates/forge-web/src/pages/repo.rs index d293de7..44a60b5 100644 --- a/crates/forge-web/src/pages/repo.rs +++ b/crates/forge-web/src/pages/repo.rs @@ -69,6 +69,7 @@ pub async fn repo_head(head: RepoHead) -> Result { description, archived, active, + hide_search, can_admin, open_issues, open_pulls, @@ -181,7 +182,7 @@ pub async fn repo_head(head: RepoHead) -> Result { if active == "code" && !description.is_empty() {

    (description.as_str())

    } - if active == "code" { + if active == "code" && !hide_search { @@ -385,7 +386,7 @@ async fn recent_pushes(banners: Vec, now: i64, lang: Lang) -> Result (banner.branch) (g::t(lang, K::HadRecentPushes)) (relative_time(lang, banner.at_unix, now)) - " — " + ". " (g::t(lang, K::CompareAndPr))

    } @@ -545,7 +546,13 @@ mod tests { .unwrap(); let demo = state .store - .create_repo(&tahinli.id, "demo", "A demo repo", Visibility::Public, "main") + .create_repo( + &tahinli.id, + "demo", + "A demo repo", + Visibility::Public, + "main", + ) .await .unwrap(); let secret = state diff --git a/crates/forge-web/src/pages/repo_collaborators.rs b/crates/forge-web/src/pages/repo_collaborators.rs index 7cd872e..e6bd3a1 100644 --- a/crates/forge-web/src/pages/repo_collaborators.rs +++ b/crates/forge-web/src/pages/repo_collaborators.rs @@ -27,6 +27,7 @@ use crate::i18n::repo_admin::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; +use crate::pages::repo_settings::settings_nav_for; use crate::state::AppState; use crate::views::{alert, avatar_url, display_name, shell}; @@ -293,9 +294,11 @@ async fn collaborators_body( let remove_action = format!("/{}/settings/collaborators/remove", frame.title); let add_action = format!("/{}/settings/collaborators/add", frame.title); let header = frame.head; + let nav_title = frame.title.clone(); let notice = notice.map(|(key, is_error)| (g::t(lang, key), is_error)); Ok(view! { repo_head(head: header) + settings_nav_for(lang: lang, title: nav_title, current: "collaborators") if let Some((text, is_error)) = notice { if is_error { alert(message: text) diff --git a/crates/forge-web/src/pages/repo_ctx.rs b/crates/forge-web/src/pages/repo_ctx.rs index b5c04e0..1c60273 100644 --- a/crates/forge-web/src/pages/repo_ctx.rs +++ b/crates/forge-web/src/pages/repo_ctx.rs @@ -58,6 +58,8 @@ pub struct RepoHead { /// The current header tab: `code`, `issues`, `pulls`, `commits`, `branches`, `tags` or /// `settings`, or `security`. pub active: &'static str, + /// Hide the header's code-search box (the code search page draws its own). + pub hide_search: bool, /// Whether the viewer may open the Settings tab. pub can_admin: bool, /// Open issues, for the Issues tab count. @@ -220,6 +222,7 @@ impl RepoCtx { description: self.repo.description.clone(), archived: self.repo.archived, active, + hide_search: false, can_admin: self.can_admin(), open_issues: self.open_issues(state).await?, open_pulls, diff --git a/crates/forge-web/src/pages/repo_rename.rs b/crates/forge-web/src/pages/repo_rename.rs index f64f270..8bcc1ab 100644 --- a/crates/forge-web/src/pages/repo_rename.rs +++ b/crates/forge-web/src/pages/repo_rename.rs @@ -22,6 +22,7 @@ use crate::i18n::repo_admin::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; +use crate::pages::repo_settings::settings_nav_for; use crate::state::AppState; use crate::views::{alert, shell}; @@ -109,6 +110,7 @@ async fn rename_body( let rename_action = format!("/{title}/settings/rename"); let transfer_action = format!("/{title}/settings/transfer"); let status_href = format!("/{title}/transfer"); + let nav_title = title.clone(); let Forms { rename_name, rename_error, @@ -117,6 +119,7 @@ async fn rename_body( } = forms; Ok(view! { repo_head(head: head) + settings_nav_for(lang: lang, title: nav_title, current: "rename") if let Some(key) = notice {
    (g::t(lang, key))
    } diff --git a/crates/forge-web/src/pages/repo_settings.rs b/crates/forge-web/src/pages/repo_settings.rs index 0f1861b..b2a33c7 100644 --- a/crates/forge-web/src/pages/repo_settings.rs +++ b/crates/forge-web/src/pages/repo_settings.rs @@ -274,6 +274,8 @@ pub async fn settings_nav_for( let mirrors = format!("/{title}/settings/mirrors"); let secrets = format!("/{title}/settings/secrets"); let general_on = current == "general"; + let collaborators_on = current == "collaborators"; + let rename_on = current == "rename"; let hooks_on = current == "webhooks"; let mirrors_on = current == "mirrors"; let secrets_on = current == "secrets"; @@ -284,8 +286,16 @@ pub async fn settings_nav_for( } else { (g::t(lang, K::General)) } - (g::t(lang, K::Collaborators)) - (g::t(lang, K::RenameTransferNav)) + if collaborators_on { + (g::t(lang, K::Collaborators)) + } else { + (g::t(lang, K::Collaborators)) + } + if rename_on { + (g::t(lang, K::RenameTransferNav)) + } else { + (g::t(lang, K::RenameTransferNav)) + } if hooks_on { (g::t(lang, K::Webhooks)) } else { diff --git a/crates/forge-web/src/pages/repo_webhooks.rs b/crates/forge-web/src/pages/repo_webhooks.rs index ef29081..6d97aec 100644 --- a/crates/forge-web/src/pages/repo_webhooks.rs +++ b/crates/forge-web/src/pages/repo_webhooks.rs @@ -1339,7 +1339,8 @@ mod tests { ); // A private repo is invisible to someone outside it. - let (status, _, _) = send(&fx.app, "GET", "/tahinli/proj/settings/hooks", &carol, &[]).await; + let (status, _, _) = + send(&fx.app, "GET", "/tahinli/proj/settings/hooks", &carol, &[]).await; assert_eq!(status, 404); } diff --git a/crates/forge-web/src/pages/settings_appearance.rs b/crates/forge-web/src/pages/settings_appearance.rs index 6fe4ed0..dad1146 100644 --- a/crates/forge-web/src/pages/settings_appearance.rs +++ b/crates/forge-web/src/pages/settings_appearance.rs @@ -248,7 +248,7 @@ async fn appearance_body(page: AppearancePage) -> Result {
    (g::t(lang, K::SidebarLabel)) -
    +
    for choice in sidebar.into_iter() {
    (g::t(lang, K::TableWhen))
    (row.when.as_str())(row.when.as_str())(row.actor.as_str())(row.action.as_str()) (row.target.as_str())(row.ip.as_str())(row.ip.as_str()) (row.details.as_str())
    + + for row in rows.into_iter() { + + + + + + + } + +
    (row.short.as_str())(row.subject.as_str())(row.author.as_str())(row.when.as_str())
    +
    } - - - for row in rows.into_iter() { - - - - - - - } - -
    (row.short.as_str())(row.subject.as_str())(row.author.as_str())(row.when.as_str())
    }) } @@ -287,14 +291,8 @@ async fn wiki_edit_body( content: String, error: Option, ) -> Result { - let title = if is_new { - g::t(lang, K::NewPage).to_owned() - } else { - name.replace('-', " ") - }; Ok(view! { -
    -

    (title.as_str())

    +
    if let Some(message) = error { alert(message: message.as_str()) @@ -353,13 +351,21 @@ async fn wiki_home(cx: &Cx) -> Result { ctx.repo.name, g::t(lang, K::Wiki) ); + let (head_title, links) = if body_html.is_some() { + ( + g::t(lang, K::Home).to_owned(), + page_links(lang, &owner_name, &repo_name, "Home", can_write), + ) + } else { + (g::t(lang, K::Wiki).to_owned(), Vec::new()) + }; let header = ctx.head(state, "wiki").await?; Ok(view! { cx => shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) - wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write) + wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: head_title.clone(), extra: links.clone()) if let Some(html) = body_html.clone() { - wiki_view_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), name: "Home".to_owned(), html: html, can_write: can_write) + wiki_view_body(html: html) } if body_html.is_none() { wiki_empty_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write) @@ -391,8 +397,8 @@ async fn wiki_pages(cx: &Cx) -> Result { Ok(view! { cx => shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) - wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write) - wiki_list_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), names: names, can_write: can_write) + wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: g::t(lang, K::AllPages).to_owned(), extra: Vec::new()) + wiki_list_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), names: names) ) }) } @@ -428,8 +434,8 @@ async fn wiki_page_view(cx: &Cx) -> Result { Ok(view! { cx => shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) - wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write) - wiki_view_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), name: page_name.clone(), html: html, can_write: can_write) + wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: can_write, title: page_name.replace('-', " "), extra: page_links(lang, &owner_name, &repo_name, &page_name, can_write)) + wiki_view_body(html: html) ) }) } @@ -463,8 +469,8 @@ async fn wiki_page_history(cx: &Cx) -> Result { Ok(view! { cx => shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) - wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: ctx.can_write()) - wiki_history_body(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), name: page_name.clone(), rows: rows) + wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: ctx.can_write(), title: format!("{} \u{b7} {}", page_name.replace('-', " "), g::t(lang, K::History)), extra: vec![(g::t(lang, K::BackToPage).to_owned(), repo_href(&owner_name, &repo_name, "wiki", &page_name))]) + wiki_history_body(lang: lang, rows: rows) ) }) } @@ -504,10 +510,15 @@ async fn edit_screen( let repo_name = ctx.repo.name.clone(); let csrf = session.csrf_token.clone(); let base = head.unwrap_or_default(); + let head_title = if is_new { + g::t(lang, K::NewPage).to_owned() + } else { + name.replace('-', " ") + }; Ok(view! { cx => shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), repo_head(head: header) - wiki_nav(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: true) + wiki_head(lang: lang, owner: owner_name.clone(), repo: repo_name.clone(), can_write: !is_new, title: head_title.clone(), extra: Vec::new()) wiki_edit_body(lang: lang, action: action, csrf: csrf, base: base, name: name.clone(), is_new: is_new, content: content, error: error) ) }) @@ -669,8 +680,8 @@ async fn wiki_settings_body( enabled: bool, ) -> Result { Ok(view! { -
    -

    (g::t(lang, K::WikiSettings))

    +
    +

    (g::t(lang, K::WikiSettings))