This is an automated email from the ASF dual-hosted git repository.

ivila pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/teaclave-trustzone-sdk.git

commit 925a5d4b268c4e2e23255d108d111be7feb48752
Author: ivila <[email protected]>
AuthorDate: Tue Mar 3 11:31:11 2026 +0800

    cargo-optee: Standardizing Cargo command execution
    
    Signed-off-by: ivila <[email protected]>
---
 cargo-optee/src/ca_builder.rs | 16 +++++------
 cargo-optee/src/common.rs     |  6 ++--
 cargo-optee/src/main.rs       | 64 ++++++-------------------------------------
 cargo-optee/src/ta_builder.rs | 26 ++++++++++--------
 4 files changed, 34 insertions(+), 78 deletions(-)

diff --git a/cargo-optee/src/ca_builder.rs b/cargo-optee/src/ca_builder.rs
index ff643e6..4533320 100644
--- a/cargo-optee/src/ca_builder.rs
+++ b/cargo-optee/src/ca_builder.rs
@@ -15,10 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use anyhow::{bail, Result};
-use std::path::{Path, PathBuf};
-use std::process::Command;
-
+use crate::cargo_command;
 use crate::common;
 use crate::common::{
     get_package_name, get_target_and_cross_compile, 
get_target_directory_from_metadata,
@@ -27,6 +24,9 @@ use crate::common::{
 };
 use crate::config::CaBuildConfig;
 
+use anyhow::{bail, Result};
+use std::path::{Path, PathBuf};
+
 // Main function to build the CA, optionally installing to a target directory
 pub fn build_ca(config: CaBuildConfig, install_dir: Option<&Path>) -> 
Result<()> {
     // Change to the CA directory
@@ -98,7 +98,7 @@ fn run_clippy(config: &CaBuildConfig) -> Result<()> {
     println!("Running cargo fmt and clippy...");
 
     // Run cargo fmt
-    let fmt_output = Command::new("cargo").arg("fmt").output()?;
+    let fmt_output = cargo_command().arg("fmt").output()?;
 
     if !fmt_output.status.success() {
         print_output_and_bail("cargo fmt", &fmt_output)?;
@@ -107,7 +107,7 @@ fn run_clippy(config: &CaBuildConfig) -> Result<()> {
     // Determine target based on arch (CA runs in Normal World Linux)
     let (target, _cross_compile) = get_target_and_cross_compile(config.arch, 
BuildMode::Ca)?;
 
-    let mut clippy_cmd = Command::new("cargo");
+    let mut clippy_cmd = cargo_command();
     clippy_cmd.arg("clippy");
     clippy_cmd.arg("--target").arg(&target);
 
@@ -136,7 +136,7 @@ fn build_binary(config: &CaBuildConfig) -> Result<()> {
     // Determine target and cross-compile based on arch (CA runs in Normal 
World Linux)
     let (target, cross_compile) = get_target_and_cross_compile(config.arch, 
BuildMode::Ca)?;
 
-    let mut build_cmd = Command::new("cargo");
+    let mut build_cmd = cargo_command();
     build_cmd.arg("build");
     build_cmd.arg("--target").arg(&target);
 
@@ -244,7 +244,7 @@ fn strip_binary(config: &CaBuildConfig) -> Result<PathBuf> {
 
     let objcopy = format!("{}objcopy", cross_compile);
 
-    let strip_output = Command::new(&objcopy)
+    let strip_output = std::process::Command::new(&objcopy)
         .arg("--strip-unneeded")
         .arg(&binary_path)
         .arg(&binary_path) // Strip in place
diff --git a/cargo-optee/src/common.rs b/cargo-optee/src/common.rs
index 7c6b418..24a44cf 100644
--- a/cargo-optee/src/common.rs
+++ b/cargo-optee/src/common.rs
@@ -23,6 +23,8 @@ use std::path::PathBuf;
 use std::process::{Command, Output};
 use toml::Value;
 
+use crate::cargo_command;
+
 /// RAII guard to ensure we return to the original directory
 pub struct ChangeDirectoryGuard {
     original: PathBuf,
@@ -190,7 +192,7 @@ pub fn print_cargo_command(cmd: &Command, description: 
&str) {
 /// Get the target directory using cargo metadata
 pub fn get_target_directory_from_metadata() -> Result<PathBuf> {
     // We're already in the project directory, so no need for --manifest-path
-    let output = Command::new("cargo")
+    let output = cargo_command()
         .arg("metadata")
         .arg("--format-version")
         .arg("1")
@@ -269,7 +271,7 @@ pub fn join_format_and_check<P: AsRef<std::path::Path>>(
 pub fn clean_project(project_path: &std::path::Path) -> Result<()> {
     println!("Cleaning build artifacts in: {:?}", project_path);
 
-    let output = Command::new("cargo")
+    let output = cargo_command()
         .arg("clean")
         .current_dir(project_path)
         .output()?;
diff --git a/cargo-optee/src/main.rs b/cargo-optee/src/main.rs
index f84f60f..7ef79ca 100644
--- a/cargo-optee/src/main.rs
+++ b/cargo-optee/src/main.rs
@@ -29,12 +29,6 @@ mod ta_builder;
 use cli::{BuildCommand, Cli, Command, CommonBuildArgs, InstallCommand};
 
 fn main() {
-    // Setup cargo environment
-    if let Err(e) = setup_cargo_environment() {
-        eprintln!("Error: {}", e);
-        process::exit(1);
-    }
-
     // Drop extra `optee` argument provided by `cargo`.
     let mut found_optee = false;
     let filtered_args: Vec<String> = env::args()
@@ -227,54 +221,12 @@ fn resolve_project_path(manifest_path: Option<&PathBuf>) 
-> anyhow::Result<PathB
     }
 }
 
-/// Setup cargo environment by checking availability and adding to PATH if 
needed
-fn setup_cargo_environment() -> anyhow::Result<()> {
-    // Check if cargo is already available in PATH
-    let cargo_available = std::process::Command::new("which")
-        .arg("cargo")
-        .output()
-        .is_ok_and(|output| output.status.success());
-
-    if cargo_available {
-        return Ok(());
-    }
-
-    // Check if ~/.cargo/bin/cargo exists
-    let cargo_bin_dir = if let Ok(home) = env::var("HOME") {
-        let cargo_path = std::path::Path::new(&home)
-            .join(".cargo")
-            .join("bin")
-            .join("cargo");
-        if cargo_path.exists() {
-            cargo_path.parent().map(|p| p.to_path_buf())
-        } else {
-            None
-        }
-    } else {
-        None
-    };
-
-    // Or check $CARGO_HOME/bin/cargo
-    let cargo_bin_dir = cargo_bin_dir.or_else(|| {
-        env::var("CARGO_HOME").ok().and_then(|cargo_home| {
-            let cargo_path = 
std::path::Path::new(&cargo_home).join("bin").join("cargo");
-            if cargo_path.exists() {
-                cargo_path.parent().map(|p| p.to_path_buf())
-            } else {
-                None
-            }
-        })
-    });
-
-    // If found, add cargo bin directory to current process PATH
-    if let Some(cargo_bin_dir) = cargo_bin_dir {
-        let current_path = env::var("PATH").unwrap_or_default();
-        let separator = if cfg!(windows) { ";" } else { ":" };
-        let new_path = format!("{}{}{}", cargo_bin_dir.display(), separator, 
current_path);
-        env::set_var("PATH", new_path);
-        return Ok(());
-    }
-
-    // If not found, prompt user to install Cargo
-    anyhow::bail!("cargo command not found. Please install Rust: curl --proto 
'=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh");
+// Get Cargo Command.
+// As a Cargo plugin, this tool requires an existing Cargo installation.
+// It also follows standard Cargo conventions by prioritizing the `CARGO`
+// environment variable when invoking the binary.
+fn cargo_command() -> process::Command {
+    // 
https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-reads
+    const ENV_CARGO: &str = "CARGO";
+    process::Command::new(env::var_os(ENV_CARGO).unwrap_or_else(|| 
"cargo".into()))
 }
diff --git a/cargo-optee/src/ta_builder.rs b/cargo-optee/src/ta_builder.rs
index 46f76cd..6557de6 100644
--- a/cargo-optee/src/ta_builder.rs
+++ b/cargo-optee/src/ta_builder.rs
@@ -15,14 +15,8 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use crate::cargo_command;
 use crate::common;
-use anyhow::{bail, Result};
-use std::env;
-use std::fs;
-use std::path::{Path, PathBuf};
-use std::process::Command;
-use tempfile::TempDir;
-
 use crate::common::{
     get_package_name, get_target_and_cross_compile, 
get_target_directory_from_metadata,
     print_cargo_command, print_output_and_bail, read_uuid_from_file, BuildMode,
@@ -30,6 +24,13 @@ use crate::common::{
 };
 use crate::config::TaBuildConfig;
 
+use anyhow::{bail, Result};
+use std::env;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use tempfile::TempDir;
+
 // Embed the target JSON files at compile time
 const AARCH64_TARGET_JSON: &str = 
include_str!("../aarch64-unknown-optee.json");
 const ARM_TARGET_JSON: &str = include_str!("../arm-unknown-optee.json");
@@ -111,7 +112,7 @@ fn run_clippy(config: &TaBuildConfig) -> Result<()> {
     println!("Running cargo fmt and clippy...");
 
     // Run cargo fmt (we're already in the project directory via 
ChangeDirectoryGuard)
-    let fmt_output = Command::new("cargo").arg("fmt").output()?;
+    let fmt_output = cargo_command().arg("fmt").output()?;
 
     if !fmt_output.status.success() {
         print_output_and_bail("cargo fmt", &fmt_output)?;
@@ -318,9 +319,6 @@ fn setup_build_command(
     };
     let (target, _cross_compile) = get_target_and_cross_compile(config.arch, 
build_mode)?;
 
-    // Determine builder (cargo or xargo)
-    let builder = if config.std { "xargo" } else { "cargo" };
-
     // Setup custom targets if using std - keep TempDir alive
     let temp_dir = if config.std {
         Some(setup_custom_targets()?)
@@ -328,7 +326,11 @@ fn setup_build_command(
         None
     };
 
-    let mut cmd = Command::new(builder);
+    // Determine builder (cargo or xargo)
+    let mut cmd = match config.std {
+        true => Command::new("xargo"),
+        false => cargo_command(),
+    };
     cmd.arg(command);
     cmd.arg("--target").arg(&target);
 


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to