Skip to main content

vertigo_cli/build/
cargo_build.rs

1use std::{
2    fs,
3    path::PathBuf,
4    time::{SystemTime, UNIX_EPOCH},
5};
6
7use crate::{
8    build::find_target::{BuildProfile, resolve_target_root},
9    commons::{ErrorCode, command::CommandRun},
10};
11
12use super::Workspace;
13
14const TARGET: &str = "wasm32-unknown-unknown";
15
16/// Value for `VERTIGO_BUILD_ID`, the variable `#[vertigo::main]` pulls into the app crate's
17/// dep-info via `option_env!`.
18///
19/// Cargo can't see that the bundling macros read `VERTIGO_BUNDLE` and write asset files, so
20/// left alone it would call the app crate fresh and we'd bundle nothing. Handing it a value
21/// that differs from last time makes cargo re-expand the crate - and unlike dropping the
22/// crate's artifacts (`cargo clean -p`), the incremental cache survives, which is the
23/// difference between a ~1s and a ~7s watch-mode rebuild.
24fn build_id() -> String {
25    SystemTime::now()
26        .duration_since(UNIX_EPOCH)
27        .map(|since_epoch| since_epoch.as_nanos().to_string())
28        .unwrap_or_default()
29}
30
31/// The variables of our environment that cargo sets for a process it runs, a test binary or
32/// `cargo run`: that package's `CARGO_PKG_*` and `CARGO_MANIFEST_*`.
33///
34/// A cargo started from such a process must go without them. Build scripts track some of them
35/// with `rerun-if-env-changed` (ring does), and cargo compares them with its own environment,
36/// so that build and the next one from a shell would each find them changed and rebuild those
37/// crates, and everything on them.
38pub fn inherited_package_env() -> Vec<String> {
39    std::env::vars_os()
40        .filter_map(|(name, _)| name.into_string().ok())
41        .filter(|name| name.starts_with("CARGO_PKG_") || name.starts_with("CARGO_MANIFEST_"))
42        .collect()
43}
44
45pub fn run_cargo_build(
46    package_name: &str,
47    vertigo_public_path: &str,
48    ws: &Workspace,
49    allow_error: bool,
50    release: bool,
51    cargo_opts: &[String],
52) -> Result<Result<PathBuf, String>, ErrorCode> {
53    log::info!("Building {package_name}");
54
55    // `--target-dir` and `--profile` can arrive through the caller's own cargo options, and
56    // then they - not `cargo metadata`, not `release` - decide where the build lands. Get
57    // this wrong and we wipe, clean and read a directory the build never touches.
58    let profile = BuildProfile::resolve(release, cargo_opts);
59    let target_dir = resolve_target_root(ws.get_target_dir(), cargo_opts)
60        .join(TARGET)
61        .join(&profile.dir);
62
63    // Reset the state that macros accumulate during expansion. Only this command sets
64    // VERTIGO_BUNDLE, so only this command can produce it. Note we wipe `static/included`
65    // and not `static` itself - the latter also holds wasm_run.js, written by vertigo's
66    // build script, which only reruns when the js actually changes.
67    let _ = fs::remove_dir_all(target_dir.join("tailwind"));
68    let _ = fs::remove_dir_all(target_dir.join("static").join("included"));
69
70    let mut command = CommandRun::new("cargo").add_param("build");
71
72    if release {
73        command = command.add_param("--locked");
74
75        // A `--profile` in cargo_opts already selects the profile, and cargo refuses to
76        // take both it and `--release`.
77        if !profile.from_cargo_opts {
78            command = command.add_param("--release");
79        }
80    }
81
82    command = command
83        .add_param("--target")
84        .add_param(TARGET)
85        .add_param("--package")
86        .add_param(package_name)
87        .env("VERTIGO_PUBLIC_PATH", vertigo_public_path)
88        // Tell macros that we're bundling so it will produce artifacts
89        .env("VERTIGO_BUNDLE", "true")
90        // Cargo tells proc macros nothing about the target directory, so hand them the
91        // path we got from `cargo metadata`
92        .env("VERTIGO_TARGET_DIR", target_dir.to_string_lossy())
93        // ...and force the macros to run again, so they repopulate what we just wiped
94        .env("VERTIGO_BUILD_ID", build_id());
95
96    for opt in cargo_opts {
97        command = command.add_param(opt);
98    }
99
100    for name in inherited_package_env() {
101        command = command.env_remove(name);
102    }
103
104    if allow_error {
105        command = command.allow_error();
106    } else {
107        command = command.set_error_code(ErrorCode::BuildFailed);
108    }
109
110    let (status, output) = command.output_with_status()?;
111
112    if status.success() {
113        Ok(Ok(target_dir))
114    } else {
115        Ok(Err(output))
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    // Run by cargo, so with the variables it sets for a test binary
124    #[test]
125    fn inherited_package_env_is_the_package_identity() {
126        let names = inherited_package_env();
127        assert!(names.iter().any(|name| name == "CARGO_PKG_NAME"));
128        assert!(names.iter().any(|name| name == "CARGO_MANIFEST_DIR"));
129        assert!(!names.iter().any(|name| name == "CARGO"));
130    }
131}