Skip to main content

theater_cli/commands/
build.rs

1use anyhow::{anyhow, Result};
2use clap::Parser;
3use std::fs;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6use tracing::{debug, error, info};
7
8use crate::{error::CliError, output::formatters::BuildResult, CommandContext};
9use theater::config::actor_manifest::ManifestConfig;
10
11#[derive(Debug, Parser)]
12pub struct BuildArgs {
13    /// Directory containing the actor project
14    #[arg(default_value = ".")]
15    pub project_dir: PathBuf,
16
17    /// Build in release mode
18    #[arg(short, long, default_value = "true")]
19    pub release: bool,
20
21    /// Clean the target directory before building
22    #[arg(short, long, default_value = "false")]
23    pub clean: bool,
24}
25
26/// Execute the build command asynchronously (modernized)
27pub async fn execute_async(args: &BuildArgs, ctx: &CommandContext) -> Result<(), CliError> {
28    let project_dir = if args.project_dir.is_absolute() {
29        args.project_dir.clone()
30    } else {
31        std::env::current_dir()
32            .map_err(|e| CliError::file_operation_failed("get current directory", ".", e))?
33            .join(&args.project_dir)
34    };
35
36    debug!("Building actor in directory: {}", project_dir.display());
37    debug!("Release mode: {}", args.release);
38    debug!("Clean build: {}", args.clean);
39
40    // Check if the directory contains a Cargo.toml file
41    let cargo_toml_path = project_dir.join("Cargo.toml");
42    if !cargo_toml_path.exists() {
43        return Err(CliError::invalid_manifest(format!(
44            "Not a Rust project directory (Cargo.toml not found): {}",
45            project_dir.display()
46        )));
47    }
48
49    // Get the package name from Cargo.toml
50    let package_name = get_package_name(&cargo_toml_path)
51        .map_err(|e| CliError::invalid_manifest(format!("Failed to parse Cargo.toml: {}", e)))?;
52
53    // Check for manifest.toml
54    let manifest_path = project_dir.join("manifest.toml");
55    let manifest_exists = manifest_path.exists();
56
57    // Perform cleaning if requested
58    if args.clean {
59        debug!("Cleaning build artifacts...");
60        let mut clean_cmd = Command::new("cargo");
61        clean_cmd.arg("clean").current_dir(&project_dir);
62
63        if let Err(e) = run_command_with_output(&mut clean_cmd, ctx.is_verbose()) {
64            error!("Failed to clean cargo artifacts: {}", e);
65            // Continue anyway, as this is not fatal
66        }
67    }
68
69    // Build the WebAssembly module
70    debug!(
71        "Building WebAssembly module for actor in {}...",
72        project_dir.display()
73    );
74
75    // Execute cargo build with WASM target
76    let mut build_cmd = Command::new("cargo");
77    build_cmd.args(["build", "--target", "wasm32-unknown-unknown"]);
78
79    if args.release {
80        build_cmd.arg("--release");
81    }
82
83    build_cmd.current_dir(&project_dir);
84
85    // Run the build command and capture output
86    let (status, stdout, stderr) = run_command_with_output(&mut build_cmd, ctx.is_verbose())
87        .map_err(|e| CliError::build_failed(format!("Failed to execute cargo build: {}", e)))?;
88
89    // Handle build failures
90    if !status.success() {
91        let error_details = if stderr.is_empty() { stdout } else { stderr };
92        return Err(CliError::build_failed(format!(
93            "Cargo build failed:\\n{}",
94            error_details
95        )));
96    }
97
98    // Construct the path to the built wasm file
99    let build_type = if args.release { "release" } else { "debug" };
100    let wasm_file_name = format!("{}.wasm", package_name.replace('-', "_"));
101    let wasm_path = project_dir
102        .join("target/wasm32-unknown-unknown")
103        .join(build_type)
104        .join(&wasm_file_name);
105
106    // Validate the wasm file exists
107    if !wasm_path.exists() {
108        return Err(CliError::build_failed(format!(
109            "Built WASM file not found at expected path: {}",
110            wasm_path.display()
111        )));
112    }
113
114    // Update the manifest.toml with the new component path if it exists
115    if manifest_exists {
116        let manifest_content = fs::read_to_string(&manifest_path).map_err(|e| {
117            CliError::file_operation_failed(
118                "read manifest.toml",
119                manifest_path.display().to_string(),
120                e,
121            )
122        })?;
123
124        let mut manifest: ManifestConfig = toml::from_str(&manifest_content).map_err(|e| {
125            CliError::invalid_manifest(format!("Failed to parse manifest.toml: {}", e))
126        })?;
127
128        // Update the package path - use absolute path to the wasm file
129        manifest.package = wasm_path.to_string_lossy().to_string();
130
131        // Write the updated manifest
132        let updated_manifest = toml::to_string(&manifest).map_err(|e| {
133            CliError::invalid_manifest(format!("Failed to serialize manifest.toml: {}", e))
134        })?;
135
136        fs::write(&manifest_path, updated_manifest).map_err(|e| {
137            CliError::file_operation_failed(
138                "write manifest.toml",
139                manifest_path.display().to_string(),
140                e,
141            )
142        })?;
143
144        info!(
145            "Updated manifest with component path: {}",
146            wasm_path.display()
147        );
148    }
149
150    // Create build result and output
151    let result = BuildResult {
152        success: true,
153        project_dir,
154        wasm_path: Some(wasm_path),
155        manifest_exists,
156        manifest_path: Some(manifest_path),
157        build_type: build_type.to_string(),
158        package_name,
159        stdout,
160        stderr,
161    };
162
163    ctx.output.output(&result, None)?;
164    Ok(())
165}
166
167/// Run a command and return the status, stdout, and stderr
168fn run_command_with_output(
169    cmd: &mut Command,
170    verbose: bool,
171) -> Result<(std::process::ExitStatus, String, String)> {
172    debug!("Running command: {:?}", cmd);
173    cmd.env("RUST_BACKTRACE", "1");
174    cmd.env("RUST_COLOR", "always");
175    cmd.env("CARGO_TERM_COLOR", "always");
176
177    if verbose {
178        // For verbose mode, we'll just let the command output directly to the console
179        // with all its colors, and then capture the output separately for the result
180        let status = cmd
181            .status()
182            .map_err(|e| anyhow!("Failed to execute command: {}", e))?;
183
184        // If we're in verbose mode and directly showing output, return empty strings for stdout/stderr
185        // since they were already displayed
186        Ok((status, String::new(), String::new()))
187    } else {
188        // For non-verbose mode, capture the output but preserve ANSI color codes
189        // Capture the output
190        let output = cmd
191            .output()
192            .map_err(|e| anyhow!("Failed to execute command: {}", e))?;
193
194        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
195        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
196
197        Ok((output.status, stdout, stderr))
198    }
199}
200
201/// Extract the package name from Cargo.toml
202fn get_package_name(cargo_toml_path: &Path) -> Result<String> {
203    let cargo_toml = std::fs::read_to_string(cargo_toml_path)?;
204
205    // Simple parse to extract package name
206    for line in cargo_toml.lines() {
207        let line = line.trim();
208        if line.starts_with("name") {
209            let parts: Vec<&str> = line.split('=').collect();
210            if parts.len() >= 2 {
211                let name = parts[1].trim().trim_matches('"').trim_matches('\'');
212                return Ok(name.to_string());
213            }
214        }
215    }
216
217    Err(anyhow!("Could not find package name in Cargo.toml"))
218}