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