use proa_assets::{AssetCatalog, AssetManifest, OUTPUT_ENV};
use std::{
fs,
path::{Path, PathBuf},
process::{Command, Output},
};
const PUBLIC_CONFIG: &str = r#"
use proa::config::{BuildConfig, Config, ProjectPaths, Result, ScriptsConfig};
pub async fn config() -> Result<Config<&'static str, String>> {
let public = proa::config::tokio::fs::read_to_string("asset-root.txt")
.await
.map_err(|error| format!("read asset-root.txt: {error}"))?;
Ok(Config {
scripts: ScriptsConfig {
dev: "cargo run",
build: "cargo build --release",
..Default::default()
},
paths: ProjectPaths {
public: Some(public),
..Default::default()
},
build: BuildConfig {
assets: Some(vec![]),
..Default::default()
},
..Config::default()
})
}
"#;
fn fixture() -> tempfile::TempDir {
let temp = tempfile::tempdir().unwrap();
fs::create_dir(temp.path().join("src")).unwrap();
fs::create_dir(temp.path().join("public")).unwrap();
fs::write(temp.path().join("Cargo.toml"), "[package]\nname = \"public_asset_fixture\"\nversion = \"0.0.0\"\nedition = \"2021\"\n[workspace]\n").unwrap();
fs::write(temp.path().join("src/main.rs"), r#"
fn main() {
assert!(option_env!("PROA_PUBLIC_ASSETS").is_none(), "output path leaked into compilation");
let path = std::env::var_os("PROA_PUBLIC_ASSETS").expect("runtime public output");
let manifest = std::fs::read_to_string(std::path::PathBuf::from(path).join("manifest.json")).unwrap();
println!("MAIN|{}|{}", std::env::args().nth(1).unwrap_or_default(), manifest.trim());
}
"#).unwrap();
fs::write(temp.path().join("proa.config.rs"), PUBLIC_CONFIG).unwrap();
fs::write(temp.path().join("asset-root.txt"), "public").unwrap();
fs::write(temp.path().join("public/logo.svg"), b"first").unwrap();
temp
}
fn cli(root: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cargo-proa"))
.current_dir(root)
.env("CARGO_TARGET_DIR", root.join("custom-target"))
.env_remove(OUTPUT_ENV)
.args(args)
.output()
.unwrap()
}
fn success(output: &Output) -> String {
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
assert!(
output.status.success(),
"{stdout}\n{}",
String::from_utf8_lossy(&output.stderr)
);
stdout
}
fn published(stdout: &str) -> PathBuf {
stdout
.lines()
.find_map(|line| {
line.strip_prefix("published ")?
.split_once(" public assets to ")
.map(|(_, path)| path.into())
})
.expect("published public catalog")
}
fn main_manifest(stdout: &str) -> AssetManifest {
assert_eq!(
stdout
.lines()
.filter(|line| line.starts_with("MAIN|"))
.count(),
1
);
let json = stdout
.lines()
.find_map(|line| line.strip_prefix("MAIN|--probe|"))
.expect("main executed after publication, with its argument");
serde_json::from_str(json).unwrap()
}
#[test]
fn tests_execute_after_publication_with_runtime_only_assets_and_harness_args() {
let temp = fixture();
let root = temp.path();
fs::remove_file(root.join("proa.config.rs")).unwrap();
fs::remove_dir_all(root.join("public")).unwrap();
fs::create_dir(root.join("tests")).unwrap();
fs::write(
root.join("build.rs"),
r#"
fn main() {
assert!(std::env::var_os("PROA_PUBLIC_ASSETS").is_none());
std::fs::create_dir_all("public").unwrap();
std::fs::write("public/generated.svg", b"build output").unwrap();
}
"#,
)
.unwrap();
fs::write(
root.join("tests/page.rs"),
r#"
#[test]
fn managed_page() {
assert!(option_env!("PROA_PUBLIC_ASSETS").is_none());
let output = std::path::PathBuf::from(std::env::var_os("PROA_PUBLIC_ASSETS").unwrap());
let manifest = std::fs::read_to_string(output.join("manifest.json")).unwrap();
assert!(manifest.contains("generated.svg"), "{manifest}");
}
#[test]
fn filtered_out() {
panic!("the CLI must forward the harness filter");
}
"#,
)
.unwrap();
let output = cli(
root,
&[
"test",
"--test",
"page",
"--offline",
"--",
"--exact",
"managed_page",
],
);
let stdout = success(&output);
assert!(stdout.contains("test managed_page ... ok"), "{stdout}");
let published = published(&stdout);
let catalog = AssetCatalog::load(published).unwrap();
assert_eq!(
fs::read(catalog.object_path("generated.svg").unwrap()).unwrap(),
b"build output"
);
}
#[test]
fn default_public_directory_can_be_absent_or_disabled() {
let temp = fixture();
let root = temp.path();
fs::remove_file(root.join("proa.config.rs")).unwrap();
fs::remove_dir_all(root.join("public")).unwrap();
fs::write(
root.join("src/main.rs"),
r#"fn main() { assert!(std::env::var_os("PROA_PUBLIC_ASSETS").is_none()); }"#,
)
.unwrap();
let run = success(&cli(root, &["run", "--offline"]));
assert!(!run.contains(" public assets to "), "{run}");
assert!(!root.join("public").exists());
fs::create_dir(root.join("public")).unwrap();
fs::write(root.join("public/logo.svg"), "logo").unwrap();
fs::write(
root.join("proa.config.rs"),
PUBLIC_CONFIG.replace("public: Some(public)", "public: None"),
)
.unwrap();
let run = success(&cli(root, &["run", "--offline"]));
assert!(!run.contains(" public assets to "), "{run}");
}
#[cfg(unix)]
struct Watcher(std::process::Child);
#[cfg(unix)]
impl Watcher {
fn wait_for(&mut self, log: &Path, message: &str, count: usize) -> String {
use std::time::{Duration, Instant};
let deadline = Instant::now() + Duration::from_secs(120);
loop {
let text = fs::read_to_string(log).unwrap();
if text.matches(message).count() >= count {
return text;
}
assert!(
self.0.try_wait().unwrap().is_none() && Instant::now() < deadline,
"{text}"
);
std::thread::sleep(Duration::from_millis(25));
}
}
}
#[cfg(unix)]
impl Drop for Watcher {
fn drop(&mut self) {
unsafe {
libc::kill(-(self.0.id() as i32), libc::SIGTERM);
}
let _ = self.0.wait();
}
}
#[cfg(unix)]
#[test]
fn test_watch_tracks_authored_inputs_without_looping_on_preparation_outputs() {
use std::{os::unix::process::CommandExt, time::Duration};
let temp = fixture();
let root = temp.path();
fs::create_dir(root.join("tests")).unwrap();
fs::create_dir(root.join("content")).unwrap();
fs::create_dir(root.join("styles")).unwrap();
fs::write(root.join("content/example.txt"), "first input").unwrap();
fs::write(root.join("styles/input.css"), ".test {}\n").unwrap();
fs::write(
root.join("styles/build css.sh"),
"{ cat styles/input.css; printf '/* %s */\\n' \"$(cat content/example.txt)\"; } > public/styles.css\n",
)
.unwrap();
fs::write(
root.join("tests/page.rs"),
r#"
#[test]
fn page_inputs() {
let content = std::fs::read_to_string("content/example.txt").unwrap();
let public = std::fs::read_to_string("public/logo.svg").unwrap();
assert!(std::env::var_os("PROA_PUBLIC_ASSETS").is_some());
println!("INPUTS|{content}|{public}");
}
"#,
)
.unwrap();
fs::write(
root.join("proa.config.rs"),
PUBLIC_CONFIG
.replace(
"scripts: ScriptsConfig {",
r#"scripts: ScriptsConfig {
css: "sh 'styles/build css.sh'",
before: proa::config::ScriptHooks {
test: vec!["prepare-fixture"],
..Default::default()
},
named: std::collections::BTreeMap::from([
("prepare-public", proa::config::ScriptConfig {
command: vec!["sh", "-c", "if [ \"$(cat public/logo.svg)\" = bad ]; then echo HOOK-READ-BAD-FIXTURE; while [ ! -e release-hook ]; do sleep 0.05; done; exit 1; fi; echo fixture > public/prepared.svg"],
..Default::default()
}),
("prepare-fixture", proa::config::ScriptConfig {
command: vec!["sh", "-c", "echo fixture > content/generated.txt"],
depends_on: vec!["prepare-public"],
outputs: vec!["content/generated.txt".to_owned()],
..Default::default()
})
]),
"#,
)
.replace("assets: Some(vec![])", "assets: None"),
)
.unwrap();
success(&cli(root, &["config", "show"]));
let log = root.join("test-watch.log");
let output = fs::File::create(&log).unwrap();
let mut watch = Watcher(
Command::new(env!("CARGO_BIN_EXE_proa"))
.current_dir(root)
.env("CARGO_TARGET_DIR", root.join("custom-target"))
.env_remove(OUTPUT_ENV)
.args([
"test",
"--test",
"page",
"--offline",
"--watch",
"--watch-path",
"content",
"--",
"--nocapture",
])
.stdout(output.try_clone().unwrap())
.stderr(output)
.process_group(0)
.spawn()
.unwrap(),
);
let waiting = "Watching for test input changes";
let first = watch.wait_for(&log, waiting, 1);
assert!(first.contains("INPUTS|first input|first"), "{first}");
let output = published(&first);
let first_catalog = AssetCatalog::load(&output).unwrap();
assert_eq!(
fs::read(first_catalog.object_path("styles.css").unwrap()).unwrap(),
b".test {}\n/* first input */\n"
);
fs::write(root.join("content/example.txt"), "updated input").unwrap();
let second = watch.wait_for(&log, waiting, 2);
assert!(second.contains("INPUTS|updated input|first"), "{second}");
let second_catalog = AssetCatalog::load(&output).unwrap();
assert_eq!(
fs::read(second_catalog.object_path("styles.css").unwrap()).unwrap(),
b".test {}\n/* updated input */\n"
);
let first_css = &first_catalog.manifest().assets["styles.css"];
let second_css = &second_catalog.manifest().assets["styles.css"];
assert!(first_css.public_path.starts_with("styles."));
assert_ne!(second_css.public_path, first_css.public_path);
assert_ne!(first_css.object, second_css.object);
fs::write(root.join("public/logo.svg"), "updated logo").unwrap();
let third = watch.wait_for(&log, waiting, 3);
assert!(
third.contains("INPUTS|updated input|updated logo"),
"{third}"
);
fs::write(root.join("public/logo.svg"), "bad").unwrap();
watch.wait_for(&log, "HOOK-READ-BAD-FIXTURE", 1);
fs::write(root.join("public/logo.svg"), "fixed logo").unwrap();
fs::write(root.join("release-hook"), "").unwrap();
let recovered = watch.wait_for(&log, waiting, 5);
assert!(
recovered.contains("test run failed; watching for changes"),
"{recovered}"
);
assert!(
recovered.contains("INPUTS|updated input|fixed logo"),
"{recovered}"
);
std::thread::sleep(Duration::from_millis(650));
let text = fs::read_to_string(&log).unwrap();
assert_eq!(text.matches("Task prepare-public").count(), 5, "{text}");
assert_eq!(
text.matches("building asset: public/styles.css").count(),
4,
"{text}"
);
}
#[cfg(unix)]
#[test]
fn watcher_recovers_output_and_rechecks_only_config_compile_inputs_on_asset_edits() {
use std::{
net::TcpListener,
os::unix::{fs::PermissionsExt, process::CommandExt},
time::Duration,
};
let temp = fixture();
let root = temp.path();
let artifacts = tempfile::tempdir().unwrap();
let target = artifacts.path().join("cargo target");
let cargo_trace = artifacts.path().join("config-cargo.log");
let cargo = artifacts.path().join("cargo-trace");
fs::write(
&cargo,
r#"#!/bin/sh
case "$1:$*" in build:*proa-config/*) echo build >> "$CONFIG_CARGO_LOG";; esac
exec "$REAL_CARGO" "$@"
"#,
)
.unwrap();
fs::set_permissions(&cargo, fs::Permissions::from_mode(0o755)).unwrap();
fs::write(
root.join("src/main.rs"),
r#"
fn main() {
let port = std::env::var("PORT").unwrap();
let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
for stream in listener.incoming() { drop(stream.unwrap()); }
}
"#,
)
.unwrap();
fs::write(root.join("public/icon.svg"), "one").unwrap();
fs::write(root.join("extra-input.txt"), "one").unwrap();
fs::create_dir(root.join("scripts")).unwrap();
for name in ["a", "b"] {
fs::write(
root.join(format!("scripts/{name}.sh")),
format!("echo WRAPPER-{name}\nexit 33\n"),
)
.unwrap();
}
let config = PUBLIC_CONFIG.replace("cargo run", "bash scripts/a.sh").replace(" Ok(Config {", r#" eprintln!("CONFIG {} {}", include_str!("public/icon.svg"), std::fs::read_to_string("public/logo.svg")?);
Ok(Config {"#);
fs::write(root.join("proa.config.rs"), &config).unwrap();
let log = artifacts.path().join("dev.log");
let output = fs::File::create(&log).unwrap();
let port = TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let mut watch = Watcher(
Command::new(env!("CARGO_BIN_EXE_proa"))
.current_dir(root)
.env("CARGO_TARGET_DIR", &target)
.env("CARGO", cargo)
.env("REAL_CARGO", env!("CARGO"))
.env("CONFIG_CARGO_LOG", &cargo_trace)
.args([
"dev",
"--offline",
"--no-reload",
"--watch",
"extra-input.txt",
"--port",
&port.to_string(),
])
.stdout(output.try_clone().unwrap())
.stderr(output)
.process_group(0)
.spawn()
.unwrap(),
);
let mut wait = |message, count| watch.wait_for(&log, message, count);
let cargo_calls = || fs::read_to_string(&cargo_trace).unwrap().lines().count();
let ready = "Proa dev ready:";
let build_started = "running linked RSJS Cargo dev build";
let first = wait(ready, 1);
let output = published(&first);
let builds = cargo_calls();
assert_eq!(builds, 1, "{first}");
let original = fs::read(output.join("manifest.json")).unwrap();
fs::remove_file(output.join("manifest.json")).unwrap();
let repaired = wait(ready, 2);
fs::rename(&output, artifacts.path().join("moved-catalog")).unwrap();
let recreated = wait(ready, 3);
for text in [&repaired, &recreated] {
assert_eq!(text.matches(build_started).count(), 1, "{text}");
}
assert_eq!(fs::read(output.join("manifest.json")).unwrap(), original);
assert_eq!(cargo_calls(), builds);
fs::write(root.join("public/logo.svg"), "two").unwrap();
let republish = "republished catalog without Cargo";
let logo = wait(ready, 4);
assert!(logo.contains("CONFIG one two"));
assert_eq!(logo.matches(republish).count(), 1, "{logo}");
assert_eq!(logo.matches(build_started).count(), 1, "{logo}");
assert_ne!(fs::read(output.join("manifest.json")).unwrap(), original);
assert_eq!(
cargo_calls(),
builds,
"runtime read should reuse the config executable"
);
fs::write(root.join("public/icon.svg"), "new-icon").unwrap();
let icon = wait(ready, 5);
assert!(icon.contains("CONFIG new-icon two"));
assert_eq!(icon.matches(republish).count(), 2, "{icon}");
assert_eq!(icon.matches(build_started).count(), 1, "{icon}");
assert_eq!(
cargo_calls(),
builds + 1,
"include_str! is a compiler input"
);
fs::write(
root.join("proa.config.rs"),
config.replace("scripts/a.sh", "scripts/b.sh"),
)
.unwrap();
let changed = wait(ready, 6);
assert!(changed.contains("use `proa run dev`"));
assert!(!changed.contains("WRAPPER-"));
fs::rename(&target, artifacts.path().join("moved-target")).unwrap();
let rebuilt = wait(ready, 7);
assert!(output.join("manifest.json").is_file());
assert_eq!(rebuilt.matches("use `proa run dev`").count(), 1);
assert_eq!(rebuilt.matches(build_started).count(), 3, "{rebuilt}");
let source = root.join("src/main.rs");
let valid_source = fs::read(&source).unwrap();
let config_builds = cargo_calls();
fs::write(
&source,
b"compile_error!(\"broken while output is missing\");",
)
.unwrap();
let failed = "linked dev rebuild failed";
let broken = wait(failed, 1);
assert!(
broken.contains("broken while output is missing"),
"{broken}"
);
assert_eq!(
cargo_calls(),
config_builds,
"an application edit outside the config inputs should reuse the config executable"
);
fs::remove_file(output.join("manifest.json")).unwrap();
std::thread::sleep(Duration::from_secs(3));
let idle = fs::read_to_string(&log).unwrap();
assert_eq!(idle.matches(build_started).count(), 4, "{idle}");
assert_eq!(idle.matches(failed).count(), 1, "{idle}");
assert!(!output.join("manifest.json").exists(), "{idle}");
fs::write(&source, &valid_source).unwrap();
let recovered = wait(ready, 8);
assert_eq!(recovered.matches(build_started).count(), 5, "{recovered}");
assert!(output.join("manifest.json").is_file(), "{recovered}");
fs::write(root.join("extra-input.txt"), "two").unwrap();
let watched = wait(ready, 9);
assert_eq!(watched.matches(build_started).count(), 6, "{watched}");
let mut compiled = b"const _: &str = include_str!(\"../public/logo.svg\");\n".to_vec();
compiled.extend(fs::read(&source).unwrap());
fs::write(&source, compiled).unwrap();
wait(ready, 10);
fs::write(root.join("public/logo.svg"), "three").unwrap();
let included = wait(ready, 11);
assert_eq!(included.matches(build_started).count(), 8, "{included}");
assert_eq!(included.matches(republish).count(), 2, "{included}");
fs::write(&source, &valid_source).unwrap();
fs::write(
root.join("build.rs"),
"fn main() { println!(\"cargo:rerun-if-changed=build.rs\"); }\n",
)
.unwrap();
wait(ready, 12);
fs::write(root.join("public/logo.svg"), "four").unwrap();
let declared = wait(ready, 13);
assert_eq!(declared.matches(build_started).count(), 9, "{declared}");
assert_eq!(declared.matches(republish).count(), 3, "{declared}");
fs::write(root.join("build.rs"), "fn main() {}\n").unwrap();
wait(ready, 14);
fs::write(root.join("public/logo.svg"), "five").unwrap();
let undeclared = wait(ready, 15);
assert_eq!(
undeclared.matches(build_started).count(),
11,
"{undeclared}"
);
assert_eq!(undeclared.matches(republish).count(), 3, "{undeclared}");
}
#[cfg(unix)]
#[test]
fn dev_restarts_a_server_that_cannot_follow_the_catalog_and_spares_one_that_can() {
use std::{net::TcpListener, os::unix::process::CommandExt};
let temp = fixture();
let root = temp.path();
let artifacts = tempfile::tempdir().unwrap();
fs::write(
root.join("src/main.rs"),
r#"
fn main() {
let port = std::env::var("PORT").unwrap();
let output = std::path::PathBuf::from(std::env::var_os("PROA_PUBLIC_ASSETS").unwrap());
let _following = std::path::Path::new("follow").exists().then(|| {
let lock = std::fs::File::open(output.join(".live-readers.lock")).unwrap();
lock.lock_shared().unwrap();
lock
});
eprintln!("SERVER-START");
let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
for stream in listener.incoming() { drop(stream.unwrap()); }
}
"#,
)
.unwrap();
fs::write(
root.join("proa.config.rs"),
PUBLIC_CONFIG.replace("\"cargo run\"", "\"proa dev\""),
)
.unwrap();
let log = artifacts.path().join("dev.log");
let output = fs::File::create(&log).unwrap();
let port = TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let mut watch = Watcher(
Command::new(env!("CARGO_BIN_EXE_proa"))
.current_dir(root)
.env("CARGO_TARGET_DIR", artifacts.path().join("target"))
.env("PORT", port.to_string())
.env("HOST", "arm64-apple-darwin20.0.0")
.env_remove("PROA_HOST")
.args(["dev", "--offline", "--no-reload"])
.stdout(output.try_clone().unwrap())
.stderr(output)
.process_group(0)
.spawn()
.unwrap(),
);
let ready = "Proa dev ready:";
let restarted = "republished catalog without Cargo";
let in_place = "republished catalog in place without restarting";
let starts = |text: &str| text.matches("SERVER-START").count();
let first = watch.wait_for(&log, ready, 1);
assert!(
first.contains(&format!("Proa dev ready: http://127.0.0.1:{port}")),
"{first}"
);
let published = published(&first);
let before = fs::read(published.join("manifest.json")).unwrap();
fs::write(root.join("follow"), "").unwrap();
fs::write(root.join("public/logo.svg"), "second").unwrap();
let after_restart = watch.wait_for(&log, ready, 2);
assert_eq!(
after_restart.matches(restarted).count(),
1,
"{after_restart}"
);
assert_eq!(
after_restart.matches(in_place).count(),
0,
"{after_restart}"
);
assert_eq!(starts(&after_restart), 2, "{after_restart}");
let second = fs::read(published.join("manifest.json")).unwrap();
assert_ne!(second, before);
fs::write(root.join("public/logo.svg"), "third").unwrap();
let after_swap = watch.wait_for(&log, in_place, 1);
assert_ne!(fs::read(published.join("manifest.json")).unwrap(), second);
fs::write(root.join("public/extra.png"), "png").unwrap();
let after_second_swap = watch.wait_for(&log, in_place, 2);
for text in [&after_swap, &after_second_swap] {
assert_eq!(text.matches(restarted).count(), 1, "{text}");
assert_eq!(text.matches(ready).count(), 2, "{text}");
assert_eq!(starts(text), 2, "{text}");
}
assert_eq!(
after_second_swap
.matches("running linked RSJS Cargo dev build")
.count(),
1,
"{after_second_swap}"
);
}
#[cfg(unix)]
#[test]
fn run_dispatches_configured_scripts_and_builtins_bypass_them() {
let temp = fixture();
let root = temp.path();
fs::create_dir(root.join("scripts")).unwrap();
fs::write(
root.join("proa.config.rs"),
PUBLIC_CONFIG
.replace("cargo run", "bash scripts/dev.sh")
.replace("cargo build --release", "bash scripts/build.sh"),
)
.unwrap();
for phase in ["dev", "build"] {
fs::write(
root.join(format!("scripts/{phase}.sh")),
format!("echo SCRIPT:{phase}\nexec \"$PROA_SCRIPT_EXECUTABLE\" {phase} \"$@\"\n"),
)
.unwrap();
}
let cli = |arguments: &[&str]| {
Command::new(env!("CARGO_BIN_EXE_cargo-proa"))
.current_dir(root.parent().unwrap())
.env("CARGO_TARGET_DIR", root.join("custom-target"))
.env_remove(OUTPUT_ENV)
.args(arguments)
.output()
.unwrap()
};
let relative_root = root.file_name().unwrap().to_str().unwrap();
let direct = cli(&["dev", "--root", relative_root, "--no-restart", "--offline"]);
assert!(!success(&direct).contains("SCRIPT:dev"));
assert!(String::from_utf8_lossy(&direct.stderr).contains("use `proa run dev`"));
let dev = success(&cli(&[
"run",
"--root",
relative_root,
"dev",
"--no-restart",
"--offline",
]));
assert_eq!(dev.matches("SCRIPT:dev").count(), 1, "{dev}");
assert!(dev.contains("MAIN||"), "{dev}");
assert!(published(&dev).join("manifest.json").is_file());
let artifact = "custom-target/exported shop";
let build = success(&cli(&[
"run",
&format!("--root={relative_root}"),
"build",
"--profile",
"dev",
"--no-check",
"--offline",
"--artifact-out",
artifact,
]));
assert_eq!(build.matches("SCRIPT:build").count(), 1, "{build}");
assert!(root.join(artifact).is_file());
let direct = cli(&[
"build",
"--root",
relative_root,
"--profile",
"dev",
"--no-check",
"--offline",
]);
assert!(!success(&direct).contains("SCRIPT:build"));
assert!(String::from_utf8_lossy(&direct.stderr).contains("use `proa run build`"));
}
#[test]
fn rsjs_minification_follows_the_config_across_reused_builds() {
let temp = fixture();
let root = temp.path();
fs::write(
root.join("src/main.rs"),
r#"
fn main() {
assert!(std::env::var_os("PROA_RSJS_MINIFY").is_none());
println!("{}", env!("PROA_RSJS_MINIFY"));
}
"#,
)
.unwrap();
let export = root
.join("custom-target")
.join(format!("probe{}", std::env::consts::EXE_SUFFIX));
let build = || {
success(&cli(
root,
&[
"build",
"--profile",
"dev",
"--offline",
"--no-check",
"--artifact-out",
export.to_str().unwrap(),
],
))
};
let run = || {
success(
&Command::new(&export)
.env_remove("PROA_RSJS_MINIFY")
.output()
.unwrap(),
)
};
fs::remove_file(root.join("proa.config.rs")).unwrap();
build();
assert_eq!(run().trim(), "1");
let warm = build();
assert!(
warm.contains("descriptor 1/1 Cargo artifacts reused; final 1/1 reused"),
"{warm}"
);
assert_eq!(run().trim(), "1");
fs::write(
root.join("proa.config.rs"),
r#"
use proa::config::{BuildConfig, Config, Result, ScriptsConfig};
pub async fn config() -> Result<Config> {
Ok(Config {
scripts: ScriptsConfig {
dev: "cargo run",
build: "cargo build --release",
..Default::default()
},
build: BuildConfig {
minify_rsjs: false,
..Default::default()
},
..Config::default()
})
}
"#,
)
.unwrap();
build();
assert_eq!(run().trim(), "0");
}
#[test]
fn build_then_run_refreshes_assets_without_rebinding_the_binary_and_keeps_failures_local() {
let temp = fixture();
let root = temp.path();
let built = success(&cli(
root,
&["build", "--profile", "dev", "--offline", "--no-check"],
));
assert!(!built.contains("MAIN|"));
let output = published(&built);
assert!(output.starts_with(fs::canonicalize(root.join("custom-target/proa-output")).unwrap()));
let old = AssetCatalog::load(&output).unwrap();
let old_object = old.object_path("logo.svg").unwrap();
let run = success(&cli(root, &["run", "--offline", "--", "--probe"]));
assert_eq!(published(&run), output);
assert_eq!(&main_manifest(&run), old.manifest());
assert!(
run.contains("descriptor 1/1 Cargo artifacts reused; final 1/1 reused"),
"{run}"
);
fs::write(root.join("public/logo.svg"), b"other").unwrap();
let edited = success(&cli(root, &["run", "--offline", "--", "--probe"]));
let current = main_manifest(&edited);
assert_eq!(published(&edited), output);
assert_ne!(
current.assets["logo.svg"].public_path,
old.manifest().assets["logo.svg"].public_path
);
assert!(
edited.contains("descriptor 1/1 Cargo artifacts reused; final 1/1 reused"),
"{edited}"
);
assert_eq!(fs::read(&old_object).unwrap(), b"first");
let loaded = AssetCatalog::load(&output).unwrap();
assert_eq!(
fs::read(loaded.object_path("logo.svg").unwrap()).unwrap(),
b"other"
);
drop(old);
drop(loaded);
success(&cli(
root,
&["build", "--profile", "dev", "--offline", "--no-check"],
));
assert!(!old_object.exists());
let pointer = fs::read(output.join("manifest.json")).unwrap();
fs::write(root.join("proa.config.rs"), "invalid Rust config").unwrap();
let invalid_config = cli(root, &["run", "--offline", "--", "--probe"]);
assert!(!invalid_config.status.success());
assert!(String::from_utf8_lossy(&invalid_config.stderr).contains("proa.config.rs"));
assert!(!String::from_utf8_lossy(&invalid_config.stdout).contains("MAIN|"));
assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
fs::write(root.join("proa.config.rs"), PUBLIC_CONFIG).unwrap();
fs::remove_file(root.join("asset-root.txt")).unwrap();
let config_error = cli(root, &["run", "--offline", "--", "--probe"]);
assert!(!config_error.status.success());
assert!(String::from_utf8_lossy(&config_error.stderr).contains("read asset-root.txt"));
assert!(!String::from_utf8_lossy(&config_error.stdout).contains("MAIN|"));
assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
fs::write(root.join("asset-root.txt"), "public").unwrap();
fs::write(root.join("public/logo.svg"), b"third").unwrap();
fs::write(root.join("src/main.rs"), "this is invalid Rust").unwrap();
let broken = cli(root, &["run", "--offline", "--", "--probe"]);
assert!(!broken.status.success());
assert!(!String::from_utf8_lossy(&broken.stdout).contains("MAIN|"));
assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
fs::write(
root.join("src/main.rs"),
"fn main() { panic!(\"must not launch\"); }",
)
.unwrap();
fs::write(root.join("asset-root.txt"), "missing-custom").unwrap();
let missing = cli(root, &["run", "--offline"]);
assert!(!missing.status.success());
assert!(
String::from_utf8_lossy(&missing.stderr).contains("publish configured public directory")
);
assert!(!String::from_utf8_lossy(&missing.stderr).contains("must not launch"));
assert_eq!(fs::read(output.join("manifest.json")).unwrap(), pointer);
}
#[test]
fn public_files_used_by_rust_or_build_scripts_remain_compiler_inputs() {
let temp = fixture();
let root = temp.path();
fs::write(root.join("public/build-input.txt"), "build-first").unwrap();
fs::write(
root.join("build.rs"),
r#"
fn main() {
println!("cargo:rerun-if-changed=public/build-input.txt");
let value = std::fs::read_to_string("public/build-input.txt").unwrap();
println!("cargo:rustc-env=PUBLIC_BUILD_INPUT={value}");
}
"#,
)
.unwrap();
fs::write(
root.join("src/main.rs"),
r#"
fn main() {
println!("COMPILED|{}|{}", include_str!("../public/logo.svg"), env!("PUBLIC_BUILD_INPUT"));
}
"#,
)
.unwrap();
let run = success(&cli(root, &["run", "--offline"]));
assert!(run.lines().any(|line| line == "COMPILED|first|build-first"));
let output = published(&run);
fs::write(root.join("public/logo.svg"), "included-second").unwrap();
let included = success(&cli(root, &["run", "--offline"]));
assert!(included
.lines()
.any(|line| line == "COMPILED|included-second|build-first"));
assert_eq!(published(&included), output);
fs::write(root.join("public/build-input.txt"), "build-second").unwrap();
let generated = success(&cli(root, &["run", "--offline"]));
assert!(generated
.lines()
.any(|line| line == "COMPILED|included-second|build-second"));
assert_eq!(published(&generated), output);
let catalog = AssetCatalog::load(output).unwrap();
assert_eq!(
fs::read(catalog.object_path("logo.svg").unwrap()).unwrap(),
b"included-second"
);
assert_eq!(
fs::read(catalog.object_path("build-input.txt").unwrap()).unwrap(),
b"build-second"
);
}
#[test]
fn dev_finalizes_before_launch_and_no_assets_skips_publication() {
let temp = fixture();
let root = temp.path();
let skipped = success(&cli(
root,
&[
"build",
"--profile",
"dev",
"--offline",
"--no-check",
"--no-assets",
],
));
assert!(!skipped.contains("published "));
assert!(!root.join("custom-target/proa-output").exists());
let dev = success(&cli(
root,
&[
"dev",
"--no-restart",
"--",
"cargo",
"run",
"--offline",
"--",
"--probe",
],
));
let manifest = main_manifest(&dev);
let catalog = AssetCatalog::load(published(&dev)).unwrap();
assert_eq!(&manifest, catalog.manifest());
assert!(dev.contains("final cache: 1/1 reused"), "{dev}");
}
#[cfg(unix)]
#[test]
fn config_runner_persists_stamp_cache_across_cli_invocations() {
use std::os::unix::fs::PermissionsExt;
let temp = fixture();
let root = temp.path();
fs::write(
root.join("proa.config.rs"),
r#"
use proa::config::{BuildConfig, Config, ProjectPaths, Result, ScriptsConfig};
pub async fn config() -> Result<Config<&'static str, String>> {
let public = proa::config::tokio::fs::read_to_string("asset-root.txt")
.await
.map_err(|error| format!("read asset-root.txt: {error}"))?;
Ok(Config {
scripts: ScriptsConfig {
dev: option_env!("PROA_TEST_DEV_CMD").unwrap_or("cargo run"),
build: "cargo build --release",
..Default::default()
},
paths: ProjectPaths {
public: Some(public),
..Default::default()
},
build: BuildConfig {
assets: Some(vec![]),
..Default::default()
},
..Config::default()
})
}
"#,
)
.unwrap();
let artifacts = tempfile::tempdir().unwrap();
let target = artifacts.path().join("cargo-target");
let cargo_trace = artifacts.path().join("config-cargo.log");
let cargo = artifacts.path().join("cargo-trace");
fs::write(
&cargo,
r#"#!/bin/sh
case "$1:$*" in build:*proa-config/*) echo build >> "$CONFIG_CARGO_LOG";; esac
exec "$REAL_CARGO" "$@"
"#,
)
.unwrap();
fs::set_permissions(&cargo, fs::Permissions::from_mode(0o755)).unwrap();
let profile = std::cell::Cell::new(None::<&str>);
let quiet = std::cell::Cell::new(false);
let run_validate = |compile_env: Option<&str>| {
let mut command = Command::new(env!("CARGO_BIN_EXE_proa"));
if let Some(value) = profile.get() {
command.env("CARGO_PROFILE_DEV_DEBUG_ASSERTIONS", value);
}
if quiet.get() {
command.env("CARGO_TERM_QUIET", "true");
} else {
command.env_remove("CARGO_TERM_QUIET");
}
command
.current_dir(root)
.env("CARGO_TARGET_DIR", &target)
.env("CARGO", &cargo)
.env("REAL_CARGO", env!("CARGO"))
.env("CARGO_NET_OFFLINE", "true")
.env("CONFIG_CARGO_LOG", &cargo_trace)
.args(["config", "validate"]);
match compile_env {
Some(value) => {
command.env("PROA_TEST_DEV_CMD", value);
}
None => {
command.env_remove("PROA_TEST_DEV_CMD");
}
}
command.output().unwrap()
};
let first = run_validate(Some("cargo run --bin secret-alpha"));
assert!(
first.status.success(),
"{}",
String::from_utf8_lossy(&first.stderr)
);
assert!(
String::from_utf8_lossy(&first.stderr).contains("compiling proa.config.rs..."),
"{}",
String::from_utf8_lossy(&first.stderr)
);
assert_eq!(fs::read_to_string(&cargo_trace).unwrap().lines().count(), 1);
let cache_files: Vec<_> = fs::read_dir(target.join("proa-config"))
.unwrap()
.filter_map(|entry| entry.ok())
.map(|entry| entry.path().join("stamp-cache.json"))
.filter(|path| path.is_file())
.collect();
assert_eq!(cache_files.len(), 1);
let persisted = fs::read_to_string(&cache_files[0]).unwrap();
assert!(persisted.contains("PROA_TEST_DEV_CMD"), "{persisted}");
assert!(!persisted.contains("secret-alpha"), "{persisted}");
let second = run_validate(Some("cargo run --bin secret-alpha"));
assert!(
second.status.success(),
"{}",
String::from_utf8_lossy(&second.stderr)
);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
1,
"second CLI process should skip cargo build when inputs and compile-time env are unchanged"
);
let env_changed = run_validate(Some("cargo run --bin secret-beta"));
assert!(
env_changed.status.success(),
"{}",
String::from_utf8_lossy(&env_changed.stderr)
);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
2,
"changing compile-time option_env!() must invalidate persisted stamp cache"
);
let env_unset = run_validate(None);
assert!(
env_unset.status.success(),
"{}",
String::from_utf8_lossy(&env_unset.stderr)
);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
3,
"unsetting compile-time option_env!() must invalidate persisted stamp cache"
);
let updated = format!(
"{}\n// touched\n",
fs::read_to_string(root.join("proa.config.rs")).unwrap()
);
fs::write(root.join("proa.config.rs"), updated).unwrap();
let file_changed = run_validate(None);
assert!(
file_changed.status.success(),
"{}",
String::from_utf8_lossy(&file_changed.stderr)
);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
4,
"editing proa.config.rs must invalidate persisted stamp cache"
);
profile.set(Some("false"));
let profile_changed = run_validate(None);
assert!(
profile_changed.status.success(),
"{}",
String::from_utf8_lossy(&profile_changed.stderr)
);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
5,
"a new CARGO_PROFILE_* setting must invalidate persisted stamp cache"
);
run_validate(None);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
5,
"an unchanged profile setting reuses the persisted stamp cache"
);
quiet.set(true);
run_validate(None);
quiet.set(false);
run_validate(None);
assert_eq!(
fs::read_to_string(&cargo_trace).unwrap().lines().count(),
5,
"CARGO_TERM_* settings must not invalidate the persisted stamp cache"
);
}
#[test]
fn build_bundles_the_public_catalog_beside_the_exported_executable() {
let temp = fixture();
let root = temp.path();
let exported_bin = temp.path().join("release-export/app");
let bundled = temp.path().join("release-export/app.assets");
let build = |extra: &[&str]| {
let mut args = vec!["build", "--offline", "--no-check", "--artifact-out"];
args.push(exported_bin.to_str().unwrap());
args.extend_from_slice(extra);
cli(root, &args)
};
let first = success(&build(&[]));
assert!(first.contains(" public assets in "), "{first}");
let catalog = AssetCatalog::load(&bundled).unwrap();
let first_url = catalog.manifest().assets["logo.svg"].public_path.clone();
assert_eq!(
fs::read(catalog.object_path("logo.svg").unwrap()).unwrap(),
b"first"
);
drop(catalog);
assert_eq!(
fs::read(bundled.join("public/_proa/immutable").join(&first_url)).unwrap(),
b"first"
);
let mut entries: Vec<_> = fs::read_dir(&bundled)
.unwrap()
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
.collect();
entries.sort();
assert_eq!(entries, [".proa-assets", "manifest.json", "public"]);
let moved = temp.path().join("deployed");
fs::create_dir(&moved).unwrap();
fs::copy(&exported_bin, moved.join("app")).unwrap();
copy_tree(&bundled, &moved.join("app.assets"));
let relocated = AssetCatalog::load(moved.join("app.assets")).unwrap();
assert_eq!(
relocated.manifest().assets["logo.svg"].public_path,
first_url
);
drop(relocated);
fs::write(root.join("public/logo.svg"), b"second").unwrap();
success(&build(&[]));
let updated = AssetCatalog::load(&bundled).unwrap();
let second_url = updated.manifest().assets["logo.svg"].public_path.clone();
assert_ne!(first_url, second_url);
drop(updated);
let started = success(&cli(
root,
&["start", "--bin", exported_bin.to_str().unwrap()],
));
let manifest: AssetManifest = serde_json::from_str(
started
.lines()
.find_map(|line| line.strip_prefix("MAIN||"))
.expect("started executable"),
)
.unwrap();
assert_eq!(manifest.assets["logo.svg"].public_path, second_url);
let blocked_bin = temp.path().join("blocked/app");
let blocked = temp.path().join("blocked/app.assets");
fs::create_dir_all(&blocked).unwrap();
fs::write(blocked.join("existing.txt"), "keep").unwrap();
let refused = cli(
root,
&[
"build",
"--offline",
"--no-check",
"--artifact-out",
blocked_bin.to_str().unwrap(),
],
);
assert!(!refused.status.success());
let stderr = String::from_utf8_lossy(&refused.stderr);
assert!(stderr.contains("is in the way"), "{stderr}");
assert_eq!(fs::read_dir(&blocked).unwrap().count(), 1);
assert!(!blocked_bin.exists());
let inside = root.join("public/app");
let overlapping = cli(
root,
&[
"build",
"--offline",
"--no-check",
"--artifact-out",
inside.to_str().unwrap(),
],
);
assert!(!overlapping.status.success());
let stderr = String::from_utf8_lossy(&overlapping.stderr);
assert!(stderr.contains("overlaps the public directory"), "{stderr}");
assert!(!root.join("public/app.assets").exists());
assert!(!inside.exists());
let directory = temp.path().join("release-dir");
fs::create_dir(&directory).unwrap();
let not_a_file = cli(
root,
&[
"build",
"--offline",
"--no-check",
"--artifact-out",
directory.to_str().unwrap(),
],
);
assert!(!not_a_file.status.success());
assert!(!temp.path().join("release-dir.assets").exists());
let interrupted_bin = temp.path().join("interrupted/app");
let interrupted = temp.path().join("interrupted/app.assets");
fs::create_dir_all(&interrupted).unwrap();
fs::write(interrupted.join(".writer.lock"), "").unwrap();
success(&cli(
root,
&[
"build",
"--offline",
"--no-check",
"--artifact-out",
interrupted_bin.to_str().unwrap(),
],
));
drop(AssetCatalog::load(&interrupted).unwrap());
let reader = AssetCatalog::load(&bundled).unwrap();
let installed = fs::metadata(&exported_bin).unwrap().modified().unwrap();
let in_use = build(&["--no-assets"]);
assert!(!in_use.status.success());
assert_eq!(
fs::metadata(&exported_bin).unwrap().modified().unwrap(),
installed
);
let stderr = String::from_utf8_lossy(&in_use.stderr);
assert!(stderr.contains("still being read"), "{stderr}");
assert!(reader.object_path("logo.svg").unwrap().is_file());
drop(reader);
success(&build(&["--no-assets"]));
assert!(exported_bin.is_file());
assert!(!bundled.exists());
}
fn copy_tree(from: &Path, to: &Path) {
fs::create_dir_all(to).unwrap();
for entry in fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
fs::copy(entry.path(), target).unwrap();
}
}
}