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        };
39
40        if build_flag.is_empty() {
41            return Ok(());
42        }
43        println!("Prebuilding target [{}]: {}", build_flag, target.name);
44
45        let mut command = Command::new("cargo");
46        command.arg("build").arg(build_flag).arg(&target.name);
47
48        if use_manifest {
49            command.args(&[
50                "--manifest-path",
51                &target.manifest_path.to_str().unwrap_or_default().to_owned(),
52            ]);
53        }
54
55        let status = command
56            .status()
57            .with_context(|| format!("Cargo build failed for target {}", target.name))?;
58
59        if !status.success() {
60            return Err(anyhow::anyhow!(
61                "Prebuild failed for target {}",
62                target.name
63            ));
64        }
65    }
66    Ok(())
67}