forge
Explore
Log in

Don't you dare go Hollow

The pages split into forge-web-pages (the shared repo, issue, CI and settings pages), forge-web-account (account, admin, org and profile) and forge-web-repo (code, pulls, discussions), so no single rustc compiles all 80k lines of pages

Browse files at this commit

bdda6d84c193b408c131e1e61054862f1eb0ecb8Ahmet Kaan GümüşParent: 42a2afe
  • refactor
    • the pages split into forge-web-pages (the shared repo, issue, CI and settings pages), forge-web-account (account, admin, org and profile) and forge-web-repo (code, pulls, discussions), so no single rustc compiles all 80k lines of pages
    • the two upper crates build in parallel and page tests that span crates move to the binary
Show full message
♻️ refactor: the pages split into forge-web-pages (the shared repo, issue, CI and settings pages), forge-web-account (account, admin, org and profile) and forge-web-repo (code, pulls, discussions), so no single rustc compiles all 80k lines of pages; the two upper crates build in parallel and page tests that span crates move to the binary

157 changed files +2706 -2492

Cargo.lockmodified+102 -22
@@ -2105,42 +2105,59 @@ dependencies = [
2105 name = "forge-web"2105 name = "forge-web"
2106 version = "0.1.0"2106 version = "0.1.0"
2107 dependencies = [2107 dependencies = [
2108- "aes-gcm 0.11.1",
2109- "async-compression",
2110 "base64 0.23.1",2108 "base64 0.23.1",
2111 "bytes",2109 "bytes",
2112- "flate2",
2113 "forge-ci",2110 "forge-ci",
2114 "forge-core",2111 "forge-core",
2115 "forge-git",2112 "forge-git",
2116 "forge-runner",2113 "forge-runner",
2117 "forge-ssh",2114 "forge-ssh",
2115+ "forge-web-account",
2116+ "forge-web-app",
2117+ "forge-web-base",
2118+ "forge-web-pages",
2119+ "forge-web-repo",
2120+ "futures-util",
2121+ "hex",
2122+ "http",
2123+ "nix 0.31.4",
2124+ "rand 0.10.4",
2125+ "reqwest",
2126+ "rpassword",
2127+ "serde_json",
2128+ "tar",
2129+ "tempfile",
2130+ "time",
2131+ "tokio",
2132+ "topcoat",
2133+ "tracing",
2134+ "tracing-subscriber",
2135+ "zip",
2136+]
2137+
2138+[[package]]
2139+name = "forge-web-account"
2140+version = "0.1.0"
2141+dependencies = [
2142+ "base64 0.23.1",
2143+ "bytes",
2144+ "forge-ci",
2145+ "forge-core",
2146+ "forge-git",
2118 "forge-web-app",2147 "forge-web-app",
2119 "forge-web-base",2148 "forge-web-base",
2149+ "forge-web-pages",
2120 "form_urlencoded",2150 "form_urlencoded",
2121 "futures-util",2151 "futures-util",
2122 "hex",2152 "hex",
2123- "hkdf 0.13.0",
2124- "hmac 0.13.0",
2125 "http",2153 "http",
2126 "http-body",2154 "http-body",
2127 "http-body-util",2155 "http-body-util",
2128 "image",2156 "image",
2129- "ipnet",
2130 "jiff 1.0.3",2157 "jiff 1.0.3",
2131- "lettre",
2132- "multer",
2133- "nix 0.31.4",
2134- "p256",
2135- "rand 0.10.4",
2136- "reqwest",
2137- "rpassword",
2138- "scraper",
2139 "serde",2158 "serde",
2140 "serde_json",2159 "serde_json",
2141 "sha2 0.11.1",2160 "sha2 0.11.1",
2142- "similar",
2143- "subtle",
2144 "tar",2161 "tar",
2145 "tempfile",2162 "tempfile",
2146 "time",2163 "time",
@@ -2148,7 +2165,6 @@ dependencies = [
2148 "tokio-util",2165 "tokio-util",
2149 "topcoat",2166 "topcoat",
2150 "tracing",2167 "tracing",
2151- "tracing-subscriber",
2152 "ulid",2168 "ulid",
2153 "webauthn-authenticator-rs",2169 "webauthn-authenticator-rs",
2154 "webauthn-rs",2170 "webauthn-rs",
@@ -2183,17 +2199,14 @@ dependencies = [
2183 "ipnet",2199 "ipnet",
2184 "jiff 1.0.3",2200 "jiff 1.0.3",
2185 "lettre",2201 "lettre",
2186- "multer",
2187 "nix 0.31.4",2202 "nix 0.31.4",
2188 "p256",2203 "p256",
2189 "rand 0.10.4",2204 "rand 0.10.4",
2190 "reqwest",2205 "reqwest",
2191- "scraper",
2192 "serde",2206 "serde",
2193 "serde_json",2207 "serde_json",
2194 "sha2 0.11.1",2208 "sha2 0.11.1",
2195 "similar",2209 "similar",
2196- "subtle",
2197 "tar",2210 "tar",
2198 "tempfile",2211 "tempfile",
2199 "time",2212 "time",
@@ -2201,9 +2214,7 @@ dependencies = [
2201 "tokio-util",2214 "tokio-util",
2202 "topcoat",2215 "topcoat",
2203 "tracing",2216 "tracing",
2204- "tracing-subscriber",
2205 "ulid",2217 "ulid",
2206- "webauthn-authenticator-rs",
2207 "zip",2218 "zip",
2208 ]2219 ]
2209 2220
@@ -2234,6 +2245,75 @@ dependencies = [
2234 "tracing",2245 "tracing",
2235 ]2246 ]
2236 2247
2248+[[package]]
2249+name = "forge-web-pages"
2250+version = "0.1.0"
2251+dependencies = [
2252+ "bytes",
2253+ "forge-ci",
2254+ "forge-core",
2255+ "forge-git",
2256+ "forge-web-app",
2257+ "forge-web-base",
2258+ "form_urlencoded",
2259+ "futures-util",
2260+ "hex",
2261+ "http",
2262+ "http-body",
2263+ "http-body-util",
2264+ "image",
2265+ "multer",
2266+ "nix 0.31.4",
2267+ "reqwest",
2268+ "serde",
2269+ "serde_json",
2270+ "similar",
2271+ "tar",
2272+ "tempfile",
2273+ "time",
2274+ "tokio",
2275+ "topcoat",
2276+ "tracing",
2277+ "zip",
2278+]
2279+
2280+[[package]]
2281+name = "forge-web-repo"
2282+version = "0.1.0"
2283+dependencies = [
2284+ "bytes",
2285+ "forge-core",
2286+ "forge-git",
2287+ "forge-web-app",
2288+ "forge-web-base",
2289+ "forge-web-pages",
2290+ "form_urlencoded",
2291+ "futures-util",
2292+ "hex",
2293+ "http",
2294+ "http-body",
2295+ "http-body-util",
2296+ "image",
2297+ "jiff 1.0.3",
2298+ "multer",
2299+ "nix 0.31.4",
2300+ "p256",
2301+ "reqwest",
2302+ "scraper",
2303+ "serde",
2304+ "serde_json",
2305+ "sha2 0.11.1",
2306+ "tar",
2307+ "tempfile",
2308+ "time",
2309+ "tokio",
2310+ "tokio-util",
2311+ "topcoat",
2312+ "tracing",
2313+ "ulid",
2314+ "zip",
2315+]
2316+
2237 [[package]]2317 [[package]]
2238 name = "form_urlencoded"2318 name = "form_urlencoded"
2239 version = "1.2.3"2319 version = "1.2.3"
Cargo.tomlmodified+6 -0
@@ -7,6 +7,9 @@ members = [
7 "crates/forge-web",7 "crates/forge-web",
8 "crates/forge-web-base",8 "crates/forge-web-base",
9 "crates/forge-web-app",9 "crates/forge-web-app",
10+ "crates/forge-web-pages",
11+ "crates/forge-web-account",
12+ "crates/forge-web-repo",
10 "crates/forge-ci",13 "crates/forge-ci",
11 "crates/forge-runner",14 "crates/forge-runner",
12 "crates/forge-e2e",15 "crates/forge-e2e",
@@ -36,6 +39,9 @@ forge-ssh = { path = "crates/forge-ssh" }
36 forge-runner = { path = "crates/forge-runner" }39 forge-runner = { path = "crates/forge-runner" }
37 forge-web-base = { path = "crates/forge-web-base" }40 forge-web-base = { path = "crates/forge-web-base" }
38 forge-web-app = { path = "crates/forge-web-app" }41 forge-web-app = { path = "crates/forge-web-app" }
42+forge-web-pages = { path = "crates/forge-web-pages" }
43+forge-web-account = { path = "crates/forge-web-account" }
44+forge-web-repo = { path = "crates/forge-web-repo" }
39 45
40 # async runtime and HTTP plumbing46 # async runtime and HTTP plumbing
41 tokio = { version = "1.54.1", features = ["full"] }47 tokio = { version = "1.54.1", features = ["full"] }
crates/forge-web-account/Cargo.tomladded+49 -0
@@ -0,0 +1,49 @@
1+[package]
2+name = "forge-web-account"
3+description = "forge account, admin, org and profile pages"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[dependencies]
10+forge-web-app.workspace = true
11+forge-web-pages.workspace = true
12+forge-core.workspace = true
13+forge-git.workspace = true
14+forge-ci.workspace = true
15+forge-web-base.workspace = true
16+topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
17+tokio.workspace = true
18+futures-util.workspace = true
19+bytes.workspace = true
20+http.workspace = true
21+http-body-util.workspace = true
22+serde.workspace = true
23+serde_json.workspace = true
24+form_urlencoded.workspace = true
25+jiff.workspace = true
26+base64.workspace = true
27+tracing.workspace = true
28+tokio-util = { workspace = true, features = ["io"] }
29+http-body.workspace = true
30+hex.workspace = true
31+sha2.workspace = true
32+time.workspace = true
33+ulid.workspace = true
34+zip = { workspace = true }
35+tar.workspace = true
36+
37+
38+webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] }
39+webauthn-rs-proto = "0.6.2"
40+
41+[dev-dependencies]
42+forge-web-pages = { workspace = true, features = ["test-support"] }
43+forge-web-app = { workspace = true, features = ["test-support"] }
44+tempfile.workspace = true
45+image = { workspace = true }
46+webauthn-authenticator-rs = { version = "0.6.2", features = ["softpasskey"] }
47+
48+[lints]
49+workspace = true
crates/forge-web-account/src/lib.rsadded+15 -0
@@ -0,0 +1,15 @@
1+//! forge pages.
2+
3+#![recursion_limit = "256"]
4+
5+#[cfg(test)]
6+pub(crate) use forge_web_app::test_support;
7+pub(crate) use forge_web_app::{
8+ accent, alerts, api, audit, auth, backup, client_ip, custom_colour, exporter, i18n, importer,
9+ live, mail, mirrors, raw, render, self_update, signatures, state, theme, throttle, views,
10+ web_push, webhooks,
11+};
12+#[cfg(test)]
13+pub(crate) use forge_web_app::{blobs, ci, notify_hub, packages_live, release_ops, replication};
14+
15+pub mod pages;
crates/forge-web/src/pages/account_tools_tests.rs → crates/forge-web-account/src/pages/account_tools_tests.rsrenamed+0 -0
crates/forge-web/src/pages/activity.rs → crates/forge-web-account/src/pages/activity.rsrenamed+0 -0
crates/forge-web/src/pages/admin_backups.rs → crates/forge-web-account/src/pages/admin_backups.rsrenamed+0 -0
crates/forge-web/src/pages/admin_health.rs → crates/forge-web-account/src/pages/admin_health.rsrenamed+0 -0
crates/forge-web/src/pages/admin_live_tests.rs → crates/forge-web-account/src/pages/admin_live_tests.rsrenamed+0 -0
crates/forge-web/src/pages/admin_mail.rs → crates/forge-web-account/src/pages/admin_mail.rsrenamed+0 -0
crates/forge-web/src/pages/admin_replication.rs → crates/forge-web-account/src/pages/admin_replication.rsrenamed+0 -0
crates/forge-web/src/pages/admin_server.rs → crates/forge-web-account/src/pages/admin_server.rsrenamed+0 -0
crates/forge-web/src/pages/admin_user_detail.rs → crates/forge-web-account/src/pages/admin_user_detail.rsrenamed+0 -0
crates/forge-web/src/pages/assets.rs → crates/forge-web-account/src/pages/assets.rsrenamed+3 -3
@@ -44,7 +44,7 @@ async fn main_css(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
44 44
45 /// The soft-navigation script (`assets/nav.js`). Served from the same origin, so the CSP's45 /// The soft-navigation script (`assets/nav.js`). Served from the same origin, so the CSP's
46 /// `script-src 'self'` covers it; the page loads it with `defer`, and without it pages still work.46 /// `script-src 'self'` covers it; the page loads it with `defer`, and without it pages still work.
47-const NAV_JS: &str = include_str!("../../assets/nav.js");47+const NAV_JS: &str = include_str!("../../../forge-web/assets/nav.js");
48 48
49 /// Immutable like `main.css`: the URL carries a content hash.49 /// Immutable like `main.css`: the URL carries a content hash.
50 #[route(GET "/assets/nav.js")]50 #[route(GET "/assets/nav.js")]
@@ -119,8 +119,8 @@ async fn custom_css_route(cx: &Cx) -> Result<(StatusCode, HeaderMap, String)> {
119 119
120 // The offline page (shown by the service worker when a page load finds the server down) and its120 // The offline page (shown by the service worker when a page load finds the server down) and its
121 // script. Not hashed and not immutable: the service worker fetches them again on each update.121 // script. Not hashed and not immutable: the service worker fetches them again on each update.
122-const OFFLINE_HTML: &str = include_str!("../../assets/offline.html");122+const OFFLINE_HTML: &str = include_str!("../../../forge-web/assets/offline.html");
123-const OFFLINE_JS: &str = include_str!("../../assets/offline.js");123+const OFFLINE_JS: &str = include_str!("../../../forge-web/assets/offline.js");
124 124
125 #[route(GET "/assets/offline.html")]125 #[route(GET "/assets/offline.html")]
126 async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {126 async fn offline_html(cx: &Cx) -> Result<(StatusCode, HeaderMap, &'static str)> {
crates/forge-web/src/pages/audit_log.rs → crates/forge-web-account/src/pages/audit_log.rsrenamed+0 -0
crates/forge-web/src/pages/avatars.rs → crates/forge-web-account/src/pages/avatars.rsrenamed+0 -0
crates/forge-web/src/pages/banner.rs → crates/forge-web-account/src/pages/banner.rsrenamed+0 -0
crates/forge-web/src/pages/explore.rs → crates/forge-web-account/src/pages/explore.rsrenamed+0 -0
crates/forge-web/src/pages/forgot.rs → crates/forge-web-account/src/pages/forgot.rsrenamed+0 -0
crates/forge-web/src/pages/home.rs → crates/forge-web-account/src/pages/home.rsrenamed+0 -0
crates/forge-web/src/pages/import.rs → crates/forge-web-account/src/pages/import.rsrenamed+0 -0
crates/forge-web/src/pages/import_tests.rs → crates/forge-web-account/src/pages/import_tests.rsrenamed+0 -0
crates/forge-web/src/pages/invites.rs → crates/forge-web-account/src/pages/invites.rsrenamed+0 -0
crates/forge-web/src/pages/login.rs → crates/forge-web-account/src/pages/login.rsrenamed+0 -0
crates/forge-web-account/src/pages/mod.rsadded+64 -0
@@ -0,0 +1,64 @@
1+//! Server-rendered pages.
2+
3+pub use forge_web_pages::pages::*;
4+
5+#[cfg(test)]
6+mod account_tools_tests;
7+pub mod activity;
8+pub mod admin_backups;
9+pub mod admin_health;
10+#[cfg(test)]
11+mod admin_live_tests;
12+pub mod admin_mail;
13+pub mod admin_replication;
14+pub mod admin_server;
15+pub mod admin_user_detail;
16+pub mod assets;
17+pub mod audit_log;
18+pub mod avatars;
19+pub mod banner;
20+pub mod explore;
21+pub mod forgot;
22+pub mod home;
23+pub mod import;
24+#[cfg(test)]
25+mod import_tests;
26+pub mod invites;
27+pub mod login;
28+pub mod needs_you;
29+pub mod new_repo;
30+pub mod not_found_page;
31+pub mod org_ctx;
32+pub mod org_live;
33+pub mod org_members;
34+pub mod org_new;
35+pub mod org_settings;
36+pub mod org_teams;
37+pub mod palette;
38+pub mod passkeys;
39+#[cfg(test)]
40+mod passkeys_tests;
41+pub mod profile;
42+pub mod profile_calendar;
43+pub mod profile_pins;
44+pub mod register;
45+#[cfg(test)]
46+mod releases_tests;
47+pub mod settings_appearance;
48+pub mod settings_export;
49+pub mod settings_gpg;
50+#[cfg(test)]
51+mod settings_gpg_tests;
52+pub mod settings_keys;
53+pub mod settings_live;
54+pub mod settings_notifications;
55+pub mod settings_profile;
56+pub mod settings_security;
57+pub mod settings_sessions;
58+pub mod settings_tokens;
59+pub mod setup;
60+pub mod shell_events;
61+pub mod snippets;
62+pub mod snippets_live;
63+pub mod theme_cookie;
64+pub mod user_prefs;
crates/forge-web/src/pages/needs_you.rs → crates/forge-web-account/src/pages/needs_you.rsrenamed+0 -0
crates/forge-web/src/pages/new_repo.rs → crates/forge-web-account/src/pages/new_repo.rsrenamed+12 -12
@@ -34,62 +34,62 @@ const LICENSES: &[(&str, &str, &str)] = &[
34 (34 (
35 "MIT",35 "MIT",
36 "MIT License",36 "MIT License",
37- include_str!("../../assets/licenses/MIT.txt"),37+ include_str!("../../../forge-web/assets/licenses/MIT.txt"),
38 ),38 ),
39 (39 (
40 "Apache-2.0",40 "Apache-2.0",
41 "Apache License 2.0",41 "Apache License 2.0",
42- include_str!("../../assets/licenses/Apache-2.0.txt"),42+ include_str!("../../../forge-web/assets/licenses/Apache-2.0.txt"),
43 ),43 ),
44 (44 (
45 "GPL-3.0-only",45 "GPL-3.0-only",
46 "GNU GPL v3",46 "GNU GPL v3",
47- include_str!("../../assets/licenses/GPL-3.0-only.txt"),47+ include_str!("../../../forge-web/assets/licenses/GPL-3.0-only.txt"),
48 ),48 ),
49 (49 (
50 "AGPL-3.0-only",50 "AGPL-3.0-only",
51 "GNU AGPL v3",51 "GNU AGPL v3",
52- include_str!("../../assets/licenses/AGPL-3.0-only.txt"),52+ include_str!("../../../forge-web/assets/licenses/AGPL-3.0-only.txt"),
53 ),53 ),
54 (54 (
55 "LGPL-3.0-only",55 "LGPL-3.0-only",
56 "GNU LGPL v3",56 "GNU LGPL v3",
57- include_str!("../../assets/licenses/LGPL-3.0-only.txt"),57+ include_str!("../../../forge-web/assets/licenses/LGPL-3.0-only.txt"),
58 ),58 ),
59 (59 (
60 "GPL-2.0-only",60 "GPL-2.0-only",
61 "GNU GPL v2",61 "GNU GPL v2",
62- include_str!("../../assets/licenses/GPL-2.0-only.txt"),62+ include_str!("../../../forge-web/assets/licenses/GPL-2.0-only.txt"),
63 ),63 ),
64 (64 (
65 "MPL-2.0",65 "MPL-2.0",
66 "Mozilla Public License 2.0",66 "Mozilla Public License 2.0",
67- include_str!("../../assets/licenses/MPL-2.0.txt"),67+ include_str!("../../../forge-web/assets/licenses/MPL-2.0.txt"),
68 ),68 ),
69 (69 (
70 "BSD-3-Clause",70 "BSD-3-Clause",
71 "BSD 3-Clause",71 "BSD 3-Clause",
72- include_str!("../../assets/licenses/BSD-3-Clause.txt"),72+ include_str!("../../../forge-web/assets/licenses/BSD-3-Clause.txt"),
73 ),73 ),
74 (74 (
75 "BSD-2-Clause",75 "BSD-2-Clause",
76 "BSD 2-Clause",76 "BSD 2-Clause",
77- include_str!("../../assets/licenses/BSD-2-Clause.txt"),77+ include_str!("../../../forge-web/assets/licenses/BSD-2-Clause.txt"),
78 ),78 ),
79 (79 (
80 "ISC",80 "ISC",
81 "ISC License",81 "ISC License",
82- include_str!("../../assets/licenses/ISC.txt"),82+ include_str!("../../../forge-web/assets/licenses/ISC.txt"),
83 ),83 ),
84 (84 (
85 "BSL-1.0",85 "BSL-1.0",
86 "Boost Software License 1.0",86 "Boost Software License 1.0",
87- include_str!("../../assets/licenses/BSL-1.0.txt"),87+ include_str!("../../../forge-web/assets/licenses/BSL-1.0.txt"),
88 ),88 ),
89 (89 (
90 "Unlicense",90 "Unlicense",
91 "The Unlicense",91 "The Unlicense",
92- include_str!("../../assets/licenses/Unlicense.txt"),92+ include_str!("../../../forge-web/assets/licenses/Unlicense.txt"),
93 ),93 ),
94 ];94 ];
95 95
crates/forge-web/src/pages/not_found_page.rs → crates/forge-web-account/src/pages/not_found_page.rsrenamed+0 -0
crates/forge-web/src/pages/org_ctx.rs → crates/forge-web-account/src/pages/org_ctx.rsrenamed+0 -0
crates/forge-web/src/pages/org_live.rs → crates/forge-web-account/src/pages/org_live.rsrenamed+0 -0
crates/forge-web/src/pages/org_members.rs → crates/forge-web-account/src/pages/org_members.rsrenamed+0 -0
crates/forge-web/src/pages/org_new.rs → crates/forge-web-account/src/pages/org_new.rsrenamed+0 -0
crates/forge-web/src/pages/org_settings.rs → crates/forge-web-account/src/pages/org_settings.rsrenamed+0 -0
crates/forge-web/src/pages/org_teams.rs → crates/forge-web-account/src/pages/org_teams.rsrenamed+0 -0
crates/forge-web/src/pages/palette.rs → crates/forge-web-account/src/pages/palette.rsrenamed+0 -0
crates/forge-web/src/pages/passkeys.rs → crates/forge-web-account/src/pages/passkeys.rsrenamed+0 -0
crates/forge-web/src/pages/passkeys_tests.rs → crates/forge-web-account/src/pages/passkeys_tests.rsrenamed+0 -0
crates/forge-web/src/pages/profile.rs → crates/forge-web-account/src/pages/profile.rsrenamed+0 -0
crates/forge-web/src/pages/profile_calendar.rs → crates/forge-web-account/src/pages/profile_calendar.rsrenamed+0 -0
crates/forge-web/src/pages/profile_pins.rs → crates/forge-web-account/src/pages/profile_pins.rsrenamed+0 -0
crates/forge-web/src/pages/register.rs → crates/forge-web-account/src/pages/register.rsrenamed+0 -0
crates/forge-web/src/pages/releases_tests.rs → crates/forge-web-account/src/pages/releases_tests.rsrenamed+0 -0
crates/forge-web/src/pages/settings_appearance.rs → crates/forge-web-account/src/pages/settings_appearance.rsrenamed+0 -0
crates/forge-web/src/pages/settings_export.rs → crates/forge-web-account/src/pages/settings_export.rsrenamed+0 -0
crates/forge-web/src/pages/settings_gpg.rs → crates/forge-web-account/src/pages/settings_gpg.rsrenamed+0 -0
crates/forge-web/src/pages/settings_gpg_tests.rs → crates/forge-web-account/src/pages/settings_gpg_tests.rsrenamed+0 -0
crates/forge-web/src/pages/settings_keys.rs → crates/forge-web-account/src/pages/settings_keys.rsrenamed+0 -0
crates/forge-web/src/pages/settings_live.rs → crates/forge-web-account/src/pages/settings_live.rsrenamed+0 -0
crates/forge-web/src/pages/settings_notifications.rs → crates/forge-web-account/src/pages/settings_notifications.rsrenamed+0 -0
crates/forge-web/src/pages/settings_profile.rs → crates/forge-web-account/src/pages/settings_profile.rsrenamed+0 -0
crates/forge-web/src/pages/settings_security.rs → crates/forge-web-account/src/pages/settings_security.rsrenamed+0 -0
crates/forge-web/src/pages/settings_sessions.rs → crates/forge-web-account/src/pages/settings_sessions.rsrenamed+0 -0
crates/forge-web/src/pages/settings_tokens.rs → crates/forge-web-account/src/pages/settings_tokens.rsrenamed+0 -0
crates/forge-web/src/pages/setup.rs → crates/forge-web-account/src/pages/setup.rsrenamed+0 -0
crates/forge-web/src/pages/shell_events.rs → crates/forge-web-account/src/pages/shell_events.rsrenamed+0 -0
crates/forge-web/src/pages/snippets.rs → crates/forge-web-account/src/pages/snippets.rsrenamed+0 -0
crates/forge-web/src/pages/snippets_live.rs → crates/forge-web-account/src/pages/snippets_live.rsrenamed+0 -0
crates/forge-web/src/pages/theme_cookie.rs → crates/forge-web-account/src/pages/theme_cookie.rsrenamed+0 -0
crates/forge-web/src/pages/user_prefs.rs → crates/forge-web-account/src/pages/user_prefs.rsrenamed+0 -0
crates/forge-web-app/Cargo.tomlmodified+0 -5
@@ -28,9 +28,7 @@ serde_json.workspace = true
28 form_urlencoded.workspace = true28 form_urlencoded.workspace = true
29 jiff.workspace = true29 jiff.workspace = true
30 base64.workspace = true30 base64.workspace = true
31-subtle.workspace = true
32 tracing.workspace = true31 tracing.workspace = true
33-tracing-subscriber = { workspace = true, features = ["env-filter"] }
34 tokio-util = { workspace = true, features = ["io"] }32 tokio-util = { workspace = true, features = ["io"] }
35 http-body.workspace = true33 http-body.workspace = true
36 rand.workspace = true34 rand.workspace = true
@@ -41,7 +39,6 @@ time.workspace = true
41 reqwest = { workspace = true }39 reqwest = { workspace = true }
42 hmac.workspace = true40 hmac.workspace = true
43 similar = { workspace = true }41 similar = { workspace = true }
44-multer.workspace = true
45 ulid.workspace = true42 ulid.workspace = true
46 lettre.workspace = true43 lettre.workspace = true
47 zip = { workspace = true }44 zip = { workspace = true }
@@ -61,8 +58,6 @@ sha2.workspace = true
61 [dev-dependencies]58 [dev-dependencies]
62 tempfile.workspace = true59 tempfile.workspace = true
63 image = { workspace = true }60 image = { workspace = true }
64-scraper = { workspace = true }
65-webauthn-authenticator-rs = { version = "0.6.2", features = ["softpasskey"] }
66 61
67 [lints]62 [lints]
68 workspace = true63 workspace = true
crates/forge-web-app/src/test_support/mod.rsmodified+15 -10
@@ -19,7 +19,6 @@ use topcoat::cookie::CookieLayer;
19 use topcoat::router::tower::TowerLayer;19 use topcoat::router::tower::TowerLayer;
20 use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt};20 use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt};
21 21
22-#[cfg(not(test))]
23 use crate::layers::RepoMovedLayer;22 use crate::layers::RepoMovedLayer;
24 use crate::state::AppState;23 use crate::state::AppState;
25 use crate::throttle::Throttle;24 use crate::throttle::Throttle;
@@ -103,26 +102,32 @@ pub async fn test_state(dir: &Path) -> AppState {
103 }102 }
104 }103 }
105 104
106-/// The public router as boot.rs builds it, minus the listeners. This crate's own tests have no105+/// The public router as boot.rs builds it, minus the listeners. A crate's own tests link only
107-/// pages, so the layers scoped to page paths are left out there.106+/// the routes below it, so the account layer joins only when its `/settings` pages are there.
108 pub fn app_router(state: AppState) -> Router {107 pub fn app_router(state: AppState) -> Router {
109 let builder = Router::builder().discover().with(state);108 let builder = Router::builder().discover().with(state);
110- #[cfg(not(test))]109+ let builder = if has_settings_pages() {
111- let builder = builder.layer(crate::layers::AccountWriteLayer);110+ builder.layer(crate::layers::AccountWriteLayer)
112- let builder = builder.layer(CookieLayer::new());111+ } else {
113- #[cfg(not(test))]112+ builder
114- let builder = builder113+ };
114+ builder
115+ .layer(CookieLayer::new())
115 .layer(RepoMovedLayer)116 .layer(RepoMovedLayer)
116 .layer(crate::layers::RepoSettingsWriteLayer)117 .layer(crate::layers::RepoSettingsWriteLayer)
117 .layer(crate::layers::PullWriteLayer)118 .layer(crate::layers::PullWriteLayer)
118 .layer(crate::layers::DiscussionWriteLayer)119 .layer(crate::layers::DiscussionWriteLayer)
119- .layer(crate::layers::OrgWriteLayer);120+ .layer(crate::layers::OrgWriteLayer)
120- builder
121 .layer(TowerLayer::new(crate::compression::ResponseCompression))121 .layer(TowerLayer::new(crate::compression::ResponseCompression))
122 .with(Compression::disable())122 .with(Compression::disable())
123 .build()123 .build()
124 }124 }
125 125
126+fn has_settings_pages() -> bool {
127+ topcoat::internal::inventory::iter::<&'static dyn topcoat::router::Page>()
128+ .any(|page| page.path().to_string().starts_with("/settings"))
129+}
130+
126 /// Creates a session for `user_id` that expires in an hour and has no user agent.131 /// Creates a session for `user_id` that expires in an hour and has no user agent.
127 pub async fn create_session(store: &Store, user_id: &str, token: &str, csrf: &str) {132 pub async fn create_session(store: &Store, user_id: &str, token: &str, csrf: &str) {
128 store133 store
crates/forge-web-pages/Cargo.tomladded+46 -0
@@ -0,0 +1,46 @@
1+[package]
2+name = "forge-web-pages"
3+description = "forge pages that the rest build on: repo, issues, CI runs, wiki, releases and settings"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[features]
10+test-support = ["forge-web-app/test-support", "dep:tempfile"]
11+
12+[dependencies]
13+forge-web-app.workspace = true
14+forge-core.workspace = true
15+forge-git.workspace = true
16+forge-ci.workspace = true
17+forge-web-base.workspace = true
18+topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
19+tokio.workspace = true
20+futures-util.workspace = true
21+bytes.workspace = true
22+http.workspace = true
23+http-body-util.workspace = true
24+serde.workspace = true
25+serde_json.workspace = true
26+form_urlencoded.workspace = true
27+tracing.workspace = true
28+http-body.workspace = true
29+hex.workspace = true
30+nix = { workspace = true }
31+time.workspace = true
32+reqwest = { workspace = true }
33+similar = { workspace = true }
34+multer.workspace = true
35+zip = { workspace = true }
36+tar.workspace = true
37+
38+tempfile = { workspace = true, optional = true }
39+
40+[dev-dependencies]
41+forge-web-app = { workspace = true, features = ["test-support"] }
42+tempfile.workspace = true
43+image = { workspace = true }
44+
45+[lints]
46+workspace = true
crates/forge-web-pages/src/lib.rsadded+13 -0
@@ -0,0 +1,13 @@
1+//! forge pages.
2+
3+#![recursion_limit = "256"]
4+
5+#[cfg(any(test, feature = "test-support"))]
6+pub(crate) use forge_web_app::test_support;
7+pub(crate) use forge_web_app::{
8+ api, audit, auth, automerge, blobs, ci, client_ip, i18n, internal, layers, live, merge,
9+ merge_queue, notify, notify_hub, oci, package_ops, post_update, raw, release_ops, render,
10+ replication, repo_stats, state, templates, views, webhooks,
11+};
12+
13+pub mod pages;
crates/forge-web/src/pages/admin_runners.rs → crates/forge-web-pages/src/pages/admin_runners.rsrenamed+1 -1
@@ -380,7 +380,7 @@ fn list_href(page: u64, notice: &str) -> String {
380 /// A text link that asks first, in place; the POST only fires from the confirm button. For actions380 /// A text link that asks first, in place; the POST only fires from the confirm button. For actions
381 /// that are not destructive, so the confirm button is soft.381 /// that are not destructive, so the confirm button is soft.
382 #[component]382 #[component]
383-pub(crate) async fn confirm_post(383+pub async fn confirm_post(
384 cx: &Cx,384 cx: &Cx,
385 lang: Lang,385 lang: Lang,
386 csrf: &str,386 csrf: &str,
crates/forge-web/src/pages/admin_users.rs → crates/forge-web-pages/src/pages/admin_users.rsrenamed+2 -2
@@ -290,7 +290,7 @@ async fn users_view(
290 290
291 /// The rail of the Users tab: Users and Invites. `current` is `users` or `invites`.291 /// The rail of the Users tab: Users and Invites. `current` is `users` or `invites`.
292 #[component]292 #[component]
293-pub(crate) async fn users_rail(cx: &Cx, lang: Lang, current: &'static str) -> Result<impl View> {293+pub async fn users_rail(cx: &Cx, lang: Lang, current: &'static str) -> Result<impl View> {
294 let items = vec![294 let items = vec![
295 RailItem {295 RailItem {
296 name: g::t(lang, K::Users).to_owned(),296 name: g::t(lang, K::Users).to_owned(),
@@ -395,7 +395,7 @@ async fn users_create(cx: &Cx, Form(form): Form<CreateUserForm>) -> Result<impl
395 }395 }
396 396
397 /// The signed-in admin, or 404 for anonymous users and non-admins alike.397 /// The signed-in admin, or 404 for anonymous users and non-admins alike.
398-pub(crate) async fn admin_only(cx: &Cx) -> Result<(User, Session)> {398+pub async fn admin_only(cx: &Cx) -> Result<(User, Session)> {
399 match current_user(cx).await? {399 match current_user(cx).await? {
400 Some(viewer) if viewer.0.is_admin => Ok(viewer),400 Some(viewer) if viewer.0.is_admin => Ok(viewer),
401 _ => Err(not_found().into()),401 _ => Err(not_found().into()),
crates/forge-web/src/pages/ci_estimate.rs → crates/forge-web-pages/src/pages/ci_estimate.rsrenamed+0 -0
crates/forge-web/src/pages/ci_fail.rs → crates/forge-web-pages/src/pages/ci_fail.rsrenamed+4 -4
@@ -38,7 +38,7 @@ fn first_error(lines: &[String]) -> Option<usize> {
38 38
39 /// The values of the failure block, read once per run page.39 /// The values of the failure block, read once per run page.
40 #[derive(Clone)]40 #[derive(Clone)]
41-pub(crate) struct FailFirst {41+pub struct FailFirst {
42 job_name: String,42 job_name: String,
43 job_href: String,43 job_href: String,
44 message: String,44 message: String,
@@ -53,7 +53,7 @@ pub(crate) struct FailFirst {
53 53
54 impl FailFirst {54 impl FailFirst {
55 /// The log line the page opens at.55 /// The log line the page opens at.
56- pub(crate) fn line_no(&self) -> Option<u64> {56+ pub fn line_no(&self) -> Option<u64> {
57 self.line_no57 self.line_no
58 }58 }
59 }59 }
@@ -78,7 +78,7 @@ fn place_in(lines: &[String]) -> Option<String> {
78 }78 }
79 79
80 /// Reads the failed job's log tail (the same bounded read as the job page) and picks the lines to show.80 /// Reads the failed job's log tail (the same bounded read as the job page) and picks the lines to show.
81-pub(crate) async fn read(81+pub async fn read(
82 state: &AppState,82 state: &AppState,
83 title: &str,83 title: &str,
84 job_id: &str,84 job_id: &str,
@@ -116,7 +116,7 @@ pub(crate) async fn read(
116 /// The failure row, pinned above the log, which opens at the first error line: why it failed, the116 /// The failure row, pinned above the log, which opens at the first error line: why it failed, the
117 /// place in the code, and a link to that line in the job's log.117 /// place in the code, and a link to that line in the job's log.
118 #[component]118 #[component]
119-pub(crate) async fn fail_first_block(cx: &Cx, lang: Lang, fail: FailFirst) -> Result<impl View> {119+pub async fn fail_first_block(cx: &Cx, lang: Lang, fail: FailFirst) -> Result<impl View> {
120 let line_href = fail.line_no.map(|no| format!("{}#L{no}", fail.job_href));120 let line_href = fail.line_no.map(|no| format!("{}#L{no}", fail.job_href));
121 let why = if fail.message.is_empty() {121 let why = if fail.message.is_empty() {
122 fail.error.clone().unwrap_or_else(|| fail.job_name.clone())122 fail.error.clone().unwrap_or_else(|| fail.job_name.clone())
crates/forge-web/src/pages/ci_job.rs → crates/forge-web-pages/src/pages/ci_job.rsrenamed+9 -9
@@ -83,11 +83,11 @@ fn whole_utf8_len(buf: &[u8]) -> usize {
83 83
84 /// What the job page shows of a log: the text, whether the start was cut, the byte offset just84 /// What the job page shows of a log: the text, whether the start was cut, the byte offset just
85 /// past the text, and the number of its first line in the whole log.85 /// past the text, and the number of its first line in the whole log.
86-pub(crate) struct Tail {86+pub struct Tail {
87- pub(crate) text: String,87+ pub text: String,
88- pub(crate) truncated: bool,88+ pub truncated: bool,
89- pub(crate) offset: u64,89+ pub offset: u64,
90- pub(crate) first_line: u64,90+ pub first_line: u64,
91 }91 }
92 92
93 /// Most logs the newline cache keeps. A full cache drops an arbitrary entry.93 /// Most logs the newline cache keeps. A full cache drops an arbitrary entry.
@@ -144,12 +144,12 @@ async fn newlines_before(path: &Path, end: u64) -> Result<u64> {
144 }144 }
145 145
146 /// The last `TAIL_BYTES` of a log, from a line boundary. A log that does not exist yet is empty.146 /// The last `TAIL_BYTES` of a log, from a line boundary. A log that does not exist yet is empty.
147-pub(crate) async fn log_tail(path: &Path) -> Result<Tail> {147+pub async fn log_tail(path: &Path) -> Result<Tail> {
148 log_tail_of(path, TAIL_BYTES).await148 log_tail_of(path, TAIL_BYTES).await
149 }149 }
150 150
151 /// The last `max` bytes of a log, from a line boundary.151 /// The last `max` bytes of a log, from a line boundary.
152-pub(crate) async fn log_tail_of(path: &Path, max: u64) -> Result<Tail> {152+pub async fn log_tail_of(path: &Path, max: u64) -> Result<Tail> {
153 let mut file = match tokio::fs::File::open(path).await {153 let mut file = match tokio::fs::File::open(path).await {
154 Ok(file) => file,154 Ok(file) => file,
155 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {155 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
@@ -199,7 +199,7 @@ pub(crate) async fn log_tail_of(path: &Path, max: u64) -> Result<Tail> {
199 /// The log from byte `offset`, at most `max` bytes. `offset` should be the start of a line, such as a199 /// The log from byte `offset`, at most `max` bytes. `offset` should be the start of a line, such as a
200 /// step's. When the file goes on past the bytes read, the text is cut back to its last newline. A log200 /// step's. When the file goes on past the bytes read, the text is cut back to its last newline. A log
201 /// that does not exist yet is empty. `truncated` is never set: nothing is cut at the start.201 /// that does not exist yet is empty. `truncated` is never set: nothing is cut at the start.
202-pub(crate) async fn log_from(path: &Path, offset: u64, max: u64) -> Result<Tail> {202+pub async fn log_from(path: &Path, offset: u64, max: u64) -> Result<Tail> {
203 let mut file = match tokio::fs::File::open(path).await {203 let mut file = match tokio::fs::File::open(path).await {
204 Ok(file) => file,204 Ok(file) => file,
205 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {205 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
@@ -248,7 +248,7 @@ pub(crate) async fn log_from(path: &Path, offset: u64, max: u64) -> Result<Tail>
248 /// log grew or its state did). The stream ends when the job is terminal and a read after seeing248 /// log grew or its state did). The stream ends when the job is terminal and a read after seeing
249 /// that returns nothing, so every byte the runner wrote is sent. A job that is gone, a read249 /// that returns nothing, so every byte the runner wrote is sent. A job that is gone, a read
250 /// error, or a repo the viewer can no longer read ends the stream.250 /// error, or a repo the viewer can no longer read ends the stream.
251-pub(crate) fn follow_log(251+pub fn follow_log(
252 store: Store,252 store: Store,
253 live: Arc<CiLive>,253 live: Arc<CiLive>,
254 job_id: String,254 job_id: String,
crates/forge-web/src/pages/ci_runs.rs → crates/forge-web-pages/src/pages/ci_runs.rsrenamed+8 -8
@@ -101,7 +101,7 @@ fn viewer_user(ctx: &RepoCtx) -> Option<&User> {
101 }101 }
102 102
103 /// Whether the viewer may change CI runs of this repo. Archived repos refuse.103 /// Whether the viewer may change CI runs of this repo. Archived repos refuse.
104-pub(crate) fn can_write(ctx: &RepoCtx) -> bool {104+pub fn can_write(ctx: &RepoCtx) -> bool {
105 authorize(105 authorize(
106 viewer_user(ctx),106 viewer_user(ctx),
107 &ctx.repo,107 &ctx.repo,
@@ -191,7 +191,7 @@ fn unix_of(stamp: &str) -> Option<i64> {
191 }191 }
192 192
193 /// "3 minutes ago" for a stamp. An unreadable stamp is shown as it is stored.193 /// "3 minutes ago" for a stamp. An unreadable stamp is shown as it is stored.
194-pub(crate) fn age_text(lang: Lang, stamp: &str) -> String {194+pub fn age_text(lang: Lang, stamp: &str) -> String {
195 match unix_of(stamp) {195 match unix_of(stamp) {
196 Some(unix) => relative_time(lang, unix, now_unix()),196 Some(unix) => relative_time(lang, unix, now_unix()),
197 None => stamp.to_owned(),197 None => stamp.to_owned(),
@@ -199,7 +199,7 @@ pub(crate) fn age_text(lang: Lang, stamp: &str) -> String {
199 }199 }
200 200
201 /// "1m 5s", or "" when the job never started. A running job counts up to now.201 /// "1m 5s", or "" when the job never started. A running job counts up to now.
202-pub(crate) fn duration_text(lang: Lang, started: Option<&str>, finished: Option<&str>) -> String {202+pub fn duration_text(lang: Lang, started: Option<&str>, finished: Option<&str>) -> String {
203 let Some(start) = started.and_then(unix_of) else {203 let Some(start) = started.and_then(unix_of) else {
204 return String::new();204 return String::new();
205 };205 };
@@ -218,7 +218,7 @@ fn secs_text(lang: Lang, secs: i64) -> String {
218 218
219 /// The duration formats of `lang` with `{m}` and `{s}` where the numbers go, for the client ticker:219 /// The duration formats of `lang` with `{m}` and `{s}` where the numbers go, for the client ticker:
220 /// the one with minutes and the seconds-only one.220 /// the one with minutes and the seconds-only one.
221-pub(crate) fn duration_templates(lang: Lang) -> (String, String) {221+pub fn duration_templates(lang: Lang) -> (String, String) {
222 (222 (
223 g::duration_minutes(lang, 111_111, 222_222)223 g::duration_minutes(lang, 111_111, 222_222)
224 .replace("111111", "{m}")224 .replace("111111", "{m}")
@@ -1472,7 +1472,7 @@ fn row_meta(run: &CiRun, jobs: &[Timing], actor: &str, lang: Lang) -> RowMeta {
1472 }1472 }
1473 1473
1474 /// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line.1474 /// Drops the ANSI escape sequences and the other control characters (a tab stays) of a log line.
1475-pub(crate) fn strip_ansi(line: &str) -> String {1475+pub fn strip_ansi(line: &str) -> String {
1476 let mut out = String::with_capacity(line.len());1476 let mut out = String::with_capacity(line.len());
1477 let mut chars = line.chars().peekable();1477 let mut chars = line.chars().peekable();
1478 while let Some(c) = chars.next() {1478 while let Some(c) = chars.next() {
@@ -1863,7 +1863,7 @@ struct RunHeader {
1863 1863
1864 /// Whether a branch, tag or pull request still reaches `oid`. A force push that overwrote the commit1864 /// Whether a branch, tag or pull request still reaches `oid`. A force push that overwrote the commit
1865 /// leaves it unreachable: its run then has no commit link and cannot be run again.1865 /// leaves it unreachable: its run then has no commit link and cannot be run again.
1866-pub(crate) async fn commit_reachable_for(path: &Path, oid: &str) -> Result<bool> {1866+pub async fn commit_reachable_for(path: &Path, oid: &str) -> Result<bool> {
1867 let (path, oid) = (path.to_path_buf(), oid.to_owned());1867 let (path, oid) = (path.to_path_buf(), oid.to_owned());
1868 Ok(tokio::task::spawn_blocking(move || commit_reachable(&path, &oid)).await??)1868 Ok(tokio::task::spawn_blocking(move || commit_reachable(&path, &oid)).await??)
1869 }1869 }
@@ -2771,7 +2771,7 @@ async fn run_page(cx: &Cx) -> Result<impl View> {
2771 2771
2772 /// The dock's bars: the newest commits of the default branch, oldest first, each with its latest CI2772 /// The dock's bars: the newest commits of the default branch, oldest first, each with its latest CI
2773 /// state. Empty when the branch cannot be read, which draws no strip.2773 /// state. Empty when the branch cannot be read, which draws no strip.
2774-pub(crate) async fn dock_bars(state: &AppState, ctx: &RepoCtx) -> Vec<StripBar> {2774+pub async fn dock_bars(state: &AppState, ctx: &RepoCtx) -> Vec<StripBar> {
2775 let path = ctx.path.clone();2775 let path = ctx.path.clone();
2776 let branch = ctx.repo.default_branch.clone();2776 let branch = ctx.repo.default_branch.clone();
2777 let head = tokio::task::spawn_blocking(move || {2777 let head = tokio::task::spawn_blocking(move || {
@@ -2832,7 +2832,7 @@ async fn manual_run_post(cx: &Cx, Form(form): Form<ManualForm>) -> Result<SeeOth
2832 Ok(see_other(run_href(&title, run.number)))2832 Ok(see_other(run_href(&title, run.number)))
2833 }2833 }
2834 2834
2835-pub(crate) async fn run_status(store: &Store, run_id: &str) -> Result<Status> {2835+pub async fn run_status(store: &Store, run_id: &str) -> Result<Status> {
2836 Ok(store2836 Ok(store
2837 .run_by_id(run_id)2837 .run_by_id(run_id)
2838 .await?2838 .await?
crates/forge-web/src/pages/code_live.rs → crates/forge-web-pages/src/pages/code_live.rsrenamed+0 -0
crates/forge-web/src/pages/discussion_settings.rs → crates/forge-web-pages/src/pages/discussion_settings.rsrenamed+1 -1
@@ -25,7 +25,7 @@ path_param!(repo);
25 /// The Discussions feature: one switch, then its hint. `enabled` is the current state. The switch submits25 /// The Discussions feature: one switch, then its hint. `enabled` is the current state. The switch submits
26 /// the form on change (`data-autosubmit`); an unchecked box sends no `enabled`, which the handler reads as off.26 /// the form on change (`data-autosubmit`); an unchecked box sends no `enabled`, which the handler reads as off.
27 #[component]27 #[component]
28-pub(crate) async fn discussions_switch(28+pub async fn discussions_switch(
29 cx: &Cx,29 cx: &Cx,
30 lang: Lang,30 lang: Lang,
31 action: String,31 action: String,
crates/forge-web/src/pages/edit_history.rs → crates/forge-web-pages/src/pages/edit_history.rsrenamed+3 -310
@@ -40,7 +40,7 @@ const CONTEXT_LINES: usize = 3;
40 const KINDS: [&str; 3] = ["issue", "comment", "review_comment"];40 const KINDS: [&str; 3] = ["issue", "comment", "review_comment"];
41 41
42 /// The history URL of one target of an item: `/{o}/{r}/{issues|pulls}/{n}/history/{kind}/{id}`.42 /// The history URL of one target of an item: `/{o}/{r}/{issues|pulls}/{n}/history/{kind}/{id}`.
43-pub(crate) fn history_href(43+pub fn history_href(
44 owner: &str,44 owner: &str,
45 repo_name: &str,45 repo_name: &str,
46 kind: ItemKind,46 kind: ItemKind,
@@ -57,7 +57,7 @@ pub(crate) fn history_href(
57 }57 }
58 58
59 /// Edit counts for a batch of targets, one query per call. Targets never edited are absent.59 /// Edit counts for a batch of targets, one query per call. Targets never edited are absent.
60-pub(crate) async fn edit_counts(60+pub async fn edit_counts(
61 state: &AppState,61 state: &AppState,
62 target_kind: &str,62 target_kind: &str,
63 ids: &[&str],63 ids: &[&str],
@@ -66,7 +66,7 @@ pub(crate) async fn edit_counts(
66 }66 }
67 67
68 /// Edit counts for the root comments and replies of `threads`, shared by every thread of a page.68 /// Edit counts for the root comments and replies of `threads`, shared by every thread of a page.
69-pub(crate) async fn thread_edit_counts(69+pub async fn thread_edit_counts(
70 state: &AppState,70 state: &AppState,
71 threads: &[Thread],71 threads: &[Thread],
72 ) -> Result<Arc<HashMap<String, u64>>> {72 ) -> Result<Arc<HashMap<String, u64>>> {
@@ -331,310 +331,3 @@ async fn issue_history(cx: &Cx) -> Result<impl View> {
331 async fn pull_history(cx: &Cx) -> Result<impl View> {331 async fn pull_history(cx: &Cx) -> Result<impl View> {
332 history_route(cx, ItemKind::Pull).await332 history_route(cx, ItemKind::Pull).await
333 }333 }
334-
335-#[cfg(test)]
336-mod tests {
337- use forge_core::{Side, Visibility};
338- use topcoat::router::request::Request;
339- use topcoat::router::{Body, Router, to_bytes};
340-
341- use crate::auth::SESSION_COOKIE;
342- use crate::test_support::fixture::{Fixture, OWNER, REPO};
343-
344- /// Sends one request and returns `(status, body)`.
345- async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
346- let mut req = Request::builder().method("GET").uri(uri);
347- if let Some(token) = token {
348- req = req.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
349- }
350- let res = router.handle(req.body(Body::empty()).unwrap()).await;
351- let status = res.status().as_u16();
352- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
353- (status, String::from_utf8_lossy(&bytes).into_owned())
354- }
355-
356- /// The repo owner with a session whose token is `tahinli`.
357- async fn tahinli(fx: &Fixture) -> forge_core::User {
358- let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
359- crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
360- owner
361- }
362-
363- async fn repo_id(fx: &Fixture) -> String {
364- fx.store
365- .repo_by_owner_and_name(OWNER, REPO)
366- .await
367- .unwrap()
368- .unwrap()
369- .id
370- }
371-
372- fn hex_oid(c: char) -> String {
373- std::iter::repeat_n(c, 40).collect()
374- }
375-
376- /// Every scenario on the public repo shares one fixture. Each makes its own issue or pull and
377- /// reads its numbers from the store, so no scenario depends on another's data.
378- #[tokio::test]
379- async fn public_histories_show_diffs_markers_and_refusals() {
380- let fx = Fixture::new(Visibility::Public).await;
381- let owner = tahinli(&fx).await;
382- let id = repo_id(&fx).await;
383-
384- // A comment edited twice: a marker on the item page and two versions with diffs.
385- let issue = fx
386- .store
387- .create_issue(&id, &owner.id, "bug", "body")
388- .await
389- .unwrap();
390- let comment = fx
391- .store
392- .add_comment(&issue.id, &owner.id, "one\ntwo\nthree")
393- .await
394- .unwrap();
395- fx.store
396- .edit_comment(&comment.id, &owner.id, "one\nTWO\nthree")
397- .await
398- .unwrap();
399- fx.store
400- .edit_comment(&comment.id, &owner.id, "one\nTWO\nthree\nfour")
401- .await
402- .unwrap();
403- let item = format!("/tahinli/demo/issues/{}", issue.number);
404- let link = format!("{item}/history/comment/{}", comment.id);
405-
406- let (status, page) = send(&fx.router, &item, None).await;
407- assert_eq!(status, 200, "edited comment: item page");
408- assert!(
409- page.contains("issue-edited"),
410- "edited comment: marker {page}"
411- );
412- assert!(
413- page.contains(&format!("href=\"{link}\"")),
414- "edited comment: link {page}"
415- );
416-
417- let (status, history) = send(&fx.router, &link, None).await;
418- assert_eq!(status, 200, "edited comment: history");
419- assert_eq!(
420- history.matches("<article").count(),
421- 2,
422- "edited comment: versions {history}"
423- );
424- assert!(
425- history.contains("diff-line del"),
426- "edited comment: del {history}"
427- );
428- assert!(history.contains("-two"), "edited comment: -two {history}");
429- assert!(history.contains("+TWO"), "edited comment: +TWO {history}");
430- assert!(history.contains("+four"), "edited comment: +four {history}");
431- assert!(
432- history.contains("tahinli"),
433- "edited comment: editor {history}"
434- );
435-
436- // A comment that was never edited has no marker.
437- let plain = fx
438- .store
439- .create_issue(&id, &owner.id, "plain", "body")
440- .await
441- .unwrap();
442- fx.store
443- .add_comment(&plain.id, &owner.id, "plain")
444- .await
445- .unwrap();
446- let (status, page) = send(
447- &fx.router,
448- &format!("/tahinli/demo/issues/{}", plain.number),
449- None,
450- )
451- .await;
452- assert_eq!(status, 200, "unedited comment: item page");
453- assert!(
454- !page.contains("issue-edited"),
455- "unedited comment: no marker {page}"
456- );
457-
458- // An issue body and title edit: the old title and the changed lines show.
459- let titled = fx
460- .store
461- .create_issue(&id, &owner.id, "old title", "a\nb\nc")
462- .await
463- .unwrap();
464- fx.store
465- .edit_issue(&titled.id, &owner.id, "new title", "a\nB\nc")
466- .await
467- .unwrap();
468- let link = format!(
469- "/tahinli/demo/issues/{}/history/issue/{}",
470- titled.number, titled.id
471- );
472- let (status, page) = send(
473- &fx.router,
474- &format!("/tahinli/demo/issues/{}", titled.number),
475- None,
476- )
477- .await;
478- assert_eq!(status, 200, "body edit: item page");
479- assert!(
480- page.contains(&format!("href=\"{link}\"")),
481- "body edit: link {page}"
482- );
483- let (status, history) = send(&fx.router, &link, None).await;
484- assert_eq!(status, 200, "body edit: history");
485- assert!(
486- history.contains("Title: old title"),
487- "body edit: title {history}"
488- );
489- assert!(history.contains("-b"), "body edit: -b {history}");
490- assert!(history.contains("+B"), "body edit: +B {history}");
491-
492- // A comment on one issue is not found under another issue's URL.
493- let other = fx
494- .store
495- .create_issue(&id, &owner.id, "second", "body")
496- .await
497- .unwrap();
498- let other_comment = fx
499- .store
500- .add_comment(&other.id, &owner.id, "x")
501- .await
502- .unwrap();
503- fx.store
504- .edit_comment(&other_comment.id, &owner.id, "y")
505- .await
506- .unwrap();
507- let (status, _) = send(
508- &fx.router,
509- &format!(
510- "/tahinli/demo/issues/{}/history/comment/{}",
511- issue.number, other_comment.id
512- ),
513- None,
514- )
515- .await;
516- assert_eq!(status, 404, "wrong item: not found");
517- let (status, _) = send(
518- &fx.router,
519- &format!(
520- "/tahinli/demo/issues/{}/history/comment/{}",
521- other.number, other_comment.id
522- ),
523- None,
524- )
525- .await;
526- assert_eq!(status, 200, "right item: found");
527-
528- // An unknown kind and a missing target are both not found.
529- let (status, _) = send(
530- &fx.router,
531- &format!(
532- "/tahinli/demo/issues/{}/history/label/{}",
533- issue.number, issue.id
534- ),
535- None,
536- )
537- .await;
538- assert_eq!(status, 404, "unknown kind");
539- let (status, _) = send(
540- &fx.router,
541- &format!(
542- "/tahinli/demo/issues/{}/history/comment/missing",
543- issue.number
544- ),
545- None,
546- )
547- .await;
548- assert_eq!(status, 404, "missing target");
549-
550- // Review comment history on a pull request, and not under the issue URL of the same number.
551- let pr = fx
552- .store
553- .create_pull(
554- &id,
555- &owner.id,
556- "change",
557- "",
558- "main",
559- &id,
560- "feature",
561- &hex_oid('a'),
562- &hex_oid('b'),
563- )
564- .await
565- .unwrap();
566- let review = fx
567- .store
568- .add_review_comment(
569- &pr.issue.id,
570- &owner.id,
571- false,
572- "a.txt",
573- Side::New,
574- 2,
575- &hex_oid('a'),
576- "+x",
577- "first",
578- )
579- .await
580- .unwrap();
581- fx.store
582- .edit_review_comment(&review.id, "second")
583- .await
584- .unwrap();
585- let link = format!(
586- "/tahinli/demo/pulls/{}/history/review_comment/{}",
587- pr.issue.number, review.id
588- );
589- let (status, history) = send(&fx.router, &link, None).await;
590- assert_eq!(status, 200, "review comment: history");
591- assert!(
592- history.contains("-first"),
593- "review comment: -first {history}"
594- );
595- assert!(
596- history.contains("+second"),
597- "review comment: +second {history}"
598- );
599- let (status, _) = send(
600- &fx.router,
601- &format!(
602- "/tahinli/demo/issues/{}/history/review_comment/{}",
603- pr.issue.number, review.id
604- ),
605- None,
606- )
607- .await;
608- assert_eq!(status, 404, "review comment under the issue URL");
609- }
610-
611- #[tokio::test]
612- async fn private_repo_is_not_found_for_anonymous() {
613- let fx = Fixture::new(Visibility::Private).await;
614- let owner = tahinli(&fx).await;
615- let id = repo_id(&fx).await;
616- let issue = fx
617- .store
618- .create_issue(&id, &owner.id, "secret", "body")
619- .await
620- .unwrap();
621- fx.store
622- .edit_issue(&issue.id, &owner.id, "secret", "body 2")
623- .await
624- .unwrap();
625- let (status, _) = send(
626- &fx.router,
627- &format!("/tahinli/demo/issues/1/history/issue/{}", issue.id),
628- None,
629- )
630- .await;
631- assert_eq!(status, 404);
632- let (status, _) = send(
633- &fx.router,
634- &format!("/tahinli/demo/issues/1/history/issue/{}", issue.id),
635- Some("tahinli"),
636- )
637- .await;
638- assert_eq!(status, 200);
639- }
640-}
crates/forge-web/src/pages/finder.rs → crates/forge-web-pages/src/pages/finder.rsrenamed+0 -0
crates/forge-web/src/pages/issue_meta.rs → crates/forge-web-pages/src/pages/issue_meta.rsrenamed+12 -22
@@ -34,14 +34,14 @@ path_param!(number);
34 34
35 /// Whether the viewer may triage this repo's issues, labels and milestones: Triage or higher, or35 /// Whether the viewer may triage this repo's issues, labels and milestones: Triage or higher, or
36 /// the owner or an instance admin, on a repo that is not archived.36 /// the owner or an instance admin, on a repo that is not archived.
37-pub(crate) fn can_triage(ctx: &RepoCtx) -> bool {37+pub fn can_triage(ctx: &RepoCtx) -> bool {
38 let actor = ctx.viewer.as_ref().map(|(user, _)| user);38 let actor = ctx.viewer.as_ref().map(|(user, _)| user);
39 !ctx.repo.archived39 !ctx.repo.archived
40 && authorize(actor, &ctx.repo, ctx.role, ctx.org_role, Action::Triage).is_ok()40 && authorize(actor, &ctx.repo, ctx.role, ctx.org_role, Action::Triage).is_ok()
41 }41 }
42 42
43 /// The repo fields and viewer flags that the label and milestone pages share.43 /// The repo fields and viewer flags that the label and milestone pages share.
44-pub(crate) struct RepoFrame {44+pub struct RepoFrame {
45 /// `owner/name`.45 /// `owner/name`.
46 pub title: String,46 pub title: String,
47 pub csrf: String,47 pub csrf: String,
@@ -53,7 +53,7 @@ pub(crate) struct RepoFrame {
53 53
54 impl RepoFrame {54 impl RepoFrame {
55 /// The frame for a page on the Issues tab group. `active` is the header tab to mark.55 /// The frame for a page on the Issues tab group. `active` is the header tab to mark.
56- pub(crate) async fn new(ctx: &RepoCtx, state: &AppState, active: &'static str) -> Result<Self> {56+ pub async fn new(ctx: &RepoCtx, state: &AppState, active: &'static str) -> Result<Self> {
57 let csrf = ctx57 let csrf = ctx
58 .viewer58 .viewer
59 .as_ref()59 .as_ref()
@@ -72,7 +72,7 @@ impl RepoFrame {
72 72
73 /// The message for a failed store write that the form can show, or the error to propagate. A73 /// The message for a failed store write that the form can show, or the error to propagate. A
74 /// missing row is 404 and anything that is not a validation error is a server error.74 /// missing row is 404 and anything that is not a validation error is a server error.
75-pub(crate) fn refusal_message(e: forge_core::Error) -> Result<String> {75+pub fn refusal_message(e: forge_core::Error) -> Result<String> {
76 if matches!(e, forge_core::Error::NotFound) {76 if matches!(e, forge_core::Error::NotFound) {
77 return Err(not_found().into());77 return Err(not_found().into());
78 }78 }
@@ -85,12 +85,7 @@ pub(crate) fn refusal_message(e: forge_core::Error) -> Result<String> {
85 /// Links between the issue-adjacent pages of a repo: Issues, Labels and Milestones. The one named85 /// Links between the issue-adjacent pages of a repo: Issues, Labels and Milestones. The one named
86 /// by `active` is the current page.86 /// by `active` is the current page.
87 #[component]87 #[component]
88-pub(crate) async fn issue_subnav(88+pub async fn issue_subnav(cx: &Cx, lang: Lang, title: String, active: String) -> Result<impl View> {
89- cx: &Cx,
90- lang: Lang,
91- title: String,
92- active: String,
93-) -> Result<impl View> {
94 let issues = format!("/{title}/issues");89 let issues = format!("/{title}/issues");
95 let labels = format!("/{title}/labels");90 let labels = format!("/{title}/labels");
96 let milestones = format!("/{title}/milestones");91 let milestones = format!("/{title}/milestones");
@@ -121,14 +116,14 @@ pub(crate) async fn issue_subnav(
121 }116 }
122 117
123 /// Every `key=value` pair of a urlencoded body, in order, with repeated keys kept.118 /// Every `key=value` pair of a urlencoded body, in order, with repeated keys kept.
124-pub(crate) fn form_pairs(raw: &[u8]) -> Vec<(String, String)> {119+pub fn form_pairs(raw: &[u8]) -> Vec<(String, String)> {
125 form_urlencoded::parse(raw)120 form_urlencoded::parse(raw)
126 .map(|(k, v)| (k.into_owned(), v.into_owned()))121 .map(|(k, v)| (k.into_owned(), v.into_owned()))
127 .collect()122 .collect()
128 }123 }
129 124
130 /// The first value for `key`, or an empty string.125 /// The first value for `key`, or an empty string.
131-pub(crate) fn form_field(pairs: &[(String, String)], key: &str) -> String {126+pub fn form_field(pairs: &[(String, String)], key: &str) -> String {
132 pairs127 pairs
133 .iter()128 .iter()
134 .find(|(k, _)| k == key)129 .find(|(k, _)| k == key)
@@ -137,7 +132,7 @@ pub(crate) fn form_field(pairs: &[(String, String)], key: &str) -> String {
137 }132 }
138 133
139 /// Every value for `key`, in order.134 /// Every value for `key`, in order.
140-pub(crate) fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> {135+pub fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> {
141 pairs136 pairs
142 .iter()137 .iter()
143 .filter(|(k, _)| k == key)138 .filter(|(k, _)| k == key)
@@ -147,7 +142,7 @@ pub(crate) fn form_all(pairs: &[(String, String)], key: &str) -> Vec<String> {
147 142
148 /// The CSRF check and triage gate for a write. Returns the signed-in user. Anonymous viewers are143 /// The CSRF check and triage gate for a write. Returns the signed-in user. Anonymous viewers are
149 /// sent to log in, a bad token is 403, and a viewer without Triage (or an archived repo) is 403.144 /// sent to log in, a bad token is 403, and a viewer without Triage (or an archived repo) is 403.
150-pub(crate) async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<User> {145+pub async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<User> {
151 let (user, _session) = require_csrf(cx, csrf).await?;146 let (user, _session) = require_csrf(cx, csrf).await?;
152 if ctx.repo.archived147 if ctx.repo.archived
153 || authorize(148 || authorize(
@@ -166,12 +161,7 @@ pub(crate) async fn triage_guard(cx: &Cx, ctx: &RepoCtx, csrf: &str) -> Result<U
166 161
167 /// Loads the issue or pull request named by `{number}` in this repo, or 404. A pull request's162 /// Loads the issue or pull request named by `{number}` in this repo, or 404. A pull request's
168 /// sidebar data lives on its issue row, so the returned `Issue` serves both.163 /// sidebar data lives on its issue row, so the returned `Issue` serves both.
169-pub(crate) async fn item_from_path(164+pub async fn item_from_path(cx: &Cx, ctx: &RepoCtx, kind: ItemKind, number: &str) -> Result<Issue> {
170- cx: &Cx,
171- ctx: &RepoCtx,
172- kind: ItemKind,
173- number: &str,
174-) -> Result<Issue> {
175 let Some(n) = number.parse::<i64>().ok() else {165 let Some(n) = number.parse::<i64>().ok() else {
176 return Err(not_found().into());166 return Err(not_found().into());
177 };167 };
@@ -190,7 +180,7 @@ pub(crate) async fn item_from_path(
190 }180 }
191 181
192 /// `/{owner}/{repo}/issues/{n}` or `/{owner}/{repo}/pulls/{n}` for this repo.182 /// `/{owner}/{repo}/issues/{n}` or `/{owner}/{repo}/pulls/{n}` for this repo.
193-pub(crate) fn item_href(ctx: &RepoCtx, kind: ItemKind, number: i64) -> String {183+pub fn item_href(ctx: &RepoCtx, kind: ItemKind, number: i64) -> String {
194 format!(184 format!(
195 "/{}/{}/{}/{number}",185 "/{}/{}/{}/{number}",
196 ctx.repo.owner_name,186 ctx.repo.owner_name,
@@ -201,7 +191,7 @@ pub(crate) fn item_href(ctx: &RepoCtx, kind: ItemKind, number: i64) -> String {
201 191
202 /// The error box with a link back to where the action came from, in the viewer's language.192 /// The error box with a link back to where the action came from, in the viewer's language.
203 #[component]193 #[component]
204-pub(crate) async fn action_error_at(194+pub async fn action_error_at(
205 cx: &Cx,195 cx: &Cx,
206 lang: Lang,196 lang: Lang,
207 message: String,197 message: String,
crates/forge-web/src/pages/issue_parts.rs → crates/forge-web-pages/src/pages/issue_parts.rsrenamed+73 -81
@@ -38,13 +38,13 @@ use crate::webhooks::emit::{Sender, emit_comment, emit_item_action};
38 /// Which kind of item a page shows. It decides the URL segment of the item's own links and which38 /// Which kind of item a page shows. It decides the URL segment of the item's own links and which
39 /// row `{number}` names (an issue row or a pull request's issue row).39 /// row `{number}` names (an issue row or a pull request's issue row).
40 #[derive(Clone, Copy, PartialEq, Eq)]40 #[derive(Clone, Copy, PartialEq, Eq)]
41-pub(crate) enum ItemKind {41+pub enum ItemKind {
42 Issue,42 Issue,
43 Pull,43 Pull,
44 }44 }
45 45
46 impl ItemKind {46 impl ItemKind {
47- pub(crate) fn segment(self) -> &'static str {47+ pub fn segment(self) -> &'static str {
48 match self {48 match self {
49 ItemKind::Issue => "issues",49 ItemKind::Issue => "issues",
50 ItemKind::Pull => "pulls",50 ItemKind::Pull => "pulls",
@@ -54,12 +54,12 @@ impl ItemKind {
54 54
55 // Permissions55 // Permissions
56 56
57-pub(crate) fn viewer(ctx: &RepoCtx) -> Option<&User> {57+pub fn viewer(ctx: &RepoCtx) -> Option<&User> {
58 ctx.viewer.as_ref().map(|(user, _)| user)58 ctx.viewer.as_ref().map(|(user, _)| user)
59 }59 }
60 60
61 /// Triage or better on this repo (owner and instance admins included). Anonymous viewers never have it.61 /// Triage or better on this repo (owner and instance admins included). Anonymous viewers never have it.
62-pub(crate) fn triage(ctx: &RepoCtx) -> bool {62+pub fn triage(ctx: &RepoCtx) -> bool {
63 authorize(63 authorize(
64 viewer(ctx),64 viewer(ctx),
65 &ctx.repo,65 &ctx.repo,
@@ -72,12 +72,12 @@ pub(crate) fn triage(ctx: &RepoCtx) -> bool {
72 72
73 /// Whether the viewer may add to an item's conversation: comments, reactions, review threads and73 /// Whether the viewer may add to an item's conversation: comments, reactions, review threads and
74 /// reviews. A locked conversation takes these from Triage holders only. Authors keep their edits.74 /// reviews. A locked conversation takes these from Triage holders only. Authors keep their edits.
75-pub(crate) fn may_converse(ctx: &RepoCtx, item: &Issue) -> bool {75+pub fn may_converse(ctx: &RepoCtx, item: &Issue) -> bool {
76 !item.locked || triage(ctx)76 !item.locked || triage(ctx)
77 }77 }
78 78
79 /// The notice shown in place of the comment form on a conversation the viewer may not add to.79 /// The notice shown in place of the comment form on a conversation the viewer may not add to.
80-pub(crate) fn lock_message(lang: Lang, item: &Issue) -> String {80+pub fn lock_message(lang: Lang, item: &Issue) -> String {
81 match item.lock_reason.as_deref() {81 match item.lock_reason.as_deref() {
82 Some(reason) => g::conversation_locked_for(lang, lock_reason_label(lang, reason)),82 Some(reason) => g::conversation_locked_for(lang, lock_reason_label(lang, reason)),
83 None => g::t(lang, K::ConversationLocked).to_owned(),83 None => g::t(lang, K::ConversationLocked).to_owned(),
@@ -85,7 +85,7 @@ pub(crate) fn lock_message(lang: Lang, item: &Issue) -> String {
85 }85 }
86 86
87 /// The reader-facing text of a lock reason. Unknown values are shown as stored.87 /// The reader-facing text of a lock reason. Unknown values are shown as stored.
88-pub(crate) fn lock_reason_label(lang: Lang, reason: &str) -> &str {88+pub fn lock_reason_label(lang: Lang, reason: &str) -> &str {
89 match reason {89 match reason {
90 "off_topic" => g::t(lang, K::LockOffTopic),90 "off_topic" => g::t(lang, K::LockOffTopic),
91 "too_heated" => g::t(lang, K::LockTooHeated),91 "too_heated" => g::t(lang, K::LockTooHeated),
@@ -97,19 +97,19 @@ pub(crate) fn lock_reason_label(lang: Lang, reason: &str) -> &str {
97 97
98 /// Whether the viewer may edit or delete an item by `author_id`: its author or a Triage holder,98 /// Whether the viewer may edit or delete an item by `author_id`: its author or a Triage holder,
99 /// signed in, on a repo that is not archived.99 /// signed in, on a repo that is not archived.
100-pub(crate) fn may_change(ctx: &RepoCtx, author_id: &str) -> bool {100+pub fn may_change(ctx: &RepoCtx, author_id: &str) -> bool {
101 !ctx.repo.archived && viewer(ctx).is_some_and(|user| user.id == author_id || triage(ctx))101 !ctx.repo.archived && viewer(ctx).is_some_and(|user| user.id == author_id || triage(ctx))
102 }102 }
103 103
104 /// Write requests need an unarchived repo and a matching CSRF token.104 /// Write requests need an unarchived repo and a matching CSRF token.
105-pub(crate) fn check_write(ctx: &RepoCtx, session: &Session, csrf: &str) -> Result<()> {105+pub fn check_write(ctx: &RepoCtx, session: &Session, csrf: &str) -> Result<()> {
106 if ctx.repo.archived || !check_csrf(session, csrf) {106 if ctx.repo.archived || !check_csrf(session, csrf) {
107 return Err(forbidden().into());107 return Err(forbidden().into());
108 }108 }
109 Ok(())109 Ok(())
110 }110 }
111 111
112-pub(crate) fn csrf_of(ctx: &RepoCtx) -> String {112+pub fn csrf_of(ctx: &RepoCtx) -> String {
113 ctx.viewer113 ctx.viewer
114 .as_ref()114 .as_ref()
115 .map(|(_, session)| session.csrf_token.clone())115 .map(|(_, session)| session.csrf_token.clone())
@@ -119,7 +119,7 @@ pub(crate) fn csrf_of(ctx: &RepoCtx) -> String {
119 // Lookups119 // Lookups
120 120
121 /// Parses an issue number: digits only, greater than zero. Anything else is 404.121 /// Parses an issue number: digits only, greater than zero. Anything else is 404.
122-pub(crate) fn parse_number(raw: &str) -> Result<i64> {122+pub fn parse_number(raw: &str) -> Result<i64> {
123 match raw.parse::<i64>() {123 match raw.parse::<i64>() {
124 Ok(n) if n > 0 && raw.bytes().all(|b| b.is_ascii_digit()) => Ok(n),124 Ok(n) if n > 0 && raw.bytes().all(|b| b.is_ascii_digit()) => Ok(n),
125 _ => Err(not_found().into()),125 _ => Err(not_found().into()),
@@ -128,13 +128,13 @@ pub(crate) fn parse_number(raw: &str) -> Result<i64> {
128 128
129 /// Wakes the live pages of an issue after a successful write to it. Pull requests have no live129 /// Wakes the live pages of an issue after a successful write to it. Pull requests have no live
130 /// page, so their writes wake nothing.130 /// page, so their writes wake nothing.
131-pub(crate) fn bump_live(state: &AppState, repo_id: &str, item: &Issue, kind: ItemKind) {131+pub fn bump_live(state: &AppState, repo_id: &str, item: &Issue, kind: ItemKind) {
132 if kind == ItemKind::Issue {132 if kind == ItemKind::Issue {
133 state.live.bump_issue(repo_id, &item.id);133 state.live.bump_issue(repo_id, &item.id);
134 }134 }
135 }135 }
136 136
137-pub(crate) async fn issue_for(state: &AppState, ctx: &RepoCtx, number: i64) -> Result<Issue> {137+pub async fn issue_for(state: &AppState, ctx: &RepoCtx, number: i64) -> Result<Issue> {
138 match state.store.issue_by_number(&ctx.repo.id, number).await? {138 match state.store.issue_by_number(&ctx.repo.id, number).await? {
139 Some(issue) => Ok(issue),139 Some(issue) => Ok(issue),
140 None => Err(not_found().into()),140 None => Err(not_found().into()),
@@ -143,7 +143,7 @@ pub(crate) async fn issue_for(state: &AppState, ctx: &RepoCtx, number: i64) -> R
143 143
144 /// The item of `kind` numbered `number` in this repo, as its issue row, or 404. A pull request144 /// The item of `kind` numbered `number` in this repo, as its issue row, or 404. A pull request
145 /// is the issue row it carries, so the comments and edit history are the same for both kinds.145 /// is the issue row it carries, so the comments and edit history are the same for both kinds.
146-pub(crate) async fn item_for(146+pub async fn item_for(
147 state: &AppState,147 state: &AppState,
148 ctx: &RepoCtx,148 ctx: &RepoCtx,
149 kind: ItemKind,149 kind: ItemKind,
@@ -159,24 +159,20 @@ pub(crate) async fn item_for(
159 }159 }
160 160
161 /// A comment of this item. A comment id from another item is 404.161 /// A comment of this item. A comment id from another item is 404.
162-pub(crate) async fn comment_for(162+pub async fn comment_for(state: &AppState, item: &Issue, comment_id: &str) -> Result<Comment> {
163- state: &AppState,
164- item: &Issue,
165- comment_id: &str,
166-) -> Result<Comment> {
167 match state.store.comment_by_id(&item.id, comment_id).await? {163 match state.store.comment_by_id(&item.id, comment_id).await? {
168 Some(comment) => Ok(comment),164 Some(comment) => Ok(comment),
169 None => Err(not_found().into()),165 None => Err(not_found().into()),
170 }166 }
171 }167 }
172 168
173-pub(crate) fn is_hex_oid(s: &str) -> bool {169+pub fn is_hex_oid(s: &str) -> bool {
174 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())170 (4..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
175 }171 }
176 172
177 /// The ids in `oids` that a branch, tag or pull request still reaches, read in one git walk. A173 /// The ids in `oids` that a branch, tag or pull request still reaches, read in one git walk. A
178 /// failed read yields none, so no stored hash links to a page that would 404.174 /// failed read yields none, so no stored hash links to a page that would 404.
179-pub(crate) async fn reachable_among(path: &std::path::Path, oids: Vec<String>) -> HashSet<String> {175+pub async fn reachable_among(path: &std::path::Path, oids: Vec<String>) -> HashSet<String> {
180 let path = path.to_owned();176 let path = path.to_owned();
181 tokio::task::spawn_blocking(move || forge_git::browse::reachable_commits(&path, &oids))177 tokio::task::spawn_blocking(move || forge_git::browse::reachable_commits(&path, &oids))
182 .await178 .await
@@ -188,7 +184,7 @@ pub(crate) async fn reachable_among(path: &std::path::Path, oids: Vec<String>) -
188 // Timeline184 // Timeline
189 185
190 /// One comment, or the item body (which uses the same item shape without a delete action).186 /// One comment, or the item body (which uses the same item shape without a delete action).
191-pub(crate) struct CommentView {187+pub struct CommentView {
192 anchor: String,188 anchor: String,
193 author: String,189 author: String,
194 /// The author's username, the link target of the name and avatar.190 /// The author's username, the link target of the name and avatar.
@@ -208,7 +204,7 @@ pub(crate) struct CommentView {
208 }204 }
209 205
210 /// Where a task checkbox toggle is posted, and which text it changes.206 /// Where a task checkbox toggle is posted, and which text it changes.
211-pub(crate) struct TaskTarget {207+pub struct TaskTarget {
212 action: String,208 action: String,
213 /// `issue` for the item body, `comment` for a comment.209 /// `issue` for the item body, `comment` for a comment.
214 kind: &'static str,210 kind: &'static str,
@@ -216,29 +212,29 @@ pub(crate) struct TaskTarget {
216 }212 }
217 213
218 /// One reaction button: a POST toggle when `enabled`, a plain count otherwise.214 /// One reaction button: a POST toggle when `enabled`, a plain count otherwise.
219-pub(crate) struct ReactionButton {215+pub struct ReactionButton {
220- pub(crate) action: String,216+ pub action: String,
221- pub(crate) csrf: String,217+ pub csrf: String,
222- pub(crate) target_kind: &'static str,218+ pub target_kind: &'static str,
223- pub(crate) target_id: String,219+ pub target_id: String,
224- pub(crate) name: &'static str,220+ pub name: &'static str,
225- pub(crate) emoji: &'static str,221+ pub emoji: &'static str,
226- pub(crate) count: usize,222+ pub count: usize,
227- pub(crate) title: String,223+ pub title: String,
228- pub(crate) active: bool,224+ pub active: bool,
229- pub(crate) enabled: bool,225+ pub enabled: bool,
230 }226 }
231 227
232 /// The reactions of one target: the existing ones, then the picker of every emoji. The picker is228 /// The reactions of one target: the existing ones, then the picker of every emoji. The picker is
233 /// only shown when `enabled`.229 /// only shown when `enabled`.
234-pub(crate) struct ReactionBar {230+pub struct ReactionBar {
235- pub(crate) chips: Vec<ReactionButton>,231+ pub chips: Vec<ReactionButton>,
236- pub(crate) picker: Vec<ReactionButton>,232+ pub picker: Vec<ReactionButton>,
237- pub(crate) enabled: bool,233+ pub enabled: bool,
238 }234 }
239 235
240 /// One timeline event as a line: the actor, `before`, an optional commit link, then `after`.236 /// One timeline event as a line: the actor, `before`, an optional commit link, then `after`.
241-pub(crate) struct EventLine {237+pub struct EventLine {
242 actor: String,238 actor: String,
243 actor_id: String,239 actor_id: String,
244 when: When,240 when: When,
@@ -257,7 +253,7 @@ const RUN_GAP_SECS: i64 = 300;
257 253
258 /// A submitted review of a pull request: its verb, its body (when it has one) and the threads it254 /// A submitted review of a pull request: its verb, its body (when it has one) and the threads it
259 /// opened, which render under it with their diff hunks.255 /// opened, which render under it with their diff hunks.
260-pub(crate) struct ReviewView {256+pub struct ReviewView {
261 anchor: String,257 anchor: String,
262 author: String,258 author: String,
263 login: String,259 login: String,
@@ -271,7 +267,7 @@ pub(crate) struct ReviewView {
271 ctx: ThreadCtx,267 ctx: ThreadCtx,
272 }268 }
273 269
274-pub(crate) enum Entry {270+pub enum Entry {
275 Comment(CommentView),271 Comment(CommentView),
276 Event(EventLine),272 Event(EventLine),
277 /// Consecutive events by one actor within a few minutes, one line.273 /// Consecutive events by one actor within a few minutes, one line.
@@ -280,14 +276,14 @@ pub(crate) enum Entry {
280 }276 }
281 277
282 /// The item body and its timeline: comments and events merged by creation time.278 /// The item body and its timeline: comments and events merged by creation time.
283-pub(crate) struct Discussion {279+pub struct Discussion {
284 /// The item's author, by display name, and when it was opened.280 /// The item's author, by display name, and when it was opened.
285- pub(crate) author: String,281+ pub author: String,
286 /// The author's username, for the profile link.282 /// The author's username, for the profile link.
287- pub(crate) author_login: String,283+ pub author_login: String,
288- pub(crate) opened: When,284+ pub opened: When,
289- pub(crate) body: CommentView,285+ pub body: CommentView,
290- pub(crate) entries: Vec<Entry>,286+ pub entries: Vec<Entry>,
291 }287 }
292 288
293 /// The one-line text for an event. `base` is `/{owner}/{repo}`; `base_branch` names the target289 /// The one-line text for an event. `base` is `/{owner}/{repo}`; `base_branch` names the target
@@ -382,7 +378,7 @@ fn event_line(
382 }378 }
383 379
384 #[component]380 #[component]
385-pub(crate) async fn comment_item(cx: &Cx, lang: Lang, item: CommentView) -> Result<impl View> {381+pub async fn comment_item(cx: &Cx, lang: Lang, item: CommentView) -> Result<impl View> {
386 let CommentView {382 let CommentView {
387 anchor,383 anchor,
388 author,384 author,
@@ -448,7 +444,7 @@ pub(crate) async fn comment_item(cx: &Cx, lang: Lang, item: CommentView) -> Resu
448 444
449 /// The reaction row under an item or comment: the buttons, then the picker when the viewer may react.445 /// The reaction row under an item or comment: the buttons, then the picker when the viewer may react.
450 #[component]446 #[component]
451-pub(crate) async fn reaction_row(cx: &Cx, lang: Lang, bar: ReactionBar) -> Result<impl View> {447+pub async fn reaction_row(cx: &Cx, lang: Lang, bar: ReactionBar) -> Result<impl View> {
452 let ReactionBar {448 let ReactionBar {
453 chips,449 chips,
454 picker,450 picker,
@@ -468,7 +464,7 @@ pub(crate) async fn reaction_row(cx: &Cx, lang: Lang, bar: ReactionBar) -> Resul
468 464
469 /// The React tool: a word that opens the reaction options in place.465 /// The React tool: a word that opens the reaction options in place.
470 #[component]466 #[component]
471-pub(crate) async fn reaction_picker(467+pub async fn reaction_picker(
472 cx: &Cx,468 cx: &Cx,
473 lang: Lang,469 lang: Lang,
474 picker: Vec<ReactionButton>,470 picker: Vec<ReactionButton>,
@@ -488,7 +484,7 @@ pub(crate) async fn reaction_picker(
488 /// One reaction button. Enabled buttons are POST forms that toggle the viewer's reaction; the484 /// One reaction button. Enabled buttons are POST forms that toggle the viewer's reaction; the
489 /// others only show the emoji and count.485 /// others only show the emoji and count.
490 #[component]486 #[component]
491-pub(crate) async fn reaction_button(cx: &Cx, button: ReactionButton) -> Result<impl View> {487+pub async fn reaction_button(cx: &Cx, button: ReactionButton) -> Result<impl View> {
492 let ReactionButton {488 let ReactionButton {
493 action,489 action,
494 csrf,490 csrf,
@@ -534,7 +530,7 @@ pub(crate) async fn reaction_button(cx: &Cx, button: ReactionButton) -> Result<i
534 }530 }
535 531
536 #[component]532 #[component]
537-pub(crate) async fn event_item(cx: &Cx, line: EventLine) -> Result<impl View> {533+pub async fn event_item(cx: &Cx, line: EventLine) -> Result<impl View> {
538 let EventLine {534 let EventLine {
539 actor,535 actor,
540 when,536 when,
@@ -570,7 +566,7 @@ pub(crate) async fn event_item(cx: &Cx, line: EventLine) -> Result<impl View> {
570 /// Consecutive events by one actor, one line: the actor, each event's words joined with " · ", then566 /// Consecutive events by one actor, one line: the actor, each event's words joined with " · ", then
571 /// the time of the last one.567 /// the time of the last one.
572 #[component]568 #[component]
573-pub(crate) async fn event_run(cx: &Cx, lines: Vec<EventLine>) -> Result<impl View> {569+pub async fn event_run(cx: &Cx, lines: Vec<EventLine>) -> Result<impl View> {
574 let actor = lines570 let actor = lines
575 .first()571 .first()
576 .map(|line| line.actor.clone())572 .map(|line| line.actor.clone())
@@ -619,7 +615,7 @@ fn dismissed_verb(lang: Lang, from: Option<ReviewState>) -> &'static str {
619 615
620 /// One submitted review: the reviewer, the verb, the dismissal reason, the body, then its threads.616 /// One submitted review: the reviewer, the verb, the dismissal reason, the body, then its threads.
621 #[component]617 #[component]
622-pub(crate) async fn review_item(cx: &Cx, lang: Lang, review: ReviewView) -> Result<impl View> {618+pub async fn review_item(cx: &Cx, lang: Lang, review: ReviewView) -> Result<impl View> {
623 let ReviewView {619 let ReviewView {
624 anchor,620 anchor,
625 author,621 author,
@@ -661,7 +657,7 @@ pub(crate) async fn review_item(cx: &Cx, lang: Lang, review: ReviewView) -> Resu
661 }657 }
662 658
663 #[component]659 #[component]
664-pub(crate) async fn timeline_entry(cx: &Cx, lang: Lang, entry: Entry) -> Result<impl View> {660+pub async fn timeline_entry(cx: &Cx, lang: Lang, entry: Entry) -> Result<impl View> {
665 Ok(view! {661 Ok(view! {
666 match entry {662 match entry {
667 Entry::Comment(item) => comment_item(lang: lang, item: item),663 Entry::Comment(item) => comment_item(lang: lang, item: item),
@@ -674,11 +670,7 @@ pub(crate) async fn timeline_entry(cx: &Cx, lang: Lang, entry: Entry) -> Result<
674 670
675 /// The body followed by every timeline entry.671 /// The body followed by every timeline entry.
676 #[component]672 #[component]
677-pub(crate) async fn discussion_timeline(673+pub async fn discussion_timeline(cx: &Cx, lang: Lang, discussion: Discussion) -> Result<impl View> {
678- cx: &Cx,
679- lang: Lang,
680- discussion: Discussion,
681-) -> Result<impl View> {
682 let Discussion { body, entries, .. } = discussion;674 let Discussion { body, entries, .. } = discussion;
683 Ok(view! {675 Ok(view! {
684 <div class="issue-timeline">676 <div class="issue-timeline">
@@ -692,7 +684,7 @@ pub(crate) async fn discussion_timeline(
692 684
693 /// Loads the body and the timeline of `item`, which is an issue or a pull request. Authors and685 /// Loads the body and the timeline of `item`, which is an issue or a pull request. Authors and
694 /// event actors are looked up in one batch.686 /// event actors are looked up in one batch.
695-pub(crate) async fn load_discussion(687+pub async fn load_discussion(
696 lang: Lang,688 lang: Lang,
697 state: &AppState,689 state: &AppState,
698 ctx: &RepoCtx,690 ctx: &RepoCtx,
@@ -941,7 +933,7 @@ fn push_label_group(lang: Lang, group: &mut Vec<EventLine>, out: &mut Vec<EventL
941 933
942 /// The reaction bar of one target, or `None` when there is nothing to show (no reactions and no934 /// The reaction bar of one target, or `None` when there is nothing to show (no reactions and no
943 /// way to react). Every reaction in the set gets a picker button.935 /// way to react). Every reaction in the set gets a picker button.
944-pub(crate) fn reaction_bar_for(936+pub fn reaction_bar_for(
945 lang: Lang,937 lang: Lang,
946 summaries: Option<&Vec<ReactionSummary>>,938 summaries: Option<&Vec<ReactionSummary>>,
947 can_react: bool,939 can_react: bool,
@@ -1118,21 +1110,21 @@ async fn review_entries(
1118 1110
1119 // Sidebar1111 // Sidebar
1120 1112
1121-pub(crate) struct LabelRow {1113+pub struct LabelRow {
1122 id: String,1114 id: String,
1123 name: String,1115 name: String,
1124 chip: String,1116 chip: String,
1125 attached: bool,1117 attached: bool,
1126 }1118 }
1127 1119
1128-pub(crate) struct MilestoneRow {1120+pub struct MilestoneRow {
1129 id: String,1121 id: String,
1130 title: String,1122 title: String,
1131 selected: bool,1123 selected: bool,
1132 }1124 }
1133 1125
1134 /// The sidebar data of one item: its labels, assignees and milestone, and the repo's choices.1126 /// The sidebar data of one item: its labels, assignees and milestone, and the repo's choices.
1135-pub(crate) struct Sidebar {1127+pub struct Sidebar {
1136 labels: Vec<LabelRow>,1128 labels: Vec<LabelRow>,
1137 assignees: Vec<String>,1129 assignees: Vec<String>,
1138 milestones: Vec<MilestoneRow>,1130 milestones: Vec<MilestoneRow>,
@@ -1142,7 +1134,7 @@ pub(crate) struct Sidebar {
1142 lock_reason: Option<String>,1134 lock_reason: Option<String>,
1143 }1135 }
1144 1136
1145-pub(crate) async fn load_sidebar(state: &AppState, repo_id: &str, item: &Issue) -> Result<Sidebar> {1137+pub async fn load_sidebar(state: &AppState, repo_id: &str, item: &Issue) -> Result<Sidebar> {
1146 let store = &state.store;1138 let store = &state.store;
1147 let all_labels = store.list_labels(repo_id).await?;1139 let all_labels = store.list_labels(repo_id).await?;
1148 let attached = store.issue_labels(&item.id).await?;1140 let attached = store.issue_labels(&item.id).await?;
@@ -1186,7 +1178,7 @@ pub(crate) async fn load_sidebar(state: &AppState, repo_id: &str, item: &Issue)
1186 }1178 }
1187 1179
1188 #[component]1180 #[component]
1189-pub(crate) async fn labels_box(1181+pub async fn labels_box(
1190 cx: &Cx,1182 cx: &Cx,
1191 lang: Lang,1183 lang: Lang,
1192 write: bool,1184 write: bool,
@@ -1234,7 +1226,7 @@ pub(crate) async fn labels_box(
1234 }1226 }
1235 1227
1236 #[component]1228 #[component]
1237-pub(crate) async fn assignees_box(1229+pub async fn assignees_box(
1238 cx: &Cx,1230 cx: &Cx,
1239 lang: Lang,1231 lang: Lang,
1240 write: bool,1232 write: bool,
@@ -1281,7 +1273,7 @@ pub(crate) async fn assignees_box(
1281 }1273 }
1282 1274
1283 #[component]1275 #[component]
1284-pub(crate) async fn milestone_box(1276+pub async fn milestone_box(
1285 cx: &Cx,1277 cx: &Cx,
1286 lang: Lang,1278 lang: Lang,
1287 write: bool,1279 write: bool,
@@ -1328,7 +1320,7 @@ pub(crate) async fn milestone_box(
1328 /// The conversation row, shown only when the conversation is locked, with its unlock word for1320 /// The conversation row, shown only when the conversation is locked, with its unlock word for
1329 /// triage holders. Locking is one of the tools at the foot of the sidebar (`item_tools`).1321 /// triage holders. Locking is one of the tools at the foot of the sidebar (`item_tools`).
1330 #[component]1322 #[component]
1331-pub(crate) async fn lock_box(1323+pub async fn lock_box(
1332 cx: &Cx,1324 cx: &Cx,
1333 lang: Lang,1325 lang: Lang,
1334 write: bool,1326 write: bool,
@@ -1366,7 +1358,7 @@ pub(crate) async fn lock_box(
1366 /// The tools at the foot of the sidebar, one quiet line: Pin issue, and Lock conversation with its1358 /// The tools at the foot of the sidebar, one quiet line: Pin issue, and Lock conversation with its
1367 /// reason. `pin` is the pin action when the issue is not pinned and the viewer may pin it.1359 /// reason. `pin` is the pin action when the issue is not pinned and the viewer may pin it.
1368 #[component]1360 #[component]
1369-pub(crate) async fn item_tools(1361+pub async fn item_tools(
1370 cx: &Cx,1362 cx: &Cx,
1371 lang: Lang,1363 lang: Lang,
1372 pin: Option<String>,1364 pin: Option<String>,
@@ -1411,7 +1403,7 @@ pub(crate) async fn item_tools(
1411 /// `/milestone` and `/lock`. `write` shows the forms instead of the read-only lists. `pin` is1403 /// `/milestone` and `/lock`. `write` shows the forms instead of the read-only lists. `pin` is
1412 /// `(pinned, action)` for an issue; the pinned row sits in the page (`pin_box`).1404 /// `(pinned, action)` for an issue; the pinned row sits in the page (`pin_box`).
1413 #[component]1405 #[component]
1414-pub(crate) async fn item_sidebar(1406+pub async fn item_sidebar(
1415 cx: &Cx,1407 cx: &Cx,
1416 lang: Lang,1408 lang: Lang,
1417 write: bool,1409 write: bool,
@@ -1459,13 +1451,13 @@ pub(crate) async fn item_sidebar(
1459 1451
1460 /// The id of the comment form. The head's Close and Reopen buttons post it with `form=`, so a1452 /// The id of the comment form. The head's Close and Reopen buttons post it with `form=`, so a
1461 /// close can carry the draft text as its comment, as it always did.1453 /// close can carry the draft text as its comment, as it always did.
1462-pub(crate) const COMMENT_FORM: &str = "item-comment";1454+pub const COMMENT_FORM: &str = "item-comment";
1463 1455
1464 /// The head tools of an item: Close (a menu of the two ways) or Reopen when closed, and the1456 /// The head tools of an item: Close (a menu of the two ways) or Reopen when closed, and the
1465 /// Subscribe or Unsubscribe pill, whose reason is its title. `close` is `(open, state action)`1457 /// Subscribe or Unsubscribe pill, whose reason is its title. `close` is `(open, state action)`
1466 /// and is given only when the viewer may close the item.1458 /// and is given only when the viewer may close the item.
1467 #[component]1459 #[component]
1468-pub(crate) async fn item_head_tools(1460+pub async fn item_head_tools(
1469 cx: &Cx,1461 cx: &Cx,
1470 lang: Lang,1462 lang: Lang,
1471 close: Option<(bool, String)>,1463 close: Option<(bool, String)>,
@@ -1497,7 +1489,7 @@ pub(crate) async fn item_head_tools(
1497 /// The comment box: the text, and Comment as its one filled button. Its label is for screen1489 /// The comment box: the text, and Comment as its one filled button. Its label is for screen
1498 /// readers only.1490 /// readers only.
1499 #[component]1491 #[component]
1500-pub(crate) async fn comment_form(1492+pub async fn comment_form(
1501 cx: &Cx,1493 cx: &Cx,
1502 lang: Lang,1494 lang: Lang,
1503 action: String,1495 action: String,
@@ -1526,17 +1518,17 @@ pub(crate) async fn comment_form(
1526 1518
1527 /// The form fields of a comment or state POST.1519 /// The form fields of a comment or state POST.
1528 #[derive(Deserialize)]1520 #[derive(Deserialize)]
1529-pub(crate) struct CommentForm {1521+pub struct CommentForm {
1530 #[serde(default)]1522 #[serde(default)]
1531- pub(crate) csrf: String,1523+ pub csrf: String,
1532 #[serde(default)]1524 #[serde(default)]
1533- pub(crate) body: String,1525+ pub body: String,
1534 #[serde(default)]1526 #[serde(default)]
1535- pub(crate) action: String,1527+ pub action: String,
1536 }1528 }
1537 1529
1538 /// What a comment or state POST did.1530 /// What a comment or state POST did.
1539-pub(crate) enum Posted {1531+pub enum Posted {
1540 /// Written. `comment_id` is the new comment, when there was text.1532 /// Written. `comment_id` is the new comment, when there was text.
1541 Saved { comment_id: Option<String> },1533 Saved { comment_id: Option<String> },
1542 /// Not written; `message` goes back to the form.1534 /// Not written; `message` goes back to the form.
@@ -1546,7 +1538,7 @@ pub(crate) enum Posted {
1546 /// Adds a comment and/or changes the state of an issue or pull request (`pull` says which). Only1538 /// Adds a comment and/or changes the state of an issue or pull request (`pull` says which). Only
1547 /// the author or a Triage holder may close or reopen; otherwise 403 and nothing is written. An1539 /// the author or a Triage holder may close or reopen; otherwise 403 and nothing is written. An
1548 /// empty comment with no state change, or a body that fails validation, is `Refused`.1540 /// empty comment with no state change, or a body that fails validation, is `Refused`.
1549-pub(crate) async fn post_comment(1541+pub async fn post_comment(
1550 lang: Lang,1542 lang: Lang,
1551 state: &AppState,1543 state: &AppState,
1552 ctx: &RepoCtx,1544 ctx: &RepoCtx,
crates/forge-web/src/pages/issues_list.rs → crates/forge-web-pages/src/pages/issues_list.rsrenamed+37 -37
@@ -44,7 +44,7 @@ const MAX_PAGE: u32 = 1000;
44 const MAX_FILTER_CHARS: usize = 256;44 const MAX_FILTER_CHARS: usize = 256;
45 45
46 #[query_params(error = bad_request)]46 #[query_params(error = bad_request)]
47-pub(crate) struct ListQuery {47+pub struct ListQuery {
48 state: Option<String>,48 state: Option<String>,
49 label: Option<String>,49 label: Option<String>,
50 milestone: Option<String>,50 milestone: Option<String>,
@@ -58,22 +58,22 @@ pub(crate) struct ListQuery {
58 }58 }
59 59
60 /// The list's filters as the page shows them. Every value here is already a valid choice.60 /// The list's filters as the page shows them. Every value here is already a valid choice.
61-pub(crate) struct Selection {61+pub struct Selection {
62 /// `open`, `closed` or `all`.62 /// `open`, `closed` or `all`.
63- pub(crate) state: &'static str,63+ pub state: &'static str,
64- pub(crate) label: String,64+ pub label: String,
65- pub(crate) milestone: String,65+ pub milestone: String,
66- pub(crate) author: String,66+ pub author: String,
67- pub(crate) assignee: String,67+ pub assignee: String,
68 /// Username with a pending review request, or `@me` (pull requests only).68 /// Username with a pending review request, or `@me` (pull requests only).
69- pub(crate) review_requested: String,69+ pub review_requested: String,
70- pub(crate) query: String,70+ pub query: String,
71 /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or71 /// Pull requests only: `true` (drafts), `false` (ready) or empty (both). A `draft:true` or
72 /// `draft:false` word in the search text sets it too.72 /// `draft:false` word in the search text sets it too.
73- pub(crate) draft: &'static str,73+ pub draft: &'static str,
74 /// `newest`, `oldest` or `updated`.74 /// `newest`, `oldest` or `updated`.
75- pub(crate) sort: &'static str,75+ pub sort: &'static str,
76- pub(crate) page: u32,76+ pub page: u32,
77 }77 }
78 78
79 /// Trimmed and cut to `MAX_FILTER_CHARS`. A missing value is empty.79 /// Trimmed and cut to `MAX_FILTER_CHARS`. A missing value is empty.
@@ -92,7 +92,7 @@ fn non_empty(value: &str) -> Option<String> {
92 }92 }
93 93
94 impl Selection {94 impl Selection {
95- pub(crate) fn parse(query: &ListQuery) -> Self {95+ pub fn parse(query: &ListQuery) -> Self {
96 let mut draft = match query.draft.as_deref().map(str::trim) {96 let mut draft = match query.draft.as_deref().map(str::trim) {
97 Some("true") => "true",97 Some("true") => "true",
98 Some("false") => "false",98 Some("false") => "false",
@@ -140,7 +140,7 @@ impl Selection {
140 }140 }
141 }141 }
142 142
143- pub(crate) fn filter(&self) -> IssueFilter {143+ pub fn filter(&self) -> IssueFilter {
144 IssueFilter {144 IssueFilter {
145 state: match self.state {145 state: match self.state {
146 "closed" => Some(IssueState::Closed),146 "closed" => Some(IssueState::Closed),
@@ -170,7 +170,7 @@ impl Selection {
170 }170 }
171 171
172 /// Whether any filter besides the state is set.172 /// Whether any filter besides the state is set.
173- pub(crate) fn has_filters(&self) -> bool {173+ pub fn has_filters(&self) -> bool {
174 !(self.label.is_empty()174 !(self.label.is_empty()
175 && self.milestone.is_empty()175 && self.milestone.is_empty()
176 && self.author.is_empty()176 && self.author.is_empty()
@@ -181,7 +181,7 @@ impl Selection {
181 }181 }
182 182
183 /// The search box text: the title query plus the `review-requested:` token when one is set.183 /// The search box text: the title query plus the `review-requested:` token when one is set.
184- pub(crate) fn search_text(&self) -> String {184+ pub fn search_text(&self) -> String {
185 if self.review_requested.is_empty() {185 if self.review_requested.is_empty() {
186 self.query.clone()186 self.query.clone()
187 } else {187 } else {
@@ -192,14 +192,14 @@ impl Selection {
192 }192 }
193 193
194 /// Resolves `@me` to the viewer's username. Anonymous viewers lose the filter.194 /// Resolves `@me` to the viewer's username. Anonymous viewers lose the filter.
195- pub(crate) fn resolve_me(&mut self, viewer: Option<&str>) {195+ pub fn resolve_me(&mut self, viewer: Option<&str>) {
196 if self.review_requested == "@me" {196 if self.review_requested == "@me" {
197 self.review_requested = viewer.map(str::to_owned).unwrap_or_default();197 self.review_requested = viewer.map(str::to_owned).unwrap_or_default();
198 }198 }
199 }199 }
200 200
201 /// The list URL with this selection, but a different state and page.201 /// The list URL with this selection, but a different state and page.
202- pub(crate) fn href(&self, base: &str, state: &str, page: u32) -> String {202+ pub fn href(&self, base: &str, state: &str, page: u32) -> String {
203 let page_text = if page > 1 {203 let page_text = if page > 1 {
204 page.to_string()204 page.to_string()
205 } else {205 } else {
@@ -225,7 +225,7 @@ impl Selection {
225 }225 }
226 226
227 /// `base` followed by a query string holding the non-empty parameters, percent-encoded.227 /// `base` followed by a query string holding the non-empty parameters, percent-encoded.
228-pub(crate) fn list_href(base: &str, params: &[(&str, &str)]) -> String {228+pub fn list_href(base: &str, params: &[(&str, &str)]) -> String {
229 let query: Vec<String> = params229 let query: Vec<String> = params
230 .iter()230 .iter()
231 .filter(|(_, value)| !value.is_empty())231 .filter(|(_, value)| !value.is_empty())
@@ -239,26 +239,26 @@ pub(crate) fn list_href(base: &str, params: &[(&str, &str)]) -> String {
239 }239 }
240 240
241 /// Unix seconds of a stored RFC 3339 stamp. An unreadable stamp gives 0.241 /// Unix seconds of a stored RFC 3339 stamp. An unreadable stamp gives 0.
242-pub(crate) fn stamp_unix(stamp: &str) -> i64 {242+pub fn stamp_unix(stamp: &str) -> i64 {
243 time::OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339)243 time::OffsetDateTime::parse(stamp, &time::format_description::well_known::Rfc3339)
244 .map_or(0, |t| t.unix_timestamp())244 .map_or(0, |t| t.unix_timestamp())
245 }245 }
246 246
247-pub(crate) struct AssigneeView {247+pub struct AssigneeView {
248- pub(crate) name: String,248+ pub name: String,
249- pub(crate) avatar: String,249+ pub avatar: String,
250 }250 }
251 251
252-pub(crate) struct LabelView {252+pub struct LabelView {
253- pub(crate) class: String,253+ pub class: String,
254- pub(crate) name: String,254+ pub name: String,
255- pub(crate) href: String,255+ pub href: String,
256 }256 }
257 257
258 #[derive(Clone)]258 #[derive(Clone)]
259-pub(crate) struct MilestoneView {259+pub struct MilestoneView {
260- pub(crate) title: String,260+ pub title: String,
261- pub(crate) href: String,261+ pub href: String,
262 }262 }
263 263
264 /// One issue row, with every string the template shows already built.264 /// One issue row, with every string the template shows already built.
@@ -359,7 +359,7 @@ fn row_view(row: RowCtx<'_>, item: &IssueListItem) -> RowView {
359 }359 }
360 360
361 /// The "N of M tasks" label for a body, or `None` without task items.361 /// The "N of M tasks" label for a body, or `None` without task items.
362-pub(crate) fn tasks_text(lang: Lang, body: &str) -> Option<String> {362+pub fn tasks_text(lang: Lang, body: &str) -> Option<String> {
363 let (done, total) = crate::render::markdown::task_progress(body);363 let (done, total) = crate::render::markdown::task_progress(body);
364 (total > 0).then(|| crate::i18n::authoring::tasks_progress(lang, done, total))364 (total > 0).then(|| crate::i18n::authoring::tasks_progress(lang, done, total))
365 }365 }
@@ -392,10 +392,10 @@ fn pinned_card(lang: Lang, owner: &str, repo: &str, issue: &forge_core::Issue) -
392 }392 }
393 393
394 /// One option of the sort select.394 /// One option of the sort select.
395-pub(crate) struct SortOption {395+pub struct SortOption {
396- pub(crate) value: &'static str,396+ pub value: &'static str,
397- pub(crate) label: &'static str,397+ pub label: &'static str,
398- pub(crate) selected: bool,398+ pub selected: bool,
399 }399 }
400 400
401 /// How many open issues match one assignee or author, from the list's total with one row asked for.401 /// How many open issues match one assignee or author, from the list's total with one row asked for.
@@ -958,8 +958,8 @@ async fn new_issue_submit(cx: &Cx, RawForm(raw): RawForm) -> Result<impl View> {
958 958
959 /// Shared test fixture for the issue and label pages: a store with one owner, one repo and a959 /// Shared test fixture for the issue and label pages: a store with one owner, one repo and a
960 /// signed-in session for the owner. The pages need no git data, so no repository is created.960 /// signed-in session for the owner. The pages need no git data, so no repository is created.
961-#[cfg(test)]961+#[cfg(any(test, feature = "test-support"))]
962-pub(crate) mod test_util {962+pub mod test_util {
963 use forge_core::{Repo, Store, User, Visibility};963 use forge_core::{Repo, Store, User, Visibility};
964 use http::HeaderMap;964 use http::HeaderMap;
965 use topcoat::router::request::Request;965 use topcoat::router::request::Request;
crates/forge-web/src/pages/issues_live.rs → crates/forge-web-pages/src/pages/issues_live.rsrenamed+0 -0
crates/forge-web-pages/src/pages/mod.rsadded+38 -0
@@ -0,0 +1,38 @@
1+//! Server-rendered pages.
2+
3+pub mod admin_runners;
4+pub mod admin_users;
5+pub mod ci_estimate;
6+pub mod ci_fail;
7+pub mod ci_job;
8+pub mod ci_runs;
9+pub mod code_live;
10+pub mod discussion_settings;
11+pub mod edit_history;
12+pub mod finder;
13+pub mod issue_meta;
14+pub mod issue_parts;
15+pub mod issues_list;
16+pub mod issues_live;
17+pub mod notifications;
18+pub mod packages;
19+pub mod packages_oci;
20+pub mod pull_live;
21+pub mod pull_reviews;
22+pub mod ref_live;
23+pub mod refs;
24+pub mod releases;
25+pub mod releases_live;
26+pub mod repo;
27+pub mod repo_ctx;
28+pub mod repo_mirrors;
29+pub mod repo_rename;
30+pub mod repo_security;
31+pub mod repo_settings;
32+pub mod repo_settings_live;
33+pub mod repo_side;
34+pub mod repo_transfer;
35+pub mod star;
36+pub mod tree;
37+pub mod wiki;
38+pub mod wiki_live;
crates/forge-web/src/pages/notifications.rs → crates/forge-web-pages/src/pages/notifications.rsrenamed+13 -587
@@ -87,7 +87,7 @@ struct WatchForm {
87 }87 }
88 88
89 /// One inbox row, with its strings ready for the view.89 /// One inbox row, with its strings ready for the view.
90-pub(crate) struct RowView {90+pub struct RowView {
91 item_class: &'static str,91 item_class: &'static str,
92 icon_class: &'static str,92 icon_class: &'static str,
93 kind_label: &'static str,93 kind_label: &'static str,
@@ -103,7 +103,7 @@ pub(crate) struct RowView {
103 }103 }
104 104
105 /// The rows of one repo, in the order they first appear in the inbox.105 /// The rows of one repo, in the order they first appear in the inbox.
106-pub(crate) struct RepoGroup {106+pub struct RepoGroup {
107 heading: String,107 heading: String,
108 href: String,108 href: String,
109 mark_action: String,109 mark_action: String,
@@ -742,7 +742,7 @@ fn unread_event(count: u64) -> topcoat::Result<Event> {
742 742
743 /// The viewer's unread count as `unread` events: one now, then one after each change to the inbox.743 /// The viewer's unread count as `unread` events: one now, then one after each change to the inbox.
744 /// Subscribed before the count is read, so a change in between is pushed again, never missed.744 /// Subscribed before the count is read, so a change in between is pushed again, never missed.
745-pub(crate) async fn unread_changes(745+pub async fn unread_changes(
746 state: &AppState,746 state: &AppState,
747 user_id: &str,747 user_id: &str,
748 ) -> Result<impl Stream<Item = Result<Event>> + Send + 'static> {748 ) -> Result<impl Stream<Item = Result<Event>> + Send + 'static> {
@@ -876,7 +876,7 @@ async fn can_manage_alerts(state: &AppState, user: &User, repo_id: &str) -> Resu
876 }876 }
877 877
878 /// Whether the viewer may read the repo right now, by their current collaborator role.878 /// Whether the viewer may read the repo right now, by their current collaborator role.
879-pub(crate) async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Result<bool> {879+pub async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Result<bool> {
880 let Some(repo) = state.store.repo_by_id(repo_id).await? else {880 let Some(repo) = state.store.repo_by_id(repo_id).await? else {
881 return Ok(false);881 return Ok(false);
882 };882 };
@@ -890,7 +890,7 @@ pub(crate) async fn can_read(state: &AppState, user: &User, repo_id: &str) -> Re
890 890
891 /// The sidebar box of an issue or pull for a signed-in viewer. Viewing the thread marks the891 /// The sidebar box of an issue or pull for a signed-in viewer. Viewing the thread marks the
892 /// viewer's inbox row for it read. `base` is the item's URL. `None` for anonymous viewers.892 /// viewer's inbox row for it read. `base` is the item's URL. `None` for anonymous viewers.
893-pub(crate) async fn notify_box_for(893+pub async fn notify_box_for(
894 state: &AppState,894 state: &AppState,
895 ctx: &RepoCtx,895 ctx: &RepoCtx,
896 issue_id: &str,896 issue_id: &str,
@@ -921,10 +921,10 @@ pub(crate) async fn notify_box_for(
921 921
922 /// The notification sidebar box data: where the form posts, the session CSRF token, and whether the922 /// The notification sidebar box data: where the form posts, the session CSRF token, and whether the
923 /// viewer is receiving notifications.923 /// viewer is receiving notifications.
924-pub(crate) struct NotifyBox {924+pub struct NotifyBox {
925- pub(crate) action: String,925+ pub action: String,
926- pub(crate) csrf: String,926+ pub csrf: String,
927- pub(crate) subscribed: bool,927+ pub subscribed: bool,
928 }928 }
929 929
930 /// The human label of a notification reason.930 /// The human label of a notification reason.
@@ -966,7 +966,7 @@ fn back(cx: &Cx) -> String {
966 /// The inbox rail's places, the same on Notifications, Needs you and Review requests, so each966 /// The inbox rail's places, the same on Notifications, Needs you and Review requests, so each
967 /// reaches the others: Unread with its count, All, Needs you, Review requests. `current` is the967 /// reaches the others: Unread with its count, All, Needs you, Review requests. `current` is the
968 /// key of the page showing it.968 /// key of the page showing it.
969-pub(crate) fn inbox_items(lang: Lang, current: &str, unread_count: u64) -> Vec<RailItem> {969+pub fn inbox_items(lang: Lang, current: &str, unread_count: u64) -> Vec<RailItem> {
970 let item = |key: &str, name: &str, val: String, href: &str| RailItem {970 let item = |key: &str, name: &str, val: String, href: &str| RailItem {
971 name: name.to_owned(),971 name: name.to_owned(),
972 val,972 val,
@@ -1003,7 +1003,7 @@ pub(crate) fn inbox_items(lang: Lang, current: &str, unread_count: u64) -> Vec<R
1003 1003
1004 /// The inbox rail as Needs you and Review requests show it, beside their sheet.1004 /// The inbox rail as Needs you and Review requests show it, beside their sheet.
1005 #[component]1005 #[component]
1006-pub(crate) async fn inbox_rail(1006+pub async fn inbox_rail(
1007 cx: &Cx,1007 cx: &Cx,
1008 lang: Lang,1008 lang: Lang,
1009 current: &str,1009 current: &str,
@@ -1092,7 +1092,7 @@ async fn inbox_list(
1092 1092
1093 /// The Subscribe or Unsubscribe pill of an issue or pull request, in its head.1093 /// The Subscribe or Unsubscribe pill of an issue or pull request, in its head.
1094 #[component]1094 #[component]
1095-pub(crate) async fn notify_pill(1095+pub async fn notify_pill(
1096 cx: &Cx,1096 cx: &Cx,
1097 lang: Lang,1097 lang: Lang,
1098 action: String,1098 action: String,
@@ -1117,7 +1117,7 @@ pub(crate) async fn notify_pill(
1117 /// POST form per level inside it (the current one marked), and the watcher count. The forms post1117 /// POST form per level inside it (the current one marked), and the watcher count. The forms post
1118 /// without JavaScript; nav.js submits them in place and closes the menu.1118 /// without JavaScript; nav.js submits them in place and closes the menu.
1119 #[component]1119 #[component]
1120-pub(crate) async fn watch_form(1120+pub async fn watch_form(
1121 cx: &Cx,1121 cx: &Cx,
1122 lang: Lang,1122 lang: Lang,
1123 action: String,1123 action: String,
@@ -1181,577 +1181,3 @@ pub(crate) async fn watch_form(
1181 </div>1181 </div>
1182 })1182 })
1183 }1183 }
1184-
1185-#[cfg(test)]
1186-mod tests {
1187- use forge_core::{Issue, Reason, Role, Store, SubState, Visibility, WatchLevel};
1188- use futures_util::StreamExt;
1189- use topcoat::router::request::Request;
1190- use topcoat::router::{Body, Router, to_bytes};
1191-
1192- use crate::auth::SESSION_COOKIE;
1193-
1194- const CSRF: &str = "notif-test-csrf";
1195-
1196- struct Site {
1197- router: Router,
1198- store: Store,
1199- git: std::sync::Arc<forge_git::GitEnv>,
1200- _dir: tempfile::TempDir,
1201- }
1202-
1203- struct Reply {
1204- status: u16,
1205- location: Option<String>,
1206- body: String,
1207- }
1208-
1209- async fn site() -> Site {
1210- let dir = tempfile::tempdir().expect("tempdir");
1211- let state = crate::test_support::test_state(dir.path()).await;
1212- let store = state.store.clone();
1213- let git = state.git.clone();
1214- let router = crate::test_support::app_router(state);
1215- Site {
1216- router,
1217- store,
1218- git,
1219- _dir: dir,
1220- }
1221- }
1222-
1223- /// Signs `user_id` in with `token` and returns the cookie header value.
1224- async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
1225- crate::test_support::create_session(store, user_id, token, CSRF).await;
1226- format!("__Host-{SESSION_COOKIE}={token}")
1227- }
1228-
1229- async fn call(
1230- site: &Site,
1231- method: &str,
1232- uri: &str,
1233- cookie: Option<&str>,
1234- form: Option<String>,
1235- ) -> Reply {
1236- let mut builder = Request::builder().method(method).uri(uri);
1237- if let Some(cookie) = cookie {
1238- builder = builder.header("cookie", cookie);
1239- }
1240- let body = match form {
1241- Some(form) => {
1242- builder = builder.header("content-type", "application/x-www-form-urlencoded");
1243- Body::from(form)
1244- }
1245- None => Body::empty(),
1246- };
1247- let res = site
1248- .router
1249- .handle(builder.body(body).expect("request"))
1250- .await;
1251- let status = res.status().as_u16();
1252- let location = res
1253- .headers()
1254- .get("location")
1255- .and_then(|v| v.to_str().ok())
1256- .map(str::to_owned);
1257- let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
1258- Reply {
1259- status,
1260- location,
1261- body: String::from_utf8_lossy(&bytes).into_owned(),
1262- }
1263- }
1264-
1265- async fn get(site: &Site, uri: &str, cookie: Option<&str>) -> Reply {
1266- call(site, "GET", uri, cookie, None).await
1267- }
1268-
1269- async fn post(site: &Site, uri: &str, cookie: &str, extra: &str) -> Reply {
1270- call(
1271- site,
1272- "POST",
1273- uri,
1274- Some(cookie),
1275- Some(format!("csrf={CSRF}{extra}")),
1276- )
1277- .await
1278- }
1279-
1280- /// Tahinli owns `demo` with one issue (#1), and Bob has a notification row for it.
1281- struct World {
1282- tahinli: forge_core::User,
1283- bob: forge_core::User,
1284- repo: forge_core::Repo,
1285- issue: Issue,
1286- }
1287-
1288- async fn world(site: &Site, visibility: Visibility) -> World {
1289- let store = &site.store;
1290- let tahinli = store
1291- .create_user("tahinli", None, "x", false)
1292- .await
1293- .expect("tahinli");
1294- let bob = store
1295- .create_user("bob", None, "x", false)
1296- .await
1297- .expect("bob");
1298- let repo = store
1299- .create_repo(&tahinli.id, "demo", "", visibility, "main")
1300- .await
1301- .expect("repo");
1302- let issue = store
1303- .create_issue(&repo.id, &tahinli.id, "First", "body")
1304- .await
1305- .expect("issue");
1306- World {
1307- tahinli,
1308- bob,
1309- repo,
1310- issue,
1311- }
1312- }
1313-
1314- async fn notify(site: &Site, w: &World, reason: Reason) {
1315- site.store
1316- .upsert_notification(
1317- &w.bob.id,
1318- &w.repo.id,
1319- &w.issue.id,
1320- reason,
1321- "comment",
1322- Some(&w.tahinli.id),
1323- )
1324- .await
1325- .expect("notification");
1326- }
1327-
1328- async fn first_note_id(site: &Site, user_id: &str) -> String {
1329- site.store
1330- .list_notifications(user_id, false, None, 50)
1331- .await
1332- .expect("list")
1333- .first()
1334- .expect("one notification")
1335- .id
1336- .clone()
1337- }
1338-
1339- #[tokio::test]
1340- async fn inbox_lists_unread_and_all_shows_read() {
1341- let site = site().await;
1342- let w = world(&site, Visibility::Public).await;
1343- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1344- notify(&site, &w, Reason::Mention).await;
1345- let id = first_note_id(&site, &w.bob.id).await;
1346- site.store.mark_read(&w.bob.id, &id).await.expect("read");
1347-
1348- let unread = get(&site, "/notifications", Some(&cookie)).await;
1349- assert_eq!(unread.status, 200);
1350- assert!(!unread.body.contains("tahinli/demo #1 First"));
1351- assert!(unread.body.contains("No unread notifications."));
1352-
1353- let all = get(&site, "/notifications?all=1", Some(&cookie)).await;
1354- assert_eq!(all.status, 200);
1355- assert!(all.body.contains("tahinli/demo #1 First"));
1356- assert!(all.body.contains("mentioned"));
1357- }
1358-
1359- #[tokio::test]
1360- async fn unread_inbox_lists_unread_rows_grouped_by_repo() {
1361- let site = site().await;
1362- let w = world(&site, Visibility::Public).await;
1363- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1364- notify(&site, &w, Reason::Assign).await;
1365-
1366- let page = get(&site, "/notifications", Some(&cookie)).await;
1367- assert_eq!(page.status, 200);
1368- assert!(page.body.contains("tahinli/demo #1 First"));
1369- assert!(page.body.contains("assigned"));
1370- assert!(page.body.contains("/notifications/mark_all_read?repo="));
1371- assert!(page.body.contains("Mark all as read"));
1372- }
1373-
1374- /// Another user cannot open or mark read a row that is not theirs. The owner's open redirects
1375- /// to the issue and marks the row read.
1376- #[tokio::test]
1377- async fn another_users_notification_is_404_and_the_owner_opens_it() {
1378- let site = site().await;
1379- let w = world(&site, Visibility::Public).await;
1380- let tahinli_cookie = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
1381- let bob_cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1382- notify(&site, &w, Reason::Comment).await;
1383- let id = first_note_id(&site, &w.bob.id).await;
1384-
1385- let res = get(
1386- &site,
1387- &format!("/notifications/{id}/open"),
1388- Some(&tahinli_cookie),
1389- )
1390- .await;
1391- assert_eq!(res.status, 404);
1392- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
1393-
1394- let read = post(
1395- &site,
1396- &format!("/notifications/{id}/read"),
1397- &tahinli_cookie,
1398- "",
1399- )
1400- .await;
1401- assert_eq!(read.status, 303);
1402- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
1403-
1404- // Bob opens his own row: it redirects to the issue and marks the row read.
1405- let res = get(
1406- &site,
1407- &format!("/notifications/{id}/open"),
1408- Some(&bob_cookie),
1409- )
1410- .await;
1411- assert_eq!(res.status, 303);
1412- assert_eq!(res.location.as_deref(), Some("/tahinli/demo/issues/1"));
1413- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
1414- }
1415-
1416- #[tokio::test]
1417- async fn mark_all_read_clears_the_inbox() {
1418- let site = site().await;
1419- let w = world(&site, Visibility::Public).await;
1420- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1421- notify(&site, &w, Reason::Comment).await;
1422-
1423- let res = post(&site, "/notifications/mark_all_read", &cookie, "").await;
1424- assert_eq!(res.status, 303);
1425- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
1426- }
1427-
1428- #[tokio::test]
1429- async fn the_stream_sends_the_count_then_each_change() {
1430- let site = site().await;
1431- let w = world(&site, Visibility::Public).await;
1432- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1433- notify(&site, &w, Reason::Mention).await;
1434-
1435- let request = Request::builder()
1436- .method("GET")
1437- .uri("/notifications/stream")
1438- .header("cookie", cookie.as_str())
1439- .body(Body::empty())
1440- .expect("request");
1441- let res = site.router.handle(request).await;
1442- assert_eq!(res.status().as_u16(), 200);
1443- assert_eq!(
1444- res.headers().get("content-type").unwrap(),
1445- "text/event-stream"
1446- );
1447- assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");
1448-
1449- let mut frames = res.into_body().into_data_stream();
1450- // The stream opens with its retry field, then the count.
1451- let retry = frames.next().await.expect("a frame").expect("data");
1452- assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
1453- let first = frames.next().await.expect("a frame").expect("data");
1454- assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");
1455-
1456- // Marking the row read pushes the new count to the open stream.
1457- let read = post(&site, "/notifications/mark_all_read", &cookie, "").await;
1458- assert_eq!(read.status, 303);
1459- let next = frames.next().await.expect("a frame").expect("data");
1460- assert_eq!(&next[..], b"event: unread\ndata: 0\n\n");
1461- }
1462-
1463- #[tokio::test]
1464- async fn corner_bell_shows_the_unread_count() {
1465- let site = site().await;
1466- let w = world(&site, Visibility::Public).await;
1467- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1468-
1469- let none = get(&site, "/explore", Some(&cookie)).await;
1470- assert!(none.body.contains("href=\"/notifications\""));
1471- assert!(!none.body.contains("<span class=\"bell-count\">"));
1472-
1473- notify(&site, &w, Reason::Mention).await;
1474- let one = get(&site, "/explore", Some(&cookie)).await;
1475- assert!(one.body.contains("<span class=\"bell-count\">1</span>"));
1476- }
1477-
1478- #[tokio::test]
1479- async fn subscription_toggles_on_an_issue_and_unknown_pull_is_404() {
1480- let site = site().await;
1481- let w = world(&site, Visibility::Public).await;
1482- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1483-
1484- let res = post(
1485- &site,
1486- "/tahinli/demo/issues/1/subscription",
1487- &cookie,
1488- "&action=subscribe",
1489- )
1490- .await;
1491- assert_eq!(res.status, 303);
1492- assert_eq!(res.location.as_deref(), Some("/tahinli/demo/issues/1"));
1493- let sub = site
1494- .store
1495- .subscription(&w.bob.id, &w.issue.id)
1496- .await
1497- .expect("sub");
1498- assert_eq!(sub, Some((SubState::Subscribed, Reason::Subscribed)));
1499-
1500- let page = get(&site, "/tahinli/demo/issues/1", Some(&cookie)).await;
1501- assert!(page.body.contains("value=\"unsubscribe\""));
1502-
1503- post(
1504- &site,
1505- "/tahinli/demo/issues/1/subscription",
1506- &cookie,
1507- "&action=unsubscribe",
1508- )
1509- .await;
1510- let sub = site
1511- .store
1512- .subscription(&w.bob.id, &w.issue.id)
1513- .await
1514- .expect("sub");
1515- assert_eq!(sub, Some((SubState::Ignored, Reason::Subscribed)));
1516-
1517- // A pull request number that does not exist is a 404 on the pulls subscription.
1518- let res = post(
1519- &site,
1520- "/tahinli/demo/pulls/1/subscription",
1521- &cookie,
1522- "&action=subscribe",
1523- )
1524- .await;
1525- assert_eq!(res.status, 404);
1526- }
1527-
1528- #[tokio::test]
1529- async fn watch_form_sets_the_level() {
1530- let site = site().await;
1531- let w = world(&site, Visibility::Public).await;
1532- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1533-
1534- let res = post(&site, "/tahinli/demo/watch", &cookie, "&level=watching").await;
1535- assert_eq!(res.status, 303);
1536- assert_eq!(
1537- site.store
1538- .watch_level(&w.bob.id, &w.repo.id)
1539- .await
1540- .expect("level"),
1541- WatchLevel::Watching
1542- );
1543-
1544- // The watch menu sits in the repo head on the code tab, which reads the repository.
1545- let bare = forge_git::repo::repo_path(&site.git.data_dir, &w.repo.id).expect("repo path");
1546- forge_git::repo::init_bare(&site.git, &bare, "main")
1547- .await
1548- .expect("init bare");
1549- let header = get(&site, "/tahinli/demo", Some(&cookie)).await;
1550- assert!(header.body.contains("action=\"/tahinli/demo/watch\""));
1551- assert!(header.body.contains("<details class=\"menu watch-menu\">"));
1552- assert!(!header.body.contains("<select"));
1553- // One form per level, and only the watched level is marked current.
1554- assert_eq!(header.body.matches("name=\"level\"").count(), 3);
1555- assert_eq!(
1556- header
1557- .body
1558- .matches("class=\"watch-option is-current\"")
1559- .count(),
1560- 1
1561- );
1562- assert_eq!(header.body.matches("class=\"watch-option\"").count(), 2);
1563- assert!(header.body.contains("1 watching"));
1564-
1565- let bad = post(&site, "/tahinli/demo/watch", &cookie, "&level=loud").await;
1566- assert_eq!(bad.status, 400);
1567- }
1568-
1569- #[tokio::test]
1570- async fn anonymous_viewers_are_sent_to_login_and_the_stream_needs_a_session() {
1571- let site = site().await;
1572- let _w = world(&site, Visibility::Public).await;
1573- let res = get(&site, "/notifications", None).await;
1574- assert_eq!(res.status, 303);
1575- assert!(res.location.unwrap_or_default().starts_with("/login"));
1576- let stream = get(&site, "/notifications/stream", None).await;
1577- assert_eq!(stream.status, 401);
1578- }
1579-
1580- #[tokio::test]
1581- async fn row_for_a_repo_the_viewer_lost_access_to_is_hidden() {
1582- let site = site().await;
1583- let w = world(&site, Visibility::Private).await;
1584- let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
1585- site.store
1586- .set_collaborator(&w.repo.id, &w.bob.id, Role::Read)
1587- .await
1588- .expect("collaborator");
1589- notify(&site, &w, Reason::Mention).await;
1590- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
1591-
1592- site.store
1593- .remove_collaborator(&w.repo.id, &w.bob.id)
1594- .await
1595- .expect("remove");
1596- let page = get(&site, "/notifications?all=1", Some(&cookie)).await;
1597- assert_eq!(page.status, 200);
1598- assert!(!page.body.contains("tahinli/demo #1 First"));
1599- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
1600- }
1601-
1602- #[tokio::test]
1603- async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
1604- let site = site().await;
1605- let w = world(&site, Visibility::Public).await;
1606- // The world's issue takes number 1, so the discussion is #2.
1607- let discussion = site
1608- .store
1609- .create_discussion(
1610- &w.repo.id,
1611- &w.tahinli.id,
1612- forge_core::discussions::DiscussionCategory::General,
1613- "Ideas",
1614- "",
1615- )
1616- .await
1617- .expect("discussion");
1618- site.store
1619- .add_discussion_comment(&discussion.id, &w.bob.id, None, "+1", false)
1620- .await
1621- .expect("reply");
1622- let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
1623- let bob = sign_in(&site.store, &w.bob.id, "bob-token").await;
1624- let open = format!("/notifications/discussions/{}/open", discussion.id);
1625-
1626- let page = get(&site, "/notifications", Some(&tahinli)).await;
1627- assert_eq!(page.status, 200);
1628- assert!(page.body.contains("Ideas"));
1629- assert!(page.body.contains(&open));
1630- assert_eq!(
1631- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1632- 1
1633- );
1634-
1635- // Bob has no row for the discussion, so he cannot open it.
1636- let other = get(&site, &open, Some(&bob)).await;
1637- assert_eq!(other.status, 404);
1638-
1639- let res = get(&site, &open, Some(&tahinli)).await;
1640- assert_eq!(res.status, 303);
1641- assert_eq!(res.location.as_deref(), Some("/tahinli/demo/discussions/2"));
1642- assert_eq!(
1643- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1644- 0
1645- );
1646-
1647- // A second discussion, cleared by mark all read.
1648- let discussion = site
1649- .store
1650- .create_discussion(
1651- &w.repo.id,
1652- &w.tahinli.id,
1653- forge_core::discussions::DiscussionCategory::General,
1654- "Ideas",
1655- "",
1656- )
1657- .await
1658- .expect("discussion");
1659- site.store
1660- .add_discussion_comment(&discussion.id, &w.bob.id, None, "+1", false)
1661- .await
1662- .expect("reply");
1663- assert_eq!(
1664- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1665- 1
1666- );
1667-
1668- let res = post(&site, "/notifications/mark_all_read", &tahinli, "").await;
1669- assert_eq!(res.status, 303);
1670- assert_eq!(
1671- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1672- 0
1673- );
1674- }
1675-
1676- #[tokio::test]
1677- async fn advisory_alerts_show_for_managers_and_open_marks_read() {
1678- let site = site().await;
1679- let w = world(&site, Visibility::Public).await;
1680- // Tahinli owns the repo, so she manages its alerts. Bob is a reader with a stale row.
1681- site.store
1682- .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2)
1683- .await
1684- .expect("alerts");
1685- site.store
1686- .notify_new_alerts(&w.bob.id, &w.repo.id, 1)
1687- .await
1688- .expect("alerts");
1689- let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
1690- let bob = sign_in(&site.store, &w.bob.id, "bob-token").await;
1691- let open = format!("/notifications/advisories/{}/open", w.repo.id);
1692-
1693- let page = get(&site, "/notifications", Some(&tahinli)).await;
1694- assert_eq!(page.status, 200);
1695- assert!(page.body.contains("Security alerts"));
1696- assert!(page.body.contains("2 new alerts"));
1697- assert!(page.body.contains(&open));
1698- assert_eq!(
1699- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1700- 1
1701- );
1702-
1703- // Bob cannot manage the alerts: his row is hidden and marked read, as lost-access rows are.
1704- let bob_page = get(&site, "/notifications", Some(&bob)).await;
1705- assert_eq!(bob_page.status, 200);
1706- assert!(!bob_page.body.contains(&open));
1707- assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
1708- let bob_open = get(&site, &open, Some(&bob)).await;
1709- assert_eq!(bob_open.status, 404);
1710-
1711- let res = get(&site, &open, Some(&tahinli)).await;
1712- assert_eq!(res.status, 303);
1713- assert_eq!(res.location.as_deref(), Some("/tahinli/demo/security"));
1714- assert_eq!(
1715- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1716- 0
1717- );
1718- }
1719-
1720- #[tokio::test]
1721- async fn advisory_rows_are_marked_read_by_mark_read_and_mark_all() {
1722- let site = site().await;
1723- let w = world(&site, Visibility::Public).await;
1724- let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
1725- let read = format!("/notifications/advisories/{}/read", w.repo.id);
1726-
1727- site.store
1728- .notify_new_alerts(&w.tahinli.id, &w.repo.id, 1)
1729- .await
1730- .expect("alerts");
1731- assert_eq!(
1732- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1733- 1
1734- );
1735- let res = post(&site, &read, &tahinli, "").await;
1736- assert_eq!(res.status, 303);
1737- assert_eq!(
1738- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1739- 0
1740- );
1741-
1742- site.store
1743- .notify_new_alerts(&w.tahinli.id, &w.repo.id, 3)
1744- .await
1745- .expect("alerts");
1746- assert_eq!(
1747- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1748- 1
1749- );
1750- let res = post(&site, "/notifications/mark_all_read", &tahinli, "").await;
1751- assert_eq!(res.status, 303);
1752- assert_eq!(
1753- site.store.unread_count(&w.tahinli.id).await.expect("count"),
1754- 0
1755- );
1756- }
1757-}
crates/forge-web/src/pages/packages.rs → crates/forge-web-pages/src/pages/packages.rsrenamed+4 -4
@@ -34,7 +34,7 @@ path_param!(name);
34 path_param!(*pkg);34 path_param!(*pkg);
35 35
36 /// One package on a list: what the Packages tab and the owner's lists show.36 /// One package on a list: what the Packages tab and the owner's lists show.
37-pub(crate) struct PackageRow {37+pub struct PackageRow {
38 pub name: String,38 pub name: String,
39 pub href: String,39 pub href: String,
40 pub latest: String,40 pub latest: String,
@@ -46,18 +46,18 @@ pub(crate) struct PackageRow {
46 }46 }
47 47
48 /// The package path of a package under its owner.48 /// The package path of a package under its owner.
49-pub(crate) fn package_href(owner: &str, name: &str) -> String {49+pub fn package_href(owner: &str, name: &str) -> String {
50 format!("/{}/-/packages/{}", enc(owner), enc(name))50 format!("/{}/-/packages/{}", enc(owner), enc(name))
51 }51 }
52 52
53 /// The owner's live `changed` stream. Its path is the owner's profile path plus `/-/packages/events`.53 /// The owner's live `changed` stream. Its path is the owner's profile path plus `/-/packages/events`.
54-pub(crate) fn events_href(owner: &str) -> String {54+pub fn events_href(owner: &str) -> String {
55 format!("/{}/-/packages/events", enc(owner))55 format!("/{}/-/packages/events", enc(owner))
56 }56 }
57 57
58 /// The packages of `owner` that `viewer` may see, with a version, newest first by name.58 /// The packages of `owner` that `viewer` may see, with a version, newest first by name.
59 /// Packages without a version are not listed.59 /// Packages without a version are not listed.
60-pub(crate) async fn package_rows(60+pub async fn package_rows(
61 state: &AppState,61 state: &AppState,
62 viewer: Option<&User>,62 viewer: Option<&User>,
63 owner: &User,63 owner: &User,
crates/forge-web/src/pages/packages_oci.rs → crates/forge-web-pages/src/pages/packages_oci.rsrenamed+0 -0
crates/forge-web/src/pages/pull_live.rs → crates/forge-web-pages/src/pages/pull_live.rsrenamed+2 -2
@@ -36,7 +36,7 @@ path_param!(number);
36 36
37 /// What one pull request page shows, as one string. `viewer` is the reader: a pending review is37 /// What one pull request page shows, as one string. `viewer` is the reader: a pending review is
38 /// the viewer's own and shows only to them.38 /// the viewer's own and shows only to them.
39-pub(crate) async fn pull_fingerprint(39+pub async fn pull_fingerprint(
40 store: &Store,40 store: &Store,
41 repo_id: &str,41 repo_id: &str,
42 pr: &PullRequest,42 pr: &PullRequest,
@@ -121,7 +121,7 @@ pub(crate) async fn pull_fingerprint(
121 }121 }
122 122
123 /// What the pull request list shows: the fingerprint of every pull of the repo, in number order.123 /// What the pull request list shows: the fingerprint of every pull of the repo, in number order.
124-pub(crate) async fn list_fingerprint(124+pub async fn list_fingerprint(
125 store: &Store,125 store: &Store,
126 repo_id: &str,126 repo_id: &str,
127 viewer: Option<&str>,127 viewer: Option<&str>,
crates/forge-web/src/pages/pull_reviews.rs → crates/forge-web-pages/src/pages/pull_reviews.rsrenamed+11 -673
@@ -53,19 +53,19 @@ path_param!(comment_id);
53 path_param!(review_id);53 path_param!(review_id);
54 54
55 /// The `review_error` codes a refused write redirects with.55 /// The `review_error` codes a refused write redirects with.
56-pub(crate) const ERR_STALE: &str = "stale";56+pub const ERR_STALE: &str = "stale";
57-pub(crate) const ERR_OWN_PR: &str = "own_pr";57+pub const ERR_OWN_PR: &str = "own_pr";
58-pub(crate) const ERR_EMPTY: &str = "empty";58+pub const ERR_EMPTY: &str = "empty";
59-pub(crate) const ERR_INVALID: &str = "invalid";59+pub const ERR_INVALID: &str = "invalid";
60-pub(crate) const ERR_BAD_LINE: &str = "bad_line";60+pub const ERR_BAD_LINE: &str = "bad_line";
61-pub(crate) const ERR_CLOSED: &str = "closed";61+pub const ERR_CLOSED: &str = "closed";
62 /// A suggestion no longer applies to the head, so it is not applied.62 /// A suggestion no longer applies to the head, so it is not applied.
63-pub(crate) const ERR_OUTDATED: &str = "outdated";63+pub const ERR_OUTDATED: &str = "outdated";
64 /// The viewer may not push to the pull request's head branch, so cannot apply a suggestion.64 /// The viewer may not push to the pull request's head branch, so cannot apply a suggestion.
65-pub(crate) const ERR_NO_PUSH: &str = "no_push";65+pub const ERR_NO_PUSH: &str = "no_push";
66 66
67 /// The message for a `review_error` code in `lang`, or `None` for an unknown code.67 /// The message for a `review_error` code in `lang`, or `None` for an unknown code.
68-pub(crate) fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> {68+pub fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> {
69 match code {69 match code {
70 ERR_STALE => Some(g::t(lang, K::ReviewErrStale)),70 ERR_STALE => Some(g::t(lang, K::ReviewErrStale)),
71 ERR_OWN_PR => Some(g::t(lang, K::ReviewErrOwnPr)),71 ERR_OWN_PR => Some(g::t(lang, K::ReviewErrOwnPr)),
@@ -118,11 +118,7 @@ struct ReviewForm {
118 /// The diff of the pull request: the merge base of `base_oid` and `head_oid` to head, with the118 /// The diff of the pull request: the merge base of `base_oid` and `head_oid` to head, with the
119 /// Files tab's limits. The Files tab and the comment routes both read it, so a line means the119 /// Files tab's limits. The Files tab and the comment routes both read it, so a line means the
120 /// same thing on both.120 /// same thing on both.
121-pub(crate) async fn pull_diff(121+pub async fn pull_diff(state: &AppState, ctx: &RepoCtx, pr: &PullRequest) -> Result<CommitDiff> {
122- state: &AppState,
123- ctx: &RepoCtx,
124- pr: &PullRequest,
125-) -> Result<CommitDiff> {
126 Ok(range_diff_files(&state.git, &ctx.path, &pr.base_oid, &pr.head_oid, LIMITS).await?)122 Ok(range_diff_files(&state.git, &ctx.path, &pr.base_oid, &pr.head_oid, LIMITS).await?)
127 }123 }
128 124
@@ -293,7 +289,7 @@ fn suggestion_applies(current: &str, root: &ReviewComment) -> bool {
293 /// The suggestion state of each thread of the pull request whose root proposes a change, keyed by289 /// The suggestion state of each thread of the pull request whose root proposes a change, keyed by
294 /// root id. A suggestion is `Ready` when it applies to the head and the viewer may apply it, and290 /// root id. A suggestion is `Ready` when it applies to the head and the viewer may apply it, and
295 /// `Outdated` when it no longer applies. A closed pull request shows none.291 /// `Outdated` when it no longer applies. A closed pull request shows none.
296-pub(crate) async fn suggest_states(292+pub async fn suggest_states(
297 state: &AppState,293 state: &AppState,
298 ctx: &RepoCtx,294 ctx: &RepoCtx,
299 pr: &PullRequest,295 pr: &PullRequest,
@@ -829,661 +825,3 @@ async fn review_dismiss(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOthe
829 Err(e) => Err(e.into()),825 Err(e) => Err(e.into()),
830 }826 }
831 }827 }
832-
833-#[cfg(test)]
834-mod tests {
835- use forge_core::reviews::{ReviewState, Side};
836- use forge_core::{IssueState, PullRequest, User, Visibility};
837- use forge_git::GitEnv;
838- use topcoat::router::request::Request;
839- use topcoat::router::{Body, Router, to_bytes};
840-
841- use crate::auth::{SESSION_COOKIE, percent_encode};
842- use crate::test_support::fixture::{Fixture, OWNER, REPO, git};
843-
844- fn cookie(token: &str) -> String {
845- format!("__Host-{SESSION_COOKIE}={token}")
846- }
847-
848- /// Sends one request through the router and returns `(status, location, body)`.
849- async fn send(
850- router: &Router,
851- method: &str,
852- uri: &str,
853- token: Option<&str>,
854- form: Option<String>,
855- ) -> (u16, Option<String>, String) {
856- let mut req = Request::builder().method(method).uri(uri);
857- if let Some(token) = token {
858- req = req.header("cookie", cookie(token));
859- }
860- let body = match form {
861- Some(form) => {
862- req = req.header("content-type", "application/x-www-form-urlencoded");
863- Body::from(form)
864- }
865- None => Body::empty(),
866- };
867- let res = router.handle(req.body(body).unwrap()).await;
868- let status = res.status().as_u16();
869- let location = res
870- .headers()
871- .get("location")
872- .map(|v| v.to_str().unwrap().to_owned());
873- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
874- (
875- status,
876- location,
877- String::from_utf8_lossy(&bytes).into_owned(),
878- )
879- }
880-
881- /// A user with a session whose CSRF token is `{token}-csrf`.
882- async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
883- let user = fx
884- .store
885- .create_user(name, None, "not-a-real-hash", false)
886- .await
887- .unwrap();
888- crate::test_support::create_session(&fx.store, &user.id, token, &format!("{token}-csrf"))
889- .await;
890- user
891- }
892-
893- /// The repo owner, signed in with token `tahinli` (CSRF `tahinli-csrf`).
894- async fn owner_session(fx: &Fixture) {
895- let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
896- crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
897- }
898-
899- fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String {
900- let mut form = format!("csrf={}", percent_encode(&format!("{token}-csrf")));
901- for (key, value) in pairs {
902- form.push_str(&format!("&{key}={}", percent_encode(value)));
903- }
904- form
905- }
906-
907- async fn pull(fx: &Fixture, number: i64) -> PullRequest {
908- let repo = fx
909- .store
910- .repo_by_owner_and_name(OWNER, REPO)
911- .await
912- .unwrap()
913- .unwrap();
914- fx.store
915- .pull_by_number(&repo.id, number)
916- .await
917- .unwrap()
918- .unwrap()
919- }
920-
921- /// Pushes a `feature` branch from the root that changes `a.txt` (`two` becomes `changed`) and
922- /// opens a pull request for it against `main`. Returns the pull request number.
923- async fn open_pull(fx: &Fixture) -> i64 {
924- let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
925- git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
926- std::fs::write(fx.work.join("a.txt"), "one\nchanged\nthree\n").unwrap();
927- git(&fx.work, &["add", "-A"]);
928- git(&fx.work, &["commit", "-q", "-m", "Change a.txt"]);
929- let head_oid = git(&fx.work, &["rev-parse", "HEAD"]);
930- git(
931- &fx.work,
932- &[
933- "push",
934- "-q",
935- &fx.bare.to_string_lossy(),
936- "HEAD:refs/heads/feature",
937- ],
938- );
939-
940- let repo = fx
941- .store
942- .repo_by_owner_and_name(OWNER, REPO)
943- .await
944- .unwrap()
945- .unwrap();
946- let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
947- let pr = fx
948- .store
949- .create_pull(
950- &repo.id, &owner.id, "Change a", "", "main", &repo.id, "feature", &head_oid,
951- &base_oid,
952- )
953- .await
954- .unwrap();
955- let env = GitEnv {
956- git_bin: "git".into(),
957- data_dir: fx.work.clone(),
958- };
959- forge_git::pulls::fetch_into_pull_ref(&env, &fx.bare, &fx.bare, &head_oid, pr.issue.number)
960- .await
961- .unwrap();
962- pr.issue.number
963- }
964-
965- /// The pull request's current head, for the `head_oid` field of a comment form.
966- async fn head_of(fx: &Fixture, number: i64) -> String {
967- pull(fx, number).await.head_oid
968- }
969-
970- /// Posts a single line comment on line `line` of the new side of `a.txt` (file index 0).
971- async fn comment_on(
972- fx: &Fixture,
973- number: i64,
974- token: &str,
975- line: &str,
976- body: &str,
977- ) -> (u16, Option<String>) {
978- let head = head_of(fx, number).await;
979- let form = csrf_form(
980- token,
981- &[
982- ("file_index", "0"),
983- ("side", "new"),
984- ("line", line),
985- ("head_oid", head.as_str()),
986- ("action", "single"),
987- ("body", body),
988- ],
989- );
990- let (status, location, _) = send(
991- &fx.router,
992- "POST",
993- &format!("/tahinli/demo/pulls/{number}/review_comments"),
994- Some(token),
995- Some(form),
996- )
997- .await;
998- (status, location)
999- }
1000-
1001- /// The id of the thread at `index` (in creation order) on the pull request.
1002- async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {
1003- let pr = pull(fx, number).await;
1004- fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index]
1005- .root
1006- .id
1007- .clone()
1008- }
1009-
1010- /// The comment body that proposes replacing line 2 of `a.txt` with `text`.
1011- fn suggestion(text: &str) -> String {
1012- format!("Try this:\n```suggestion\n{text}\n```")
1013- }
1014-
1015- /// Posts the apply form for suggestion block 0 of comment `comment_id`.
1016- async fn apply_as(
1017- fx: &Fixture,
1018- number: i64,
1019- token: &str,
1020- comment_id: &str,
1021- ) -> (u16, Option<String>) {
1022- let form = csrf_form(token, &[("block", "0"), ("return", "files")]);
1023- let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply");
1024- let (status, location, _) = send(&fx.router, "POST", &uri, Some(token), Some(form)).await;
1025- (status, location)
1026- }
1027-
1028- /// Comment posting rules and a pending review, on one open pull. Scenarios run in order:
1029- /// the rejected posts first (no thread), then the first thread, then the pending review.
1030- #[tokio::test]
1031- async fn comment_rules_and_pending_review_on_one_pull() {
1032- let fx = Fixture::new(Visibility::Public).await;
1033- owner_session(&fx).await;
1034- let number = open_pull(&fx).await;
1035- let pr = pull(&fx, number).await;
1036-
1037- // A line outside the diff is rejected and leaves no thread.
1038- let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await;
1039- assert_eq!(status, 303, "outside diff");
1040- assert!(
1041- location.unwrap().contains("review_error=bad_line"),
1042- "outside diff"
1043- );
1044- assert!(
1045- fx.store
1046- .review_threads(&pr.issue.id, None)
1047- .await
1048- .unwrap()
1049- .is_empty(),
1050- "outside diff left a thread"
1051- );
1052-
1053- // A head that is not the pull's current head is rejected.
1054- let zero = "0".repeat(40);
1055- let form = csrf_form(
1056- "tahinli",
1057- &[
1058- ("file_index", "0"),
1059- ("side", "new"),
1060- ("line", "2"),
1061- ("head_oid", zero.as_str()),
1062- ("action", "single"),
1063- ("body", "Stale"),
1064- ],
1065- );
1066- let (status, location, _) = send(
1067- &fx.router,
1068- "POST",
1069- &format!("/tahinli/demo/pulls/{number}/review_comments"),
1070- Some("tahinli"),
1071- Some(form),
1072- )
1073- .await;
1074- assert_eq!(status, 303, "stale head");
1075- assert_eq!(
1076- location.as_deref(),
1077- Some(format!("/tahinli/demo/pulls/{number}/files?review_error=stale").as_str()),
1078- "stale head"
1079- );
1080- assert!(
1081- fx.store
1082- .review_threads(&pr.issue.id, None)
1083- .await
1084- .unwrap()
1085- .is_empty(),
1086- "stale head left a thread"
1087- );
1088-
1089- // A single comment on an added line creates a thread that carries its hunk.
1090- let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await;
1091- assert_eq!(status, 303, "single comment");
1092- assert_eq!(
1093- location.as_deref(),
1094- Some(format!("/tahinli/demo/pulls/{number}/files#L-0-new-2").as_str()),
1095- "single comment"
1096- );
1097- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1098- assert_eq!(threads.len(), 1, "single comment");
1099- let root = &threads[0].root;
1100- assert_eq!(
1101- (root.path.as_str(), root.side, root.line),
1102- ("a.txt", Side::New, 2),
1103- "single comment"
1104- );
1105- assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment");
1106- assert!(!root.pending, "single comment");
1107-
1108- // A pending review comment is hidden from everyone but its author until submitted.
1109- let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
1110- let head = pr.head_oid.clone();
1111- let form = csrf_form(
1112- "tahinli",
1113- &[
1114- ("file_index", "0"),
1115- ("side", "new"),
1116- ("line", "2"),
1117- ("head_oid", head.as_str()),
1118- ("action", "review"),
1119- ("body", "Draft"),
1120- ],
1121- );
1122- let (status, _, _) = send(
1123- &fx.router,
1124- "POST",
1125- &format!("/tahinli/demo/pulls/{number}/review_comments"),
1126- Some("tahinli"),
1127- Some(form),
1128- )
1129- .await;
1130- assert_eq!(status, 303, "pending start");
1131- assert_eq!(
1132- fx.store
1133- .review_threads(&pr.issue.id, None)
1134- .await
1135- .unwrap()
1136- .len(),
1137- 1,
1138- "pending thread hidden from everyone"
1139- );
1140- let mine = fx
1141- .store
1142- .review_threads(&pr.issue.id, Some(&tahinli.id))
1143- .await
1144- .unwrap();
1145- assert_eq!(mine.len(), 2, "author sees the pending thread");
1146- assert!(
1147- mine.iter().any(|t| t.root.pending),
1148- "the author's draft is pending"
1149- );
1150-
1151- let form = csrf_form("tahinli", &[("state", "comment"), ("body", "Done")]);
1152- let (status, _, _) = send(
1153- &fx.router,
1154- "POST",
1155- &format!("/tahinli/demo/pulls/{number}/reviews"),
1156- Some("tahinli"),
1157- Some(form),
1158- )
1159- .await;
1160- assert_eq!(status, 303, "submit review");
1161- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1162- assert_eq!(threads.len(), 2, "submitted review is public");
1163- assert!(threads.iter().all(|t| !t.root.pending), "submitted review");
1164-
1165- // Anonymous writes redirect to login, and a missing CSRF token is forbidden.
1166- let uri = format!("/tahinli/demo/pulls/{number}/review_comments");
1167- let form = csrf_form(
1168- "tahinli",
1169- &[
1170- ("file_index", "0"),
1171- ("side", "new"),
1172- ("line", "2"),
1173- ("head_oid", head.as_str()),
1174- ("action", "single"),
1175- ("body", "Anon"),
1176- ],
1177- );
1178- let (status, location, _) = send(&fx.router, "POST", &uri, None, Some(form)).await;
1179- assert_eq!(status, 303, "anonymous write");
1180- assert!(location.unwrap().starts_with("/login"), "anonymous write");
1181- let form =
1182- format!("file_index=0&side=new&line=2&head_oid={head}&action=single&body=NoCsrf");
1183- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1184- assert_eq!(status, 403, "missing csrf");
1185- }
1186-
1187- /// Reply, edit, resolve and delete on the threads of one pull. Each scenario acts on its
1188- /// own thread (the first for reply, edit and resolve, the second for delete).
1189- #[tokio::test]
1190- async fn thread_reply_edit_resolve_and_delete() {
1191- let fx = Fixture::new(Visibility::Public).await;
1192- owner_session(&fx).await;
1193- sign_in(&fx, "bob", "bob").await;
1194- let number = open_pull(&fx).await;
1195- comment_on(&fx, number, "tahinli", "2", "First").await;
1196- let pr = pull(&fx, number).await;
1197- let root = root_at(&fx, number, 0).await;
1198-
1199- // A reader replies into the thread and is sent back to its root.
1200- let form = csrf_form("bob", &[("body", "Reply")]);
1201- let (status, location, _) = send(
1202- &fx.router,
1203- "POST",
1204- &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"),
1205- Some("bob"),
1206- Some(form),
1207- )
1208- .await;
1209- assert_eq!(status, 303, "reply");
1210- assert_eq!(
1211- location.as_deref(),
1212- Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()),
1213- "reply"
1214- );
1215- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1216- assert_eq!(threads[0].replies.len(), 1, "reply");
1217- assert_eq!(threads[0].replies[0].author_name, "bob", "reply");
1218-
1219- // Only the author may open the edit form, post an edit, or resolve.
1220- let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit");
1221- let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await;
1222- assert_eq!(status, 200, "edit form");
1223- assert!(body.contains("Save comment"), "edit form");
1224- let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await;
1225- assert_eq!(status, 403, "edit form for a non-author");
1226- let form = csrf_form("bob", &[("body", "Hijacked")]);
1227- let (status, _, _) = send(&fx.router, "POST", &edit, Some("bob"), Some(form)).await;
1228- assert_eq!(status, 403, "edit by a non-author");
1229- let form = csrf_form("tahinli", &[("body", "Edited")]);
1230- let (status, location, _) =
1231- send(&fx.router, "POST", &edit, Some("tahinli"), Some(form)).await;
1232- assert_eq!(status, 303, "edit");
1233- assert_eq!(
1234- location.as_deref(),
1235- Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()),
1236- "edit"
1237- );
1238- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1239- assert_eq!(threads[0].root.body, "Edited", "edit");
1240-
1241- let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve");
1242- let form = csrf_form("bob", &[("resolved", "1")]);
1243- let (status, _, _) = send(&fx.router, "POST", &resolve, Some("bob"), Some(form)).await;
1244- assert_eq!(status, 403, "resolve by a reader");
1245- let form = csrf_form("tahinli", &[("resolved", "1")]);
1246- let (status, _, _) = send(&fx.router, "POST", &resolve, Some("tahinli"), Some(form)).await;
1247- assert_eq!(status, 303, "resolve");
1248- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1249- assert!(threads[0].root.resolved, "resolve");
1250-
1251- // Delete removes only the second thread, and only for its author.
1252- comment_on(&fx, number, "tahinli", "2", "Doomed").await;
1253- let doomed = root_at(&fx, number, 1).await;
1254- let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete");
1255- let form = csrf_form("bob", &[]);
1256- let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
1257- assert_eq!(status, 403, "delete by a non-author");
1258- let form = csrf_form("tahinli", &[]);
1259- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1260- assert_eq!(status, 303, "delete");
1261- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1262- assert_eq!(threads.len(), 1, "delete");
1263- assert_eq!(threads[0].root.id, root, "delete kept the other thread");
1264- }
1265-
1266- /// Reviews on one pull: a reader approves, the author cannot approve their own pull, and
1267- /// after the pull closes it takes comments but no reviews.
1268- #[tokio::test]
1269- async fn reviews_approve_then_close_the_pull() {
1270- let fx = Fixture::new(Visibility::Public).await;
1271- owner_session(&fx).await;
1272- sign_in(&fx, "bob", "bob").await;
1273- let number = open_pull(&fx).await;
1274- let pr = pull(&fx, number).await;
1275- let uri = format!("/tahinli/demo/pulls/{number}/reviews");
1276-
1277- // A reader's approval is recorded.
1278- let form = csrf_form("bob", &[("state", "approve")]);
1279- let (status, location, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
1280- assert_eq!(status, 303, "reader approval");
1281- assert!(location.unwrap().contains("#review-"), "reader approval");
1282- let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap();
1283- assert_eq!(reviews.len(), 1, "reader approval");
1284- assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval");
1285-
1286- // The author's approval is refused.
1287- let form = csrf_form("tahinli", &[("state", "approve")]);
1288- let (status, location, _) =
1289- send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1290- assert_eq!(status, 303, "author approval");
1291- assert_eq!(
1292- location.as_deref(),
1293- Some(format!("/tahinli/demo/pulls/{number}?review_error=own_pr").as_str()),
1294- "author approval"
1295- );
1296- assert_eq!(
1297- fx.store.list_reviews(&pr.issue.id).await.unwrap().len(),
1298- 1,
1299- "author approval"
1300- );
1301-
1302- // Once closed, comments still land but reviews are refused.
1303- let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
1304- fx.store
1305- .set_issue_state(
1306- &pr.issue.id,
1307- Some(&tahinli.id),
1308- IssueState::Closed,
1309- None,
1310- serde_json::Value::Null,
1311- )
1312- .await
1313- .unwrap();
1314- let (status, location) = comment_on(&fx, number, "tahinli", "2", "After close").await;
1315- assert_eq!(status, 303, "comment on a closed pull");
1316- assert!(
1317- location.unwrap().contains("#L-0-new-2"),
1318- "comment on a closed pull"
1319- );
1320- let form = csrf_form("tahinli", &[("state", "approve")]);
1321- let (status, location, _) =
1322- send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1323- assert_eq!(status, 303, "review on a closed pull");
1324- assert!(
1325- location.unwrap().ends_with("?review_error=closed"),
1326- "review on a closed pull"
1327- );
1328- }
1329-
1330- #[tokio::test]
1331- async fn dismiss_needs_write_and_a_reason() {
1332- let fx = Fixture::new(Visibility::Public).await;
1333- owner_session(&fx).await;
1334- sign_in(&fx, "bob", "bob").await;
1335- let number = open_pull(&fx).await;
1336- let pr = pull(&fx, number).await;
1337- let form = csrf_form("bob", &[("state", "request_changes")]);
1338- send(
1339- &fx.router,
1340- "POST",
1341- &format!("/tahinli/demo/pulls/{number}/reviews"),
1342- Some("bob"),
1343- Some(form),
1344- )
1345- .await;
1346- let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
1347- let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id);
1348-
1349- let form = csrf_form("bob", &[("reason", "mine")]);
1350- let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
1351- assert_eq!(status, 403, "dismiss by a reader");
1352-
1353- let form = csrf_form("tahinli", &[("reason", " ")]);
1354- let (status, location, _) =
1355- send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1356- assert_eq!(status, 303, "blank reason");
1357- assert!(
1358- location.unwrap().ends_with("?review_error=empty"),
1359- "blank reason"
1360- );
1361-
1362- let form = csrf_form("tahinli", &[("reason", "Addressed")]);
1363- let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1364- assert_eq!(status, 303, "dismiss");
1365- let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
1366- assert_eq!(review.state, ReviewState::Dismissed, "dismiss");
1367- }
1368-
1369- /// The apply-suggestion flow on one pull: a reader without push access sees no button, an
1370- /// outdated suggestion is refused after the head moves, and a fresh suggestion applies.
1371- #[tokio::test]
1372- async fn suggestions_reader_outdated_and_apply() {
1373- let fx = Fixture::new(Visibility::Public).await;
1374- owner_session(&fx).await;
1375- sign_in(&fx, "rita", "rita").await;
1376- let number = open_pull(&fx).await;
1377- let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
1378- assert_eq!(status, 303, "first suggestion");
1379- let first = root_at(&fx, number, 0).await;
1380-
1381- // A reader without push access sees the diff but no apply button, and is refused.
1382- let page = get(&fx, number, "rita").await;
1383- assert!(page.contains("Suggested change"), "the diff still shows");
1384- assert!(
1385- !page.contains("Apply suggestion"),
1386- "no apply button without push access"
1387- );
1388- let (status, location) = apply_as(&fx, number, "rita", &first).await;
1389- assert_eq!(status, 303, "reader apply");
1390- assert!(
1391- location.unwrap().contains("review_error=no_push"),
1392- "reader apply"
1393- );
1394-
1395- // The head moves on: the first suggestion is outdated, shown without apply, and refused.
1396- let pr = pull(&fx, number).await;
1397- std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();
1398- git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);
1399- let moved = git(&fx.work, &["rev-parse", "HEAD"]);
1400- git(
1401- &fx.work,
1402- &[
1403- "push",
1404- "-q",
1405- &fx.bare.to_string_lossy(),
1406- "HEAD:refs/heads/feature",
1407- ],
1408- );
1409- fx.store
1410- .update_pull_head(&pr.issue.id, &moved)
1411- .await
1412- .unwrap();
1413-
1414- let page = get(&fx, number, "tahinli").await;
1415- assert!(
1416- page.contains("This suggestion is outdated"),
1417- "outdated note shown"
1418- );
1419- assert!(
1420- !page.contains("Apply suggestion"),
1421- "no apply button when outdated"
1422- );
1423- let (status, location) = apply_as(&fx, number, "tahinli", &first).await;
1424- assert_eq!(status, 303, "outdated apply");
1425- assert!(
1426- location.unwrap().contains("review_error=outdated"),
1427- "outdated apply"
1428- );
1429- assert_eq!(
1430- git(&fx.bare, &["rev-parse", "feature"]),
1431- moved,
1432- "nothing was committed"
1433- );
1434- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1435- assert!(
1436- !threads[0].root.resolved,
1437- "a refused apply leaves the thread open"
1438- );
1439-
1440- // A fresh suggestion against the moved head applies as a commit by the commenter.
1441- let before = pull(&fx, number).await.head_oid;
1442- assert_eq!(before, moved, "the head is the moved commit");
1443- let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
1444- assert_eq!(status, 303, "fresh suggestion");
1445- let second = root_at(&fx, number, 1).await;
1446- let (status, location) = apply_as(&fx, number, "tahinli", &second).await;
1447- assert_eq!(status, 303, "apply");
1448- assert!(!location.unwrap().contains("review_error"), "apply");
1449-
1450- let pr = pull(&fx, number).await;
1451- assert_ne!(
1452- pr.head_oid, before,
1453- "the head moved to the suggestion commit"
1454- );
1455- assert_eq!(
1456- git(&fx.bare, &["show", &format!("{}:a.txt", pr.head_oid)]),
1457- "one\ntwo!\nthree",
1458- "apply"
1459- );
1460- assert_eq!(
1461- git(&fx.bare, &["log", "-1", "--format=%an", &pr.head_oid]),
1462- "tahinli",
1463- "apply"
1464- );
1465- let message = git(&fx.bare, &["log", "-1", "--format=%B", &pr.head_oid]);
1466- assert!(
1467- message.starts_with("Apply suggestion from review"),
1468- "{message}"
1469- );
1470- assert!(
1471- message.contains("Co-authored-by: tahinli <"),
1472- "commenter trailer: {message}"
1473- );
1474- assert_eq!(
1475- git(&fx.bare, &["rev-parse", "feature"]),
1476- pr.head_oid,
1477- "apply"
1478- );
1479- let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1480- assert!(threads[1].root.resolved, "applying resolves the thread");
1481- }
1482-
1483- /// The Files tab of the pull request as `token` sees it.
1484- async fn get(fx: &Fixture, number: i64, token: &str) -> String {
1485- let uri = format!("/tahinli/demo/pulls/{number}/files");
1486- let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await;
1487- body
1488- }
1489-}
crates/forge-web/src/pages/ref_live.rs → crates/forge-web-pages/src/pages/ref_live.rsrenamed+0 -0
crates/forge-web/src/pages/refs.rs → crates/forge-web-pages/src/pages/refs.rsrenamed+1 -1
@@ -79,7 +79,7 @@ pub struct RefRow {
79 }79 }
80 80
81 /// Refs of `kind` with the commit each points at, in table order.81 /// Refs of `kind` with the commit each points at, in table order.
82-pub(crate) async fn ref_rows(82+pub async fn ref_rows(
83 path: PathBuf,83 path: PathBuf,
84 kind: RefKind,84 kind: RefKind,
85 repo: &RepoRow,85 repo: &RepoRow,
crates/forge-web/src/pages/releases.rs → crates/forge-web-pages/src/pages/releases.rsrenamed+2 -2
@@ -90,7 +90,7 @@ fn viewer_user(ctx: &RepoCtx) -> Option<&User> {
90 }90 }
91 91
92 /// Whether the viewer may change releases of this repo. Archived repos refuse.92 /// Whether the viewer may change releases of this repo. Archived repos refuse.
93-pub(crate) fn can_write(ctx: &RepoCtx) -> bool {93+pub fn can_write(ctx: &RepoCtx) -> bool {
94 authorize(94 authorize(
95 viewer_user(ctx),95 viewer_user(ctx),
96 &ctx.repo,96 &ctx.repo,
@@ -193,7 +193,7 @@ pub struct ReleaseCard {
193 pub href: String,193 pub href: String,
194 pub edit_href: String,194 pub edit_href: String,
195 pub body: String,195 pub body: String,
196- pub(crate) when: When,196+ pub when: When,
197 pub author: String,197 pub author: String,
198 pub draft: bool,198 pub draft: bool,
199 pub prerelease: bool,199 pub prerelease: bool,
crates/forge-web/src/pages/releases_live.rs → crates/forge-web-pages/src/pages/releases_live.rsrenamed+2 -2
@@ -41,7 +41,7 @@ pub fn tag_live_url(title: &str, tag: &str) -> String {
41 41
42 /// What the release list shows: the latest release and every release the viewer may see, with42 /// What the release list shows: the latest release and every release the viewer may see, with
43 /// their assets (names, sizes, download counts).43 /// their assets (names, sizes, download counts).
44-pub(crate) async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool) -> Result<String> {44+pub async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool) -> Result<String> {
45 let latest = store45 let latest = store
46 .latest_release(repo_id)46 .latest_release(repo_id)
47 .await?47 .await?
@@ -61,7 +61,7 @@ pub(crate) async fn list_fingerprint(store: &Store, repo_id: &str, writer: bool)
61 61
62 /// What one release page shows. `gone` once the release is missing, or is a draft the viewer may62 /// What one release page shows. `gone` once the release is missing, or is a draft the viewer may
63 /// not see (the page answers 404 for both).63 /// not see (the page answers 404 for both).
64-pub(crate) async fn release_fingerprint(64+pub async fn release_fingerprint(
65 store: &Store,65 store: &Store,
66 repo_id: &str,66 repo_id: &str,
67 tag: &str,67 tag: &str,
crates/forge-web/src/pages/repo.rs → crates/forge-web-pages/src/pages/repo.rsrenamed+0 -480
@@ -503,483 +503,3 @@ async fn repo_page(cx: &Cx) -> Result<impl View> {
503 async fn repo_other_methods(cx: &Cx) -> Result<&'static str> {503 async fn repo_other_methods(cx: &Cx) -> Result<&'static str> {
504 Err(not_found().into())504 Err(not_found().into())
505 }505 }
506-
507-#[cfg(test)]
508-mod tests {
509- use std::path::Path;
510- use std::process::Command;
511- use std::time::Duration;
512-
513- use forge_core::Visibility;
514- use forge_core::time::stamp_before;
515-
516- use forge_git::repo::{init_bare, repo_path};
517-
518- use topcoat::router::request::Request;
519- use topcoat::router::{Body, Router, to_bytes};
520-
521- use crate::auth::SESSION_COOKIE;
522- use crate::state::AppState;
523-
524- async fn app(dir: &Path) -> (Router, AppState) {
525- let state = crate::test_support::test_state(dir).await;
526- (crate::test_support::app_router(state.clone()), state)
527- }
528-
529- fn git(dir: &Path, args: &[&str]) {
530- let status = Command::new("git")
531- .current_dir(dir)
532- .env("GIT_CONFIG_NOSYSTEM", "1")
533- .args([
534- "-c",
535- "user.name=Test",
536- "-c",
537- "user.email=test@example.com",
538- "-c",
539- "commit.gpgsign=false",
540- ])
541- .args(args)
542- .status()
543- .expect("git runs");
544- assert!(status.success(), "git {args:?} failed");
545- }
546-
547- /// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).
548- async fn fixture(dir: &Path) -> (Router, AppState) {
549- let (router, state) = app(dir).await;
550- let tahinli = state
551- .store
552- .create_user("tahinli", None, "x", false)
553- .await
554- .unwrap();
555- let demo = state
556- .store
557- .create_repo(
558- &tahinli.id,
559- "demo",
560- "A demo repo",
561- Visibility::Public,
562- "main",
563- )
564- .await
565- .unwrap();
566- let secret = state
567- .store
568- .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main")
569- .await
570- .unwrap();
571- for repo in [&demo, &secret] {
572- let path = repo_path(&state.config.data_dir, &repo.id).unwrap();
573- init_bare(&state.git, &path, "main").await.unwrap();
574- }
575-
576- let work = dir.join("work");
577- std::fs::create_dir_all(work.join("src")).unwrap();
578- std::fs::create_dir_all(work.join("docs")).unwrap();
579- std::fs::write(work.join("README.md"), "# Demo\n\nHello from the README.\n").unwrap();
580- std::fs::write(
581- work.join("src/main.rs"),
582- "fn main() {\n println!(\"hi\");\n}\n",
583- )
584- .unwrap();
585- std::fs::write(
586- work.join("docs/guide.md"),
587- "# Guide\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
588- )
589- .unwrap();
590- std::fs::write(work.join("data.bin"), [0u8, 1, 2]).unwrap();
591- git(&work, &["init", "-q", "-b", "main"]);
592- git(&work, &["add", "-A"]);
593- git(&work, &["commit", "-q", "-m", "first commit"]);
594- let demo_path = repo_path(&state.config.data_dir, &demo.id).unwrap();
595- git(
596- &work,
597- &["push", "-q", demo_path.to_str().unwrap(), "main:main"],
598- );
599- (router, state)
600- }
601-
602- async fn get(router: &Router, uri: &str) -> (u16, String) {
603- let req = Request::builder()
604- .method("GET")
605- .uri(uri)
606- .body(Body::empty())
607- .unwrap();
608- let res = router.handle(req).await;
609- let status = res.status().as_u16();
610- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
611- (status, String::from_utf8_lossy(&bytes).into_owned())
612- }
613-
614- // The read-only tests below share one fixture: they only read the demo repo, so each scenario
615- // sees the same pristine contents.
616-
617- #[tokio::test]
618- async fn demo_pages_render_from_the_repo_contents() {
619- let dir = tempfile::tempdir().unwrap();
620- let (router, _) = fixture(dir.path()).await;
621-
622- // Home renders the README, the tree, the clone popover and the archive links.
623- let (status, body) = get(&router, "/tahinli/demo").await;
624- assert_eq!(status, 200);
625- assert!(body.contains("Hello from the README"), "README rendered");
626- assert!(
627- body.contains("/tahinli/demo/tree/main/src"),
628- "root tree listed"
629- );
630- assert!(
631- body.contains("class=\"clone pop\""),
632- "clone popover rendered"
633- );
634- assert!(body.contains("value=\"https://forge.test/tahinli/demo.git\""));
635- assert!(body.contains("git@forge.test:tahinli/demo.git"));
636- assert!(
637- body.contains("readonly"),
638- "clone URLs are selectable, read-only fields"
639- );
640- assert!(body.contains("/tahinli/demo/archive/main.tar.gz"));
641- assert!(body.contains("/tahinli/demo/branches"));
642- assert!(body.contains("data-ref-filter"), "branch switcher rendered");
643-
644- // Trees list their entries and link to subtrees and blobs.
645- let (status, body) = get(&router, "/tahinli/demo/tree/main/src").await;
646- assert_eq!(status, 200);
647- assert!(body.contains("main.rs"));
648- assert!(body.contains("/tahinli/demo/blob/main/src/main.rs"));
649- let (status, body) = get(&router, "/tahinli/demo/tree/main").await;
650- assert_eq!(status, 200);
651- assert!(body.contains("/tahinli/demo/tree/main/docs"));
652-
653- // Rust source is highlighted with line anchors.
654- let (status, body) = get(&router, "/tahinli/demo/blob/main/src/main.rs").await;
655- assert_eq!(status, 200);
656- assert!(body.contains("id=\"L1\""));
657- assert!(body.contains("href=\"#L2\""));
658- assert!(body.contains("<span class="), "syntax classes applied");
659- assert!(body.contains("/assets/highlight.css?v="));
660-
661- // Markdown renders unless the viewer asks for the plain source.
662- let (status, body) = get(&router, "/tahinli/demo/blob/main/docs/guide.md").await;
663- assert_eq!(status, 200);
664- assert!(
665- body.contains("markdown-body") && body.contains("<table>"),
666- "GFM table rendered"
667- );
668- let (status, body) = get(&router, "/tahinli/demo/blob/main/docs/guide.md?plain=1").await;
669- assert_eq!(status, 200);
670- assert!(body.contains("file-table"), "source shown as lines");
671- assert!(!body.contains("markdown-body"), "not rendered");
672-
673- // Binary blobs show their size instead of content.
674- let (status, body) = get(&router, "/tahinli/demo/blob/main/data.bin").await;
675- assert_eq!(status, 200);
676- assert!(body.contains("Binary file, 3 bytes"));
677-
678- // Fixed segment routes win over the repo catch-all.
679- let (status, body) = get(&router, "/tahinli/demo/branches").await;
680- assert_eq!(status, 200);
681- assert!(body.contains("default"), "default branch marked");
682- let (status, body) = get(&router, "/tahinli/demo/tags").await;
683- assert_eq!(status, 200);
684- assert!(body.contains("Nothing here yet."));
685- let (status, body) = get(&router, "/tahinli/demo/tree/main").await;
686- assert_eq!(status, 200);
687- assert!(body.contains("README.md"));
688- let (status, body) = get(&router, "/tahinli/demo").await;
689- assert_eq!(status, 200);
690- assert!(body.contains("Hello from the README"));
691- }
692-
693- #[tokio::test]
694- async fn missing_paths_and_private_repos_are_404_for_anonymous() {
695- let dir = tempfile::tempdir().unwrap();
696- let (router, _) = fixture(dir.path()).await;
697- for uri in [
698- "/tahinli/demo/tree/main/nope",
699- "/tahinli/demo/tree/nosuchref",
700- "/tahinli/demo/blob/main/nope.rs",
701- "/tahinli/demo/blob/main/src",
702- "/tahinli/demo/blob/main",
703- ] {
704- let (status, _) = get(&router, uri).await;
705- assert_eq!(status, 404, "{uri}");
706- }
707- for uri in [
708- "/tahinli/secret",
709- "/tahinli/secret/tree/main",
710- "/tahinli/secret/blob/main/x",
711- "/tahinli/secret/branches",
712- "/tahinli/secret/tags",
713- ] {
714- let (status, _) = get(&router, uri).await;
715- assert_eq!(status, 404, "{uri}");
716- }
717- }
718-
719- const ZERO_OID: &str = "0000000000000000000000000000000000000000";
720- const OID: &str = "1111111111111111111111111111111111111111";
721- const BANNER: &str = "had recent pushes";
722-
723- /// Creates a session for `user_id` and returns the cookie header value.
724- async fn sign_in(state: &AppState, user_id: &str, token: &str) -> String {
725- crate::test_support::create_session(&state.store, user_id, token, "csrf").await;
726- format!("__Host-{SESSION_COOKIE}={token}")
727- }
728-
729- async fn get_as(router: &Router, uri: &str, cookie: Option<&str>) -> (u16, String) {
730- let mut builder = Request::builder().method("GET").uri(uri);
731- if let Some(cookie) = cookie {
732- builder = builder.header("cookie", cookie);
733- }
734- let res = router.handle(builder.body(Body::empty()).unwrap()).await;
735- let status = res.status().as_u16();
736- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
737- (status, String::from_utf8_lossy(&bytes).into_owned())
738- }
739-
740- /// Points `branch` at the bare repo's `main`, so the branch exists.
741- fn make_branch(bare: &Path, branch: &str) {
742- let full = format!("refs/heads/{branch}");
743- git(bare, &["update-ref", &full, "refs/heads/main"]);
744- }
745-
746- /// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.
747- async fn record_push(
748- state: &AppState,
749- repo_id: &str,
750- actor_id: &str,
751- branch: &str,
752- age: Duration,
753- ) {
754- let at = stamp_before(age);
755- let full = format!("refs/heads/{branch}");
756- state
757- .store
758- .record_push_event_at(repo_id, actor_id, &full, ZERO_OID, OID, &at)
759- .await
760- .unwrap();
761- }
762-
763- async fn demo_repo(state: &AppState) -> forge_core::Repo {
764- state
765- .store
766- .repo_by_owner_and_name("tahinli", "demo")
767- .await
768- .unwrap()
769- .unwrap()
770- }
771-
772- #[tokio::test]
773- async fn recent_push_banner_links_to_compare() {
774- let dir = tempfile::tempdir().unwrap();
775- let (router, state) = fixture(dir.path()).await;
776- let demo = demo_repo(&state).await;
777- make_branch(
778- &repo_path(&state.config.data_dir, &demo.id).unwrap(),
779- "feature",
780- );
781- record_push(
782- &state,
783- &demo.id,
784- &demo.owner_id,
785- "feature",
786- Duration::from_secs(300),
787- )
788- .await;
789- let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
790-
791- let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
792- assert_eq!(status, 200);
793- assert!(body.contains("had recent pushes"), "{body}");
794- assert!(body.contains("5 minutes ago</time>"), "{body}");
795- assert!(body.contains("compare/main...feature"), "{body}");
796- assert!(body.contains("Compare &amp; pull request"), "{body}");
797- }
798-
799- #[tokio::test]
800- async fn push_older_than_an_hour_shows_no_banner() {
801- let dir = tempfile::tempdir().unwrap();
802- let (router, state) = fixture(dir.path()).await;
803- let demo = demo_repo(&state).await;
804- make_branch(
805- &repo_path(&state.config.data_dir, &demo.id).unwrap(),
806- "feature",
807- );
808- record_push(
809- &state,
810- &demo.id,
811- &demo.owner_id,
812- "feature",
813- Duration::from_secs(7200),
814- )
815- .await;
816- let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
817-
818- let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
819- assert_eq!(status, 200);
820- assert!(!body.contains(BANNER), "{body}");
821- }
822-
823- #[tokio::test]
824- async fn default_branch_push_shows_no_banner() {
825- let dir = tempfile::tempdir().unwrap();
826- let (router, state) = fixture(dir.path()).await;
827- let demo = demo_repo(&state).await;
828- record_push(
829- &state,
830- &demo.id,
831- &demo.owner_id,
832- "main",
833- Duration::from_secs(300),
834- )
835- .await;
836- let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
837-
838- let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
839- assert_eq!(status, 200);
840- assert!(!body.contains(BANNER), "{body}");
841- }
842-
843- #[tokio::test]
844- async fn open_pull_request_suppresses_banner() {
845- let dir = tempfile::tempdir().unwrap();
846- let (router, state) = fixture(dir.path()).await;
847- let demo = demo_repo(&state).await;
848- make_branch(
849- &repo_path(&state.config.data_dir, &demo.id).unwrap(),
850- "feature",
851- );
852- record_push(
853- &state,
854- &demo.id,
855- &demo.owner_id,
856- "feature",
857- Duration::from_secs(300),
858- )
859- .await;
860- state
861- .store
862- .create_pull(
863- &demo.id,
864- &demo.owner_id,
865- "Add feature",
866- "",
867- "main",
868- &demo.id,
869- "feature",
870- OID,
871- OID,
872- )
873- .await
874- .unwrap();
875- let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
876-
877- let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
878- assert_eq!(status, 200);
879- assert!(!body.contains(BANNER), "{body}");
880- }
881-
882- #[tokio::test]
883- async fn other_users_push_shows_no_banner() {
884- let dir = tempfile::tempdir().unwrap();
885- let (router, state) = fixture(dir.path()).await;
886- let demo = demo_repo(&state).await;
887- let bob = state
888- .store
889- .create_user("bob", None, "x", false)
890- .await
891- .unwrap();
892- make_branch(
893- &repo_path(&state.config.data_dir, &demo.id).unwrap(),
894- "feature",
895- );
896- record_push(
897- &state,
898- &demo.id,
899- &bob.id,
900- "feature",
901- Duration::from_secs(300),
902- )
903- .await;
904- let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
905-
906- let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
907- assert_eq!(status, 200);
908- assert!(!body.contains(BANNER), "{body}");
909- }
910-
911- #[tokio::test]
912- async fn anonymous_viewer_sees_no_banner() {
913- let dir = tempfile::tempdir().unwrap();
914- let (router, state) = fixture(dir.path()).await;
915- let demo = demo_repo(&state).await;
916- make_branch(
917- &repo_path(&state.config.data_dir, &demo.id).unwrap(),
918- "feature",
919- );
920- record_push(
921- &state,
922- &demo.id,
923- &demo.owner_id,
924- "feature",
925- Duration::from_secs(300),
926- )
927- .await;
928-
929- let (status, body) = get_as(&router, "/tahinli/demo", None).await;
930- assert_eq!(status, 200);
931- assert!(!body.contains(BANNER), "{body}");
932- }
933-
934- #[tokio::test]
935- async fn fork_push_links_to_parent_compare() {
936- let dir = tempfile::tempdir().unwrap();
937- let (router, state) = fixture(dir.path()).await;
938- let demo = demo_repo(&state).await;
939- let bob = state
940- .store
941- .create_user("bob", None, "x", false)
942- .await
943- .unwrap();
944- let fork = state
945- .store
946- .create_fork(&demo, &bob.id, "demo")
947- .await
948- .unwrap();
949- let fork_path = repo_path(&state.config.data_dir, &fork.id).unwrap();
950- init_bare(&state.git, &fork_path, "main").await.unwrap();
951- let demo_path = repo_path(&state.config.data_dir, &demo.id).unwrap();
952- git(
953- &fork_path,
954- &[
955- "fetch",
956- "-q",
957- demo_path.to_str().unwrap(),
958- "refs/heads/main:refs/heads/main",
959- ],
960- );
961- make_branch(&fork_path, "feature");
962- record_push(
963- &state,
964- &fork.id,
965- &bob.id,
966- "feature",
967- Duration::from_secs(300),
968- )
969- .await;
970- let cookie = sign_in(&state, &bob.id, "bob-token").await;
971-
972- // On the parent, the viewer's fork branch compares as owner:branch.
973- let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
974- assert_eq!(status, 200);
975- assert!(body.contains("compare/main...bob%3Afeature"), "{body}");
976-
977- // On the fork itself, the link goes to the parent's compare page.
978- let (status, body) = get_as(&router, "/bob/demo", Some(&cookie)).await;
979- assert_eq!(status, 200);
980- assert!(
981- body.contains("/tahinli/demo/compare/main...bob%3Afeature"),
982- "{body}"
983- );
984- }
985-}
crates/forge-web/src/pages/repo_ctx.rs → crates/forge-web-pages/src/pages/repo_ctx.rsrenamed+0 -0
crates/forge-web/src/pages/repo_mirrors.rs → crates/forge-web-pages/src/pages/repo_mirrors.rsrenamed+0 -0
crates/forge-web/src/pages/repo_rename.rs → crates/forge-web-pages/src/pages/repo_rename.rsrenamed+1 -1
@@ -50,7 +50,7 @@ struct TransferForm {
50 /// The Rename topic of the danger zone: the form opens in place. `error` is a refused name, and the50 /// The Rename topic of the danger zone: the form opens in place. `error` is a refused name, and the
51 /// form opens with it and keeps the typed `name`.51 /// form opens with it and keeps the typed `name`.
52 #[component]52 #[component]
53-pub(crate) async fn rename_section(53+pub async fn rename_section(
54 cx: &Cx,54 cx: &Cx,
55 lang: Lang,55 lang: Lang,
56 title: String,56 title: String,
crates/forge-web/src/pages/repo_security.rs → crates/forge-web-pages/src/pages/repo_security.rsrenamed+1 -1
@@ -71,7 +71,7 @@ fn security_href(title: &str) -> String {
71 }71 }
72 72
73 /// Whether the viewer may manage alerts: Write, Maintain or Admin on the repo, or its owner.73 /// Whether the viewer may manage alerts: Write, Maintain or Admin on the repo, or its owner.
74-pub(crate) fn can_write(ctx: &RepoCtx) -> bool {74+pub fn can_write(ctx: &RepoCtx) -> bool {
75 let actor = ctx.viewer.as_ref().map(|(user, _)| user);75 let actor = ctx.viewer.as_ref().map(|(user, _)| user);
76 authorize(actor, &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok()76 authorize(actor, &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_ok()
77 }77 }
crates/forge-web/src/pages/repo_settings.rs → crates/forge-web-pages/src/pages/repo_settings.rsrenamed+12 -12
@@ -51,7 +51,7 @@ path_param!(repo);
51 51
52 /// The `?section=` query of the settings page. Unknown values show General.52 /// The `?section=` query of the settings page. Unknown values show General.
53 #[query_params(error = bad_request)]53 #[query_params(error = bad_request)]
54-pub(crate) struct SectionQuery {54+pub struct SectionQuery {
55 section: Option<String>,55 section: Option<String>,
56 }56 }
57 57
@@ -196,7 +196,7 @@ pub fn take_notice(cx: &Cx) -> Option<String> {
196 }196 }
197 197
198 /// Sets the one-line notice shown on the next settings page view.198 /// Sets the one-line notice shown on the next settings page view.
199-pub(crate) fn set_settings_notice(cx: &Cx, word: &'static str) {199+pub fn set_settings_notice(cx: &Cx, word: &'static str) {
200 cookies(cx).add(200 cookies(cx).add(
201 Cookie::build((SETTINGS_NOTICE_COOKIE, word))201 Cookie::build((SETTINGS_NOTICE_COOKIE, word))
202 .path("/")202 .path("/")
@@ -272,16 +272,16 @@ pub async fn notice_banner_for(cx: &Cx, lang: Lang, title: Option<String>) -> Re
272 272
273 /// What the danger zone's forms show when one came back with an error: the drafts the viewer typed and273 /// What the danger zone's forms show when one came back with an error: the drafts the viewer typed and
274 /// the error each form got. A fresh page has the repo's own name in the rename form and nothing else.274 /// the error each form got. A fresh page has the repo's own name in the rename form and nothing else.
275-pub(crate) struct DangerForms {275+pub struct DangerForms {
276- pub(crate) rename_name: String,276+ pub rename_name: String,
277- pub(crate) rename_error: Option<String>,277+ pub rename_error: Option<String>,
278- pub(crate) transfer_owner: String,278+ pub transfer_owner: String,
279- pub(crate) transfer_error: Option<String>,279+ pub transfer_error: Option<String>,
280- pub(crate) delete_error: Option<String>,280+ pub delete_error: Option<String>,
281 }281 }
282 282
283 impl DangerForms {283 impl DangerForms {
284- pub(crate) fn fresh(ctx: &RepoCtx) -> Self {284+ pub fn fresh(ctx: &RepoCtx) -> Self {
285 Self {285 Self {
286 rename_name: ctx.repo.name.clone(),286 rename_name: ctx.repo.name.clone(),
287 rename_error: None,287 rename_error: None,
@@ -905,7 +905,7 @@ struct SettingsView {
905 905
906 /// What a settings page shows: its section, a notice, a rule draft and the danger zone's forms. A906 /// What a settings page shows: its section, a notice, a rule draft and the danger zone's forms. A
907 /// page drawn again after a refused POST passes what the viewer had typed.907 /// page drawn again after a refused POST passes what the viewer had typed.
908-pub(crate) struct Shown {908+pub struct Shown {
909 section: &'static str,909 section: &'static str,
910 notice: Option<(K, bool)>,910 notice: Option<(K, bool)>,
911 draft: Option<RuleDraft>,911 draft: Option<RuleDraft>,
@@ -914,7 +914,7 @@ pub(crate) struct Shown {
914 914
915 impl Shown {915 impl Shown {
916 /// The danger zone, with its forms as they came back.916 /// The danger zone, with its forms as they came back.
917- pub(crate) fn danger(danger: DangerForms) -> Self {917+ pub fn danger(danger: DangerForms) -> Self {
918 Self {918 Self {
919 section: "danger",919 section: "danger",
920 notice: None,920 notice: None,
@@ -926,7 +926,7 @@ impl Shown {
926 926
927 /// Draws the settings page at `shown.section`. The page and every POST that is refused draw through927 /// Draws the settings page at `shown.section`. The page and every POST that is refused draw through
928 /// here, so a refused form comes back as the same page with its message.928 /// here, so a refused form comes back as the same page with its message.
929-pub(crate) async fn render_settings(929+pub async fn render_settings(
930 cx: &Cx,930 cx: &Cx,
931 ctx: RepoCtx,931 ctx: RepoCtx,
932 user: User,932 user: User,
crates/forge-web/src/pages/repo_settings_live.rs → crates/forge-web-pages/src/pages/repo_settings_live.rsrenamed+0 -0
crates/forge-web/src/pages/repo_side.rs → crates/forge-web-pages/src/pages/repo_side.rsrenamed+0 -0
crates/forge-web/src/pages/repo_transfer.rs → crates/forge-web-pages/src/pages/repo_transfer.rsrenamed+5 -5
@@ -53,7 +53,7 @@ fn summary_text(lang: Lang, transfer: &PendingTransfer) -> TransferSummary {
53 }53 }
54 54
55 /// The pending-transfer sentence, with its expiry as a live relative time between two parts.55 /// The pending-transfer sentence, with its expiry as a live relative time between two parts.
56-pub(crate) struct TransferSummary {56+pub struct TransferSummary {
57 before: String,57 before: String,
58 expires_at: String,58 expires_at: String,
59 after: &'static str,59 after: &'static str,
@@ -62,7 +62,7 @@ pub(crate) struct TransferSummary {
62 /// The open transfer of a repo as the danger zone shows it: its sentence, and the action forms the62 /// The open transfer of a repo as the danger zone shows it: its sentence, and the action forms the
63 /// viewer may use. An action is `None` when hidden.63 /// viewer may use. An action is `None` when hidden.
64 #[derive(Default)]64 #[derive(Default)]
65-pub(crate) struct TransferStatus {65+pub struct TransferStatus {
66 summary: Option<TransferSummary>,66 summary: Option<TransferSummary>,
67 accept: Option<String>,67 accept: Option<String>,
68 decline: Option<String>,68 decline: Option<String>,
@@ -71,7 +71,7 @@ pub(crate) struct TransferStatus {
71 71
72 /// Reads the open transfer of the repo for the viewer. Only the danger zone shows it, to a viewer who72 /// Reads the open transfer of the repo for the viewer. Only the danger zone shows it, to a viewer who
73 /// may delete the repo, so cancel is always offered when there is one.73 /// may delete the repo, so cancel is always offered when there is one.
74-pub(crate) async fn transfer_status(74+pub async fn transfer_status(
75 state: &AppState,75 state: &AppState,
76 lang: Lang,76 lang: Lang,
77 repo_id: &str,77 repo_id: &str,
@@ -93,7 +93,7 @@ pub(crate) async fn transfer_status(
93 /// starts one (`POST /{owner}/{repo}/settings/transfer`), which opens in place. A form that came back93 /// starts one (`POST /{owner}/{repo}/settings/transfer`), which opens in place. A form that came back
94 /// with an error opens with it.94 /// with an error opens with it.
95 #[component]95 #[component]
96-pub(crate) async fn transfer_section(96+pub async fn transfer_section(
97 cx: &Cx,97 cx: &Cx,
98 lang: Lang,98 lang: Lang,
99 title: String,99 title: String,
@@ -278,7 +278,7 @@ struct InboxRow {
278 /// none. The forms post to `/-/transfers/{id}/...`, so they work for a target who cannot read a278 /// none. The forms post to `/-/transfers/{id}/...`, so they work for a target who cannot read a
279 /// private repo.279 /// private repo.
280 #[component]280 #[component]
281-pub(crate) async fn transfer_list_for(281+pub async fn transfer_list_for(
282 cx: &Cx,282 cx: &Cx,
283 lang: Lang,283 lang: Lang,
284 transfers: Vec<PendingTransfer>,284 transfers: Vec<PendingTransfer>,
crates/forge-web/src/pages/star.rs → crates/forge-web-pages/src/pages/star.rsrenamed+1 -1
@@ -57,7 +57,7 @@ async fn set_starred(cx: &Cx, csrf: &str, starred: bool) -> Result<SeeOther> {
57 /// The Referer as a path to return to: its path and query when it points at this host, or the57 /// The Referer as a path to return to: its path and query when it points at this host, or the
58 /// referer itself when it is already a local relative path. `None` for anything else, including a58 /// referer itself when it is already a local relative path. `None` for anything else, including a
59 /// missing or foreign Referer.59 /// missing or foreign Referer.
60-pub(crate) fn return_path(cx: &Cx) -> Option<String> {60+pub fn return_path(cx: &Cx) -> Option<String> {
61 let headers = headers(cx);61 let headers = headers(cx);
62 let referer = headers.get(REFERER)?.to_str().ok()?;62 let referer = headers.get(REFERER)?.to_str().ok()?;
63 let candidate = match referer.parse::<http::Uri>().ok()? {63 let candidate = match referer.parse::<http::Uri>().ok()? {
crates/forge-web/src/pages/tree.rs → crates/forge-web-pages/src/pages/tree.rsrenamed+1 -1
@@ -227,7 +227,7 @@ pub fn entry_rows(
227 /// The account a commit's author address belongs to: a verified address of any user, or else the227 /// The account a commit's author address belongs to: a verified address of any user, or else the
228 /// address the repo's owner has on their account, verified or not, since an instance without mail228 /// address the repo's owner has on their account, verified or not, since an instance without mail
229 /// cannot verify one and only people the owner let in can push here.229 /// cannot verify one and only people the owner let in can push here.
230-pub(crate) async fn author_account(230+pub async fn author_account(
231 state: &AppState,231 state: &AppState,
232 repo: &RepoRow,232 repo: &RepoRow,
233 email: &str,233 email: &str,
crates/forge-web/src/pages/wiki.rs → crates/forge-web-pages/src/pages/wiki.rsrenamed+3 -3
@@ -66,12 +66,12 @@ where
66 }66 }
67 67
68 /// The wiki directory of the repo, whether or not it exists yet.68 /// The wiki directory of the repo, whether or not it exists yet.
69-pub(crate) fn wiki_dir(state: &AppState, ctx: &RepoCtx) -> Result<PathBuf> {69+pub fn wiki_dir(state: &AppState, ctx: &RepoCtx) -> Result<PathBuf> {
70 Ok(wiki_path(&state.config.data_dir, &ctx.repo.id).map_err(forge_core::Error::from)?)70 Ok(wiki_path(&state.config.data_dir, &ctx.repo.id).map_err(forge_core::Error::from)?)
71 }71 }
72 72
73 /// 404 unless the repo's wiki is on. The header tab is hidden in the same case.73 /// 404 unless the repo's wiki is on. The header tab is hidden in the same case.
74-pub(crate) async fn ensure_enabled(state: &AppState, ctx: &RepoCtx) -> Result<()> {74+pub async fn ensure_enabled(state: &AppState, ctx: &RepoCtx) -> Result<()> {
75 if state.store.wiki_enabled(&ctx.repo.id).await? {75 if state.store.wiki_enabled(&ctx.repo.id).await? {
76 Ok(())76 Ok(())
77 } else {77 } else {
@@ -770,7 +770,7 @@ async fn save(cx: &Cx, ctx: &RepoCtx, form: &EditForm, name: &str) -> Result<Sav
770 /// The Wiki feature in the Features topic of the General settings page: one switch that submits on770 /// The Wiki feature in the Features topic of the General settings page: one switch that submits on
771 /// change (`data-autosubmit`), then its hint. `enabled` is the current state.771 /// change (`data-autosubmit`), then its hint. `enabled` is the current state.
772 #[component]772 #[component]
773-pub(crate) async fn wiki_switch(773+pub async fn wiki_switch(
774 cx: &Cx,774 cx: &Cx,
775 action: String,775 action: String,
776 csrf: String,776 csrf: String,
crates/forge-web/src/pages/wiki_live.rs → crates/forge-web-pages/src/pages/wiki_live.rsrenamed+0 -0
crates/forge-web-repo/Cargo.tomladded+48 -0
@@ -0,0 +1,48 @@
1+[package]
2+name = "forge-web-repo"
3+description = "forge code, pull request, discussion and issue view pages"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[dependencies]
10+forge-web-app.workspace = true
11+forge-web-pages.workspace = true
12+forge-core.workspace = true
13+forge-git.workspace = true
14+forge-web-base.workspace = true
15+topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
16+tokio.workspace = true
17+futures-util.workspace = true
18+bytes.workspace = true
19+http.workspace = true
20+http-body-util.workspace = true
21+serde.workspace = true
22+serde_json.workspace = true
23+form_urlencoded.workspace = true
24+jiff.workspace = true
25+tracing.workspace = true
26+tokio-util = { workspace = true, features = ["io"] }
27+http-body.workspace = true
28+hex.workspace = true
29+nix = { workspace = true }
30+sha2.workspace = true
31+time.workspace = true
32+reqwest = { workspace = true }
33+multer.workspace = true
34+ulid.workspace = true
35+zip = { workspace = true }
36+tar.workspace = true
37+p256.workspace = true
38+
39+
40+[dev-dependencies]
41+forge-web-pages = { workspace = true, features = ["test-support"] }
42+forge-web-app = { workspace = true, features = ["test-support"] }
43+tempfile.workspace = true
44+image = { workspace = true }
45+scraper = { workspace = true }
46+
47+[lints]
48+workspace = true
crates/forge-web-repo/src/lib.rsadded+13 -0
@@ -0,0 +1,13 @@
1+//! forge pages.
2+
3+#![recursion_limit = "256"]
4+
5+#[cfg(test)]
6+pub(crate) use forge_web_app::test_support;
7+pub(crate) use forge_web_app::{
8+ api, audit, auth, automerge, blobs, ci, i18n, internal, layers, lfs, lfs_pointer, live, merge,
9+ merge_queue, mirrors, notify, post_update, raw, render, signatures, state, templates, views,
10+ web_push, webhooks,
11+};
12+
13+pub mod pages;
crates/forge-web/src/pages/archive.rs → crates/forge-web-repo/src/pages/archive.rsrenamed+0 -0
crates/forge-web/src/pages/authoring.rs → crates/forge-web-repo/src/pages/authoring.rsrenamed+0 -0
crates/forge-web/src/pages/authoring_tests.rs → crates/forge-web-repo/src/pages/authoring_tests.rsrenamed+0 -0
crates/forge-web/src/pages/blame.rs → crates/forge-web-repo/src/pages/blame.rsrenamed+0 -0
crates/forge-web/src/pages/blob.rs → crates/forge-web-repo/src/pages/blob.rsrenamed+0 -0
crates/forge-web/src/pages/branches.rs → crates/forge-web-repo/src/pages/branches.rsrenamed+0 -0
crates/forge-web/src/pages/browse_tests.rs → crates/forge-web-repo/src/pages/browse_tests.rsrenamed+0 -0
crates/forge-web/src/pages/ci_badge.rs → crates/forge-web-repo/src/pages/ci_badge.rsrenamed+0 -0
crates/forge-web/src/pages/ci_tests.rs → crates/forge-web-repo/src/pages/ci_tests.rsrenamed+0 -0
crates/forge-web/src/pages/code_search.rs → crates/forge-web-repo/src/pages/code_search.rsrenamed+0 -0
crates/forge-web/src/pages/commit.rs → crates/forge-web-repo/src/pages/commit.rsrenamed+0 -0
crates/forge-web/src/pages/commits.rs → crates/forge-web-repo/src/pages/commits.rsrenamed+0 -0
crates/forge-web/src/pages/compare.rs → crates/forge-web-repo/src/pages/compare.rsrenamed+0 -0
crates/forge-web/src/pages/discussion_actions.rs → crates/forge-web-repo/src/pages/discussion_actions.rsrenamed+0 -0
crates/forge-web/src/pages/discussion_live.rs → crates/forge-web-repo/src/pages/discussion_live.rsrenamed+0 -0
crates/forge-web/src/pages/discussion_live_tests.rs → crates/forge-web-repo/src/pages/discussion_live_tests.rsrenamed+0 -0
crates/forge-web/src/pages/discussion_view.rs → crates/forge-web-repo/src/pages/discussion_view.rsrenamed+0 -0
crates/forge-web/src/pages/discussions.rs → crates/forge-web-repo/src/pages/discussions.rsrenamed+0 -0
crates/forge-web/src/pages/fork.rs → crates/forge-web-repo/src/pages/fork.rsrenamed+0 -0
crates/forge-web/src/pages/issue_meta_tests.rs → crates/forge-web-repo/src/pages/issue_meta_tests.rsrenamed+0 -0
crates/forge-web/src/pages/issue_pin.rs → crates/forge-web-repo/src/pages/issue_pin.rsrenamed+0 -0
crates/forge-web/src/pages/issue_pin_tests.rs → crates/forge-web-repo/src/pages/issue_pin_tests.rsrenamed+0 -0
crates/forge-web/src/pages/issue_view.rs → crates/forge-web-repo/src/pages/issue_view.rsrenamed+0 -0
crates/forge-web/src/pages/labels_css.rs → crates/forge-web-repo/src/pages/labels_css.rsrenamed+0 -0
crates/forge-web/src/pages/labels_page.rs → crates/forge-web-repo/src/pages/labels_page.rsrenamed+0 -0
crates/forge-web/src/pages/merge_queue.rs → crates/forge-web-repo/src/pages/merge_queue.rsrenamed+0 -0
crates/forge-web/src/pages/milestones_page.rs → crates/forge-web-repo/src/pages/milestones_page.rsrenamed+0 -0
crates/forge-web-repo/src/pages/mod.rsadded+56 -0
@@ -0,0 +1,56 @@
1+//! Server-rendered pages.
2+
3+pub use forge_web_pages::pages::*;
4+
5+pub mod archive;
6+pub mod authoring;
7+#[cfg(test)]
8+mod authoring_tests;
9+pub mod blame;
10+pub mod blob;
11+pub mod branches;
12+#[cfg(test)]
13+mod browse_tests;
14+pub mod ci_badge;
15+#[cfg(test)]
16+mod ci_tests;
17+pub mod code_search;
18+pub mod commit;
19+pub mod commits;
20+pub mod compare;
21+pub mod discussion_actions;
22+pub mod discussion_live;
23+#[cfg(test)]
24+mod discussion_live_tests;
25+pub mod discussion_view;
26+pub mod discussions;
27+pub mod fork;
28+#[cfg(test)]
29+mod issue_meta_tests;
30+pub mod issue_pin;
31+#[cfg(test)]
32+mod issue_pin_tests;
33+pub mod issue_view;
34+pub mod labels_css;
35+pub mod labels_page;
36+pub mod merge_queue;
37+pub mod milestones_page;
38+pub mod pull_branch;
39+pub mod pull_files;
40+pub mod pull_flow;
41+pub mod pull_view;
42+pub mod pulls_list;
43+pub mod pulls_merge;
44+pub mod push;
45+pub mod reactions;
46+#[cfg(test)]
47+mod reactions_tests;
48+pub mod repo_collaborators;
49+pub mod repo_scrub;
50+pub mod repo_secrets;
51+#[cfg(test)]
52+mod repo_settings_live_tests;
53+pub mod repo_webhooks;
54+pub mod review_requests;
55+#[cfg(test)]
56+mod security_tab_tests;
crates/forge-web/src/pages/pull_branch.rs → crates/forge-web-repo/src/pages/pull_branch.rsrenamed+0 -0
crates/forge-web/src/pages/pull_files.rs → crates/forge-web-repo/src/pages/pull_files.rsrenamed+0 -0
crates/forge-web/src/pages/pull_flow.rs → crates/forge-web-repo/src/pages/pull_flow.rsrenamed+0 -0
crates/forge-web/src/pages/pull_view.rs → crates/forge-web-repo/src/pages/pull_view.rsrenamed+0 -0
crates/forge-web/src/pages/pulls_list.rs → crates/forge-web-repo/src/pages/pulls_list.rsrenamed+0 -0
crates/forge-web/src/pages/pulls_merge.rs → crates/forge-web-repo/src/pages/pulls_merge.rsrenamed+0 -0
crates/forge-web/src/pages/push.rs → crates/forge-web-repo/src/pages/push.rsrenamed+5 -4
@@ -228,10 +228,11 @@ fn changed_event() -> Result<Event> {
228 228
229 /// The service worker. It must sit at the origin root to control every page, so it has its own229 /// The service worker. It must sit at the origin root to control every page, so it has its own
230 /// route rather than the immutable `/assets` ones. Revalidated on each load.230 /// route rather than the immutable `/assets` ones. Revalidated on each load.
231-const SW_JS: &str = include_str!("../../assets/sw.js");231+const SW_JS: &str = include_str!("../../../forge-web/assets/sw.js");
232-const ICON_192: &[u8] = include_bytes!("../../assets/icons/icon-192.png");232+const ICON_192: &[u8] = include_bytes!("../../../forge-web/assets/icons/icon-192.png");
233-const ICON_512: &[u8] = include_bytes!("../../assets/icons/icon-512.png");233+const ICON_512: &[u8] = include_bytes!("../../../forge-web/assets/icons/icon-512.png");
234-const APPLE_TOUCH_ICON: &[u8] = include_bytes!("../../assets/icons/apple-touch-icon.png");234+const APPLE_TOUCH_ICON: &[u8] =
235+ include_bytes!("../../../forge-web/assets/icons/apple-touch-icon.png");
235 236
236 /// The web app manifest: installing Forge from the browser gives a standalone app with these icons.237 /// The web app manifest: installing Forge from the browser gives a standalone app with these icons.
237 const MANIFEST: &str = r##"{238 const MANIFEST: &str = r##"{
crates/forge-web/src/pages/reactions.rs → crates/forge-web-repo/src/pages/reactions.rsrenamed+0 -0
crates/forge-web/src/pages/reactions_tests.rs → crates/forge-web-repo/src/pages/reactions_tests.rsrenamed+0 -0
crates/forge-web/src/pages/repo_collaborators.rs → crates/forge-web-repo/src/pages/repo_collaborators.rsrenamed+0 -0
crates/forge-web/src/pages/repo_scrub.rs → crates/forge-web-repo/src/pages/repo_scrub.rsrenamed+0 -0
crates/forge-web/src/pages/repo_secrets.rs → crates/forge-web-repo/src/pages/repo_secrets.rsrenamed+0 -0
crates/forge-web/src/pages/repo_settings_live_tests.rs → crates/forge-web-repo/src/pages/repo_settings_live_tests.rsrenamed+0 -0
crates/forge-web/src/pages/repo_webhooks.rs → crates/forge-web-repo/src/pages/repo_webhooks.rsrenamed+0 -0
crates/forge-web/src/pages/review_requests.rs → crates/forge-web-repo/src/pages/review_requests.rsrenamed+0 -0
crates/forge-web/src/pages/security_tab_tests.rs → crates/forge-web-repo/src/pages/security_tab_tests.rsrenamed+0 -0
crates/forge-web/Cargo.tomlmodified+4 -24
@@ -12,57 +12,37 @@ path = "src/main.rs"
12 12
13 [dependencies]13 [dependencies]
14 forge-core.workspace = true14 forge-core.workspace = true
15-ipnet.workspace = true
16 forge-git.workspace = true15 forge-git.workspace = true
17 forge-ssh.workspace = true16 forge-ssh.workspace = true
18 forge-ci.workspace = true17 forge-ci.workspace = true
19 forge-web-base.workspace = true18 forge-web-base.workspace = true
20 forge-web-app.workspace = true19 forge-web-app.workspace = true
20+forge-web-pages.workspace = true
21+forge-web-account.workspace = true
22+forge-web-repo.workspace = true
21 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }23 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
22 tokio.workspace = true24 tokio.workspace = true
23 futures-util.workspace = true25 futures-util.workspace = true
24 bytes.workspace = true26 bytes.workspace = true
25 http.workspace = true27 http.workspace = true
26-http-body-util.workspace = true
27-async-compression.workspace = true
28-serde.workspace = true
29 serde_json.workspace = true28 serde_json.workspace = true
30-form_urlencoded.workspace = true
31-jiff.workspace = true
32 base64.workspace = true29 base64.workspace = true
33-subtle.workspace = true
34 tracing.workspace = true30 tracing.workspace = true
35 tracing-subscriber = { workspace = true, features = ["env-filter"] }31 tracing-subscriber = { workspace = true, features = ["env-filter"] }
36-tokio-util = { workspace = true, features = ["io"] }
37-http-body.workspace = true
38 rpassword.workspace = true32 rpassword.workspace = true
39 rand.workspace = true33 rand.workspace = true
40 hex.workspace = true34 hex.workspace = true
41 nix = { workspace = true }35 nix = { workspace = true }
42-sha2.workspace = true
43 time.workspace = true36 time.workspace = true
44 reqwest = { workspace = true }37 reqwest = { workspace = true }
45-hmac.workspace = true
46-similar = { workspace = true }
47-multer.workspace = true
48-ulid.workspace = true
49 forge-runner = { workspace = true }38 forge-runner = { workspace = true }
50-lettre.workspace = true
51 zip = { workspace = true }39 zip = { workspace = true }
52 tar.workspace = true40 tar.workspace = true
53-flate2.workspace = true
54-webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "conditional-ui"] }
55-webauthn-rs-proto = "0.6.2"
56-p256.workspace = true
57-hkdf.workspace = true
58-aes-gcm.workspace = true
59 41
60 [dev-dependencies]42 [dev-dependencies]
43+forge-web-pages = { workspace = true, features = ["test-support"] }
61 forge-web-app = { workspace = true, features = ["test-support"] }44 forge-web-app = { workspace = true, features = ["test-support"] }
62 tempfile.workspace = true45 tempfile.workspace = true
63-image = { workspace = true }
64-scraper = { workspace = true }
65-webauthn-authenticator-rs = { version = "0.6.2", features = ["softpasskey"] }
66 46
67 [lints]47 [lints]
68 workspace = true48 workspace = true
crates/forge-web/src/boot.rsmodified+1 -1
@@ -162,7 +162,7 @@ pub async fn serve(
162 crate::alerts::on_boot(&state).await;162 crate::alerts::on_boot(&state).await;
163 crate::ci::reaper::spawn(state.clone());163 crate::ci::reaper::spawn(state.clone());
164 crate::prune::spawn(state.clone());164 crate::prune::spawn(state.clone());
165- crate::pages::admin_health::spawn_repo_size(state.clone());165+ forge_web_account::pages::admin_health::spawn_repo_size(state.clone());
166 crate::ci::scheduled::spawn(state.clone());166 crate::ci::scheduled::spawn(state.clone());
167 167
168 // Topcoat's builder-wide compression is off because it cannot filter by content type or path.168 // Topcoat's builder-wide compression is off because it cannot filter by content type or path.
crates/forge-web/src/lib.rsdeleted+0 -1
@@ -1 +0,0 @@
1-
crates/forge-web/src/main.rsmodified+10 -9
@@ -6,17 +6,17 @@
6 6
7 #![recursion_limit = "256"]7 #![recursion_limit = "256"]
8 8
9+use forge_web_repo as _;
10+
9 // Modules that live in forge-web-base and forge-web-app, so they compile once and are not rebuilt with the pages.11 // Modules that live in forge-web-base and forge-web-app, so they compile once and are not rebuilt with the pages.
10-#[cfg(test)]
11-pub(crate) use forge_web_app::test_support;
12 pub(crate) use forge_web_app::{12 pub(crate) use forge_web_app::{
13- accent, admin_client, advisories, alerts, api, audit, auth, automerge, backup, blobs, ci,13+ admin_client, advisories, alerts, audit, auth, backup, blobs, ci, compression, exporter,
14- client_ip, compression, custom_colour, exporter, hook_cmd, i18n, importer, internal, layers,14+ hook_cmd, importer, internal, layers, lfs, live, mail, mirrors, notify_hub, packages_live,
15- lfs, lfs_pointer, live, mail, merge, merge_queue, mirrors, notify, notify_hub, oci,15+ prune, raw, replication, self_update, signatures, ssh_backend, state, throttle, web_push,
16- package_ops, packages_live, post_update, prune, raw, release_ops, render, replication,16+ webhooks,
17- repo_stats, self_update, signatures, ssh_backend, state, templates, theme, throttle, views,
18- web_push, webhooks,
19 };17 };
18+#[cfg(test)]
19+pub(crate) use forge_web_app::{test_support, views};
20 20
21 mod admin_cli;21 mod admin_cli;
22 mod boot;22 mod boot;
@@ -26,7 +26,8 @@ mod compression_route_tests;
26 mod gitea_route_tests;26 mod gitea_route_tests;
27 #[cfg(test)]27 #[cfg(test)]
28 mod importer_route_tests;28 mod importer_route_tests;
29-mod pages;29+#[cfg(test)]
30+mod page_route_tests;
30 #[cfg(test)]31 #[cfg(test)]
31 mod route_list_tests;32 mod route_list_tests;
32 #[cfg(test)]33 #[cfg(test)]
crates/forge-web/src/page_route_tests/edit_history.rsadded+303 -0
@@ -0,0 +1,303 @@
1+use forge_core::{Side, Visibility};
2+use topcoat::router::request::Request;
3+use topcoat::router::{Body, Router, to_bytes};
4+
5+use crate::auth::SESSION_COOKIE;
6+use crate::test_support::fixture::{Fixture, OWNER, REPO};
7+
8+/// Sends one request and returns `(status, body)`.
9+async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
10+ let mut req = Request::builder().method("GET").uri(uri);
11+ if let Some(token) = token {
12+ req = req.header("cookie", format!("__Host-{SESSION_COOKIE}={token}"));
13+ }
14+ let res = router.handle(req.body(Body::empty()).unwrap()).await;
15+ let status = res.status().as_u16();
16+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
17+ (status, String::from_utf8_lossy(&bytes).into_owned())
18+}
19+
20+/// The repo owner with a session whose token is `tahinli`.
21+async fn tahinli(fx: &Fixture) -> forge_core::User {
22+ let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
23+ crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
24+ owner
25+}
26+
27+async fn repo_id(fx: &Fixture) -> String {
28+ fx.store
29+ .repo_by_owner_and_name(OWNER, REPO)
30+ .await
31+ .unwrap()
32+ .unwrap()
33+ .id
34+}
35+
36+fn hex_oid(c: char) -> String {
37+ std::iter::repeat_n(c, 40).collect()
38+}
39+
40+/// Every scenario on the public repo shares one fixture. Each makes its own issue or pull and
41+/// reads its numbers from the store, so no scenario depends on another's data.
42+#[tokio::test]
43+async fn public_histories_show_diffs_markers_and_refusals() {
44+ let fx = Fixture::new(Visibility::Public).await;
45+ let owner = tahinli(&fx).await;
46+ let id = repo_id(&fx).await;
47+
48+ // A comment edited twice: a marker on the item page and two versions with diffs.
49+ let issue = fx
50+ .store
51+ .create_issue(&id, &owner.id, "bug", "body")
52+ .await
53+ .unwrap();
54+ let comment = fx
55+ .store
56+ .add_comment(&issue.id, &owner.id, "one\ntwo\nthree")
57+ .await
58+ .unwrap();
59+ fx.store
60+ .edit_comment(&comment.id, &owner.id, "one\nTWO\nthree")
61+ .await
62+ .unwrap();
63+ fx.store
64+ .edit_comment(&comment.id, &owner.id, "one\nTWO\nthree\nfour")
65+ .await
66+ .unwrap();
67+ let item = format!("/tahinli/demo/issues/{}", issue.number);
68+ let link = format!("{item}/history/comment/{}", comment.id);
69+
70+ let (status, page) = send(&fx.router, &item, None).await;
71+ assert_eq!(status, 200, "edited comment: item page");
72+ assert!(
73+ page.contains("issue-edited"),
74+ "edited comment: marker {page}"
75+ );
76+ assert!(
77+ page.contains(&format!("href=\"{link}\"")),
78+ "edited comment: link {page}"
79+ );
80+
81+ let (status, history) = send(&fx.router, &link, None).await;
82+ assert_eq!(status, 200, "edited comment: history");
83+ assert_eq!(
84+ history.matches("<article").count(),
85+ 2,
86+ "edited comment: versions {history}"
87+ );
88+ assert!(
89+ history.contains("diff-line del"),
90+ "edited comment: del {history}"
91+ );
92+ assert!(history.contains("-two"), "edited comment: -two {history}");
93+ assert!(history.contains("+TWO"), "edited comment: +TWO {history}");
94+ assert!(history.contains("+four"), "edited comment: +four {history}");
95+ assert!(
96+ history.contains("tahinli"),
97+ "edited comment: editor {history}"
98+ );
99+
100+ // A comment that was never edited has no marker.
101+ let plain = fx
102+ .store
103+ .create_issue(&id, &owner.id, "plain", "body")
104+ .await
105+ .unwrap();
106+ fx.store
107+ .add_comment(&plain.id, &owner.id, "plain")
108+ .await
109+ .unwrap();
110+ let (status, page) = send(
111+ &fx.router,
112+ &format!("/tahinli/demo/issues/{}", plain.number),
113+ None,
114+ )
115+ .await;
116+ assert_eq!(status, 200, "unedited comment: item page");
117+ assert!(
118+ !page.contains("issue-edited"),
119+ "unedited comment: no marker {page}"
120+ );
121+
122+ // An issue body and title edit: the old title and the changed lines show.
123+ let titled = fx
124+ .store
125+ .create_issue(&id, &owner.id, "old title", "a\nb\nc")
126+ .await
127+ .unwrap();
128+ fx.store
129+ .edit_issue(&titled.id, &owner.id, "new title", "a\nB\nc")
130+ .await
131+ .unwrap();
132+ let link = format!(
133+ "/tahinli/demo/issues/{}/history/issue/{}",
134+ titled.number, titled.id
135+ );
136+ let (status, page) = send(
137+ &fx.router,
138+ &format!("/tahinli/demo/issues/{}", titled.number),
139+ None,
140+ )
141+ .await;
142+ assert_eq!(status, 200, "body edit: item page");
143+ assert!(
144+ page.contains(&format!("href=\"{link}\"")),
145+ "body edit: link {page}"
146+ );
147+ let (status, history) = send(&fx.router, &link, None).await;
148+ assert_eq!(status, 200, "body edit: history");
149+ assert!(
150+ history.contains("Title: old title"),
151+ "body edit: title {history}"
152+ );
153+ assert!(history.contains("-b"), "body edit: -b {history}");
154+ assert!(history.contains("+B"), "body edit: +B {history}");
155+
156+ // A comment on one issue is not found under another issue's URL.
157+ let other = fx
158+ .store
159+ .create_issue(&id, &owner.id, "second", "body")
160+ .await
161+ .unwrap();
162+ let other_comment = fx
163+ .store
164+ .add_comment(&other.id, &owner.id, "x")
165+ .await
166+ .unwrap();
167+ fx.store
168+ .edit_comment(&other_comment.id, &owner.id, "y")
169+ .await
170+ .unwrap();
171+ let (status, _) = send(
172+ &fx.router,
173+ &format!(
174+ "/tahinli/demo/issues/{}/history/comment/{}",
175+ issue.number, other_comment.id
176+ ),
177+ None,
178+ )
179+ .await;
180+ assert_eq!(status, 404, "wrong item: not found");
181+ let (status, _) = send(
182+ &fx.router,
183+ &format!(
184+ "/tahinli/demo/issues/{}/history/comment/{}",
185+ other.number, other_comment.id
186+ ),
187+ None,
188+ )
189+ .await;
190+ assert_eq!(status, 200, "right item: found");
191+
192+ // An unknown kind and a missing target are both not found.
193+ let (status, _) = send(
194+ &fx.router,
195+ &format!(
196+ "/tahinli/demo/issues/{}/history/label/{}",
197+ issue.number, issue.id
198+ ),
199+ None,
200+ )
201+ .await;
202+ assert_eq!(status, 404, "unknown kind");
203+ let (status, _) = send(
204+ &fx.router,
205+ &format!(
206+ "/tahinli/demo/issues/{}/history/comment/missing",
207+ issue.number
208+ ),
209+ None,
210+ )
211+ .await;
212+ assert_eq!(status, 404, "missing target");
213+
214+ // Review comment history on a pull request, and not under the issue URL of the same number.
215+ let pr = fx
216+ .store
217+ .create_pull(
218+ &id,
219+ &owner.id,
220+ "change",
221+ "",
222+ "main",
223+ &id,
224+ "feature",
225+ &hex_oid('a'),
226+ &hex_oid('b'),
227+ )
228+ .await
229+ .unwrap();
230+ let review = fx
231+ .store
232+ .add_review_comment(
233+ &pr.issue.id,
234+ &owner.id,
235+ false,
236+ "a.txt",
237+ Side::New,
238+ 2,
239+ &hex_oid('a'),
240+ "+x",
241+ "first",
242+ )
243+ .await
244+ .unwrap();
245+ fx.store
246+ .edit_review_comment(&review.id, "second")
247+ .await
248+ .unwrap();
249+ let link = format!(
250+ "/tahinli/demo/pulls/{}/history/review_comment/{}",
251+ pr.issue.number, review.id
252+ );
253+ let (status, history) = send(&fx.router, &link, None).await;
254+ assert_eq!(status, 200, "review comment: history");
255+ assert!(
256+ history.contains("-first"),
257+ "review comment: -first {history}"
258+ );
259+ assert!(
260+ history.contains("+second"),
261+ "review comment: +second {history}"
262+ );
263+ let (status, _) = send(
264+ &fx.router,
265+ &format!(
266+ "/tahinli/demo/issues/{}/history/review_comment/{}",
267+ pr.issue.number, review.id
268+ ),
269+ None,
270+ )
271+ .await;
272+ assert_eq!(status, 404, "review comment under the issue URL");
273+}
274+
275+#[tokio::test]
276+async fn private_repo_is_not_found_for_anonymous() {
277+ let fx = Fixture::new(Visibility::Private).await;
278+ let owner = tahinli(&fx).await;
279+ let id = repo_id(&fx).await;
280+ let issue = fx
281+ .store
282+ .create_issue(&id, &owner.id, "secret", "body")
283+ .await
284+ .unwrap();
285+ fx.store
286+ .edit_issue(&issue.id, &owner.id, "secret", "body 2")
287+ .await
288+ .unwrap();
289+ let (status, _) = send(
290+ &fx.router,
291+ &format!("/tahinli/demo/issues/1/history/issue/{}", issue.id),
292+ None,
293+ )
294+ .await;
295+ assert_eq!(status, 404);
296+ let (status, _) = send(
297+ &fx.router,
298+ &format!("/tahinli/demo/issues/1/history/issue/{}", issue.id),
299+ Some("tahinli"),
300+ )
301+ .await;
302+ assert_eq!(status, 200);
303+}
crates/forge-web/src/page_route_tests/mod.rsadded+6 -0
@@ -0,0 +1,6 @@
1+//! Page tests that need pages from more than one page crate.
2+
3+mod edit_history;
4+mod notifications;
5+mod pull_reviews;
6+mod repo;
crates/forge-web/src/page_route_tests/notifications.rsadded+570 -0
@@ -0,0 +1,570 @@
1+use forge_core::{Issue, Reason, Role, Store, SubState, Visibility, WatchLevel};
2+use futures_util::StreamExt;
3+use topcoat::router::request::Request;
4+use topcoat::router::{Body, Router, to_bytes};
5+
6+use crate::auth::SESSION_COOKIE;
7+
8+const CSRF: &str = "notif-test-csrf";
9+
10+struct Site {
11+ router: Router,
12+ store: Store,
13+ git: std::sync::Arc<forge_git::GitEnv>,
14+ _dir: tempfile::TempDir,
15+}
16+
17+struct Reply {
18+ status: u16,
19+ location: Option<String>,
20+ body: String,
21+}
22+
23+async fn site() -> Site {
24+ let dir = tempfile::tempdir().expect("tempdir");
25+ let state = crate::test_support::test_state(dir.path()).await;
26+ let store = state.store.clone();
27+ let git = state.git.clone();
28+ let router = crate::test_support::app_router(state);
29+ Site {
30+ router,
31+ store,
32+ git,
33+ _dir: dir,
34+ }
35+}
36+
37+/// Signs `user_id` in with `token` and returns the cookie header value.
38+async fn sign_in(store: &Store, user_id: &str, token: &str) -> String {
39+ crate::test_support::create_session(store, user_id, token, CSRF).await;
40+ format!("__Host-{SESSION_COOKIE}={token}")
41+}
42+
43+async fn call(
44+ site: &Site,
45+ method: &str,
46+ uri: &str,
47+ cookie: Option<&str>,
48+ form: Option<String>,
49+) -> Reply {
50+ let mut builder = Request::builder().method(method).uri(uri);
51+ if let Some(cookie) = cookie {
52+ builder = builder.header("cookie", cookie);
53+ }
54+ let body = match form {
55+ Some(form) => {
56+ builder = builder.header("content-type", "application/x-www-form-urlencoded");
57+ Body::from(form)
58+ }
59+ None => Body::empty(),
60+ };
61+ let res = site
62+ .router
63+ .handle(builder.body(body).expect("request"))
64+ .await;
65+ let status = res.status().as_u16();
66+ let location = res
67+ .headers()
68+ .get("location")
69+ .and_then(|v| v.to_str().ok())
70+ .map(str::to_owned);
71+ let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
72+ Reply {
73+ status,
74+ location,
75+ body: String::from_utf8_lossy(&bytes).into_owned(),
76+ }
77+}
78+
79+async fn get(site: &Site, uri: &str, cookie: Option<&str>) -> Reply {
80+ call(site, "GET", uri, cookie, None).await
81+}
82+
83+async fn post(site: &Site, uri: &str, cookie: &str, extra: &str) -> Reply {
84+ call(
85+ site,
86+ "POST",
87+ uri,
88+ Some(cookie),
89+ Some(format!("csrf={CSRF}{extra}")),
90+ )
91+ .await
92+}
93+
94+/// Tahinli owns `demo` with one issue (#1), and Bob has a notification row for it.
95+struct World {
96+ tahinli: forge_core::User,
97+ bob: forge_core::User,
98+ repo: forge_core::Repo,
99+ issue: Issue,
100+}
101+
102+async fn world(site: &Site, visibility: Visibility) -> World {
103+ let store = &site.store;
104+ let tahinli = store
105+ .create_user("tahinli", None, "x", false)
106+ .await
107+ .expect("tahinli");
108+ let bob = store
109+ .create_user("bob", None, "x", false)
110+ .await
111+ .expect("bob");
112+ let repo = store
113+ .create_repo(&tahinli.id, "demo", "", visibility, "main")
114+ .await
115+ .expect("repo");
116+ let issue = store
117+ .create_issue(&repo.id, &tahinli.id, "First", "body")
118+ .await
119+ .expect("issue");
120+ World {
121+ tahinli,
122+ bob,
123+ repo,
124+ issue,
125+ }
126+}
127+
128+async fn notify(site: &Site, w: &World, reason: Reason) {
129+ site.store
130+ .upsert_notification(
131+ &w.bob.id,
132+ &w.repo.id,
133+ &w.issue.id,
134+ reason,
135+ "comment",
136+ Some(&w.tahinli.id),
137+ )
138+ .await
139+ .expect("notification");
140+}
141+
142+async fn first_note_id(site: &Site, user_id: &str) -> String {
143+ site.store
144+ .list_notifications(user_id, false, None, 50)
145+ .await
146+ .expect("list")
147+ .first()
148+ .expect("one notification")
149+ .id
150+ .clone()
151+}
152+
153+#[tokio::test]
154+async fn inbox_lists_unread_and_all_shows_read() {
155+ let site = site().await;
156+ let w = world(&site, Visibility::Public).await;
157+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
158+ notify(&site, &w, Reason::Mention).await;
159+ let id = first_note_id(&site, &w.bob.id).await;
160+ site.store.mark_read(&w.bob.id, &id).await.expect("read");
161+
162+ let unread = get(&site, "/notifications", Some(&cookie)).await;
163+ assert_eq!(unread.status, 200);
164+ assert!(!unread.body.contains("tahinli/demo #1 First"));
165+ assert!(unread.body.contains("No unread notifications."));
166+
167+ let all = get(&site, "/notifications?all=1", Some(&cookie)).await;
168+ assert_eq!(all.status, 200);
169+ assert!(all.body.contains("tahinli/demo #1 First"));
170+ assert!(all.body.contains("mentioned"));
171+}
172+
173+#[tokio::test]
174+async fn unread_inbox_lists_unread_rows_grouped_by_repo() {
175+ let site = site().await;
176+ let w = world(&site, Visibility::Public).await;
177+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
178+ notify(&site, &w, Reason::Assign).await;
179+
180+ let page = get(&site, "/notifications", Some(&cookie)).await;
181+ assert_eq!(page.status, 200);
182+ assert!(page.body.contains("tahinli/demo #1 First"));
183+ assert!(page.body.contains("assigned"));
184+ assert!(page.body.contains("/notifications/mark_all_read?repo="));
185+ assert!(page.body.contains("Mark all as read"));
186+}
187+
188+/// Another user cannot open or mark read a row that is not theirs. The owner's open redirects
189+/// to the issue and marks the row read.
190+#[tokio::test]
191+async fn another_users_notification_is_404_and_the_owner_opens_it() {
192+ let site = site().await;
193+ let w = world(&site, Visibility::Public).await;
194+ let tahinli_cookie = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
195+ let bob_cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
196+ notify(&site, &w, Reason::Comment).await;
197+ let id = first_note_id(&site, &w.bob.id).await;
198+
199+ let res = get(
200+ &site,
201+ &format!("/notifications/{id}/open"),
202+ Some(&tahinli_cookie),
203+ )
204+ .await;
205+ assert_eq!(res.status, 404);
206+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
207+
208+ let read = post(
209+ &site,
210+ &format!("/notifications/{id}/read"),
211+ &tahinli_cookie,
212+ "",
213+ )
214+ .await;
215+ assert_eq!(read.status, 303);
216+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
217+
218+ // Bob opens his own row: it redirects to the issue and marks the row read.
219+ let res = get(
220+ &site,
221+ &format!("/notifications/{id}/open"),
222+ Some(&bob_cookie),
223+ )
224+ .await;
225+ assert_eq!(res.status, 303);
226+ assert_eq!(res.location.as_deref(), Some("/tahinli/demo/issues/1"));
227+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
228+}
229+
230+#[tokio::test]
231+async fn mark_all_read_clears_the_inbox() {
232+ let site = site().await;
233+ let w = world(&site, Visibility::Public).await;
234+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
235+ notify(&site, &w, Reason::Comment).await;
236+
237+ let res = post(&site, "/notifications/mark_all_read", &cookie, "").await;
238+ assert_eq!(res.status, 303);
239+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
240+}
241+
242+#[tokio::test]
243+async fn the_stream_sends_the_count_then_each_change() {
244+ let site = site().await;
245+ let w = world(&site, Visibility::Public).await;
246+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
247+ notify(&site, &w, Reason::Mention).await;
248+
249+ let request = Request::builder()
250+ .method("GET")
251+ .uri("/notifications/stream")
252+ .header("cookie", cookie.as_str())
253+ .body(Body::empty())
254+ .expect("request");
255+ let res = site.router.handle(request).await;
256+ assert_eq!(res.status().as_u16(), 200);
257+ assert_eq!(
258+ res.headers().get("content-type").unwrap(),
259+ "text/event-stream"
260+ );
261+ assert_eq!(res.headers().get("x-accel-buffering").unwrap(), "no");
262+
263+ let mut frames = res.into_body().into_data_stream();
264+ // The stream opens with its retry field, then the count.
265+ let retry = frames.next().await.expect("a frame").expect("data");
266+ assert!(retry.starts_with(b"retry: 1000"), "{retry:?}");
267+ let first = frames.next().await.expect("a frame").expect("data");
268+ assert_eq!(&first[..], b"event: unread\ndata: 1\n\n");
269+
270+ // Marking the row read pushes the new count to the open stream.
271+ let read = post(&site, "/notifications/mark_all_read", &cookie, "").await;
272+ assert_eq!(read.status, 303);
273+ let next = frames.next().await.expect("a frame").expect("data");
274+ assert_eq!(&next[..], b"event: unread\ndata: 0\n\n");
275+}
276+
277+#[tokio::test]
278+async fn corner_bell_shows_the_unread_count() {
279+ let site = site().await;
280+ let w = world(&site, Visibility::Public).await;
281+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
282+
283+ let none = get(&site, "/explore", Some(&cookie)).await;
284+ assert!(none.body.contains("href=\"/notifications\""));
285+ assert!(!none.body.contains("<span class=\"bell-count\">"));
286+
287+ notify(&site, &w, Reason::Mention).await;
288+ let one = get(&site, "/explore", Some(&cookie)).await;
289+ assert!(one.body.contains("<span class=\"bell-count\">1</span>"));
290+}
291+
292+#[tokio::test]
293+async fn subscription_toggles_on_an_issue_and_unknown_pull_is_404() {
294+ let site = site().await;
295+ let w = world(&site, Visibility::Public).await;
296+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
297+
298+ let res = post(
299+ &site,
300+ "/tahinli/demo/issues/1/subscription",
301+ &cookie,
302+ "&action=subscribe",
303+ )
304+ .await;
305+ assert_eq!(res.status, 303);
306+ assert_eq!(res.location.as_deref(), Some("/tahinli/demo/issues/1"));
307+ let sub = site
308+ .store
309+ .subscription(&w.bob.id, &w.issue.id)
310+ .await
311+ .expect("sub");
312+ assert_eq!(sub, Some((SubState::Subscribed, Reason::Subscribed)));
313+
314+ let page = get(&site, "/tahinli/demo/issues/1", Some(&cookie)).await;
315+ assert!(page.body.contains("value=\"unsubscribe\""));
316+
317+ post(
318+ &site,
319+ "/tahinli/demo/issues/1/subscription",
320+ &cookie,
321+ "&action=unsubscribe",
322+ )
323+ .await;
324+ let sub = site
325+ .store
326+ .subscription(&w.bob.id, &w.issue.id)
327+ .await
328+ .expect("sub");
329+ assert_eq!(sub, Some((SubState::Ignored, Reason::Subscribed)));
330+
331+ // A pull request number that does not exist is a 404 on the pulls subscription.
332+ let res = post(
333+ &site,
334+ "/tahinli/demo/pulls/1/subscription",
335+ &cookie,
336+ "&action=subscribe",
337+ )
338+ .await;
339+ assert_eq!(res.status, 404);
340+}
341+
342+#[tokio::test]
343+async fn watch_form_sets_the_level() {
344+ let site = site().await;
345+ let w = world(&site, Visibility::Public).await;
346+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
347+
348+ let res = post(&site, "/tahinli/demo/watch", &cookie, "&level=watching").await;
349+ assert_eq!(res.status, 303);
350+ assert_eq!(
351+ site.store
352+ .watch_level(&w.bob.id, &w.repo.id)
353+ .await
354+ .expect("level"),
355+ WatchLevel::Watching
356+ );
357+
358+ // The watch menu sits in the repo head on the code tab, which reads the repository.
359+ let bare = forge_git::repo::repo_path(&site.git.data_dir, &w.repo.id).expect("repo path");
360+ forge_git::repo::init_bare(&site.git, &bare, "main")
361+ .await
362+ .expect("init bare");
363+ let header = get(&site, "/tahinli/demo", Some(&cookie)).await;
364+ assert!(header.body.contains("action=\"/tahinli/demo/watch\""));
365+ assert!(header.body.contains("<details class=\"menu watch-menu\">"));
366+ assert!(!header.body.contains("<select"));
367+ // One form per level, and only the watched level is marked current.
368+ assert_eq!(header.body.matches("name=\"level\"").count(), 3);
369+ assert_eq!(
370+ header
371+ .body
372+ .matches("class=\"watch-option is-current\"")
373+ .count(),
374+ 1
375+ );
376+ assert_eq!(header.body.matches("class=\"watch-option\"").count(), 2);
377+ assert!(header.body.contains("1 watching"));
378+
379+ let bad = post(&site, "/tahinli/demo/watch", &cookie, "&level=loud").await;
380+ assert_eq!(bad.status, 400);
381+}
382+
383+#[tokio::test]
384+async fn anonymous_viewers_are_sent_to_login_and_the_stream_needs_a_session() {
385+ let site = site().await;
386+ let _w = world(&site, Visibility::Public).await;
387+ let res = get(&site, "/notifications", None).await;
388+ assert_eq!(res.status, 303);
389+ assert!(res.location.unwrap_or_default().starts_with("/login"));
390+ let stream = get(&site, "/notifications/stream", None).await;
391+ assert_eq!(stream.status, 401);
392+}
393+
394+#[tokio::test]
395+async fn row_for_a_repo_the_viewer_lost_access_to_is_hidden() {
396+ let site = site().await;
397+ let w = world(&site, Visibility::Private).await;
398+ let cookie = sign_in(&site.store, &w.bob.id, "bob-token").await;
399+ site.store
400+ .set_collaborator(&w.repo.id, &w.bob.id, Role::Read)
401+ .await
402+ .expect("collaborator");
403+ notify(&site, &w, Reason::Mention).await;
404+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 1);
405+
406+ site.store
407+ .remove_collaborator(&w.repo.id, &w.bob.id)
408+ .await
409+ .expect("remove");
410+ let page = get(&site, "/notifications?all=1", Some(&cookie)).await;
411+ assert_eq!(page.status, 200);
412+ assert!(!page.body.contains("tahinli/demo #1 First"));
413+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
414+}
415+
416+#[tokio::test]
417+async fn discussion_replies_show_in_the_inbox_and_clear_by_open_or_mark_all() {
418+ let site = site().await;
419+ let w = world(&site, Visibility::Public).await;
420+ // The world's issue takes number 1, so the discussion is #2.
421+ let discussion = site
422+ .store
423+ .create_discussion(
424+ &w.repo.id,
425+ &w.tahinli.id,
426+ forge_core::discussions::DiscussionCategory::General,
427+ "Ideas",
428+ "",
429+ )
430+ .await
431+ .expect("discussion");
432+ site.store
433+ .add_discussion_comment(&discussion.id, &w.bob.id, None, "+1", false)
434+ .await
435+ .expect("reply");
436+ let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
437+ let bob = sign_in(&site.store, &w.bob.id, "bob-token").await;
438+ let open = format!("/notifications/discussions/{}/open", discussion.id);
439+
440+ let page = get(&site, "/notifications", Some(&tahinli)).await;
441+ assert_eq!(page.status, 200);
442+ assert!(page.body.contains("Ideas"));
443+ assert!(page.body.contains(&open));
444+ assert_eq!(
445+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
446+ 1
447+ );
448+
449+ // Bob has no row for the discussion, so he cannot open it.
450+ let other = get(&site, &open, Some(&bob)).await;
451+ assert_eq!(other.status, 404);
452+
453+ let res = get(&site, &open, Some(&tahinli)).await;
454+ assert_eq!(res.status, 303);
455+ assert_eq!(res.location.as_deref(), Some("/tahinli/demo/discussions/2"));
456+ assert_eq!(
457+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
458+ 0
459+ );
460+
461+ // A second discussion, cleared by mark all read.
462+ let discussion = site
463+ .store
464+ .create_discussion(
465+ &w.repo.id,
466+ &w.tahinli.id,
467+ forge_core::discussions::DiscussionCategory::General,
468+ "Ideas",
469+ "",
470+ )
471+ .await
472+ .expect("discussion");
473+ site.store
474+ .add_discussion_comment(&discussion.id, &w.bob.id, None, "+1", false)
475+ .await
476+ .expect("reply");
477+ assert_eq!(
478+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
479+ 1
480+ );
481+
482+ let res = post(&site, "/notifications/mark_all_read", &tahinli, "").await;
483+ assert_eq!(res.status, 303);
484+ assert_eq!(
485+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
486+ 0
487+ );
488+}
489+
490+#[tokio::test]
491+async fn advisory_alerts_show_for_managers_and_open_marks_read() {
492+ let site = site().await;
493+ let w = world(&site, Visibility::Public).await;
494+ // Tahinli owns the repo, so she manages its alerts. Bob is a reader with a stale row.
495+ site.store
496+ .notify_new_alerts(&w.tahinli.id, &w.repo.id, 2)
497+ .await
498+ .expect("alerts");
499+ site.store
500+ .notify_new_alerts(&w.bob.id, &w.repo.id, 1)
501+ .await
502+ .expect("alerts");
503+ let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
504+ let bob = sign_in(&site.store, &w.bob.id, "bob-token").await;
505+ let open = format!("/notifications/advisories/{}/open", w.repo.id);
506+
507+ let page = get(&site, "/notifications", Some(&tahinli)).await;
508+ assert_eq!(page.status, 200);
509+ assert!(page.body.contains("Security alerts"));
510+ assert!(page.body.contains("2 new alerts"));
511+ assert!(page.body.contains(&open));
512+ assert_eq!(
513+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
514+ 1
515+ );
516+
517+ // Bob cannot manage the alerts: his row is hidden and marked read, as lost-access rows are.
518+ let bob_page = get(&site, "/notifications", Some(&bob)).await;
519+ assert_eq!(bob_page.status, 200);
520+ assert!(!bob_page.body.contains(&open));
521+ assert_eq!(site.store.unread_count(&w.bob.id).await.expect("count"), 0);
522+ let bob_open = get(&site, &open, Some(&bob)).await;
523+ assert_eq!(bob_open.status, 404);
524+
525+ let res = get(&site, &open, Some(&tahinli)).await;
526+ assert_eq!(res.status, 303);
527+ assert_eq!(res.location.as_deref(), Some("/tahinli/demo/security"));
528+ assert_eq!(
529+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
530+ 0
531+ );
532+}
533+
534+#[tokio::test]
535+async fn advisory_rows_are_marked_read_by_mark_read_and_mark_all() {
536+ let site = site().await;
537+ let w = world(&site, Visibility::Public).await;
538+ let tahinli = sign_in(&site.store, &w.tahinli.id, "tahinli-token").await;
539+ let read = format!("/notifications/advisories/{}/read", w.repo.id);
540+
541+ site.store
542+ .notify_new_alerts(&w.tahinli.id, &w.repo.id, 1)
543+ .await
544+ .expect("alerts");
545+ assert_eq!(
546+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
547+ 1
548+ );
549+ let res = post(&site, &read, &tahinli, "").await;
550+ assert_eq!(res.status, 303);
551+ assert_eq!(
552+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
553+ 0
554+ );
555+
556+ site.store
557+ .notify_new_alerts(&w.tahinli.id, &w.repo.id, 3)
558+ .await
559+ .expect("alerts");
560+ assert_eq!(
561+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
562+ 1
563+ );
564+ let res = post(&site, "/notifications/mark_all_read", &tahinli, "").await;
565+ assert_eq!(res.status, 303);
566+ assert_eq!(
567+ site.store.unread_count(&w.tahinli.id).await.expect("count"),
568+ 0
569+ );
570+}
crates/forge-web/src/page_route_tests/pull_reviews.rsadded+647 -0
@@ -0,0 +1,647 @@
1+use forge_core::reviews::{ReviewState, Side};
2+use forge_core::{IssueState, PullRequest, User, Visibility};
3+use forge_git::GitEnv;
4+use topcoat::router::request::Request;
5+use topcoat::router::{Body, Router, to_bytes};
6+
7+use crate::auth::{SESSION_COOKIE, percent_encode};
8+use crate::test_support::fixture::{Fixture, OWNER, REPO, git};
9+
10+fn cookie(token: &str) -> String {
11+ format!("__Host-{SESSION_COOKIE}={token}")
12+}
13+
14+/// Sends one request through the router and returns `(status, location, body)`.
15+async fn send(
16+ router: &Router,
17+ method: &str,
18+ uri: &str,
19+ token: Option<&str>,
20+ form: Option<String>,
21+) -> (u16, Option<String>, String) {
22+ let mut req = Request::builder().method(method).uri(uri);
23+ if let Some(token) = token {
24+ req = req.header("cookie", cookie(token));
25+ }
26+ let body = match form {
27+ Some(form) => {
28+ req = req.header("content-type", "application/x-www-form-urlencoded");
29+ Body::from(form)
30+ }
31+ None => Body::empty(),
32+ };
33+ let res = router.handle(req.body(body).unwrap()).await;
34+ let status = res.status().as_u16();
35+ let location = res
36+ .headers()
37+ .get("location")
38+ .map(|v| v.to_str().unwrap().to_owned());
39+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
40+ (
41+ status,
42+ location,
43+ String::from_utf8_lossy(&bytes).into_owned(),
44+ )
45+}
46+
47+/// A user with a session whose CSRF token is `{token}-csrf`.
48+async fn sign_in(fx: &Fixture, name: &str, token: &str) -> User {
49+ let user = fx
50+ .store
51+ .create_user(name, None, "not-a-real-hash", false)
52+ .await
53+ .unwrap();
54+ crate::test_support::create_session(&fx.store, &user.id, token, &format!("{token}-csrf")).await;
55+ user
56+}
57+
58+/// The repo owner, signed in with token `tahinli` (CSRF `tahinli-csrf`).
59+async fn owner_session(fx: &Fixture) {
60+ let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
61+ crate::test_support::create_session(&fx.store, &owner.id, "tahinli", "tahinli-csrf").await;
62+}
63+
64+fn csrf_form(token: &str, pairs: &[(&str, &str)]) -> String {
65+ let mut form = format!("csrf={}", percent_encode(&format!("{token}-csrf")));
66+ for (key, value) in pairs {
67+ form.push_str(&format!("&{key}={}", percent_encode(value)));
68+ }
69+ form
70+}
71+
72+async fn pull(fx: &Fixture, number: i64) -> PullRequest {
73+ let repo = fx
74+ .store
75+ .repo_by_owner_and_name(OWNER, REPO)
76+ .await
77+ .unwrap()
78+ .unwrap();
79+ fx.store
80+ .pull_by_number(&repo.id, number)
81+ .await
82+ .unwrap()
83+ .unwrap()
84+}
85+
86+/// Pushes a `feature` branch from the root that changes `a.txt` (`two` becomes `changed`) and
87+/// opens a pull request for it against `main`. Returns the pull request number.
88+async fn open_pull(fx: &Fixture) -> i64 {
89+ let base_oid = git(&fx.work, &["rev-parse", "HEAD"]);
90+ git(&fx.work, &["checkout", "-q", "-b", "feature", &fx.root]);
91+ std::fs::write(fx.work.join("a.txt"), "one\nchanged\nthree\n").unwrap();
92+ git(&fx.work, &["add", "-A"]);
93+ git(&fx.work, &["commit", "-q", "-m", "Change a.txt"]);
94+ let head_oid = git(&fx.work, &["rev-parse", "HEAD"]);
95+ git(
96+ &fx.work,
97+ &[
98+ "push",
99+ "-q",
100+ &fx.bare.to_string_lossy(),
101+ "HEAD:refs/heads/feature",
102+ ],
103+ );
104+
105+ let repo = fx
106+ .store
107+ .repo_by_owner_and_name(OWNER, REPO)
108+ .await
109+ .unwrap()
110+ .unwrap();
111+ let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
112+ let pr = fx
113+ .store
114+ .create_pull(
115+ &repo.id, &owner.id, "Change a", "", "main", &repo.id, "feature", &head_oid, &base_oid,
116+ )
117+ .await
118+ .unwrap();
119+ let env = GitEnv {
120+ git_bin: "git".into(),
121+ data_dir: fx.work.clone(),
122+ };
123+ forge_git::pulls::fetch_into_pull_ref(&env, &fx.bare, &fx.bare, &head_oid, pr.issue.number)
124+ .await
125+ .unwrap();
126+ pr.issue.number
127+}
128+
129+/// The pull request's current head, for the `head_oid` field of a comment form.
130+async fn head_of(fx: &Fixture, number: i64) -> String {
131+ pull(fx, number).await.head_oid
132+}
133+
134+/// Posts a single line comment on line `line` of the new side of `a.txt` (file index 0).
135+async fn comment_on(
136+ fx: &Fixture,
137+ number: i64,
138+ token: &str,
139+ line: &str,
140+ body: &str,
141+) -> (u16, Option<String>) {
142+ let head = head_of(fx, number).await;
143+ let form = csrf_form(
144+ token,
145+ &[
146+ ("file_index", "0"),
147+ ("side", "new"),
148+ ("line", line),
149+ ("head_oid", head.as_str()),
150+ ("action", "single"),
151+ ("body", body),
152+ ],
153+ );
154+ let (status, location, _) = send(
155+ &fx.router,
156+ "POST",
157+ &format!("/tahinli/demo/pulls/{number}/review_comments"),
158+ Some(token),
159+ Some(form),
160+ )
161+ .await;
162+ (status, location)
163+}
164+
165+/// The id of the thread at `index` (in creation order) on the pull request.
166+async fn root_at(fx: &Fixture, number: i64, index: usize) -> String {
167+ let pr = pull(fx, number).await;
168+ fx.store.review_threads(&pr.issue.id, None).await.unwrap()[index]
169+ .root
170+ .id
171+ .clone()
172+}
173+
174+/// The comment body that proposes replacing line 2 of `a.txt` with `text`.
175+fn suggestion(text: &str) -> String {
176+ format!("Try this:\n```suggestion\n{text}\n```")
177+}
178+
179+/// Posts the apply form for suggestion block 0 of comment `comment_id`.
180+async fn apply_as(
181+ fx: &Fixture,
182+ number: i64,
183+ token: &str,
184+ comment_id: &str,
185+) -> (u16, Option<String>) {
186+ let form = csrf_form(token, &[("block", "0"), ("return", "files")]);
187+ let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply");
188+ let (status, location, _) = send(&fx.router, "POST", &uri, Some(token), Some(form)).await;
189+ (status, location)
190+}
191+
192+/// Comment posting rules and a pending review, on one open pull. Scenarios run in order:
193+/// the rejected posts first (no thread), then the first thread, then the pending review.
194+#[tokio::test]
195+async fn comment_rules_and_pending_review_on_one_pull() {
196+ let fx = Fixture::new(Visibility::Public).await;
197+ owner_session(&fx).await;
198+ let number = open_pull(&fx).await;
199+ let pr = pull(&fx, number).await;
200+
201+ // A line outside the diff is rejected and leaves no thread.
202+ let (status, location) = comment_on(&fx, number, "tahinli", "99", "Nope").await;
203+ assert_eq!(status, 303, "outside diff");
204+ assert!(
205+ location.unwrap().contains("review_error=bad_line"),
206+ "outside diff"
207+ );
208+ assert!(
209+ fx.store
210+ .review_threads(&pr.issue.id, None)
211+ .await
212+ .unwrap()
213+ .is_empty(),
214+ "outside diff left a thread"
215+ );
216+
217+ // A head that is not the pull's current head is rejected.
218+ let zero = "0".repeat(40);
219+ let form = csrf_form(
220+ "tahinli",
221+ &[
222+ ("file_index", "0"),
223+ ("side", "new"),
224+ ("line", "2"),
225+ ("head_oid", zero.as_str()),
226+ ("action", "single"),
227+ ("body", "Stale"),
228+ ],
229+ );
230+ let (status, location, _) = send(
231+ &fx.router,
232+ "POST",
233+ &format!("/tahinli/demo/pulls/{number}/review_comments"),
234+ Some("tahinli"),
235+ Some(form),
236+ )
237+ .await;
238+ assert_eq!(status, 303, "stale head");
239+ assert_eq!(
240+ location.as_deref(),
241+ Some(format!("/tahinli/demo/pulls/{number}/files?review_error=stale").as_str()),
242+ "stale head"
243+ );
244+ assert!(
245+ fx.store
246+ .review_threads(&pr.issue.id, None)
247+ .await
248+ .unwrap()
249+ .is_empty(),
250+ "stale head left a thread"
251+ );
252+
253+ // A single comment on an added line creates a thread that carries its hunk.
254+ let (status, location) = comment_on(&fx, number, "tahinli", "2", "Looks good").await;
255+ assert_eq!(status, 303, "single comment");
256+ assert_eq!(
257+ location.as_deref(),
258+ Some(format!("/tahinli/demo/pulls/{number}/files#L-0-new-2").as_str()),
259+ "single comment"
260+ );
261+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
262+ assert_eq!(threads.len(), 1, "single comment");
263+ let root = &threads[0].root;
264+ assert_eq!(
265+ (root.path.as_str(), root.side, root.line),
266+ ("a.txt", Side::New, 2),
267+ "single comment"
268+ );
269+ assert_eq!(root.diff_hunk, " one\n-two\n+changed", "single comment");
270+ assert!(!root.pending, "single comment");
271+
272+ // A pending review comment is hidden from everyone but its author until submitted.
273+ let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
274+ let head = pr.head_oid.clone();
275+ let form = csrf_form(
276+ "tahinli",
277+ &[
278+ ("file_index", "0"),
279+ ("side", "new"),
280+ ("line", "2"),
281+ ("head_oid", head.as_str()),
282+ ("action", "review"),
283+ ("body", "Draft"),
284+ ],
285+ );
286+ let (status, _, _) = send(
287+ &fx.router,
288+ "POST",
289+ &format!("/tahinli/demo/pulls/{number}/review_comments"),
290+ Some("tahinli"),
291+ Some(form),
292+ )
293+ .await;
294+ assert_eq!(status, 303, "pending start");
295+ assert_eq!(
296+ fx.store
297+ .review_threads(&pr.issue.id, None)
298+ .await
299+ .unwrap()
300+ .len(),
301+ 1,
302+ "pending thread hidden from everyone"
303+ );
304+ let mine = fx
305+ .store
306+ .review_threads(&pr.issue.id, Some(&tahinli.id))
307+ .await
308+ .unwrap();
309+ assert_eq!(mine.len(), 2, "author sees the pending thread");
310+ assert!(
311+ mine.iter().any(|t| t.root.pending),
312+ "the author's draft is pending"
313+ );
314+
315+ let form = csrf_form("tahinli", &[("state", "comment"), ("body", "Done")]);
316+ let (status, _, _) = send(
317+ &fx.router,
318+ "POST",
319+ &format!("/tahinli/demo/pulls/{number}/reviews"),
320+ Some("tahinli"),
321+ Some(form),
322+ )
323+ .await;
324+ assert_eq!(status, 303, "submit review");
325+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
326+ assert_eq!(threads.len(), 2, "submitted review is public");
327+ assert!(threads.iter().all(|t| !t.root.pending), "submitted review");
328+
329+ // Anonymous writes redirect to login, and a missing CSRF token is forbidden.
330+ let uri = format!("/tahinli/demo/pulls/{number}/review_comments");
331+ let form = csrf_form(
332+ "tahinli",
333+ &[
334+ ("file_index", "0"),
335+ ("side", "new"),
336+ ("line", "2"),
337+ ("head_oid", head.as_str()),
338+ ("action", "single"),
339+ ("body", "Anon"),
340+ ],
341+ );
342+ let (status, location, _) = send(&fx.router, "POST", &uri, None, Some(form)).await;
343+ assert_eq!(status, 303, "anonymous write");
344+ assert!(location.unwrap().starts_with("/login"), "anonymous write");
345+ let form = format!("file_index=0&side=new&line=2&head_oid={head}&action=single&body=NoCsrf");
346+ let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
347+ assert_eq!(status, 403, "missing csrf");
348+}
349+
350+/// Reply, edit, resolve and delete on the threads of one pull. Each scenario acts on its
351+/// own thread (the first for reply, edit and resolve, the second for delete).
352+#[tokio::test]
353+async fn thread_reply_edit_resolve_and_delete() {
354+ let fx = Fixture::new(Visibility::Public).await;
355+ owner_session(&fx).await;
356+ sign_in(&fx, "bob", "bob").await;
357+ let number = open_pull(&fx).await;
358+ comment_on(&fx, number, "tahinli", "2", "First").await;
359+ let pr = pull(&fx, number).await;
360+ let root = root_at(&fx, number, 0).await;
361+
362+ // A reader replies into the thread and is sent back to its root.
363+ let form = csrf_form("bob", &[("body", "Reply")]);
364+ let (status, location, _) = send(
365+ &fx.router,
366+ "POST",
367+ &format!("/tahinli/demo/pulls/{number}/review_comments/{root}/reply"),
368+ Some("bob"),
369+ Some(form),
370+ )
371+ .await;
372+ assert_eq!(status, 303, "reply");
373+ assert_eq!(
374+ location.as_deref(),
375+ Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()),
376+ "reply"
377+ );
378+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
379+ assert_eq!(threads[0].replies.len(), 1, "reply");
380+ assert_eq!(threads[0].replies[0].author_name, "bob", "reply");
381+
382+ // Only the author may open the edit form, post an edit, or resolve.
383+ let edit = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/edit");
384+ let (status, _, body) = send(&fx.router, "GET", &edit, Some("tahinli"), None).await;
385+ assert_eq!(status, 200, "edit form");
386+ assert!(body.contains("Save comment"), "edit form");
387+ let (status, _, _) = send(&fx.router, "GET", &edit, Some("bob"), None).await;
388+ assert_eq!(status, 403, "edit form for a non-author");
389+ let form = csrf_form("bob", &[("body", "Hijacked")]);
390+ let (status, _, _) = send(&fx.router, "POST", &edit, Some("bob"), Some(form)).await;
391+ assert_eq!(status, 403, "edit by a non-author");
392+ let form = csrf_form("tahinli", &[("body", "Edited")]);
393+ let (status, location, _) = send(&fx.router, "POST", &edit, Some("tahinli"), Some(form)).await;
394+ assert_eq!(status, 303, "edit");
395+ assert_eq!(
396+ location.as_deref(),
397+ Some(format!("/tahinli/demo/pulls/{number}#rc-{root}").as_str()),
398+ "edit"
399+ );
400+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
401+ assert_eq!(threads[0].root.body, "Edited", "edit");
402+
403+ let resolve = format!("/tahinli/demo/pulls/{number}/review_comments/{root}/resolve");
404+ let form = csrf_form("bob", &[("resolved", "1")]);
405+ let (status, _, _) = send(&fx.router, "POST", &resolve, Some("bob"), Some(form)).await;
406+ assert_eq!(status, 403, "resolve by a reader");
407+ let form = csrf_form("tahinli", &[("resolved", "1")]);
408+ let (status, _, _) = send(&fx.router, "POST", &resolve, Some("tahinli"), Some(form)).await;
409+ assert_eq!(status, 303, "resolve");
410+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
411+ assert!(threads[0].root.resolved, "resolve");
412+
413+ // Delete removes only the second thread, and only for its author.
414+ comment_on(&fx, number, "tahinli", "2", "Doomed").await;
415+ let doomed = root_at(&fx, number, 1).await;
416+ let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{doomed}/delete");
417+ let form = csrf_form("bob", &[]);
418+ let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
419+ assert_eq!(status, 403, "delete by a non-author");
420+ let form = csrf_form("tahinli", &[]);
421+ let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
422+ assert_eq!(status, 303, "delete");
423+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
424+ assert_eq!(threads.len(), 1, "delete");
425+ assert_eq!(threads[0].root.id, root, "delete kept the other thread");
426+}
427+
428+/// Reviews on one pull: a reader approves, the author cannot approve their own pull, and
429+/// after the pull closes it takes comments but no reviews.
430+#[tokio::test]
431+async fn reviews_approve_then_close_the_pull() {
432+ let fx = Fixture::new(Visibility::Public).await;
433+ owner_session(&fx).await;
434+ sign_in(&fx, "bob", "bob").await;
435+ let number = open_pull(&fx).await;
436+ let pr = pull(&fx, number).await;
437+ let uri = format!("/tahinli/demo/pulls/{number}/reviews");
438+
439+ // A reader's approval is recorded.
440+ let form = csrf_form("bob", &[("state", "approve")]);
441+ let (status, location, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
442+ assert_eq!(status, 303, "reader approval");
443+ assert!(location.unwrap().contains("#review-"), "reader approval");
444+ let reviews = fx.store.list_reviews(&pr.issue.id).await.unwrap();
445+ assert_eq!(reviews.len(), 1, "reader approval");
446+ assert_eq!(reviews[0].state, ReviewState::Approved, "reader approval");
447+
448+ // The author's approval is refused.
449+ let form = csrf_form("tahinli", &[("state", "approve")]);
450+ let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
451+ assert_eq!(status, 303, "author approval");
452+ assert_eq!(
453+ location.as_deref(),
454+ Some(format!("/tahinli/demo/pulls/{number}?review_error=own_pr").as_str()),
455+ "author approval"
456+ );
457+ assert_eq!(
458+ fx.store.list_reviews(&pr.issue.id).await.unwrap().len(),
459+ 1,
460+ "author approval"
461+ );
462+
463+ // Once closed, comments still land but reviews are refused.
464+ let tahinli = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
465+ fx.store
466+ .set_issue_state(
467+ &pr.issue.id,
468+ Some(&tahinli.id),
469+ IssueState::Closed,
470+ None,
471+ serde_json::Value::Null,
472+ )
473+ .await
474+ .unwrap();
475+ let (status, location) = comment_on(&fx, number, "tahinli", "2", "After close").await;
476+ assert_eq!(status, 303, "comment on a closed pull");
477+ assert!(
478+ location.unwrap().contains("#L-0-new-2"),
479+ "comment on a closed pull"
480+ );
481+ let form = csrf_form("tahinli", &[("state", "approve")]);
482+ let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
483+ assert_eq!(status, 303, "review on a closed pull");
484+ assert!(
485+ location.unwrap().ends_with("?review_error=closed"),
486+ "review on a closed pull"
487+ );
488+}
489+
490+#[tokio::test]
491+async fn dismiss_needs_write_and_a_reason() {
492+ let fx = Fixture::new(Visibility::Public).await;
493+ owner_session(&fx).await;
494+ sign_in(&fx, "bob", "bob").await;
495+ let number = open_pull(&fx).await;
496+ let pr = pull(&fx, number).await;
497+ let form = csrf_form("bob", &[("state", "request_changes")]);
498+ send(
499+ &fx.router,
500+ "POST",
501+ &format!("/tahinli/demo/pulls/{number}/reviews"),
502+ Some("bob"),
503+ Some(form),
504+ )
505+ .await;
506+ let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
507+ let uri = format!("/tahinli/demo/pulls/{number}/reviews/{}/dismiss", review.id);
508+
509+ let form = csrf_form("bob", &[("reason", "mine")]);
510+ let (status, _, _) = send(&fx.router, "POST", &uri, Some("bob"), Some(form)).await;
511+ assert_eq!(status, 403, "dismiss by a reader");
512+
513+ let form = csrf_form("tahinli", &[("reason", " ")]);
514+ let (status, location, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
515+ assert_eq!(status, 303, "blank reason");
516+ assert!(
517+ location.unwrap().ends_with("?review_error=empty"),
518+ "blank reason"
519+ );
520+
521+ let form = csrf_form("tahinli", &[("reason", "Addressed")]);
522+ let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
523+ assert_eq!(status, 303, "dismiss");
524+ let review = fx.store.list_reviews(&pr.issue.id).await.unwrap().remove(0);
525+ assert_eq!(review.state, ReviewState::Dismissed, "dismiss");
526+}
527+
528+/// The apply-suggestion flow on one pull: a reader without push access sees no button, an
529+/// outdated suggestion is refused after the head moves, and a fresh suggestion applies.
530+#[tokio::test]
531+async fn suggestions_reader_outdated_and_apply() {
532+ let fx = Fixture::new(Visibility::Public).await;
533+ owner_session(&fx).await;
534+ sign_in(&fx, "rita", "rita").await;
535+ let number = open_pull(&fx).await;
536+ let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
537+ assert_eq!(status, 303, "first suggestion");
538+ let first = root_at(&fx, number, 0).await;
539+
540+ // A reader without push access sees the diff but no apply button, and is refused.
541+ let page = get(&fx, number, "rita").await;
542+ assert!(page.contains("Suggested change"), "the diff still shows");
543+ assert!(
544+ !page.contains("Apply suggestion"),
545+ "no apply button without push access"
546+ );
547+ let (status, location) = apply_as(&fx, number, "rita", &first).await;
548+ assert_eq!(status, 303, "reader apply");
549+ assert!(
550+ location.unwrap().contains("review_error=no_push"),
551+ "reader apply"
552+ );
553+
554+ // The head moves on: the first suggestion is outdated, shown without apply, and refused.
555+ let pr = pull(&fx, number).await;
556+ std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();
557+ git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);
558+ let moved = git(&fx.work, &["rev-parse", "HEAD"]);
559+ git(
560+ &fx.work,
561+ &[
562+ "push",
563+ "-q",
564+ &fx.bare.to_string_lossy(),
565+ "HEAD:refs/heads/feature",
566+ ],
567+ );
568+ fx.store
569+ .update_pull_head(&pr.issue.id, &moved)
570+ .await
571+ .unwrap();
572+
573+ let page = get(&fx, number, "tahinli").await;
574+ assert!(
575+ page.contains("This suggestion is outdated"),
576+ "outdated note shown"
577+ );
578+ assert!(
579+ !page.contains("Apply suggestion"),
580+ "no apply button when outdated"
581+ );
582+ let (status, location) = apply_as(&fx, number, "tahinli", &first).await;
583+ assert_eq!(status, 303, "outdated apply");
584+ assert!(
585+ location.unwrap().contains("review_error=outdated"),
586+ "outdated apply"
587+ );
588+ assert_eq!(
589+ git(&fx.bare, &["rev-parse", "feature"]),
590+ moved,
591+ "nothing was committed"
592+ );
593+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
594+ assert!(
595+ !threads[0].root.resolved,
596+ "a refused apply leaves the thread open"
597+ );
598+
599+ // A fresh suggestion against the moved head applies as a commit by the commenter.
600+ let before = pull(&fx, number).await.head_oid;
601+ assert_eq!(before, moved, "the head is the moved commit");
602+ let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
603+ assert_eq!(status, 303, "fresh suggestion");
604+ let second = root_at(&fx, number, 1).await;
605+ let (status, location) = apply_as(&fx, number, "tahinli", &second).await;
606+ assert_eq!(status, 303, "apply");
607+ assert!(!location.unwrap().contains("review_error"), "apply");
608+
609+ let pr = pull(&fx, number).await;
610+ assert_ne!(
611+ pr.head_oid, before,
612+ "the head moved to the suggestion commit"
613+ );
614+ assert_eq!(
615+ git(&fx.bare, &["show", &format!("{}:a.txt", pr.head_oid)]),
616+ "one\ntwo!\nthree",
617+ "apply"
618+ );
619+ assert_eq!(
620+ git(&fx.bare, &["log", "-1", "--format=%an", &pr.head_oid]),
621+ "tahinli",
622+ "apply"
623+ );
624+ let message = git(&fx.bare, &["log", "-1", "--format=%B", &pr.head_oid]);
625+ assert!(
626+ message.starts_with("Apply suggestion from review"),
627+ "{message}"
628+ );
629+ assert!(
630+ message.contains("Co-authored-by: tahinli <"),
631+ "commenter trailer: {message}"
632+ );
633+ assert_eq!(
634+ git(&fx.bare, &["rev-parse", "feature"]),
635+ pr.head_oid,
636+ "apply"
637+ );
638+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
639+ assert!(threads[1].root.resolved, "applying resolves the thread");
640+}
641+
642+/// The Files tab of the pull request as `token` sees it.
643+async fn get(fx: &Fixture, number: i64, token: &str) -> String {
644+ let uri = format!("/tahinli/demo/pulls/{number}/files");
645+ let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await;
646+ body
647+}
crates/forge-web/src/page_route_tests/repo.rsadded+470 -0
@@ -0,0 +1,470 @@
1+use std::path::Path;
2+use std::process::Command;
3+use std::time::Duration;
4+
5+use forge_core::Visibility;
6+use forge_core::time::stamp_before;
7+
8+use forge_git::repo::{init_bare, repo_path};
9+
10+use topcoat::router::request::Request;
11+use topcoat::router::{Body, Router, to_bytes};
12+
13+use crate::auth::SESSION_COOKIE;
14+use crate::state::AppState;
15+
16+async fn app(dir: &Path) -> (Router, AppState) {
17+ let state = crate::test_support::test_state(dir).await;
18+ (crate::test_support::app_router(state.clone()), state)
19+}
20+
21+fn git(dir: &Path, args: &[&str]) {
22+ let status = Command::new("git")
23+ .current_dir(dir)
24+ .env("GIT_CONFIG_NOSYSTEM", "1")
25+ .args([
26+ "-c",
27+ "user.name=Test",
28+ "-c",
29+ "user.email=test@example.com",
30+ "-c",
31+ "commit.gpgsign=false",
32+ ])
33+ .args(args)
34+ .status()
35+ .expect("git runs");
36+ assert!(status.success(), "git {args:?} failed");
37+}
38+
39+/// `tahinli/demo` (public, default branch `main` with content) and `tahinli/secret` (private, empty).
40+async fn fixture(dir: &Path) -> (Router, AppState) {
41+ let (router, state) = app(dir).await;
42+ let tahinli = state
43+ .store
44+ .create_user("tahinli", None, "x", false)
45+ .await
46+ .unwrap();
47+ let demo = state
48+ .store
49+ .create_repo(
50+ &tahinli.id,
51+ "demo",
52+ "A demo repo",
53+ Visibility::Public,
54+ "main",
55+ )
56+ .await
57+ .unwrap();
58+ let secret = state
59+ .store
60+ .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main")
61+ .await
62+ .unwrap();
63+ for repo in [&demo, &secret] {
64+ let path = repo_path(&state.config.data_dir, &repo.id).unwrap();
65+ init_bare(&state.git, &path, "main").await.unwrap();
66+ }
67+
68+ let work = dir.join("work");
69+ std::fs::create_dir_all(work.join("src")).unwrap();
70+ std::fs::create_dir_all(work.join("docs")).unwrap();
71+ std::fs::write(work.join("README.md"), "# Demo\n\nHello from the README.\n").unwrap();
72+ std::fs::write(
73+ work.join("src/main.rs"),
74+ "fn main() {\n println!(\"hi\");\n}\n",
75+ )
76+ .unwrap();
77+ std::fs::write(
78+ work.join("docs/guide.md"),
79+ "# Guide\n\n| a | b |\n|---|---|\n| 1 | 2 |\n",
80+ )
81+ .unwrap();
82+ std::fs::write(work.join("data.bin"), [0u8, 1, 2]).unwrap();
83+ git(&work, &["init", "-q", "-b", "main"]);
84+ git(&work, &["add", "-A"]);
85+ git(&work, &["commit", "-q", "-m", "first commit"]);
86+ let demo_path = repo_path(&state.config.data_dir, &demo.id).unwrap();
87+ git(
88+ &work,
89+ &["push", "-q", demo_path.to_str().unwrap(), "main:main"],
90+ );
91+ (router, state)
92+}
93+
94+async fn get(router: &Router, uri: &str) -> (u16, String) {
95+ let req = Request::builder()
96+ .method("GET")
97+ .uri(uri)
98+ .body(Body::empty())
99+ .unwrap();
100+ let res = router.handle(req).await;
101+ let status = res.status().as_u16();
102+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
103+ (status, String::from_utf8_lossy(&bytes).into_owned())
104+}
105+
106+// The read-only tests below share one fixture: they only read the demo repo, so each scenario
107+// sees the same pristine contents.
108+
109+#[tokio::test]
110+async fn demo_pages_render_from_the_repo_contents() {
111+ let dir = tempfile::tempdir().unwrap();
112+ let (router, _) = fixture(dir.path()).await;
113+
114+ // Home renders the README, the tree, the clone popover and the archive links.
115+ let (status, body) = get(&router, "/tahinli/demo").await;
116+ assert_eq!(status, 200);
117+ assert!(body.contains("Hello from the README"), "README rendered");
118+ assert!(
119+ body.contains("/tahinli/demo/tree/main/src"),
120+ "root tree listed"
121+ );
122+ assert!(
123+ body.contains("class=\"clone pop\""),
124+ "clone popover rendered"
125+ );
126+ assert!(body.contains("value=\"https://forge.test/tahinli/demo.git\""));
127+ assert!(body.contains("git@forge.test:tahinli/demo.git"));
128+ assert!(
129+ body.contains("readonly"),
130+ "clone URLs are selectable, read-only fields"
131+ );
132+ assert!(body.contains("/tahinli/demo/archive/main.tar.gz"));
133+ assert!(body.contains("/tahinli/demo/branches"));
134+ assert!(body.contains("data-ref-filter"), "branch switcher rendered");
135+
136+ // Trees list their entries and link to subtrees and blobs.
137+ let (status, body) = get(&router, "/tahinli/demo/tree/main/src").await;
138+ assert_eq!(status, 200);
139+ assert!(body.contains("main.rs"));
140+ assert!(body.contains("/tahinli/demo/blob/main/src/main.rs"));
141+ let (status, body) = get(&router, "/tahinli/demo/tree/main").await;
142+ assert_eq!(status, 200);
143+ assert!(body.contains("/tahinli/demo/tree/main/docs"));
144+
145+ // Rust source is highlighted with line anchors.
146+ let (status, body) = get(&router, "/tahinli/demo/blob/main/src/main.rs").await;
147+ assert_eq!(status, 200);
148+ assert!(body.contains("id=\"L1\""));
149+ assert!(body.contains("href=\"#L2\""));
150+ assert!(body.contains("<span class="), "syntax classes applied");
151+ assert!(body.contains("/assets/highlight.css?v="));
152+
153+ // Markdown renders unless the viewer asks for the plain source.
154+ let (status, body) = get(&router, "/tahinli/demo/blob/main/docs/guide.md").await;
155+ assert_eq!(status, 200);
156+ assert!(
157+ body.contains("markdown-body") && body.contains("<table>"),
158+ "GFM table rendered"
159+ );
160+ let (status, body) = get(&router, "/tahinli/demo/blob/main/docs/guide.md?plain=1").await;
161+ assert_eq!(status, 200);
162+ assert!(body.contains("file-table"), "source shown as lines");
163+ assert!(!body.contains("markdown-body"), "not rendered");
164+
165+ // Binary blobs show their size instead of content.
166+ let (status, body) = get(&router, "/tahinli/demo/blob/main/data.bin").await;
167+ assert_eq!(status, 200);
168+ assert!(body.contains("Binary file, 3 bytes"));
169+
170+ // Fixed segment routes win over the repo catch-all.
171+ let (status, body) = get(&router, "/tahinli/demo/branches").await;
172+ assert_eq!(status, 200);
173+ assert!(body.contains("default"), "default branch marked");
174+ let (status, body) = get(&router, "/tahinli/demo/tags").await;
175+ assert_eq!(status, 200);
176+ assert!(body.contains("Nothing here yet."));
177+ let (status, body) = get(&router, "/tahinli/demo/tree/main").await;
178+ assert_eq!(status, 200);
179+ assert!(body.contains("README.md"));
180+ let (status, body) = get(&router, "/tahinli/demo").await;
181+ assert_eq!(status, 200);
182+ assert!(body.contains("Hello from the README"));
183+}
184+
185+#[tokio::test]
186+async fn missing_paths_and_private_repos_are_404_for_anonymous() {
187+ let dir = tempfile::tempdir().unwrap();
188+ let (router, _) = fixture(dir.path()).await;
189+ for uri in [
190+ "/tahinli/demo/tree/main/nope",
191+ "/tahinli/demo/tree/nosuchref",
192+ "/tahinli/demo/blob/main/nope.rs",
193+ "/tahinli/demo/blob/main/src",
194+ "/tahinli/demo/blob/main",
195+ ] {
196+ let (status, _) = get(&router, uri).await;
197+ assert_eq!(status, 404, "{uri}");
198+ }
199+ for uri in [
200+ "/tahinli/secret",
201+ "/tahinli/secret/tree/main",
202+ "/tahinli/secret/blob/main/x",
203+ "/tahinli/secret/branches",
204+ "/tahinli/secret/tags",
205+ ] {
206+ let (status, _) = get(&router, uri).await;
207+ assert_eq!(status, 404, "{uri}");
208+ }
209+}
210+
211+const ZERO_OID: &str = "0000000000000000000000000000000000000000";
212+const OID: &str = "1111111111111111111111111111111111111111";
213+const BANNER: &str = "had recent pushes";
214+
215+/// Creates a session for `user_id` and returns the cookie header value.
216+async fn sign_in(state: &AppState, user_id: &str, token: &str) -> String {
217+ crate::test_support::create_session(&state.store, user_id, token, "csrf").await;
218+ format!("__Host-{SESSION_COOKIE}={token}")
219+}
220+
221+async fn get_as(router: &Router, uri: &str, cookie: Option<&str>) -> (u16, String) {
222+ let mut builder = Request::builder().method("GET").uri(uri);
223+ if let Some(cookie) = cookie {
224+ builder = builder.header("cookie", cookie);
225+ }
226+ let res = router.handle(builder.body(Body::empty()).unwrap()).await;
227+ let status = res.status().as_u16();
228+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
229+ (status, String::from_utf8_lossy(&bytes).into_owned())
230+}
231+
232+/// Points `branch` at the bare repo's `main`, so the branch exists.
233+fn make_branch(bare: &Path, branch: &str) {
234+ let full = format!("refs/heads/{branch}");
235+ git(bare, &["update-ref", &full, "refs/heads/main"]);
236+}
237+
238+/// Records a push of `branch` to `repo_id` by `actor_id`, `age` ago.
239+async fn record_push(state: &AppState, repo_id: &str, actor_id: &str, branch: &str, age: Duration) {
240+ let at = stamp_before(age);
241+ let full = format!("refs/heads/{branch}");
242+ state
243+ .store
244+ .record_push_event_at(repo_id, actor_id, &full, ZERO_OID, OID, &at)
245+ .await
246+ .unwrap();
247+}
248+
249+async fn demo_repo(state: &AppState) -> forge_core::Repo {
250+ state
251+ .store
252+ .repo_by_owner_and_name("tahinli", "demo")
253+ .await
254+ .unwrap()
255+ .unwrap()
256+}
257+
258+#[tokio::test]
259+async fn recent_push_banner_links_to_compare() {
260+ let dir = tempfile::tempdir().unwrap();
261+ let (router, state) = fixture(dir.path()).await;
262+ let demo = demo_repo(&state).await;
263+ make_branch(
264+ &repo_path(&state.config.data_dir, &demo.id).unwrap(),
265+ "feature",
266+ );
267+ record_push(
268+ &state,
269+ &demo.id,
270+ &demo.owner_id,
271+ "feature",
272+ Duration::from_secs(300),
273+ )
274+ .await;
275+ let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
276+
277+ let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
278+ assert_eq!(status, 200);
279+ assert!(body.contains("had recent pushes"), "{body}");
280+ assert!(body.contains("5 minutes ago</time>"), "{body}");
281+ assert!(body.contains("compare/main...feature"), "{body}");
282+ assert!(body.contains("Compare &amp; pull request"), "{body}");
283+}
284+
285+#[tokio::test]
286+async fn push_older_than_an_hour_shows_no_banner() {
287+ let dir = tempfile::tempdir().unwrap();
288+ let (router, state) = fixture(dir.path()).await;
289+ let demo = demo_repo(&state).await;
290+ make_branch(
291+ &repo_path(&state.config.data_dir, &demo.id).unwrap(),
292+ "feature",
293+ );
294+ record_push(
295+ &state,
296+ &demo.id,
297+ &demo.owner_id,
298+ "feature",
299+ Duration::from_secs(7200),
300+ )
301+ .await;
302+ let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
303+
304+ let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
305+ assert_eq!(status, 200);
306+ assert!(!body.contains(BANNER), "{body}");
307+}
308+
309+#[tokio::test]
310+async fn default_branch_push_shows_no_banner() {
311+ let dir = tempfile::tempdir().unwrap();
312+ let (router, state) = fixture(dir.path()).await;
313+ let demo = demo_repo(&state).await;
314+ record_push(
315+ &state,
316+ &demo.id,
317+ &demo.owner_id,
318+ "main",
319+ Duration::from_secs(300),
320+ )
321+ .await;
322+ let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
323+
324+ let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
325+ assert_eq!(status, 200);
326+ assert!(!body.contains(BANNER), "{body}");
327+}
328+
329+#[tokio::test]
330+async fn open_pull_request_suppresses_banner() {
331+ let dir = tempfile::tempdir().unwrap();
332+ let (router, state) = fixture(dir.path()).await;
333+ let demo = demo_repo(&state).await;
334+ make_branch(
335+ &repo_path(&state.config.data_dir, &demo.id).unwrap(),
336+ "feature",
337+ );
338+ record_push(
339+ &state,
340+ &demo.id,
341+ &demo.owner_id,
342+ "feature",
343+ Duration::from_secs(300),
344+ )
345+ .await;
346+ state
347+ .store
348+ .create_pull(
349+ &demo.id,
350+ &demo.owner_id,
351+ "Add feature",
352+ "",
353+ "main",
354+ &demo.id,
355+ "feature",
356+ OID,
357+ OID,
358+ )
359+ .await
360+ .unwrap();
361+ let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
362+
363+ let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
364+ assert_eq!(status, 200);
365+ assert!(!body.contains(BANNER), "{body}");
366+}
367+
368+#[tokio::test]
369+async fn other_users_push_shows_no_banner() {
370+ let dir = tempfile::tempdir().unwrap();
371+ let (router, state) = fixture(dir.path()).await;
372+ let demo = demo_repo(&state).await;
373+ let bob = state
374+ .store
375+ .create_user("bob", None, "x", false)
376+ .await
377+ .unwrap();
378+ make_branch(
379+ &repo_path(&state.config.data_dir, &demo.id).unwrap(),
380+ "feature",
381+ );
382+ record_push(
383+ &state,
384+ &demo.id,
385+ &bob.id,
386+ "feature",
387+ Duration::from_secs(300),
388+ )
389+ .await;
390+ let cookie = sign_in(&state, &demo.owner_id, "tahinli-token").await;
391+
392+ let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
393+ assert_eq!(status, 200);
394+ assert!(!body.contains(BANNER), "{body}");
395+}
396+
397+#[tokio::test]
398+async fn anonymous_viewer_sees_no_banner() {
399+ let dir = tempfile::tempdir().unwrap();
400+ let (router, state) = fixture(dir.path()).await;
401+ let demo = demo_repo(&state).await;
402+ make_branch(
403+ &repo_path(&state.config.data_dir, &demo.id).unwrap(),
404+ "feature",
405+ );
406+ record_push(
407+ &state,
408+ &demo.id,
409+ &demo.owner_id,
410+ "feature",
411+ Duration::from_secs(300),
412+ )
413+ .await;
414+
415+ let (status, body) = get_as(&router, "/tahinli/demo", None).await;
416+ assert_eq!(status, 200);
417+ assert!(!body.contains(BANNER), "{body}");
418+}
419+
420+#[tokio::test]
421+async fn fork_push_links_to_parent_compare() {
422+ let dir = tempfile::tempdir().unwrap();
423+ let (router, state) = fixture(dir.path()).await;
424+ let demo = demo_repo(&state).await;
425+ let bob = state
426+ .store
427+ .create_user("bob", None, "x", false)
428+ .await
429+ .unwrap();
430+ let fork = state
431+ .store
432+ .create_fork(&demo, &bob.id, "demo")
433+ .await
434+ .unwrap();
435+ let fork_path = repo_path(&state.config.data_dir, &fork.id).unwrap();
436+ init_bare(&state.git, &fork_path, "main").await.unwrap();
437+ let demo_path = repo_path(&state.config.data_dir, &demo.id).unwrap();
438+ git(
439+ &fork_path,
440+ &[
441+ "fetch",
442+ "-q",
443+ demo_path.to_str().unwrap(),
444+ "refs/heads/main:refs/heads/main",
445+ ],
446+ );
447+ make_branch(&fork_path, "feature");
448+ record_push(
449+ &state,
450+ &fork.id,
451+ &bob.id,
452+ "feature",
453+ Duration::from_secs(300),
454+ )
455+ .await;
456+ let cookie = sign_in(&state, &bob.id, "bob-token").await;
457+
458+ // On the parent, the viewer's fork branch compares as owner:branch.
459+ let (status, body) = get_as(&router, "/tahinli/demo", Some(&cookie)).await;
460+ assert_eq!(status, 200);
461+ assert!(body.contains("compare/main...bob%3Afeature"), "{body}");
462+
463+ // On the fork itself, the link goes to the parent's compare page.
464+ let (status, body) = get_as(&router, "/bob/demo", Some(&cookie)).await;
465+ assert_eq!(status, 200);
466+ assert!(
467+ body.contains("/tahinli/demo/compare/main...bob%3Afeature"),
468+ "{body}"
469+ );
470+}
crates/forge-web/src/pages/mod.rsdeleted+0 -150
@@ -1,150 +0,0 @@
1-//! Server-rendered pages.
2-
3-#[cfg(test)]
4-mod account_tools_tests;
5-pub mod activity;
6-pub mod admin_backups;
7-pub mod admin_health;
8-#[cfg(test)]
9-mod admin_live_tests;
10-pub mod admin_mail;
11-pub mod admin_replication;
12-pub mod admin_runners;
13-pub mod admin_server;
14-pub mod admin_user_detail;
15-pub mod admin_users;
16-pub mod archive;
17-pub mod assets;
18-pub mod audit_log;
19-pub mod authoring;
20-#[cfg(test)]
21-mod authoring_tests;
22-pub mod avatars;
23-pub mod banner;
24-pub mod blame;
25-pub mod blob;
26-pub mod branches;
27-#[cfg(test)]
28-mod browse_tests;
29-pub mod ci_badge;
30-pub mod ci_estimate;
31-pub mod ci_fail;
32-pub mod ci_job;
33-pub mod ci_runs;
34-#[cfg(test)]
35-mod ci_tests;
36-pub mod code_live;
37-pub mod code_search;
38-pub mod commit;
39-pub mod commits;
40-pub mod compare;
41-pub mod discussion_actions;
42-pub mod discussion_live;
43-#[cfg(test)]
44-mod discussion_live_tests;
45-pub mod discussion_settings;
46-pub mod discussion_view;
47-pub mod discussions;
48-pub mod edit_history;
49-pub mod explore;
50-pub mod finder;
51-pub mod forgot;
52-pub mod fork;
53-pub mod home;
54-pub mod import;
55-#[cfg(test)]
56-mod import_tests;
57-pub mod invites;
58-pub mod issue_meta;
59-#[cfg(test)]
60-mod issue_meta_tests;
61-pub mod issue_parts;
62-pub mod issue_pin;
63-#[cfg(test)]
64-mod issue_pin_tests;
65-pub mod issue_view;
66-pub mod issues_list;
67-pub mod issues_live;
68-pub mod labels_css;
69-pub mod labels_page;
70-pub mod login;
71-pub mod merge_queue;
72-pub mod milestones_page;
73-pub mod needs_you;
74-pub mod new_repo;
75-pub mod not_found_page;
76-pub mod notifications;
77-pub mod org_ctx;
78-pub mod org_live;
79-pub mod org_members;
80-pub mod org_new;
81-pub mod org_settings;
82-pub mod org_teams;
83-pub mod packages;
84-pub mod packages_oci;
85-pub mod palette;
86-pub mod passkeys;
87-#[cfg(test)]
88-mod passkeys_tests;
89-pub mod profile;
90-pub mod profile_calendar;
91-pub mod profile_pins;
92-pub mod pull_branch;
93-pub mod pull_files;
94-pub mod pull_flow;
95-pub mod pull_live;
96-pub mod pull_reviews;
97-pub mod pull_view;
98-pub mod pulls_list;
99-pub mod pulls_merge;
100-pub mod push;
101-pub mod reactions;
102-#[cfg(test)]
103-mod reactions_tests;
104-pub mod ref_live;
105-pub mod refs;
106-pub mod register;
107-pub mod releases;
108-pub mod releases_live;
109-#[cfg(test)]
110-mod releases_tests;
111-pub mod repo;
112-pub mod repo_collaborators;
113-pub mod repo_ctx;
114-pub mod repo_mirrors;
115-pub mod repo_rename;
116-pub mod repo_scrub;
117-pub mod repo_secrets;
118-pub mod repo_security;
119-pub mod repo_settings;
120-pub mod repo_settings_live;
121-#[cfg(test)]
122-mod repo_settings_live_tests;
123-pub mod repo_side;
124-pub mod repo_transfer;
125-pub mod repo_webhooks;
126-pub mod review_requests;
127-#[cfg(test)]
128-mod security_tab_tests;
129-pub mod settings_appearance;
130-pub mod settings_export;
131-pub mod settings_gpg;
132-#[cfg(test)]
133-mod settings_gpg_tests;
134-pub mod settings_keys;
135-pub mod settings_live;
136-pub mod settings_notifications;
137-pub mod settings_profile;
138-pub mod settings_security;
139-pub mod settings_sessions;
140-pub mod settings_tokens;
141-pub mod setup;
142-pub mod shell_events;
143-pub mod snippets;
144-pub mod snippets_live;
145-pub mod star;
146-pub mod theme_cookie;
147-pub mod tree;
148-pub mod user_prefs;
149-pub mod wiki;
150-pub mod wiki_live;
crates/forge-web/src/templates_route_tests.rsmodified+1 -1
@@ -1,7 +1,7 @@
1 use forge_core::Visibility;1 use forge_core::Visibility;
2 2
3-use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, send};
4 use crate::test_support::fixture::{Fixture, git};3 use crate::test_support::fixture::{Fixture, git};
4+use forge_web_pages::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, send};
5 5
6 const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n";6 const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n";
7 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";7 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";