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