cargo_e/
e_prebuild.rs

1use anyhow::{Context, Result};
2use std::process::Command;
3
4use crate::e_target::{CargoTarget, TargetKind};
5
6/// Prebuilds all given targets by invoking `cargo build` with the appropriate flags.
7///
8/// This function supports all target kinds:
9/// - **Example:** Runs `cargo build --example <name>`
10/// - **ExtendedExample:** Runs `cargo build --example <name> --manifest-path <manifest_path>`
11/// - **Binary:** Runs `cargo build --bin <name>`
12/// - **ExtendedBinary:** Runs `cargo build --bin <name> --manifest-path <manifest_path>`
13///
14/// # Parameters
15///
16/// - `targets`: A slice of `Example` instances representing the targets to prebuild.
17///
18/// # Returns
19///
20/// Returns `Ok(())` if all targets build successfully; otherwise, returns an error.
21pub fn prebuild_examples(targets: &[CargoTarget]) -> Result<()> {
22    for target in targets {
23        // Determine the build flag and whether to include the manifest path
24        let (build_flag, use_manifest) = match target.kind {
25            TargetKind::Example => ("--example", false),
26            TargetKind::ExtendedExample => ("--example", true),
27            TargetKind::Binary => ("--bin", false),
28            TargetKind::ExtendedBinary => ("--bin", true),
29            TargetKind::ManifestTauriExample => ("", true),
30            TargetKind::ManifestTauri => ("", true),
31            TargetKind::Test => ("--test", true),
32            TargetKind::Manifest => ("", true),
33            TargetKind::Bench => ("", true),
34            TargetKind::ManifestDioxus => ("", true),
35            TargetKind::ManifestDioxusExample => ("", true),
36            TargetKind::ManifestLeptos => ("", true),
37            TargetKind::Unknown => ("", true),
38            _ => ("", true),
39        };
40
41        if build_flag.is_empty() {
42            return Ok(());
43        }
44        println!("Prebuilding target [{}]: {}", build_flag, target.name);
45
46        let mut command = Command::new("cargo");
47        command.arg("build").arg(build_flag).arg(&target.name);
48
49        if use_manifest {
50            command.args(&[
51                "--manifest-path",
52                &target.manifest_path.to_str().unwrap_or_default().to_owned(),
53            ]);
54        }
55
56        let status = command
57            .status()
58            .with_context(|| format!("Cargo build failed for target {}", target.name))?;
59
60        if !status.success() {
61            return Err(anyhow::anyhow!(
62                "Prebuild failed for target {}",
63                target.name
64            ));
65        }
66    }
67    Ok(())
68}