forge
Explore
Log in

Don't you dare go Hollow

A push no longer rebuilds what did not change: the runner gives each tracked file the time its content last changed, so cargo and make skip unchanged code after a fresh checkout

Browse files at this commit

158fa0f4059044b945c2cad5de17bf7b551dafa8Ahmet Kaan GümüşParent: 3aaf5ef
  • perf
    • a push no longer rebuilds what did not change: the runner gives each tracked file the time its content last changed, so cargo and make skip unchanged code after a fresh checkout
    • forge-ci has no build script, so a new commit no longer recompiles every crate, and only release builds read git for the commit shown in the version
    • one build job runs unit tests, the release build, then the e2e tests against the binary it ships, so forge compiles once fewer and e2e takes seconds
    • incremental is back on for test builds, on trial
  • refactor
    • e2e tests move to forge-e2e and modules with no routes and no dependency on pages move to forge-web-base
    • debug builds show unknown for commit and date
Show full message
⚡ perf(ci): a push no longer rebuilds what did not change: the runner gives each tracked file the time its content last changed, so cargo and make skip unchanged code after a fresh checkout; forge-ci has no build script, so a new commit no longer recompiles every crate, and only release builds read git for the commit shown in the version; one build job runs unit tests, the release build, then the e2e tests against the binary it ships, so forge compiles once fewer and e2e takes seconds; incremental is back on for test builds, on trial; ♻️ refactor: e2e tests move to forge-e2e and modules with no routes and no dependency on pages move to forge-web-base; debug builds show unknown for commit and date
.forge/ci.tomlmodified+17 -27
@@ -1,13 +1,12 @@
1 # CI for forge itself. Format: docs/ci.md, parser: crates/forge-ci/src/config.rs.1 # CI for forge itself. Format: docs/ci.md, parser: crates/forge-ci/src/config.rs.
2 #2 #
3-# The workflow has no branch condition, so the build job also runs for pull requests.3+# The workflow has no branch condition, so the job also runs for pull requests.
4-# build has `needs = ["test"]`, so it starts only after test succeeds. Only one job uses the4+# One job does everything, so its steps run one at a time and no memory is declared. An earlier run
5-# runner's memory at a time, so no memory is declared. An earlier run with concurrency 4 hit a5+# with concurrency 4 hit a host-wide OOM and the kernel killed rustc mid-build.
6-# host-wide OOM and the kernel killed rustc mid-build.6+# A tag push matching "v*" publishes a release with the job's binaries and SHA256SUMS, and
7-# The build job's artifacts are still only used7+# self-update deploys forge-<arch>-linux. Both happen only when the job succeeded.
8-# once the whole run is green: a tag push matching "v*" publishes a release with the build job's8+#
9-# binaries and SHA256SUMS, and self-update deploys forge-<arch>-linux, only when every job in the run,9+# The job is named build because self-update's `job` setting and the release assets name it.
10-# including test, succeeded.
11 10
12 [on]11 [on]
13 push = ["main"]12 push = ["main"]
@@ -15,31 +14,22 @@ pull_request = true
15 manual = true14 manual = true
16 tags = ["v*"]15 tags = ["v*"]
17 16
18-[jobs.test]17+[jobs.build]
19 image = "docker.io/library/rust:1"18 image = "docker.io/library/rust:1"
20 # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo.19 # Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo.
21 # CARGO_HOME in the workspace puts the downloaded crates in the cache, so a run downloads only new ones.20 # CARGO_HOME in the workspace puts the downloaded crates in the cache, so a run downloads only new ones.
22 # That places turso_core's source inside this repo, and its build.rs then watches our .git/HEAD, which21 # That places turso_core's source inside this repo, and its build.rs then watches our .git/HEAD, which
23 # is new in every job, so it would rebuild on every run. With SOURCE_DATE_EPOCH set it skips git.22 # is new in every job, so it would rebuild on every run. With SOURCE_DATE_EPOCH set it skips git.
24-env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_INCREMENTAL = "0", CARGO_HOME = "/workspace/.cargo-home", SOURCE_DATE_EPOCH = "0" }23+# Incremental stays on for the test builds, which `target` in the cache lets them reuse. It is on
25-# main.rs holds the whole forge-web crate, so `cargo test` compiles it twice: the `forge` binary24+# trial: it was turned off in 4c4575a to avoid OOM kills, so set CARGO_INCREMENTAL = "0" if they return.
26-# (the e2e tests run it) and its unit-test harness, ~3.4 GB of rustc each. Built in parallel they25+# The dist profile has incremental off.
27-# hit the runner's box cap and got OOM-killed now and then. The e2e build makes the binary first,26+env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_HOME = "/workspace/.cargo-home", SOURCE_DATE_EPOCH = "0" }
28-# alone; the full run reuses it and compiles only the harness.27+# Unit tests run first, so a failure shows before the release build. The e2e tests then run against
29-run = """28+# the binary this job ships, so forge is not compiled a third time just for them.
30-cargo test --workspace --no-run --test e2e
31-cargo test --workspace
32-"""
33-cache = ["target", ".cargo-home"]
34-timeout_minutes = 120
35-
36-[jobs.build]
37-image = "docker.io/library/rust:1"
38-needs = ["test"]
39-# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit).
40-env = { CARGO_INCREMENTAL = "0", CARGO_HOME = "/workspace/.cargo-home", SOURCE_DATE_EPOCH = "0" }
41 run = """29 run = """
30+cargo test --workspace --exclude forge-e2e
42 cargo build --profile dist -p forge-web -p forge-runner31 cargo build --profile dist -p forge-web -p forge-runner
32+FORGE_BIN="$PWD/target/dist/forge" cargo test -p forge-e2e
43 ARCH=$(uname -m)33 ARCH=$(uname -m)
44 cp target/dist/forge forge-$ARCH-linux34 cp target/dist/forge forge-$ARCH-linux
45 cp target/dist/forge-runner forge-runner-$ARCH-linux35 cp target/dist/forge-runner forge-runner-$ARCH-linux
@@ -47,7 +37,7 @@ sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS
47 """37 """
48 artifacts = ["forge-*-linux", "SHA256SUMS"]38 artifacts = ["forge-*-linux", "SHA256SUMS"]
49 cache = ["target", ".cargo-home"]39 cache = ["target", ".cargo-home"]
50-timeout_minutes = 12040+timeout_minutes = 240
51 41
52 [release]42 [release]
53 assets = ["build:forge-*-linux", "build:SHA256SUMS"]43 assets = ["build:forge-*-linux", "build:SHA256SUMS"]
Cargo.lockmodified+50 -7
@@ -1873,6 +1873,28 @@ dependencies = [
1873 "zip",1873 "zip",
1874 ]1874 ]
1875 1875
1876+[[package]]
1877+name = "forge-e2e"
1878+version = "0.1.0"
1879+dependencies = [
1880+ "base64 0.23.1",
1881+ "flate2",
1882+ "forge-ci",
1883+ "forge-core",
1884+ "forge-git",
1885+ "forge-runner",
1886+ "hex",
1887+ "reqwest",
1888+ "scraper",
1889+ "serde_json",
1890+ "sha2 0.11.1",
1891+ "tar",
1892+ "tempfile",
1893+ "tokio",
1894+ "tokio-util",
1895+ "zip",
1896+]
1897+
1876 [[package]]1898 [[package]]
1877 name = "forge-git"1899 name = "forge-git"
1878 version = "0.1.0"1900 version = "0.1.0"
@@ -1942,18 +1964,16 @@ name = "forge-web"
1942 version = "0.1.0"1964 version = "0.1.0"
1943 dependencies = [1965 dependencies = [
1944 "aes-gcm 0.11.1",1966 "aes-gcm 0.11.1",
1945- "ammonia",
1946 "async-compression",1967 "async-compression",
1947 "base64 0.23.1",1968 "base64 0.23.1",
1948 "bytes",1969 "bytes",
1949- "comrak",
1950- "emojis",
1951 "flate2",1970 "flate2",
1952 "forge-ci",1971 "forge-ci",
1953 "forge-core",1972 "forge-core",
1954 "forge-git",1973 "forge-git",
1955 "forge-runner",1974 "forge-runner",
1956 "forge-ssh",1975 "forge-ssh",
1976+ "forge-web-base",
1957 "form_urlencoded",1977 "form_urlencoded",
1958 "futures-util",1978 "futures-util",
1959 "grass",1979 "grass",
@@ -1969,7 +1989,6 @@ dependencies = [
1969 "lettre",1989 "lettre",
1970 "multer",1990 "multer",
1971 "nix 0.31.3",1991 "nix 0.31.3",
1972- "object_store",
1973 "p256",1992 "p256",
1974 "rand 0.10.3",1993 "rand 0.10.3",
1975 "reqwest",1994 "reqwest",
@@ -1980,15 +1999,12 @@ dependencies = [
1980 "sha2 0.11.1",1999 "sha2 0.11.1",
1981 "similar",2000 "similar",
1982 "subtle",2001 "subtle",
1983- "syntect",
1984 "tar",2002 "tar",
1985 "tempfile",2003 "tempfile",
1986 "time",2004 "time",
1987 "tokio",2005 "tokio",
1988 "tokio-util",2006 "tokio-util",
1989 "topcoat",2007 "topcoat",
1990- "tower",
1991- "tower-http 0.7.1",
1992 "tracing",2008 "tracing",
1993 "tracing-subscriber",2009 "tracing-subscriber",
1994 "ulid",2010 "ulid",
@@ -1998,6 +2014,33 @@ dependencies = [
1998 "zip",2014 "zip",
1999 ]2015 ]
2000 2016
2017+[[package]]
2018+name = "forge-web-base"
2019+version = "0.1.0"
2020+dependencies = [
2021+ "ammonia",
2022+ "bytes",
2023+ "comrak",
2024+ "emojis",
2025+ "forge-core",
2026+ "forge-git",
2027+ "futures-util",
2028+ "hex",
2029+ "http",
2030+ "http-body",
2031+ "object_store",
2032+ "serde_json",
2033+ "sha2 0.11.1",
2034+ "syntect",
2035+ "tempfile",
2036+ "time",
2037+ "tokio",
2038+ "topcoat",
2039+ "tower",
2040+ "tower-http 0.7.1",
2041+ "tracing",
2042+]
2043+
2001 [[package]]2044 [[package]]
2002 name = "form_urlencoded"2045 name = "form_urlencoded"
2003 version = "1.2.2"2046 version = "1.2.2"
Cargo.tomlmodified+3 -0
@@ -5,8 +5,10 @@ members = [
5 "crates/forge-git",5 "crates/forge-git",
6 "crates/forge-ssh",6 "crates/forge-ssh",
7 "crates/forge-web",7 "crates/forge-web",
8+ "crates/forge-web-base",
8 "crates/forge-ci",9 "crates/forge-ci",
9 "crates/forge-runner",10 "crates/forge-runner",
11+ "crates/forge-e2e",
10 ]12 ]
11 13
12 [workspace.package]14 [workspace.package]
@@ -31,6 +33,7 @@ forge-ci = { path = "crates/forge-ci" }
31 forge-git = { path = "crates/forge-git" }33 forge-git = { path = "crates/forge-git" }
32 forge-ssh = { path = "crates/forge-ssh" }34 forge-ssh = { path = "crates/forge-ssh" }
33 forge-runner = { path = "crates/forge-runner" }35 forge-runner = { path = "crates/forge-runner" }
36+forge-web-base = { path = "crates/forge-web-base" }
34 37
35 # async runtime and HTTP plumbing38 # async runtime and HTTP plumbing
36 tokio = { version = "1.53.3", features = ["full"] }39 tokio = { version = "1.53.3", features = ["full"] }
crates/forge-ci/build.rs → crates/forge-ci/build_identity.rsrenamed+19 -8
@@ -1,11 +1,14 @@
1-//! Emits the build identity: the git commit short sha, whether the tree was dirty, and the commit1+// Build identity for the binary crates. Not a build script of its own: each binary's build.rs pulls
2-//! date. It falls back to the FORGE_BUILD_COMMIT and FORGE_BUILD_DATE environment variables when2+// this file in with `include!("../forge-ci/build_identity.rs");` and calls `emit_identity()`. It
3-//! there is no git (a source tarball, a sandbox without the binary), and then to "unknown".3+// emits FORGE_GIT_SHA, FORGE_GIT_DATE and FORGE_GIT_DIRTY for that crate.
4-//! The dirty flag is only re-evaluated when HEAD or its ref moves.4+//
5-5+// Only release builds read git: the commit, its date and the dirty flag, with a rerun when HEAD
6-use std::{env, process::Command};6+// moves. Any other profile emits "unknown" and no per-commit input, so a new commit does not
7+// rebuild debug or test binaries. Release falls back to the FORGE_BUILD_COMMIT and FORGE_BUILD_DATE
8+// environment variables when there is no git (a source tarball, a sandbox without the binary).
7 9
8 fn git(args: &[&str]) -> Option<String> {10 fn git(args: &[&str]) -> Option<String> {
11+ use std::process::Command;
9 let out = Command::new("git").args(args).output().ok()?;12 let out = Command::new("git").args(args).output().ok()?;
10 if !out.status.success() {13 if !out.status.success() {
11 return None;14 return None;
@@ -14,10 +17,18 @@ fn git(args: &[&str]) -> Option<String> {
14 (!text.is_empty()).then_some(text)17 (!text.is_empty()).then_some(text)
15 }18 }
16 19
17-fn main() {20+pub fn emit_identity() {
21+ use std::env;
22+
23+ if env::var("PROFILE").as_deref() != Ok("release") {
24+ println!("cargo:rustc-env=FORGE_GIT_SHA=unknown");
25+ println!("cargo:rustc-env=FORGE_GIT_DATE=unknown");
26+ println!("cargo:rustc-env=FORGE_GIT_DIRTY=0");
27+ return;
28+ }
29+
18 println!("cargo:rerun-if-env-changed=FORGE_BUILD_COMMIT");30 println!("cargo:rerun-if-env-changed=FORGE_BUILD_COMMIT");
19 println!("cargo:rerun-if-env-changed=FORGE_BUILD_DATE");31 println!("cargo:rerun-if-env-changed=FORGE_BUILD_DATE");
20- println!("cargo:rerun-if-changed=build.rs");
21 if let Some(head) = git(&["rev-parse", "--git-path", "HEAD"]) {32 if let Some(head) = git(&["rev-parse", "--git-path", "HEAD"]) {
22 println!("cargo:rerun-if-changed={head}");33 println!("cargo:rerun-if-changed={head}");
23 }34 }
crates/forge-ci/src/build.rsmodified+36 -6
@@ -1,18 +1,48 @@
1 //! The build identity of this binary: version, git commit, commit date. Shared by the server and1 //! The build identity of this binary: version, git commit, commit date. Shared by the server and
2 //! the runner, which are the same binary, so a runner can be compared to the server it talks to.2 //! the runner, which are the same binary, so a runner can be compared to the server it talks to.
3 3
4+use std::sync::OnceLock;
5+
4 /// The crate version.6 /// The crate version.
5 pub const VERSION: &str = env!("CARGO_PKG_VERSION");7 pub const VERSION: &str = env!("CARGO_PKG_VERSION");
6-/// Short git sha of the commit built, or "unknown".8+
7-pub const COMMIT: &str = env!("FORGE_GIT_SHA");9+struct Identity {
8-/// Commit date (YYYY-MM-DD), or "unknown".10+ commit: &'static str,
9-pub const DATE: &str = env!("FORGE_GIT_DATE");11+ date: &'static str,
12+ dirty: bool,
13+}
14+
15+static IDENTITY: OnceLock<Identity> = OnceLock::new();
16+
17+/// Sets the commit, commit date and dirty flag of the running binary. Each binary sets this first
18+/// thing in main, so this crate has no per-commit input and a new commit does not rebuild
19+/// everything that depends on it. A second call is ignored.
20+pub fn set_identity(commit: &'static str, date: &'static str, dirty: bool) {
21+ let _ = IDENTITY.set(Identity {
22+ commit,
23+ date,
24+ dirty,
25+ });
26+}
27+
28+/// Short git sha of the commit built, or "unknown" before [`set_identity`].
29+pub fn commit() -> &'static str {
30+ IDENTITY.get().map_or("unknown", |i| i.commit)
31+}
32+
33+/// Commit date (YYYY-MM-DD), or "unknown" before [`set_identity`].
34+pub fn date() -> &'static str {
35+ IDENTITY.get().map_or("unknown", |i| i.date)
36+}
37+
10 /// True when the tree had uncommitted changes to tracked files at build time.38 /// True when the tree had uncommitted changes to tracked files at build time.
11-pub const DIRTY: bool = matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1");39+pub fn dirty() -> bool {
40+ IDENTITY.get().is_some_and(|i| i.dirty)
41+}
12 42
13 /// `0.1.0 (cf8e648, 2026-10-20)`, with `cf8e648-dirty` for a dirty tree.43 /// `0.1.0 (cf8e648, 2026-10-20)`, with `cf8e648-dirty` for a dirty tree.
14 pub fn display() -> String {44 pub fn display() -> String {
15- format_build(VERSION, COMMIT, DATE, DIRTY)45+ format_build(VERSION, commit(), date(), dirty())
16 }46 }
17 47
18 pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> String {48 pub fn format_build(version: &str, commit: &str, date: &str, dirty: bool) -> String {
crates/forge-e2e/Cargo.tomladded+32 -0
@@ -0,0 +1,32 @@
1+[package]
2+name = "forge-e2e"
3+description = "End-to-end tests for the forge binary: HTTP, git, SSH and CI over real servers"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[[test]]
10+name = "e2e"
11+path = "tests/e2e/main.rs"
12+
13+[dev-dependencies]
14+forge-core.workspace = true
15+forge-ci.workspace = true
16+forge-git.workspace = true
17+forge-runner = { workspace = true, features = ["test-host-executor"] }
18+tokio.workspace = true
19+tokio-util = { workspace = true, features = ["io"] }
20+reqwest.workspace = true
21+serde_json.workspace = true
22+base64.workspace = true
23+sha2.workspace = true
24+hex.workspace = true
25+flate2.workspace = true
26+tar.workspace = true
27+zip = { workspace = true }
28+tempfile.workspace = true
29+scraper = { workspace = true }
30+
31+[lints]
32+workspace = true
crates/forge-e2e/src/lib.rsadded+1 -0
@@ -0,0 +1 @@
1+//! End-to-end tests for the forge binary. The tests live in `tests/e2e`.
crates/forge-web/tests/e2e/account_mail_e2e.rs → crates/forge-e2e/tests/e2e/account_mail_e2e.rsrenamed+0 -0
crates/forge-web/tests/e2e/advisories_e2e.rs → crates/forge-e2e/tests/e2e/advisories_e2e.rsrenamed+2 -2
@@ -9,7 +9,7 @@
9 //! - a reader without Write gets a 404 on the page.9 //! - a reader without Write gets a 404 on the page.
10 10
11 use crate::common::{11 use crate::common::{
12- BIN, Http, Resp, Server, input_value, launch_with, login, pick_ports, tool_on_path,12+ Http, Resp, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path,
13 write_config_with,13 write_config_with,
14 };14 };
15 use std::fs;15 use std::fs;
@@ -122,7 +122,7 @@ async fn boot() -> Booted {
122 }122 }
123 123
124 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {124 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
125- let out = Command::new(BIN)125+ let out = Command::new(bin())
126 .arg("--config")126 .arg("--config")
127 .arg(config)127 .arg(config)
128 .args(["admin", "create-user", username])128 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/branch_protection_e2e.rs → crates/forge-e2e/tests/e2e/branch_protection_e2e.rsrenamed+2 -2
@@ -3,7 +3,7 @@
3 //! while the server runs. Helpers mirror `git_e2e.rs`.3 //! while the server runs. Helpers mirror `git_e2e.rs`.
4 4
5 use crate::common::{5 use crate::common::{
6- BIN, Http, Ports, Server, describe, input_value, launch, login, pick_ports, relaunch,6+ Http, Ports, Server, bin, describe, input_value, launch, login, pick_ports, relaunch,
7 tool_on_path, write_config,7 tool_on_path, write_config,
8 };8 };
9 use std::fs;9 use std::fs;
@@ -15,7 +15,7 @@ use forge_core::Store;
15 const TAHINLI_PW: &str = "tahinli-password-123";15 const TAHINLI_PW: &str = "tahinli-password-123";
16 16
17 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {17 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
18- let out = Command::new(BIN)18+ let out = Command::new(bin())
19 .arg("--config")19 .arg("--config")
20 .arg(config)20 .arg(config)
21 .args(["admin", "create-user", username])21 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/browse_e2e.rs → crates/forge-e2e/tests/e2e/browse_e2e.rsrenamed+2 -2
@@ -5,7 +5,7 @@
5 //! Cookies are handled by hand, as in `git_e2e.rs`: the session cookie is `__Host-forge_session`5 //! Cookies are handled by hand, as in `git_e2e.rs`: the session cookie is `__Host-forge_session`
6 //! with `Secure`, so a cookie jar would not send it over plain http.6 //! with `Secure`, so a cookie jar would not send it over plain http.
7 7
8-use crate::common::{BIN, describe, input_value, launch, pick_ports, tool_on_path, write_config};8+use crate::common::{bin, describe, input_value, launch, pick_ports, tool_on_path, write_config};
9 use std::fs;9 use std::fs;
10 use std::path::Path;10 use std::path::Path;
11 use std::process::{Command, Output};11 use std::process::{Command, Output};
@@ -147,7 +147,7 @@ fn assert_latest_bar(body: &str, what: &str, subject: &str, oid: &str, count: &s
147 }147 }
148 148
149 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {149 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
150- let out = Command::new(BIN)150+ let out = Command::new(bin())
151 .arg("--config")151 .arg("--config")
152 .arg(config)152 .arg(config)
153 .args(["admin", "create-user", username])153 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/ci_e2e.rs → crates/forge-e2e/tests/e2e/ci_e2e.rsrenamed+2 -2
@@ -11,7 +11,7 @@
11 //! - a live log: `log.txt` streams while a job runs and ends when the job finishes.11 //! - a live log: `log.txt` streams while a job runs and ends when the job finishes.
12 12
13 use crate::common::{13 use crate::common::{
14- BIN, FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, write_config,14+ FAST_CLAIMS, Http, Server, bin, input_value, launch_with, login, pick_ports, write_config,
15 };15 };
16 use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest};16 use forge_ci::proto::{JobAssignment, Outcome, RegisterRequest};
17 use forge_runner::client::ForgeClient;17 use forge_runner::client::ForgeClient;
@@ -104,7 +104,7 @@ fn first_text(body: &str, selector: &str) -> String {
104 }104 }
105 105
106 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {106 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
107- let out = Command::new(BIN)107+ let out = Command::new(bin())
108 .arg("--config")108 .arg("--config")
109 .arg(config)109 .arg(config)
110 .args(["admin", "create-user", username])110 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/common/http.rs → crates/forge-e2e/tests/e2e/common/http.rsrenamed+0 -0
crates/forge-web/tests/e2e/common/mod.rs → crates/forge-e2e/tests/e2e/common/mod.rsrenamed+44 -2
@@ -13,13 +13,55 @@ use std::fs;
13 use std::net::TcpStream;13 use std::net::TcpStream;
14 use std::path::{Path, PathBuf};14 use std::path::{Path, PathBuf};
15 use std::process::{Child, Command, ExitStatus, Output, Stdio};15 use std::process::{Child, Command, ExitStatus, Output, Stdio};
16+use std::sync::OnceLock;
16 use std::time::{Duration, Instant};17 use std::time::{Duration, Instant};
17 18
18 mod http;19 mod http;
19 20
20 pub use http::{Http, Resp, cookie_named, login};21 pub use http::{Http, Resp, cookie_named, login};
21 22
22-pub const BIN: &str = env!("CARGO_BIN_EXE_forge");23+/// The forge binary the tests start. `env!("CARGO_BIN_EXE_forge")` would only work in the package
24+/// that owns the binary, and these tests live in `forge-e2e`, which does not depend on forge-web.
25+/// CI sets `FORGE_BIN` to the prebuilt release binary. Without it, the dev-profile binary is built
26+/// once per test run, so `cargo test --workspace` works with no extra steps.
27+pub fn bin() -> &'static str {
28+ static BIN: OnceLock<String> = OnceLock::new();
29+ BIN.get_or_init(|| match std::env::var("FORGE_BIN") {
30+ Ok(path) if !path.is_empty() => path,
31+ _ => build_forge(),
32+ })
33+ .as_str()
34+}
35+
36+/// Builds `forge` with cargo and returns the executable path cargo reports for it.
37+fn build_forge() -> String {
38+ let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_owned());
39+ let output = Command::new(&cargo)
40+ .args([
41+ "build",
42+ "-p",
43+ "forge-web",
44+ "--bin",
45+ "forge",
46+ "--message-format=json-render-diagnostics",
47+ ])
48+ .current_dir(env!("CARGO_MANIFEST_DIR"))
49+ .stderr(Stdio::inherit())
50+ .output()
51+ .unwrap_or_else(|e| panic!("failed to run `{cargo} build -p forge-web --bin forge`: {e}"));
52+ assert!(
53+ output.status.success(),
54+ "`{cargo} build -p forge-web --bin forge` failed ({})",
55+ output.status
56+ );
57+ let stdout = String::from_utf8(output.stdout).expect("cargo output is UTF-8");
58+ stdout
59+ .lines()
60+ .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
61+ .find(|msg| msg["reason"] == "compiler-artifact" && msg["target"]["name"] == "forge")
62+ .and_then(|msg| msg["executable"].as_str().map(str::to_owned))
63+ .unwrap_or_else(|| panic!("cargo build reported no executable for the forge binary"))
64+}
23 65
24 /// How long a freshly spawned server gets to answer on all three listeners.66 /// How long a freshly spawned server gets to answer on all three listeners.
25 const READY_TIMEOUT: Duration = Duration::from_secs(30);67 const READY_TIMEOUT: Duration = Duration::from_secs(30);
@@ -180,7 +222,7 @@ pub async fn relaunch(config: &Path, log_path: &Path, ports: Ports) -> Server {
180 222
181 fn spawn(config: &Path, log_path: &Path) -> Server {223 fn spawn(config: &Path, log_path: &Path) -> Server {
182 let log = fs::File::create(log_path).expect("log file");224 let log = fs::File::create(log_path).expect("log file");
183- let child = Command::new(BIN)225+ let child = Command::new(bin())
184 .arg("--config")226 .arg("--config")
185 .arg(config)227 .arg(config)
186 .arg("serve")228 .arg("serve")
crates/forge-web/tests/e2e/community_i18n_e2e.rs → crates/forge-e2e/tests/e2e/community_i18n_e2e.rsrenamed+2 -2
@@ -4,14 +4,14 @@
4 use std::process::Command;4 use std::process::Command;
5 use std::time::Duration;5 use std::time::Duration;
6 6
7-use crate::common::{BIN, describe, launch, pick_ports, write_config};7+use crate::common::{bin, describe, launch, pick_ports, write_config};
8 use reqwest::header::ACCEPT_LANGUAGE;8 use reqwest::header::ACCEPT_LANGUAGE;
9 9
10 const PW: &str = "tahinli-password-123";10 const PW: &str = "tahinli-password-123";
11 11
12 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.12 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
13 fn admin(config: &std::path::Path, args: &[&str]) {13 fn admin(config: &std::path::Path, args: &[&str]) {
14- let out = Command::new(BIN)14+ let out = Command::new(bin())
15 .arg("--config")15 .arg("--config")
16 .arg(config)16 .arg(config)
17 .arg("admin")17 .arg("admin")
crates/forge-web/tests/e2e/discussions_e2e.rs → crates/forge-e2e/tests/e2e/discussions_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! owner can still write.4 //! owner can still write.
5 5
6 use crate::common::{6 use crate::common::{
7- BIN, Http, input_value, launch, login, pick_ports, tool_on_path, write_config,7+ Http, bin, input_value, launch, login, pick_ports, tool_on_path, write_config,
8 };8 };
9 use std::path::Path;9 use std::path::Path;
10 use std::process::Command;10 use std::process::Command;
@@ -13,7 +13,7 @@ const TAHINLI_PW: &str = "tahinli-password-123";
13 const BOB_PW: &str = "bob-password-4567";13 const BOB_PW: &str = "bob-password-4567";
14 14
15 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {15 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
16- let out = Command::new(BIN)16+ let out = Command::new(bin())
17 .arg("--config")17 .arg("--config")
18 .arg(config)18 .arg(config)
19 .args(["admin", "create-user", username])19 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/git_e2e.rs → crates/forge-e2e/tests/e2e/git_e2e.rsrenamed+2 -2
@@ -5,7 +5,7 @@
5 //! cookie jar would not send it over plain http. The test parses `Set-Cookie` and sends `Cookie`.5 //! cookie jar would not send it over plain http. The test parses `Set-Cookie` and sends `Cookie`.
6 6
7 use crate::common::{7 use crate::common::{
8- BIN, Http, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,8+ Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
9 };9 };
10 use std::fs;10 use std::fs;
11 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
@@ -17,7 +17,7 @@ const TAHINLI_PW: &str = "tahinli-password-123";
17 const BOB_PW: &str = "bob-password-4567";17 const BOB_PW: &str = "bob-password-4567";
18 18
19 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {19 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
20- let out = Command::new(BIN)20+ let out = Command::new(bin())
21 .arg("--config")21 .arg("--config")
22 .arg(config)22 .arg(config)
23 .args(["admin", "create-user", username])23 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/i18n_e2e.rs → crates/forge-e2e/tests/e2e/i18n_e2e.rsrenamed+2 -2
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
5 use std::process::Command;5 use std::process::Command;
6 6
7 use crate::common::{7 use crate::common::{
8- BIN, Http, Server, describe, input_value, launch, login, pick_ports, write_config,8+ Http, Server, bin, describe, input_value, launch, login, pick_ports, write_config,
9 };9 };
10 use forge_core::Store;10 use forge_core::Store;
11 11
@@ -13,7 +13,7 @@ const PW: &str = "tahinli-password-123";
13 13
14 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.14 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
15 fn admin(config: &Path, args: &[&str]) {15 fn admin(config: &Path, args: &[&str]) {
16- let out = Command::new(BIN)16+ let out = Command::new(bin())
17 .arg("--config")17 .arg("--config")
18 .arg(config)18 .arg(config)
19 .arg("admin")19 .arg("admin")
crates/forge-web/tests/e2e/issue_close_e2e.rs → crates/forge-e2e/tests/e2e/issue_close_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! file, and every push is a real `git push` through the git HTTP endpoints.4 //! file, and every push is a real `git push` through the git HTTP endpoints.
5 5
6 use crate::common::{6 use crate::common::{
7- BIN, Http, input_value, launch, login, pick_ports, relaunch, tool_on_path, write_config,7+ Http, bin, input_value, launch, login, pick_ports, relaunch, tool_on_path, write_config,
8 };8 };
9 use std::fs;9 use std::fs;
10 use std::future::Future;10 use std::future::Future;
@@ -18,7 +18,7 @@ const TAHINLI_PW: &str = "tahinli-password-123";
18 const BOB_PW: &str = "bob-password-4567";18 const BOB_PW: &str = "bob-password-4567";
19 19
20 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {20 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
21- let out = Command::new(BIN)21+ let out = Command::new(bin())
22 .arg("--config")22 .arg("--config")
23 .arg(config)23 .arg(config)
24 .args(["admin", "create-user", username])24 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/lfs_e2e.rs → crates/forge-e2e/tests/e2e/lfs_e2e.rsrenamed+2 -2
@@ -5,7 +5,7 @@
5 //! Git config is isolated from the developer's machine: `HOME` and `GIT_CONFIG_GLOBAL` point into5 //! Git config is isolated from the developer's machine: `HOME` and `GIT_CONFIG_GLOBAL` point into
6 //! the test's temp dir.6 //! the test's temp dir.
7 7
8-use crate::common::{BIN, Http, describe, input_value, launch, login, pick_ports, write_config};8+use crate::common::{Http, bin, describe, input_value, launch, login, pick_ports, write_config};
9 use std::fs;9 use std::fs;
10 use std::path::Path;10 use std::path::Path;
11 use std::process::{Command, Output};11 use std::process::{Command, Output};
@@ -14,7 +14,7 @@ const TAHINLI_PW: &str = "tahinli-password-123";
14 const FILE_SIZE: usize = 100 * 1024;14 const FILE_SIZE: usize = 100 * 1024;
15 15
16 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {16 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
17- let out = Command::new(BIN)17+ let out = Command::new(bin())
18 .arg("--config")18 .arg("--config")
19 .arg(config)19 .arg(config)
20 .args(["admin", "create-user", username])20 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/main.rs → crates/forge-e2e/tests/e2e/main.rsrenamed+0 -0
crates/forge-web/tests/e2e/merge_queue_e2e.rs → crates/forge-e2e/tests/e2e/merge_queue_e2e.rsrenamed+2 -2
@@ -10,7 +10,7 @@
10 #![allow(dead_code)]10 #![allow(dead_code)]
11 11
12 use crate::common::{12 use crate::common::{
13- BIN, FAST_CLAIMS, Http, Server, input_value, launch_with, login, pick_ports, tool_on_path,13+ FAST_CLAIMS, Http, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path,
14 write_config,14 write_config,
15 };15 };
16 use forge_ci::proto::{JobAssignment, RegisterRequest};16 use forge_ci::proto::{JobAssignment, RegisterRequest};
@@ -46,7 +46,7 @@ fn first_text(body: &str, selector: &str) -> String {
46 }46 }
47 47
48 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {48 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
49- let out = Command::new(BIN)49+ let out = Command::new(bin())
50 .arg("--config")50 .arg("--config")
51 .arg(config)51 .arg(config)
52 .args(["admin", "create-user", username])52 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/mirrors_e2e.rs → crates/forge-e2e/tests/e2e/mirrors_e2e.rsrenamed+2 -2
@@ -10,7 +10,7 @@
10 //! - the mirror pages and the server log never contain the access token.10 //! - the mirror pages and the server log never contain the access token.
11 11
12 use crate::common::{12 use crate::common::{
13- BIN, Http, Server, input_value, launch_with, login, pick_ports, tool_on_path, write_config_with,13+ Http, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path, write_config_with,
14 };14 };
15 use std::collections::BTreeSet;15 use std::collections::BTreeSet;
16 use std::fs;16 use std::fs;
@@ -37,7 +37,7 @@ fn form_actions(body: &str, suffix: &str) -> Vec<String> {
37 }37 }
38 38
39 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {39 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
40- let out = Command::new(BIN)40+ let out = Command::new(bin())
41 .arg("--config")41 .arg("--config")
42 .arg(config)42 .arg(config)
43 .args(["admin", "create-user", username])43 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/oci_e2e.rs → crates/forge-e2e/tests/e2e/oci_e2e.rsrenamed+2 -2
@@ -5,7 +5,7 @@
5 //! up through the store before the server starts, since the web has no way to make one private.5 //! up through the store before the server starts, since the web has no way to make one private.
6 //! The last test drives podman when it is installed; it is ignored by default.6 //! The last test drives podman when it is installed; it is ignored by default.
7 7
8-use crate::common::{BIN, Server, describe, launch, pick_ports, tool_on_path, write_config};8+use crate::common::{Server, bin, describe, launch, pick_ports, tool_on_path, write_config};
9 use std::path::Path;9 use std::path::Path;
10 use std::process::Command;10 use std::process::Command;
11 use std::time::Duration;11 use std::time::Duration;
@@ -118,7 +118,7 @@ impl Http {
118 118
119 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.119 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
120 fn admin(config: &Path, args: &[&str]) {120 fn admin(config: &Path, args: &[&str]) {
121- let out = Command::new(BIN)121+ let out = Command::new(bin())
122 .arg("--config")122 .arg("--config")
123 .arg(config)123 .arg(config)
124 .arg("admin")124 .arg("admin")
crates/forge-web/tests/e2e/orgs_core_e2e.rs → crates/forge-e2e/tests/e2e/orgs_core_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! are written straight into the database before the server starts.4 //! are written straight into the database before the server starts.
5 5
6 use crate::common::{6 use crate::common::{
7- BIN, Http, Resp, Server, cookie_named, describe, input_value, launch, pick_ports, write_config,7+ Http, Resp, Server, bin, cookie_named, describe, input_value, launch, pick_ports, write_config,
8 };8 };
9 use std::future::Future;9 use std::future::Future;
10 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
@@ -25,7 +25,7 @@ const ORG_SESSION: &str = "org-session-token-for-tests-0123456789";
25 25
26 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.26 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
27 fn admin(config: &Path, args: &[&str]) {27 fn admin(config: &Path, args: &[&str]) {
28- let out = Command::new(BIN)28+ let out = Command::new(bin())
29 .arg("--config")29 .arg("--config")
30 .arg(config)30 .arg(config)
31 .arg("admin")31 .arg("admin")
crates/forge-web/tests/e2e/orgs_live_e2e.rs → crates/forge-e2e/tests/e2e/orgs_live_e2e.rsrenamed+2 -2
@@ -3,7 +3,7 @@
3 //! and reads each stream. It also checks that each stream refuses the viewers its page refuses.3 //! and reads each stream. It also checks that each stream refuses the viewers its page refuses.
4 4
5 use crate::common::{5 use crate::common::{
6- BIN, Http, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,6+ Http, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
7 };7 };
8 use std::path::Path;8 use std::path::Path;
9 use std::process::{Command, Output};9 use std::process::{Command, Output};
@@ -30,7 +30,7 @@ fn live_url(body: &str) -> Option<String> {
30 30
31 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.31 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
32 fn admin(config: &Path, args: &[&str]) -> Output {32 fn admin(config: &Path, args: &[&str]) -> Output {
33- let out = Command::new(BIN)33+ let out = Command::new(bin())
34 .arg("--config")34 .arg("--config")
35 .arg(config)35 .arg(config)
36 .arg("admin")36 .arg("admin")
crates/forge-web/tests/e2e/orgs_ui_e2e.rs → crates/forge-e2e/tests/e2e/orgs_ui_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! handled by hand, as in `repo_collaborators_e2e.rs`.4 //! handled by hand, as in `repo_collaborators_e2e.rs`.
5 5
6 use crate::common::{6 use crate::common::{
7- BIN, Http, Resp, describe, input_value, launch, launch_with, login, pick_ports, tool_on_path,7+ Http, Resp, bin, describe, input_value, launch, launch_with, login, pick_ports, tool_on_path,
8 write_config,8 write_config,
9 };9 };
10 use std::fs;10 use std::fs;
@@ -43,7 +43,7 @@ fn owner_options(body: &str) -> Vec<String> {
43 43
44 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.44 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
45 fn admin(config: &Path, args: &[&str]) -> Output {45 fn admin(config: &Path, args: &[&str]) -> Output {
46- let out = Command::new(BIN)46+ let out = Command::new(bin())
47 .arg("--config")47 .arg("--config")
48 .arg(config)48 .arg(config)
49 .arg("admin")49 .arg("admin")
crates/forge-web/tests/e2e/packages_e2e.rs → crates/forge-e2e/tests/e2e/packages_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! private package are seeded through the store before the server starts, since the web API has4 //! private package are seeded through the store before the server starts, since the web API has
5 //! no way to make a package private.5 //! no way to make a package private.
6 6
7-use crate::common::{BIN, Server, describe, launch, pick_ports, write_config};7+use crate::common::{Server, bin, describe, launch, pick_ports, write_config};
8 use std::io::Write;8 use std::io::Write;
9 use std::path::Path;9 use std::path::Path;
10 use std::process::Command;10 use std::process::Command;
@@ -90,7 +90,7 @@ impl Http {
90 90
91 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.91 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
92 fn admin(config: &Path, args: &[&str]) {92 fn admin(config: &Path, args: &[&str]) {
93- let out = Command::new(BIN)93+ let out = Command::new(bin())
94 .arg("--config")94 .arg("--config")
95 .arg(config)95 .arg(config)
96 .arg("admin")96 .arg("admin")
crates/forge-web/tests/e2e/pulls_e2e.rs → crates/forge-e2e/tests/e2e/pulls_e2e.rsrenamed+2 -2
@@ -6,7 +6,7 @@
6 //! a fork pull merged by squash, and a conflict that blocks the merge.6 //! a fork pull merged by squash, and a conflict that blocks the merge.
7 7
8 use crate::common::{8 use crate::common::{
9- BIN, Http, Resp, Server, input_value, launch, login, pick_ports, tool_on_path, write_config,9+ Http, Resp, Server, bin, input_value, launch, login, pick_ports, tool_on_path, write_config,
10 };10 };
11 use std::fs;11 use std::fs;
12 use std::path::{Path, PathBuf};12 use std::path::{Path, PathBuf};
@@ -31,7 +31,7 @@ fn state_badge(body: &str) -> String {
31 }31 }
32 32
33 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {33 fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
34- let out = Command::new(BIN)34+ let out = Command::new(bin())
35 .arg("--config")35 .arg("--config")
36 .arg(config)36 .arg(config)
37 .args(["admin", "create-user", username])37 .args(["admin", "create-user", username])
crates/forge-web/tests/e2e/repo_collaborators_e2e.rs → crates/forge-e2e/tests/e2e/repo_collaborators_e2e.rsrenamed+2 -2
@@ -3,7 +3,7 @@
3 //! its POST forms over HTTP. Cookies are handled by hand (see `repo_settings_e2e.rs`).3 //! its POST forms over HTTP. Cookies are handled by hand (see `repo_settings_e2e.rs`).
4 4
5 use crate::common::{5 use crate::common::{
6- BIN, Http, Resp, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path,6+ Http, Resp, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path,
7 write_config,7 write_config,
8 };8 };
9 use std::fs;9 use std::fs;
@@ -17,7 +17,7 @@ const PW: &str = "tahinli-password-123";
17 17
18 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.18 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
19 fn admin(config: &Path, args: &[&str]) -> Output {19 fn admin(config: &Path, args: &[&str]) -> Output {
20- let out = Command::new(BIN)20+ let out = Command::new(bin())
21 .arg("--config")21 .arg("--config")
22 .arg(config)22 .arg(config)
23 .arg("admin")23 .arg("admin")
crates/forge-web/tests/e2e/repo_rename_e2e.rs → crates/forge-e2e/tests/e2e/repo_rename_e2e.rsrenamed+2 -2
@@ -6,7 +6,7 @@
6 //! which a cookie jar would not send over plain http.6 //! which a cookie jar would not send over plain http.
7 7
8 use crate::common::{8 use crate::common::{
9- BIN, Http, Resp, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,9+ Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
10 };10 };
11 use std::fs;11 use std::fs;
12 use std::path::Path;12 use std::path::Path;
@@ -30,7 +30,7 @@ fn form_action(body: &str, suffix: &str) -> String {
30 30
31 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.31 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
32 fn admin(config: &Path, args: &[&str]) {32 fn admin(config: &Path, args: &[&str]) {
33- let out = Command::new(BIN)33+ let out = Command::new(bin())
34 .arg("--config")34 .arg("--config")
35 .arg(config)35 .arg(config)
36 .arg("admin")36 .arg("admin")
crates/forge-web/tests/e2e/repo_settings_e2e.rs → crates/forge-e2e/tests/e2e/repo_settings_e2e.rsrenamed+2 -2
@@ -5,7 +5,7 @@
5 //! which a cookie jar would not send over plain http.5 //! which a cookie jar would not send over plain http.
6 6
7 use crate::common::{7 use crate::common::{
8- BIN, Http, Resp, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path,8+ Http, Resp, bin, cookie_named, describe, input_value, launch, login, pick_ports, tool_on_path,
9 write_config,9 write_config,
10 };10 };
11 use std::fs;11 use std::fs;
@@ -19,7 +19,7 @@ const PW: &str = "tahinli-password-123";
19 19
20 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.20 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
21 fn admin(config: &Path, args: &[&str]) -> Output {21 fn admin(config: &Path, args: &[&str]) -> Output {
22- let out = Command::new(BIN)22+ let out = Command::new(bin())
23 .arg("--config")23 .arg("--config")
24 .arg(config)24 .arg(config)
25 .arg("admin")25 .arg("admin")
crates/forge-web/tests/e2e/repo_transfer_e2e.rs → crates/forge-e2e/tests/e2e/repo_transfer_e2e.rsrenamed+2 -2
@@ -6,7 +6,7 @@
6 //! which a cookie jar would not send over plain http.6 //! which a cookie jar would not send over plain http.
7 7
8 use crate::common::{8 use crate::common::{
9- BIN, Http, Resp, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,9+ Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
10 };10 };
11 use std::fs;11 use std::fs;
12 use std::process::Command;12 use std::process::Command;
@@ -30,7 +30,7 @@ fn form_action(body: &str, suffix: &str) -> String {
30 30
31 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.31 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
32 fn admin(config: &std::path::Path, args: &[&str]) {32 fn admin(config: &std::path::Path, args: &[&str]) {
33- let out = Command::new(BIN)33+ let out = Command::new(bin())
34 .arg("--config")34 .arg("--config")
35 .arg(config)35 .arg(config)
36 .arg("admin")36 .arg("admin")
crates/forge-web/tests/e2e/runner_subcommand.rs → crates/forge-e2e/tests/e2e/runner_subcommand.rsrenamed+3 -1
@@ -8,8 +8,10 @@ use std::process::Command;
8 8
9 use tempfile::TempDir;9 use tempfile::TempDir;
10 10
11+use crate::common::bin;
12+
11 fn forge() -> Command {13 fn forge() -> Command {
12- Command::new(env!("CARGO_BIN_EXE_forge"))14+ Command::new(bin())
13 }15 }
14 16
15 /// Unprivileged user namespaces, as `crates/forge-runner/tests/sandbox.rs` checks them.17 /// Unprivileged user namespaces, as `crates/forge-runner/tests/sandbox.rs` checks them.
crates/forge-web/tests/e2e/section_nav_e2e.rs → crates/forge-e2e/tests/e2e/section_nav_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 4
5 #![allow(dead_code)]5 #![allow(dead_code)]
6 6
7-use crate::common::{BIN, Http, Server, describe, launch, login, pick_ports, write_config};7+use crate::common::{Http, Server, bin, describe, launch, login, pick_ports, write_config};
8 use std::path::Path;8 use std::path::Path;
9 use std::process::Command;9 use std::process::Command;
10 10
@@ -93,7 +93,7 @@ fn theme_button(body: &str) -> (String, String) {
93 93
94 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.94 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
95 fn admin(config: &Path, args: &[&str]) {95 fn admin(config: &Path, args: &[&str]) {
96- let out = Command::new(BIN)96+ let out = Command::new(bin())
97 .arg("--config")97 .arg("--config")
98 .arg(config)98 .arg(config)
99 .arg("admin")99 .arg("admin")
crates/forge-web/tests/e2e/snippets_e2e.rs → crates/forge-e2e/tests/e2e/snippets_e2e.rsrenamed+2 -2
@@ -3,7 +3,7 @@
3 //! `Secure`. Files are fetched from the user-content listener, as a browser would.3 //! `Secure`. Files are fetched from the user-content listener, as a browser would.
4 4
5 use crate::common::{5 use crate::common::{
6- BIN, Http, Server, describe, input_value, launch, login, pick_ports, write_config,6+ Http, Server, bin, describe, input_value, launch, login, pick_ports, write_config,
7 };7 };
8 use std::path::{Path, PathBuf};8 use std::path::{Path, PathBuf};
9 use std::process::Command;9 use std::process::Command;
@@ -35,7 +35,7 @@ fn link_href(body: &str, text: &str) -> String {
35 35
36 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.36 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
37 fn admin(config: &Path, args: &[&str]) {37 fn admin(config: &Path, args: &[&str]) {
38- let out = Command::new(BIN)38+ let out = Command::new(bin())
39 .arg("--config")39 .arg("--config")
40 .arg(config)40 .arg(config)
41 .arg("admin")41 .arg("admin")
crates/forge-web/tests/e2e/stars_e2e.rs → crates/forge-e2e/tests/e2e/stars_e2e.rsrenamed+2 -2
@@ -3,7 +3,7 @@
3 //! HTTP. Cookies are set by hand because the session cookie is `__Host-` and `Secure`.3 //! HTTP. Cookies are set by hand because the session cookie is `__Host-` and `Secure`.
4 4
5 use crate::common::{5 use crate::common::{
6- BIN, Http, Resp, Server, describe, input_value, launch, login, pick_ports, tool_on_path,6+ Http, Resp, Server, bin, describe, input_value, launch, login, pick_ports, tool_on_path,
7 write_config,7 write_config,
8 };8 };
9 use std::fs;9 use std::fs;
@@ -17,7 +17,7 @@ const PW: &str = "tahinli-password-123";
17 17
18 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.18 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
19 fn admin(config: &Path, args: &[&str]) {19 fn admin(config: &Path, args: &[&str]) {
20- let out = Command::new(BIN)20+ let out = Command::new(bin())
21 .arg("--config")21 .arg("--config")
22 .arg(config)22 .arg(config)
23 .arg("admin")23 .arg("admin")
crates/forge-web/tests/e2e/ui_prefs_e2e.rs → crates/forge-e2e/tests/e2e/ui_prefs_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! because the session cookie is `__Host-` and `Secure`.4 //! because the session cookie is `__Host-` and `Secure`.
5 5
6 use crate::common::{6 use crate::common::{
7- BIN, Http, Server, cookie_named, describe, input_value, launch, login, pick_ports, write_config,7+ Http, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports, write_config,
8 };8 };
9 use std::path::Path;9 use std::path::Path;
10 use std::process::Command;10 use std::process::Command;
@@ -105,7 +105,7 @@ fn pressed_theme(body: &str) -> Option<String> {
105 105
106 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.106 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
107 fn admin(config: &Path, args: &[&str]) {107 fn admin(config: &Path, args: &[&str]) {
108- let out = Command::new(BIN)108+ let out = Command::new(bin())
109 .arg("--config")109 .arg("--config")
110 .arg(config)110 .arg(config)
111 .arg("admin")111 .arg("admin")
crates/forge-web/tests/e2e/user_delete_e2e.rs → crates/forge-e2e/tests/e2e/user_delete_e2e.rsrenamed+2 -2
@@ -4,7 +4,7 @@
4 //! session cookie is `__Host-` and `Secure`.4 //! session cookie is `__Host-` and `Secure`.
5 5
6 use crate::common::{6 use crate::common::{
7- BIN, Http, Resp, Server, cookie_named, describe, input_value, launch, login, pick_ports,7+ Http, Resp, Server, bin, cookie_named, describe, input_value, launch, login, pick_ports,
8 write_config,8 write_config,
9 };9 };
10 use std::fs;10 use std::fs;
@@ -23,7 +23,7 @@ const PW: &str = "tahinli-password-123";
23 23
24 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.24 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
25 fn admin(config: &Path, args: &[&str]) {25 fn admin(config: &Path, args: &[&str]) {
26- let out = Command::new(BIN)26+ let out = Command::new(bin())
27 .arg("--config")27 .arg("--config")
28 .arg(config)28 .arg(config)
29 .arg("admin")29 .arg("admin")
crates/forge-web/tests/e2e/wiki_e2e.rs → crates/forge-e2e/tests/e2e/wiki_e2e.rsrenamed+2 -2
@@ -6,7 +6,7 @@
6 //! which a cookie jar would not send over plain http.6 //! which a cookie jar would not send over plain http.
7 7
8 use crate::common::{8 use crate::common::{
9- BIN, Http, Resp, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,9+ Http, Resp, bin, describe, input_value, launch, login, pick_ports, tool_on_path, write_config,
10 };10 };
11 use std::fs;11 use std::fs;
12 use std::path::Path;12 use std::path::Path;
@@ -20,7 +20,7 @@ const PW: &str = "tahinli-password-123";
20 20
21 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.21 /// Runs an admin subcommand with the password in FORGE_PASSWORD and asserts it succeeded.
22 fn admin(config: &Path, args: &[&str]) {22 fn admin(config: &Path, args: &[&str]) {
23- let out = Command::new(BIN)23+ let out = Command::new(bin())
24 .arg("--config")24 .arg("--config")
25 .arg(config)25 .arg(config)
26 .arg("admin")26 .arg("admin")
crates/forge-runner/build.rsadded+10 -0
@@ -0,0 +1,10 @@
1+//! Emits the build identity (FORGE_GIT_SHA, FORGE_GIT_DATE, FORGE_GIT_DIRTY) for this binary.
2+//! The logic lives in forge-ci's build_identity.rs, shared with forge-web.
3+
4+include!("../forge-ci/build_identity.rs");
5+
6+fn main() {
7+ println!("cargo:rerun-if-changed=build.rs");
8+ println!("cargo:rerun-if-changed=../forge-ci/build_identity.rs");
9+ emit_identity();
10+}
crates/forge-runner/src/cache.rsmodified+275 -9
@@ -6,13 +6,16 @@
6 //! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids6 //! Layout under `work_dir/.cache`. The leading dot keeps it apart from job dirs, since job ids
7 //! never start with one:7 //! never start with one:
8 //! - `<sha256 of repo, job name and key>/` is one entry. It holds `p0`, `p1`, ... for the cached8 //! - `<sha256 of repo, job name and key>/` is one entry. It holds `p0`, `p1`, ... for the cached
9-//! paths, `manifest.json` (the workspace path of each `pN`) and `meta.json`.9+//! paths, `manifest.json` (the workspace path of each `pN`), `meta.json` and `stamps.json`.
10 //! - `.new-<job>` and `.old-<job>` are one job's scratch dirs. A crashed job can leave them behind,10 //! - `.new-<job>` and `.old-<job>` are one job's scratch dirs. A crashed job can leave them behind,
11 //! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-<job>` is swept too: older11 //! and [`CacheStore::sweep_stale`] removes them at startup. `.inuse-<job>` is swept too: older
12 //! runners moved an entry there while a job used it.12 //! runners moved an entry there while a job used it.
13+//! - `.stamps-<job>` is one job's file of tracked-file stamps, written at restore and copied into
14+//! the entry at save. It sits here, not in the workspace, so the job cannot change it.
13 //!15 //!
14 //! A restore never fails a job. A failure is logged and the job runs without the cache.16 //! A restore never fails a job. A failure is logged and the job runs without the cache.
15 17
18+use std::collections::BTreeMap;
16 use std::fs;19 use std::fs;
17 use std::io;20 use std::io;
18 use std::path::{Component, Path, PathBuf};21 use std::path::{Component, Path, PathBuf};
@@ -37,7 +40,8 @@ const MAX_KEY_LEN: usize = 256;
37 const MAX_STDERR: usize = 500;40 const MAX_STDERR: usize = 500;
38 const MANIFEST: &str = "manifest.json";41 const MANIFEST: &str = "manifest.json";
39 const META: &str = "meta.json";42 const META: &str = "meta.json";
40-const SCRATCH_PREFIXES: [&str; 3] = [".inuse-", ".new-", ".old-"];43+const STAMPS: &str = "stamps.json";
44+const SCRATCH_PREFIXES: [&str; 4] = [".inuse-", ".new-", ".old-", ".stamps-"];
41 45
42 /// Errors from the build cache. They are logged to the job, never returned to the forge.46 /// Errors from the build cache. They are logged to the job, never returned to the forge.
43 #[derive(Debug, thiserror::Error)]47 #[derive(Debug, thiserror::Error)]
@@ -52,6 +56,24 @@ pub enum CacheError {
52 NotDir(PathBuf),56 NotDir(PathBuf),
53 #[error("cp failed: {0}")]57 #[error("cp failed: {0}")]
54 Copy(String),58 Copy(String),
59+ #[error("git ls-tree failed: {0}")]
60+ Git(String),
61+}
62+
63+/// One tracked file's stamp: the blob it had and the mtime it was given, in Unix seconds.
64+#[derive(Debug, Clone, Serialize, Deserialize)]
65+struct Stamp {
66+ blob: String,
67+ mtime: i64,
68+}
69+
70+/// Tracked file path to its stamp. Read from `stamps.json`, and written to the job's scratch file.
71+type Stamps = BTreeMap<String, Stamp>;
72+
73+/// What one restored entry gave the job: its size and the stamps it recorded.
74+struct Restored {
75+ size: u64,
76+ stamps: Stamps,
55 }77 }
56 78
57 /// What `meta.json` records about one entry.79 /// What `meta.json` records about one entry.
@@ -136,15 +158,17 @@ impl CacheStore {
136 };158 };
137 159
138 if !job.cache_key.is_empty()160 if !job.cache_key.is_empty()
139- && let Some(size) = self161+ && let Some(restored) = self
140 .restore_from(job, &job.cache_key, workspace, &wanted, &mut lines)162 .restore_from(job, &job.cache_key, workspace, &wanted, &mut lines)
141 .await163 .await
142 {164 {
143 lines.push(format!(165 lines.push(format!(
144 "runner: cache hit {} ({})",166 "runner: cache hit {} ({})",
145 job.cache_key,167 job.cache_key,
146- human(size)168+ human(restored.size)
147 ));169 ));
170+ self.stamp_files(job, workspace, &restored.stamps, &mut lines)
171+ .await;
148 return lines;172 return lines;
149 }173 }
150 174
@@ -152,16 +176,19 @@ impl CacheStore {
152 if key.is_empty() || key.len() > MAX_KEY_LEN {176 if key.is_empty() || key.len() > MAX_KEY_LEN {
153 continue;177 continue;
154 }178 }
155- if self179+ if let Some(restored) = self
156 .restore_from(job, key, workspace, &wanted, &mut lines)180 .restore_from(job, key, workspace, &wanted, &mut lines)
157 .await181 .await
158- .is_some()
159 {182 {
160 lines.push(format!("runner: cache restored from fallback {key}"));183 lines.push(format!("runner: cache restored from fallback {key}"));
184+ self.stamp_files(job, workspace, &restored.stamps, &mut lines)
185+ .await;
161 return lines;186 return lines;
162 }187 }
163 }188 }
164 lines.push("runner: cache miss".to_owned());189 lines.push("runner: cache miss".to_owned());
190+ self.stamp_files(job, workspace, &Stamps::new(), &mut lines)
191+ .await;
165 lines192 lines
166 }193 }
167 194
@@ -193,7 +220,7 @@ impl CacheStore {
193 }220 }
194 221
195 /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is.222 /// Copies the entry for `key`'s wanted paths into the workspace. The entry is left as it is.
196- /// Returns the entry size when at least one path was restored.223+ /// Returns the entry size and stamps when at least one path was restored.
197 async fn restore_from(224 async fn restore_from(
198 &self,225 &self,
199 job: &JobAssignment,226 job: &JobAssignment,
@@ -201,7 +228,7 @@ impl CacheStore {
201 workspace: &Path,228 workspace: &Path,
202 wanted: &[PathBuf],229 wanted: &[PathBuf],
203 lines: &mut Vec<String>,230 lines: &mut Vec<String>,
204- ) -> Option<u64> {231+ ) -> Option<Restored> {
205 let _guard = self.lock.read().await;232 let _guard = self.lock.read().await;
206 let source = self.entry_dir(&job.repo, &job.job_name, key);233 let source = self.entry_dir(&job.repo, &job.job_name, key);
207 if !is_dir(&source) {234 if !is_dir(&source) {
@@ -214,6 +241,8 @@ impl CacheStore {
214 return None;241 return None;
215 }242 }
216 };243 };
244+ // Read under the lock, so the stamps belong to the entry copied here.
245+ let stamps = read_stamps(&source);
217 let mut restored = 0usize;246 let mut restored = 0usize;
218 for (k, rel) in selected(&manifest, wanted, lines) {247 for (k, rel) in selected(&manifest, wanted, lines) {
219 let src = source.join(format!("p{k}"));248 let src = source.join(format!("p{k}"));
@@ -229,10 +258,117 @@ impl CacheStore {
229 if restored == 0 {258 if restored == 0 {
230 return None;259 return None;
231 }260 }
232- Some(match read_meta(&source) {261+ let size = match read_meta(&source) {
233 Some(meta) => meta.size_bytes,262 Some(meta) => meta.size_bytes,
234 None => dir_size(&source).await,263 None => dir_size(&source).await,
264+ };
265+ Some(Restored { size, stamps })
266+ }
267+
268+ /// Sets each tracked file's mtime to when its content last changed. A file whose blob matches
269+ /// `previous` keeps that stamp, and any other file gets the current time. The new stamps go to
270+ /// the job's scratch file for the save. Never fails the job.
271+ async fn stamp_files(
272+ &self,
273+ job: &JobAssignment,
274+ workspace: &Path,
275+ previous: &Stamps,
276+ lines: &mut Vec<String>,
277+ ) {
278+ match self.try_stamp_files(job, workspace, previous).await {
279+ Ok((kept, changed)) => {
280+ if !previous.is_empty() {
281+ lines.push(format!(
282+ "runner: file times restored ({kept} unchanged, {changed} changed)"
283+ ));
284+ }
285+ }
286+ Err(e) => lines.push(format!("runner: cache stamps skipped: {e}")),
287+ }
288+ }
289+
290+ /// The work of [`CacheStore::stamp_files`]. Returns how many files kept their stamp and how
291+ /// many got the current time.
292+ async fn try_stamp_files(
293+ &self,
294+ job: &JobAssignment,
295+ workspace: &Path,
296+ previous: &Stamps,
297+ ) -> Result<(usize, usize), CacheError> {
298+ // The checkout is at the job's commit, so HEAD lists exactly the tracked files.
299+ let listing = Command::new("git")
300+ .arg("-C")
301+ .arg(workspace)
302+ .args(["ls-tree", "-r", "-z", "HEAD"])
303+ .stdin(Stdio::null())
304+ .stderr(Stdio::piped())
305+ .kill_on_drop(true)
306+ .output()
307+ .await?;
308+ if !listing.status.success() {
309+ let stderr: String = String::from_utf8_lossy(&listing.stderr)
310+ .chars()
311+ .take(MAX_STDERR)
312+ .collect();
313+ return Err(CacheError::Git(stderr.trim().to_owned()));
314+ }
315+
316+ let now = unix_secs(SystemTime::now());
317+ let mut stamps = Stamps::new();
318+ let mut files = Vec::new();
319+ let (mut kept, mut changed) = (0usize, 0usize);
320+ // Records are `<mode> <type> <oid>\t<path>`, NUL terminated. Only regular files count.
321+ for record in listing.stdout.split(|b| *b == 0).filter(|r| !r.is_empty()) {
322+ let Some(tab) = record.iter().position(|b| *b == b'\t') else {
323+ continue;
324+ };
325+ let (info, path) = (&record[..tab], &record[tab + 1..]);
326+ let (Ok(info), Ok(path)) = (std::str::from_utf8(info), std::str::from_utf8(path))
327+ else {
328+ continue;
329+ };
330+ let mut fields = info.split(' ');
331+ let mode = fields.next();
332+ let blob = fields.nth(1);
333+ let (Some(mode), Some(blob)) = (mode, blob) else {
334+ continue;
335+ };
336+ if mode != "100644" && mode != "100755" {
337+ continue;
338+ }
339+ let mtime = match previous.get(path) {
340+ Some(old) if old.blob == blob => {
341+ kept += 1;
342+ old.mtime
343+ }
344+ _ => {
345+ changed += 1;
346+ now
347+ }
348+ };
349+ stamps.insert(
350+ path.to_owned(),
351+ Stamp {
352+ blob: blob.to_owned(),
353+ mtime,
354+ },
355+ );
356+ files.push((workspace.join(path), mtime));
357+ }
358+
359+ tokio::task::spawn_blocking(move || {
360+ for (path, secs) in &files {
361+ // A file that cannot be stamped keeps its checkout time. That is not a failure.
362+ let _ = time_of(*secs).and_then(|time| set_mtime(path, time));
363+ }
235 })364 })
365+ .await
366+ .map_err(io::Error::other)?;
367+
368+ // A first job on a fresh runner gets here before any save has made the root.
369+ tokio::fs::create_dir_all(&self.root).await?;
370+ write_json(&self.scratch(".stamps-", &job.job_id), &stamps).await?;
371+ Ok((kept, changed))
236 }372 }
237 373
238 /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked374 /// Builds the new entry in `.new-<job>` and installs it over the old one. Caller has checked
@@ -272,6 +408,11 @@ impl CacheStore {
272 408
273 // Measured before the metadata files are written, so the size is the cached data only.409 // Measured before the metadata files are written, so the size is the cached data only.
274 let size = dir_size(&new).await;410 let size = dir_size(&new).await;
411+ // The stamps the job's restore wrote. Missing when the restore did not get that far.
412+ let stamps = self.scratch(".stamps-", &job.job_id);
413+ if exists_no_follow(&stamps) {
414+ tokio::fs::copy(&stamps, new.join(STAMPS)).await?;
415+ }
275 write_json(&new.join(MANIFEST), &manifest).await?;416 write_json(&new.join(MANIFEST), &manifest).await?;
276 let meta = Meta {417 let meta = Meta {
277 repo: job.repo.clone(),418 repo: job.repo.clone(),
@@ -585,6 +726,38 @@ fn read_meta(dir: &Path) -> Option<Meta> {
585 serde_json::from_slice(&bytes).ok()726 serde_json::from_slice(&bytes).ok()
586 }727 }
587 728
729+/// The stamps an entry recorded. An entry without a readable `stamps.json` has none.
730+fn read_stamps(dir: &Path) -> Stamps {
731+ fs::read(dir.join(STAMPS))
732+ .ok()
733+ .and_then(|bytes| serde_json::from_slice(&bytes).ok())
734+ .unwrap_or_default()
735+}
736+
737+/// Sets a regular file's modification time. A symlink or other kind is refused, not followed.
738+fn set_mtime(path: &Path, time: SystemTime) -> io::Result<()> {
739+ if !fs::symlink_metadata(path)?.is_file() {
740+ return Err(io::Error::other("not a regular file"));
741+ }
742+ fs::File::open(path)?.set_modified(time)
743+}
744+
745+/// A stamp's Unix seconds as a time. Negative or out of range values are refused.
746+fn time_of(secs: i64) -> io::Result<SystemTime> {
747+ u64::try_from(secs)
748+ .ok()
749+ .and_then(|s| UNIX_EPOCH.checked_add(Duration::from_secs(s)))
750+ .ok_or_else(|| io::Error::other("time out of range"))
751+}
752+
753+/// Unix seconds of `now`, or 0 before the epoch.
754+fn unix_secs(now: SystemTime) -> i64 {
755+ now.duration_since(UNIX_EPOCH)
756+ .ok()
757+ .and_then(|d| i64::try_from(d.as_secs()).ok())
758+ .unwrap_or(0)
759+}
760+
588 fn read_manifest(dir: &Path) -> Result<Vec<String>, CacheError> {761 fn read_manifest(dir: &Path) -> Result<Vec<String>, CacheError> {
589 let bytes = fs::read(dir.join(MANIFEST))?;762 let bytes = fs::read(dir.join(MANIFEST))?;
590 serde_json::from_slice(&bytes).map_err(|e| CacheError::Io(io::Error::other(e)))763 serde_json::from_slice(&bytes).map_err(|e| CacheError::Io(io::Error::other(e)))
@@ -1010,4 +1183,97 @@ mod tests {
1010 }1183 }
1011 assert!(keep.is_dir(), "entries are kept");1184 assert!(keep.is_dir(), "entries are kept");
1012 }1185 }
1186+
1187+ /// Runs git in `dir` with a fixed identity. Fails the test when git fails.
1188+ fn git(dir: &Path, args: &[&str]) {
1189+ let ok = std::process::Command::new("git")
1190+ .arg("-C")
1191+ .arg(dir)
1192+ .args(args)
1193+ .env("GIT_AUTHOR_NAME", "ci")
1194+ .env("GIT_AUTHOR_EMAIL", "ci@example.com")
1195+ .env("GIT_COMMITTER_NAME", "ci")
1196+ .env("GIT_COMMITTER_EMAIL", "ci@example.com")
1197+ .status()
1198+ .expect("git runs")
1199+ .success();
1200+ assert!(ok, "git {args:?} failed");
1201+ }
1202+
1203+ fn mtime_secs(path: &Path) -> u64 {
1204+ fs::metadata(path)
1205+ .and_then(|m| m.modified())
1206+ .expect("mtime")
1207+ .duration_since(UNIX_EPOCH)
1208+ .expect("after the epoch")
1209+ .as_secs()
1210+ }
1211+
1212+ #[tokio::test]
1213+ async fn unchanged_files_keep_their_stamp_and_changed_files_get_a_new_one() {
1214+ let dir = tempfile::tempdir().expect("tempdir");
1215+ let store = store(dir.path(), 1 << 30);
1216+ let origin = dir.path().join("origin");
1217+ let origin_str = origin.to_str().expect("utf8 path").to_owned();
1218+ fs::create_dir_all(&origin).expect("mkdir");
1219+ git(&origin, &["init", "--quiet"]);
1220+ fs::write(origin.join("a.txt"), "a").expect("write");
1221+ fs::write(origin.join("b.txt"), "b").expect("write");
1222+ git(&origin, &["add", "."]);
1223+ git(
1224+ &origin,
1225+ &[
1226+ "-c",
1227+ "commit.gpgsign=false",
1228+ "commit",
1229+ "--quiet",
1230+ "-m",
1231+ "one",
1232+ ],
1233+ );
1234+
1235+ // The first run is a miss. It saves an entry from its checkout.
1236+ git(dir.path(), &["clone", "--quiet", &origin_str, "ws1"]);
1237+ let ws1 = dir.path().join("ws1");
1238+ let first = job("job_1", "ref:main", &[], &["target"]);
1239+ store.restore(&first, &ws1).await;
1240+ fs::create_dir_all(ws1.join("target")).expect("mkdir");
1241+ fs::write(ws1.join("target/out.bin"), "built").expect("write");
1242+ store.save(&first, Outcome::Success, &ws1).await;
1243+ let a_stamp = mtime_secs(&ws1.join("a.txt"));
1244+
1245+ // The next commit changes only b.txt. The sleep makes a new stamp a later second.
1246+ fs::write(origin.join("b.txt"), "b2").expect("write");
1247+ git(&origin, &["add", "."]);
1248+ git(
1249+ &origin,
1250+ &[
1251+ "-c",
1252+ "commit.gpgsign=false",
1253+ "commit",
1254+ "--quiet",
1255+ "-m",
1256+ "two",
1257+ ],
1258+ );
1259+ git(dir.path(), &["clone", "--quiet", &origin_str, "ws2"]);
1260+ tokio::time::sleep(Duration::from_millis(1100)).await;
1261+
1262+ let ws2 = dir.path().join("ws2");
1263+ let second = job("job_2", "ref:main", &[], &["target"]);
1264+ let lines = store.restore(&second, &ws2).await;
1265+ assert!(
1266+ lines.contains(&"runner: file times restored (1 unchanged, 1 changed)".to_owned()),
1267+ "{lines:?}"
1268+ );
1269+ assert_eq!(
1270+ mtime_secs(&ws2.join("a.txt")),
1271+ a_stamp,
1272+ "unchanged keeps its stamp"
1273+ );
1274+ assert!(
1275+ mtime_secs(&ws2.join("b.txt")) > a_stamp,
1276+ "a changed file is newer"
1277+ );
1278+ }
1013 }1279 }
crates/forge-runner/src/main.rsmodified+5 -0
@@ -5,6 +5,11 @@
5 use std::process::ExitCode;5 use std::process::ExitCode;
6 6
7 fn main() -> ExitCode {7 fn main() -> ExitCode {
8+ forge_ci::build::set_identity(
9+ env!("FORGE_GIT_SHA"),
10+ env!("FORGE_GIT_DATE"),
11+ matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"),
12+ );
8 // The hidden helpers run before any runtime or subscriber exists.13 // The hidden helpers run before any runtime or subscriber exists.
9 if forge_runner::cli::is_sandbox_invocation() {14 if forge_runner::cli::is_sandbox_invocation() {
10 std::process::exit(forge_runner::cli::hidden_main());15 std::process::exit(forge_runner::cli::hidden_main());
crates/forge-web-base/Cargo.tomladded+35 -0
@@ -0,0 +1,35 @@
1+[package]
2+name = "forge-web-base"
3+description = "forge web building blocks that do not depend on the pages: i18n, rendering, themes, templates, blobs and compression"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[dependencies]
10+forge-core.workspace = true
11+forge-git.workspace = true
12+topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
13+tokio.workspace = true
14+futures-util.workspace = true
15+bytes.workspace = true
16+http.workspace = true
17+http-body.workspace = true
18+serde_json.workspace = true
19+hex.workspace = true
20+sha2.workspace = true
21+time.workspace = true
22+tracing.workspace = true
23+tower.workspace = true
24+tower-http.workspace = true
25+object_store.workspace = true
26+comrak = { workspace = true }
27+emojis.workspace = true
28+ammonia = { workspace = true }
29+syntect = { workspace = true }
30+
31+[dev-dependencies]
32+tempfile.workspace = true
33+
34+[lints]
35+workspace = true
crates/forge-web/src/accent.rs → crates/forge-web-base/src/accent.rsrenamed+0 -0
crates/forge-web/src/accent_palette.rs → crates/forge-web-base/src/accent_palette.rsrenamed+0 -0
crates/forge-web/src/blobs.rs → crates/forge-web-base/src/blobs.rsrenamed+0 -0
crates/forge-web/src/compression.rs → crates/forge-web-base/src/compression.rsrenamed+0 -11
@@ -246,17 +246,6 @@ mod tests {
246 assert_eq!(encoding(&router, "/tahinli/demo/blob.bin").await, None);246 assert_eq!(encoding(&router, "/tahinli/demo/blob.bin").await, None);
247 }247 }
248 248
249- #[tokio::test]
250- async fn public_css_asset_is_gzipped() {
251- let dir = tempfile::tempdir().expect("tempdir");
252- let state = crate::test_support::test_state(dir.path()).await;
253- let router = crate::test_support::app_router(state);
254- assert_eq!(
255- encoding(&router, "/assets/main.css").await.as_deref(),
256- Some("gzip")
257- );
258- }
259-
260 #[test]249 #[test]
261 fn policy_skips_small_streamed_and_already_encoded_bodies() {250 fn policy_skips_small_streamed_and_already_encoded_bodies() {
262 let small = Response::builder()251 let small = Response::builder()
crates/forge-web/src/custom_colour.rs → crates/forge-web-base/src/custom_colour.rsrenamed+0 -0
crates/forge-web/src/i18n/accents.rs → crates/forge-web-base/src/i18n/accents.rsrenamed+0 -0
crates/forge-web/src/i18n/accounts.rs → crates/forge-web-base/src/i18n/accounts.rsrenamed+0 -0
crates/forge-web/src/i18n/admin.rs → crates/forge-web-base/src/i18n/admin.rsrenamed+0 -0
crates/forge-web/src/i18n/alerts.rs → crates/forge-web-base/src/i18n/alerts.rsrenamed+0 -0
crates/forge-web/src/i18n/authoring.rs → crates/forge-web-base/src/i18n/authoring.rsrenamed+0 -0
crates/forge-web/src/i18n/browse.rs → crates/forge-web-base/src/i18n/browse.rsrenamed+0 -0
crates/forge-web/src/i18n/code.rs → crates/forge-web-base/src/i18n/code.rsrenamed+0 -0
crates/forge-web/src/i18n/community.rs → crates/forge-web-base/src/i18n/community.rsrenamed+0 -0
crates/forge-web/src/i18n/integrations.rs → crates/forge-web-base/src/i18n/integrations.rsrenamed+0 -0
crates/forge-web/src/i18n/issues.rs → crates/forge-web-base/src/i18n/issues.rsrenamed+0 -0
crates/forge-web/src/i18n/link.rs → crates/forge-web-base/src/i18n/link.rsrenamed+0 -0
crates/forge-web/src/i18n/merge_queue.rs → crates/forge-web-base/src/i18n/merge_queue.rsrenamed+0 -0
crates/forge-web/src/i18n/migrate.rs → crates/forge-web-base/src/i18n/migrate.rsrenamed+0 -0
crates/forge-web/src/i18n/misc.rs → crates/forge-web-base/src/i18n/misc.rsrenamed+0 -0
crates/forge-web/src/i18n/mod.rs → crates/forge-web-base/src/i18n/mod.rsrenamed+0 -0
crates/forge-web/src/i18n/needs.rs → crates/forge-web-base/src/i18n/needs.rsrenamed+0 -0
crates/forge-web/src/i18n/orgs.rs → crates/forge-web-base/src/i18n/orgs.rsrenamed+0 -0
crates/forge-web/src/i18n/packages.rs → crates/forge-web-base/src/i18n/packages.rsrenamed+0 -0
crates/forge-web/src/i18n/pulls.rs → crates/forge-web-base/src/i18n/pulls.rsrenamed+0 -0
crates/forge-web/src/i18n/pulls_review.rs → crates/forge-web-base/src/i18n/pulls_review.rsrenamed+0 -0
crates/forge-web/src/i18n/push.rs → crates/forge-web-base/src/i18n/push.rsrenamed+0 -0
crates/forge-web/src/i18n/releases_ci.rs → crates/forge-web-base/src/i18n/releases_ci.rsrenamed+0 -0
crates/forge-web/src/i18n/repo_admin.rs → crates/forge-web-base/src/i18n/repo_admin.rsrenamed+0 -0
crates/forge-web/src/i18n/server_settings.rs → crates/forge-web-base/src/i18n/server_settings.rsrenamed+0 -0
crates/forge-web/src/i18n/timeline.rs → crates/forge-web-base/src/i18n/timeline.rsrenamed+0 -0
crates/forge-web-base/src/lib.rsadded+14 -0
@@ -0,0 +1,14 @@
1+//! Web modules that do not depend on the pages. They compile once in this crate, so a change in
2+//! forge-web's pages does not rebuild them.
3+
4+pub mod accent;
5+pub mod accent_palette;
6+pub mod blobs;
7+pub mod compression;
8+pub mod custom_colour;
9+pub mod i18n;
10+pub mod render;
11+pub mod repo_stats;
12+pub mod templates;
13+pub mod theme;
14+pub mod throttle;
crates/forge-web/src/render/commit_message.rs → crates/forge-web-base/src/render/commit_message.rsrenamed+0 -0
crates/forge-web/src/render/emoji.rs → crates/forge-web-base/src/render/emoji.rsrenamed+0 -0
crates/forge-web/src/render/gitmojis.LICENSE → crates/forge-web-base/src/render/gitmojis.LICENSErenamed+0 -0
crates/forge-web/src/render/gitmojis.json → crates/forge-web-base/src/render/gitmojis.jsonrenamed+0 -0
crates/forge-web/src/render/highlight.rs → crates/forge-web-base/src/render/highlight.rsrenamed+0 -0
crates/forge-web/src/render/markdown.rs → crates/forge-web-base/src/render/markdown.rsrenamed+0 -0
crates/forge-web/src/render/mod.rs → crates/forge-web-base/src/render/mod.rsrenamed+0 -0
crates/forge-web/src/repo_stats.rs → crates/forge-web-base/src/repo_stats.rsrenamed+0 -0
crates/forge-web/src/templates.rs → crates/forge-web-base/src/templates.rsrenamed+0 -272
@@ -262,275 +262,3 @@ mod tests {
262 assert_eq!(t.body, "Body\r\n");262 assert_eq!(t.body, "Body\r\n");
263 }263 }
264 }264 }
265-
266-#[cfg(test)]
267-mod route_tests {
268- use forge_core::Visibility;
269-
270- use crate::pages::commits::test_support::{Fixture, git};
271- use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, send};
272-
273- 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";
274- const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";
275-
276- /// A repo whose default branch gets `files` committed on top of the fixture's history.
277- /// Tahinli is signed in.
278- async fn setup(files: &[(&str, &str)]) -> Fixture {
279- let fx = Fixture::new(Visibility::Public).await;
280- for (path, text) in files {
281- let full = fx.work.join(path);
282- std::fs::create_dir_all(full.parent().unwrap()).unwrap();
283- std::fs::write(full, text).unwrap();
284- }
285- git(&fx.work, &["add", "-A"]);
286- git(&fx.work, &["commit", "-q", "-m", "Add templates"]);
287- git(
288- &fx.work,
289- &[
290- "push",
291- "-q",
292- &fx.bare.to_string_lossy(),
293- "HEAD:refs/heads/main",
294- ],
295- );
296- let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
297- crate::test_support::create_session(&fx.store, &owner.id, TOKEN, CSRF).await;
298- fx
299- }
300-
301- fn new_issue_uri(query: &str) -> String {
302- format!("/{OWNER}/{REPO}/issues/new{query}")
303- }
304-
305- /// The text of the tag that starts at `needle`, up to its closing `>`.
306- fn tag_at(html: &str, needle: &str) -> String {
307- let at = html.find(needle).expect("needle in page");
308- let end = html[at..].find('>').expect("tag end") + at;
309- html[at..end].to_owned()
310- }
311-
312- #[tokio::test]
313- async fn several_templates_show_a_chooser() {
314- let fx = setup(&[
315- (".forge/ISSUE_TEMPLATE/bug.md", BUG),
316- (".forge/ISSUE_TEMPLATE/feature.md", FEATURE),
317- ])
318- .await;
319- let reply = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[]).await;
320- assert_eq!(reply.status, 200);
321- let html = reply.text();
322- assert!(html.contains("Bug report"));
323- assert!(html.contains("Something broke"));
324- assert!(html.contains("issues/new?template=bug\""));
325- assert!(html.contains("issues/new?template=feature\""));
326- assert!(html.contains("Open a blank issue"));
327- assert!(html.contains("issues/new?blank=1\""));
328- assert!(!html.contains("name=\"title\""));
329- }
330-
331- #[tokio::test]
332- async fn chosen_template_prefills_and_preselects_existing_labels() {
333- let fx = setup(&[
334- (".forge/ISSUE_TEMPLATE/bug.md", BUG),
335- (".forge/ISSUE_TEMPLATE/feature.md", FEATURE),
336- ])
337- .await;
338- let repo = fx
339- .store
340- .repo_by_owner_and_name(OWNER, REPO)
341- .await
342- .unwrap()
343- .unwrap();
344- fx.store
345- .create_label(&repo.id, "bug", "#d73a4a", "")
346- .await
347- .unwrap();
348- fx.store
349- .create_label(&repo.id, "docs", "#0075ca", "")
350- .await
351- .unwrap();
352- let bug_id = fx
353- .store
354- .list_labels(&repo.id)
355- .await
356- .unwrap()
357- .into_iter()
358- .find(|l| l.name == "bug")
359- .unwrap()
360- .id;
361-
362- let reply = send(
363- &fx.router,
364- "GET",
365- &new_issue_uri("?template=bug"),
366- true,
367- None,
368- &[],
369- )
370- .await;
371- assert_eq!(reply.status, 200);
372- let html = reply.text();
373- assert!(html.contains("name=\"title\""));
374- assert!(html.contains("value=\"[Bug]:\""));
375- assert!(html.contains("## Steps to reproduce"));
376- assert!(!html.contains("Choose a template"));
377- assert!(tag_at(&html, &format!("value=\"{bug_id}\"")).contains("checked"));
378- assert!(!html.contains("value=\"needs triage\""));
379- assert_eq!(html.matches("name=\"label\"").count(), 2);
380- let docs_id = fx
381- .store
382- .list_labels(&repo.id)
383- .await
384- .unwrap()
385- .into_iter()
386- .find(|l| l.name == "docs")
387- .unwrap()
388- .id;
389- assert!(!tag_at(&html, &format!("value=\"{docs_id}\"")).contains("checked"));
390- }
391-
392- #[tokio::test]
393- async fn blank_issue_from_chooser_is_empty() {
394- let fx = setup(&[
395- (".forge/ISSUE_TEMPLATE/bug.md", BUG),
396- (".forge/ISSUE_TEMPLATE/feature.md", FEATURE),
397- ])
398- .await;
399- let reply = send(
400- &fx.router,
401- "GET",
402- &new_issue_uri("?blank=1"),
403- true,
404- None,
405- &[],
406- )
407- .await;
408- let html = reply.text();
409- assert!(html.contains("name=\"title\""));
410- assert!(!html.contains("Steps to reproduce"));
411- assert!(!html.contains("Choose a template"));
412- }
413-
414- #[tokio::test]
415- async fn single_template_prefills_without_chooser() {
416- let fx = setup(&[(".forge/ISSUE_TEMPLATE/bug.md", BUG)]).await;
417- let html = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[])
418- .await
419- .text();
420- assert!(html.contains("value=\"[Bug]:\""));
421- assert!(html.contains("## Steps to reproduce"));
422- assert!(!html.contains("Open a blank issue"));
423- }
424-
425- #[tokio::test]
426- async fn single_file_under_github_is_used_as_is() {
427- let fx = setup(&[(".github/ISSUE_TEMPLATE.md", "Plain body text\n")]).await;
428- let html = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[])
429- .await
430- .text();
431- assert!(html.contains("Plain body text"));
432- }
433-
434- #[tokio::test]
435- async fn chooser_lists_at_most_twenty_templates() {
436- let names: Vec<String> = (0..21).map(|n| format!("t{n:02}")).collect();
437- let files: Vec<(String, String)> = names
438- .iter()
439- .map(|n| {
440- (
441- format!(".forge/ISSUE_TEMPLATE/{n}.md"),
442- format!("body {n}\n"),
443- )
444- })
445- .collect();
446- let refs: Vec<(&str, &str)> = files
447- .iter()
448- .map(|(p, t)| (p.as_str(), t.as_str()))
449- .collect();
450- let fx = setup(&refs).await;
451- let html = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[])
452- .await
453- .text();
454- assert!(html.contains("issues/new?template=t19\""));
455- assert!(!html.contains("issues/new?template=t20\""));
456- }
457-
458- #[tokio::test]
459- async fn submitting_with_a_label_applies_it_to_the_issue() {
460- let fx = setup(&[(".forge/ISSUE_TEMPLATE/bug.md", BUG)]).await;
461- let repo = fx
462- .store
463- .repo_by_owner_and_name(OWNER, REPO)
464- .await
465- .unwrap()
466- .unwrap();
467- fx.store
468- .create_label(&repo.id, "bug", "#d73a4a", "")
469- .await
470- .unwrap();
471- let bug_id = fx
472- .store
473- .list_labels(&repo.id)
474- .await
475- .unwrap()
476- .into_iter()
477- .next()
478- .unwrap()
479- .id;
480- let form = format!("csrf={CSRF}&title=Crash+on+start&body=details&label={bug_id}");
481- let reply = send(
482- &fx.router,
483- "POST",
484- &new_issue_uri(""),
485- true,
486- Some(&form),
487- &[],
488- )
489- .await;
490- assert_eq!(reply.status, 303);
491- let issue = fx
492- .store
493- .issue_by_number(&repo.id, 1)
494- .await
495- .unwrap()
496- .unwrap();
497- let labels = fx.store.issue_labels(&issue.id).await.unwrap();
498- assert_eq!(labels.len(), 1);
499- assert_eq!(labels[0].name, "bug");
500- }
501-
502- #[tokio::test]
503- async fn compare_form_starts_with_the_pull_request_template() {
504- let fx = setup(&[(
505- ".forge/PULL_REQUEST_TEMPLATE.md",
506- "## Summary\n\nWhat changed?\n",
507- )])
508- .await;
509- git(&fx.work, &["checkout", "-q", "-b", "feature"]);
510- std::fs::write(fx.work.join("feature.txt"), "feature\n").unwrap();
511- git(&fx.work, &["add", "-A"]);
512- git(&fx.work, &["commit", "-q", "-m", "Add feature file"]);
513- git(
514- &fx.work,
515- &[
516- "push",
517- "-q",
518- &fx.bare.to_string_lossy(),
519- "feature:refs/heads/feature",
520- ],
521- );
522- git(&fx.work, &["checkout", "-q", "main"]);
523-
524- let reply = send(
525- &fx.router,
526- "GET",
527- &format!("/{OWNER}/{REPO}/compare/main...feature"),
528- true,
529- None,
530- &[],
531- )
532- .await;
533- assert_eq!(reply.status, 200);
534- assert!(reply.text().contains("What changed?"));
535- }
536-}
crates/forge-web/src/theme.rs → crates/forge-web-base/src/theme.rsrenamed+0 -0
crates/forge-web/src/throttle.rs → crates/forge-web-base/src/throttle.rsrenamed+0 -0
crates/forge-web/Cargo.tomlmodified+1 -8
@@ -16,6 +16,7 @@ ipnet.workspace = true
16 forge-git.workspace = true16 forge-git.workspace = true
17 forge-ssh.workspace = true17 forge-ssh.workspace = true
18 forge-ci.workspace = true18 forge-ci.workspace = true
19+forge-web-base.workspace = true
19 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }20 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
20 tokio.workspace = true21 tokio.workspace = true
21 futures-util.workspace = true22 futures-util.workspace = true
@@ -39,16 +40,9 @@ hex.workspace = true
39 nix = { workspace = true }40 nix = { workspace = true }
40 sha2.workspace = true41 sha2.workspace = true
41 time.workspace = true42 time.workspace = true
42-comrak = { workspace = true }
43-emojis.workspace = true
44-ammonia = { workspace = true }
45-syntect = { workspace = true }
46 reqwest = { workspace = true }43 reqwest = { workspace = true }
47 hmac.workspace = true44 hmac.workspace = true
48 similar = { workspace = true }45 similar = { workspace = true }
49-tower = { workspace = true }
50-tower-http = { workspace = true }
51-object_store.workspace = true
52 multer.workspace = true46 multer.workspace = true
53 ulid.workspace = true47 ulid.workspace = true
54 forge-runner = { workspace = true }48 forge-runner = { workspace = true }
@@ -69,7 +63,6 @@ sha2.workspace = true
69 63
70 [dev-dependencies]64 [dev-dependencies]
71 tempfile.workspace = true65 tempfile.workspace = true
72-forge-runner = { workspace = true, features = ["test-host-executor"] }
73 image = { workspace = true }66 image = { workspace = true }
74 scraper = { workspace = true }67 scraper = { workspace = true }
75 webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] }68 webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] }
crates/forge-web/build.rsmodified+11 -5
@@ -2,15 +2,16 @@
2 //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as2 //! asset also gets a content hash (FORGE_MAIN_CSS_V, FORGE_NAV_JS_V) that the page links use as
3 //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one.3 //! their cache-busting query, so an unchanged file keeps its URL and a changed one gets a new one.
4 //!4 //!
5-//! The accent colours and the neutral bases come from `src/accent_palette.rs`, the same data the5+//! The accent colours and the neutral bases come from `forge-web-base/src/accent_palette.rs`, the
6-//! app reads. This script turns it into `_accents.scss` in OUT_DIR, which main.scss imports.6+//! same data the app reads. This script turns it into `_accents.scss` in OUT_DIR, which main.scss
7+//! imports.
7 8
8 use std::{env, fs, path::PathBuf};9 use std::{env, fs, path::PathBuf};
9 10
10 use hex::encode;11 use hex::encode;
11 use sha2::{Digest, Sha256};12 use sha2::{Digest, Sha256};
12 13
13-#[path = "src/accent_palette.rs"]14+#[path = "../forge-web-base/src/accent_palette.rs"]
14 #[allow(dead_code)]15 #[allow(dead_code)]
15 mod accent_palette;16 mod accent_palette;
16 17
@@ -19,6 +20,8 @@ use accent_palette::{
19 Tokens,20 Tokens,
20 };21 };
21 22
23+include!("../forge-ci/build_identity.rs");
24+
22 /// First 12 hex characters of the SHA-256 of `bytes`.25 /// First 12 hex characters of the SHA-256 of `bytes`.
23 fn content_version(bytes: &[u8]) -> String {26 fn content_version(bytes: &[u8]) -> String {
24 encode(Sha256::digest(bytes))[..12].to_string()27 encode(Sha256::digest(bytes))[..12].to_string()
@@ -149,7 +152,7 @@ fn swatch_rules(css: &mut String) {
149 /// chips.152 /// chips.
150 fn accents_scss() -> String {153 fn accents_scss() -> String {
151 let mut css = String::from(154 let mut css = String::from(
152- "/* Generated by crates/forge-web/build.rs from src/accent_palette.rs. Edit that file. */\n",155+ "/* Generated by crates/forge-web/build.rs from forge-web-base/src/accent_palette.rs. Edit that file. */\n",
153 );156 );
154 assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first");157 assert_eq!(PALETTES[0].id, DEFAULT, "the default palette comes first");
155 assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first");158 assert_eq!(BASES[0].id, BASE_DEFAULT, "the default base comes first");
@@ -166,9 +169,12 @@ fn accents_scss() -> String {
166 169
167 fn main() {170 fn main() {
168 println!("cargo:rerun-if-env-changed=FORGE_BUILD_SHA");171 println!("cargo:rerun-if-env-changed=FORGE_BUILD_SHA");
172+ println!("cargo:rerun-if-changed=build.rs");
173+ println!("cargo:rerun-if-changed=../forge-ci/build_identity.rs");
174+ emit_identity();
169 println!("cargo:rerun-if-changed=../../style");175 println!("cargo:rerun-if-changed=../../style");
170 println!("cargo:rerun-if-changed=assets/nav.js");176 println!("cargo:rerun-if-changed=assets/nav.js");
171- println!("cargo:rerun-if-changed=src/accent_palette.rs");177+ println!("cargo:rerun-if-changed=../forge-web-base/src/accent_palette.rs");
172 178
173 let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string());179 let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string());
174 println!("cargo:rustc-env=FORGE_BUILD_SHA={sha}");180 println!("cargo:rustc-env=FORGE_BUILD_SHA={sha}");
crates/forge-web/src/compression_route_tests.rsadded+25 -0
@@ -0,0 +1,25 @@
1+//! The public router gzips its stylesheet. The response compression policy is tested in
2+//! forge-web-base, next to the layer; this checks it is wired into the real app router.
3+
4+use http::header::{ACCEPT_ENCODING, CONTENT_ENCODING};
5+use topcoat::router::Body;
6+
7+#[tokio::test]
8+async fn public_css_asset_is_gzipped() {
9+ let dir = tempfile::tempdir().expect("tempdir");
10+ let state = crate::test_support::test_state(dir.path()).await;
11+ let router = crate::test_support::app_router(state);
12+ let request = http::Request::builder()
13+ .uri("/assets/main.css")
14+ .header(ACCEPT_ENCODING, "gzip")
15+ .body(Body::empty())
16+ .expect("request");
17+ let response = router.handle(request).await;
18+ assert_eq!(
19+ response
20+ .headers()
21+ .get(CONTENT_ENCODING)
22+ .map(|v| v.to_str().expect("ascii")),
23+ Some("gzip")
24+ );
25+}
crates/forge-web/src/main.rsmodified+15 -12
@@ -6,9 +6,12 @@
6 6
7 #![recursion_limit = "256"]7 #![recursion_limit = "256"]
8 8
9-mod accent;9+// Modules that moved to forge-web-base, so they compile once and are not rebuilt with the pages.
10-#[allow(dead_code)] // build.rs uses the whole file; the app reads only part of it.10+pub(crate) use forge_web_base::{
11-mod accent_palette;11+ accent, accent_palette, blobs, compression, custom_colour, i18n, render, repo_stats, templates,
12+ theme, throttle,
13+};
14+
12 mod access;15 mod access;
13 mod admin_cli;16 mod admin_cli;
14 mod admin_client;17 mod admin_client;
@@ -19,17 +22,15 @@ mod audit;
19 mod auth;22 mod auth;
20 mod automerge;23 mod automerge;
21 mod backup;24 mod backup;
22-mod blobs;
23 mod boot;25 mod boot;
24 mod ci;26 mod ci;
25 mod client_ip;27 mod client_ip;
26-mod compression;28+#[cfg(test)]
27-mod custom_colour;29+mod compression_route_tests;
28 mod exporter;30 mod exporter;
29 mod git_auth;31 mod git_auth;
30 mod git_http;32 mod git_http;
31 mod hook_cmd;33 mod hook_cmd;
32-mod i18n;
33 mod importer;34 mod importer;
34 mod internal;35 mod internal;
35 mod lfs;36 mod lfs;
@@ -49,18 +50,15 @@ mod prune;
49 mod pulls_sync;50 mod pulls_sync;
50 mod raw;51 mod raw;
51 mod release_ops;52 mod release_ops;
52-mod render;
53 mod replication;53 mod replication;
54-mod repo_stats;
55 mod self_update;54 mod self_update;
56 mod signatures;55 mod signatures;
57 mod ssh_backend;56 mod ssh_backend;
58 mod state;57 mod state;
59-mod templates;58+#[cfg(test)]
59+mod templates_route_tests;
60 #[cfg(test)]60 #[cfg(test)]
61 mod test_support;61 mod test_support;
62-mod theme;
63-mod throttle;
64 mod views;62 mod views;
65 mod web_push;63 mod web_push;
66 mod webhooks;64 mod webhooks;
@@ -154,6 +152,11 @@ fn reexec_with_allocator_env(raw: &[std::ffi::OsString]) {
154 }152 }
155 153
156 fn main() -> ExitCode {154 fn main() -> ExitCode {
155+ forge_ci::build::set_identity(
156+ env!("FORGE_GIT_SHA"),
157+ env!("FORGE_GIT_DATE"),
158+ matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"),
159+ );
157 // The sandbox helpers must start before any runtime or subscriber exists.160 // The sandbox helpers must start before any runtime or subscriber exists.
158 if forge_runner::cli::is_sandbox_invocation() {161 if forge_runner::cli::is_sandbox_invocation() {
159 std::process::exit(forge_runner::cli::hidden_main());162 std::process::exit(forge_runner::cli::hidden_main());
crates/forge-web/src/pages/admin_health.rsmodified+7 -3
@@ -408,15 +408,19 @@ async fn gather(state: &AppState, lang: Lang) -> Result<Health> {
408 let uptime = uptime_secs().map_or_else(|| at(lang, A::Unavailable).to_owned(), duration_short);408 let uptime = uptime_secs().map_or_else(|| at(lang, A::Unavailable).to_owned(), duration_short);
409 let build = format!(409 let build = format!(
410 "{}{}",410 "{}{}",
411- forge_ci::build::COMMIT,411+ forge_ci::build::commit(),
412- if forge_ci::build::DIRTY { "-dirty" } else { "" }412+ if forge_ci::build::dirty() {
413+ "-dirty"
414+ } else {
415+ ""
416+ }
413 );417 );
414 let meta = meta_line(418 let meta = meta_line(
415 lang,419 lang,
416 &uptime,420 &uptime,
417 forge_ci::build::VERSION,421 forge_ci::build::VERSION,
418 &build,422 &build,
419- forge_ci::build::DATE,423+ forge_ci::build::date(),
420 );424 );
421 425
422 let attention = usize::from(usage.as_ref().is_some_and(|u| u.bad))426 let attention = usize::from(usage.as_ref().is_some_and(|u| u.bad))
crates/forge-web/src/templates_route_tests.rsadded+268 -0
@@ -0,0 +1,268 @@
1+use forge_core::Visibility;
2+
3+use crate::pages::commits::test_support::{Fixture, git};
4+use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, send};
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";
7+const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";
8+
9+/// A repo whose default branch gets `files` committed on top of the fixture's history.
10+/// Tahinli is signed in.
11+async fn setup(files: &[(&str, &str)]) -> Fixture {
12+ let fx = Fixture::new(Visibility::Public).await;
13+ for (path, text) in files {
14+ let full = fx.work.join(path);
15+ std::fs::create_dir_all(full.parent().unwrap()).unwrap();
16+ std::fs::write(full, text).unwrap();
17+ }
18+ git(&fx.work, &["add", "-A"]);
19+ git(&fx.work, &["commit", "-q", "-m", "Add templates"]);
20+ git(
21+ &fx.work,
22+ &[
23+ "push",
24+ "-q",
25+ &fx.bare.to_string_lossy(),
26+ "HEAD:refs/heads/main",
27+ ],
28+ );
29+ let owner = fx.store.user_by_username(OWNER).await.unwrap().unwrap();
30+ crate::test_support::create_session(&fx.store, &owner.id, TOKEN, CSRF).await;
31+ fx
32+}
33+
34+fn new_issue_uri(query: &str) -> String {
35+ format!("/{OWNER}/{REPO}/issues/new{query}")
36+}
37+
38+/// The text of the tag that starts at `needle`, up to its closing `>`.
39+fn tag_at(html: &str, needle: &str) -> String {
40+ let at = html.find(needle).expect("needle in page");
41+ let end = html[at..].find('>').expect("tag end") + at;
42+ html[at..end].to_owned()
43+}
44+
45+#[tokio::test]
46+async fn several_templates_show_a_chooser() {
47+ let fx = setup(&[
48+ (".forge/ISSUE_TEMPLATE/bug.md", BUG),
49+ (".forge/ISSUE_TEMPLATE/feature.md", FEATURE),
50+ ])
51+ .await;
52+ let reply = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[]).await;
53+ assert_eq!(reply.status, 200);
54+ let html = reply.text();
55+ assert!(html.contains("Bug report"));
56+ assert!(html.contains("Something broke"));
57+ assert!(html.contains("issues/new?template=bug\""));
58+ assert!(html.contains("issues/new?template=feature\""));
59+ assert!(html.contains("Open a blank issue"));
60+ assert!(html.contains("issues/new?blank=1\""));
61+ assert!(!html.contains("name=\"title\""));
62+}
63+
64+#[tokio::test]
65+async fn chosen_template_prefills_and_preselects_existing_labels() {
66+ let fx = setup(&[
67+ (".forge/ISSUE_TEMPLATE/bug.md", BUG),
68+ (".forge/ISSUE_TEMPLATE/feature.md", FEATURE),
69+ ])
70+ .await;
71+ let repo = fx
72+ .store
73+ .repo_by_owner_and_name(OWNER, REPO)
74+ .await
75+ .unwrap()
76+ .unwrap();
77+ fx.store
78+ .create_label(&repo.id, "bug", "#d73a4a", "")
79+ .await
80+ .unwrap();
81+ fx.store
82+ .create_label(&repo.id, "docs", "#0075ca", "")
83+ .await
84+ .unwrap();
85+ let bug_id = fx
86+ .store
87+ .list_labels(&repo.id)
88+ .await
89+ .unwrap()
90+ .into_iter()
91+ .find(|l| l.name == "bug")
92+ .unwrap()
93+ .id;
94+
95+ let reply = send(
96+ &fx.router,
97+ "GET",
98+ &new_issue_uri("?template=bug"),
99+ true,
100+ None,
101+ &[],
102+ )
103+ .await;
104+ assert_eq!(reply.status, 200);
105+ let html = reply.text();
106+ assert!(html.contains("name=\"title\""));
107+ assert!(html.contains("value=\"[Bug]:\""));
108+ assert!(html.contains("## Steps to reproduce"));
109+ assert!(!html.contains("Choose a template"));
110+ assert!(tag_at(&html, &format!("value=\"{bug_id}\"")).contains("checked"));
111+ assert!(!html.contains("value=\"needs triage\""));
112+ assert_eq!(html.matches("name=\"label\"").count(), 2);
113+ let docs_id = fx
114+ .store
115+ .list_labels(&repo.id)
116+ .await
117+ .unwrap()
118+ .into_iter()
119+ .find(|l| l.name == "docs")
120+ .unwrap()
121+ .id;
122+ assert!(!tag_at(&html, &format!("value=\"{docs_id}\"")).contains("checked"));
123+}
124+
125+#[tokio::test]
126+async fn blank_issue_from_chooser_is_empty() {
127+ let fx = setup(&[
128+ (".forge/ISSUE_TEMPLATE/bug.md", BUG),
129+ (".forge/ISSUE_TEMPLATE/feature.md", FEATURE),
130+ ])
131+ .await;
132+ let reply = send(
133+ &fx.router,
134+ "GET",
135+ &new_issue_uri("?blank=1"),
136+ true,
137+ None,
138+ &[],
139+ )
140+ .await;
141+ let html = reply.text();
142+ assert!(html.contains("name=\"title\""));
143+ assert!(!html.contains("Steps to reproduce"));
144+ assert!(!html.contains("Choose a template"));
145+}
146+
147+#[tokio::test]
148+async fn single_template_prefills_without_chooser() {
149+ let fx = setup(&[(".forge/ISSUE_TEMPLATE/bug.md", BUG)]).await;
150+ let html = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[])
151+ .await
152+ .text();
153+ assert!(html.contains("value=\"[Bug]:\""));
154+ assert!(html.contains("## Steps to reproduce"));
155+ assert!(!html.contains("Open a blank issue"));
156+}
157+
158+#[tokio::test]
159+async fn single_file_under_github_is_used_as_is() {
160+ let fx = setup(&[(".github/ISSUE_TEMPLATE.md", "Plain body text\n")]).await;
161+ let html = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[])
162+ .await
163+ .text();
164+ assert!(html.contains("Plain body text"));
165+}
166+
167+#[tokio::test]
168+async fn chooser_lists_at_most_twenty_templates() {
169+ let names: Vec<String> = (0..21).map(|n| format!("t{n:02}")).collect();
170+ let files: Vec<(String, String)> = names
171+ .iter()
172+ .map(|n| {
173+ (
174+ format!(".forge/ISSUE_TEMPLATE/{n}.md"),
175+ format!("body {n}\n"),
176+ )
177+ })
178+ .collect();
179+ let refs: Vec<(&str, &str)> = files
180+ .iter()
181+ .map(|(p, t)| (p.as_str(), t.as_str()))
182+ .collect();
183+ let fx = setup(&refs).await;
184+ let html = send(&fx.router, "GET", &new_issue_uri(""), true, None, &[])
185+ .await
186+ .text();
187+ assert!(html.contains("issues/new?template=t19\""));
188+ assert!(!html.contains("issues/new?template=t20\""));
189+}
190+
191+#[tokio::test]
192+async fn submitting_with_a_label_applies_it_to_the_issue() {
193+ let fx = setup(&[(".forge/ISSUE_TEMPLATE/bug.md", BUG)]).await;
194+ let repo = fx
195+ .store
196+ .repo_by_owner_and_name(OWNER, REPO)
197+ .await
198+ .unwrap()
199+ .unwrap();
200+ fx.store
201+ .create_label(&repo.id, "bug", "#d73a4a", "")
202+ .await
203+ .unwrap();
204+ let bug_id = fx
205+ .store
206+ .list_labels(&repo.id)
207+ .await
208+ .unwrap()
209+ .into_iter()
210+ .next()
211+ .unwrap()
212+ .id;
213+ let form = format!("csrf={CSRF}&title=Crash+on+start&body=details&label={bug_id}");
214+ let reply = send(
215+ &fx.router,
216+ "POST",
217+ &new_issue_uri(""),
218+ true,
219+ Some(&form),
220+ &[],
221+ )
222+ .await;
223+ assert_eq!(reply.status, 303);
224+ let issue = fx
225+ .store
226+ .issue_by_number(&repo.id, 1)
227+ .await
228+ .unwrap()
229+ .unwrap();
230+ let labels = fx.store.issue_labels(&issue.id).await.unwrap();
231+ assert_eq!(labels.len(), 1);
232+ assert_eq!(labels[0].name, "bug");
233+}
234+
235+#[tokio::test]
236+async fn compare_form_starts_with_the_pull_request_template() {
237+ let fx = setup(&[(
238+ ".forge/PULL_REQUEST_TEMPLATE.md",
239+ "## Summary\n\nWhat changed?\n",
240+ )])
241+ .await;
242+ git(&fx.work, &["checkout", "-q", "-b", "feature"]);
243+ std::fs::write(fx.work.join("feature.txt"), "feature\n").unwrap();
244+ git(&fx.work, &["add", "-A"]);
245+ git(&fx.work, &["commit", "-q", "-m", "Add feature file"]);
246+ git(
247+ &fx.work,
248+ &[
249+ "push",
250+ "-q",
251+ &fx.bare.to_string_lossy(),
252+ "feature:refs/heads/feature",
253+ ],
254+ );
255+ git(&fx.work, &["checkout", "-q", "main"]);
256+
257+ let reply = send(
258+ &fx.router,
259+ "GET",
260+ &format!("/{OWNER}/{REPO}/compare/main...feature"),
261+ true,
262+ None,
263+ &[],
264+ )
265+ .await;
266+ assert_eq!(reply.status, 200);
267+ assert!(reply.text().contains("What changed?"));
268+}
docs/architecture.mdmodified+3 -1
@@ -47,6 +47,8 @@ project_git/
47 forge-git/ safe git command builder, process spawn and streaming, pkt-line, repo init, managed gitconfig, version check47 forge-git/ safe git command builder, process spawn and streaming, pkt-line, repo init, managed gitconfig, version check
48 forge-ssh/ russh server: pubkey auth, exec allow-list and parse, GIT_PROTOCOL env, piping, timeouts48 forge-ssh/ russh server: pubkey auth, exec allow-list and parse, GIT_PROTOCOL env, piping, timeouts
49 forge-web/ crate, builds the `forge` binary: Topcoat UI, auth, smart-HTTP routes, internal hook API, `hook` subcommand, admin CLI49 forge-web/ crate, builds the `forge` binary: Topcoat UI, auth, smart-HTTP routes, internal hook API, `hook` subcommand, admin CLI
50+ forge-web-base/ forge-web modules with no routes and no dependency on pages: i18n, render, theme and accents, templates, blobs
51+ forge-e2e/ end-to-end tests. They run `FORGE_BIN` when it is set, so CI tests the binary it ships, and otherwise build `forge`
50 ```52 ```
51 53
52 Module ownership (from the contract):54 Module ownership (from the contract):
@@ -486,7 +488,7 @@ Don't:
486 - Repo create with the ID-based path. Visibility, collaborators, archive flag.488 - Repo create with the ID-based path. Visibility, collaborators, archive flag.
487 - Smart HTTP (`info/refs`, upload-pack, receive-pack, gzip, streaming) and SSH (exec allow-list, `GIT_PROTOCOL`, piping, exit status).489 - Smart HTTP (`info/refs`, upload-pack, receive-pack, gzip, streaming) and SSH (exec allow-list, `GIT_PROTOCOL`, piping, exit status).
488 - Pre-receive policy (archived, default-branch delete and force-push, bad ref names) and post-receive `push_events`. Minimal UI: setup, login, dashboard, new repo, repo page, settings, admin users, `/healthz`.490 - Pre-receive policy (archived, default-branch delete and force-push, bad ref names) and post-receive `push_events`. Minimal UI: setup, login, dashboard, new repo, repo page, settings, admin users, `/healthz`.
489-- Tests: unit tests in core and git; end-to-end `tests/e2e/git_e2e.rs` over HTTPS and SSH, with negative cases (bad token, cross-user private 404, forced default-branch push rejected, unknown SSH command rejected, traversal rejected, POST without CSRF rejected).491+- Tests: unit tests in core and git; end-to-end `crates/forge-e2e/tests/e2e/git_e2e.rs` over HTTPS and SSH, with negative cases (bad token, cross-user private 404, forced default-branch push rejected, unknown SSH command rejected, traversal rejected, POST without CSRF rejected).
490 492
491 ### Repo browsing and raw files493 ### Repo browsing and raw files
492 494
docs/ci.mdmodified+6 -0
@@ -764,6 +764,12 @@ cargo test --workspace
764 764
765 Setting `CARGO_HOME` to a path inside the workspace keeps the downloaded crates in the cache too.765 Setting `CARGO_HOME` to a path inside the workspace keeps the downloaded crates in the cache too.
766 766
767+Each job checks out its commit fresh, so every file would get a new modification time and tools that
768+compare times would rebuild everything. The runner avoids this: when it restores a cache, it sets
769+each tracked file's modification time to when that file's content last changed, as the restored
770+cache saw it. A file that did not change keeps its old time, and a changed file gets the current
771+time. Tools that compare times, such as cargo and make, therefore rebuild only what changed.
772+
767 ## Forge limits (`[ci]`)773 ## Forge limits (`[ci]`)
768 774
769 The `[ci]` section of `forge.toml` controls CI on the forge. These are the defaults:775 The `[ci]` section of `forge.toml` controls CI on the forge. These are the defaults: