From d15c4f2c6e98e470e1784fc7c2dbed5b0bf8391d Mon Sep 17 00:00:00 2001 From: Eric Swanson <64809312+ericswanson-dfinity@users.noreply.github.com> Date: Tue, 24 Sep 2024 15:31:31 -0600 Subject: [PATCH] refactor: direct_or_shell_command (#3924) --- src/dfx/src/lib/builders/mod.rs | 18 +++--------------- src/dfx/src/util/command.rs | 21 +++++++++++++++++++++ src/dfx/src/util/mod.rs | 1 + 3 files changed, 25 insertions(+), 15 deletions(-) create mode 100644 src/dfx/src/util/command.rs diff --git a/src/dfx/src/lib/builders/mod.rs b/src/dfx/src/lib/builders/mod.rs index 3e9ae991ed..2ba74ec65f 100644 --- a/src/dfx/src/lib/builders/mod.rs +++ b/src/dfx/src/lib/builders/mod.rs @@ -18,7 +18,7 @@ use std::fmt::Write; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::process::Stdio; use std::sync::Arc; mod assets; @@ -27,6 +27,7 @@ mod motoko; mod pull; mod rust; +use crate::util::command::direct_or_shell_command; pub use custom::custom_download; #[derive(Debug)] @@ -336,20 +337,7 @@ pub fn execute_command( if command.is_empty() { return Ok(vec![]); } - let words = shell_words::split(command) - .with_context(|| format!("Cannot parse command '{}'.", command))?; - let canonical_result = dfx_core::fs::canonicalize(&cwd.join(&words[0])); - let mut cmd = if words.len() == 1 && canonical_result.is_ok() { - // If the command is a file, execute it directly. - let file = canonical_result.unwrap(); - Command::new(file) - } else { - // Execute the command in `sh -c` to allow pipes. - let mut sh_cmd = Command::new("sh"); - sh_cmd.args(["-c", command]); - sh_cmd - }; - cmd.current_dir(cwd); + let mut cmd = direct_or_shell_command(command, cwd)?; if !catch_output { cmd.stdin(Stdio::inherit()) diff --git a/src/dfx/src/util/command.rs b/src/dfx/src/util/command.rs new file mode 100644 index 0000000000..dabcdf61cb --- /dev/null +++ b/src/dfx/src/util/command.rs @@ -0,0 +1,21 @@ +use crate::lib::error::DfxResult; +use anyhow::Context; +use std::path::Path; +use std::process::Command; + +pub fn direct_or_shell_command(s: &str, cwd: &Path) -> DfxResult { + let words = shell_words::split(s).with_context(|| format!("Cannot parse command '{}'.", s))?; + let canonical_result = dfx_core::fs::canonicalize(&cwd.join(&words[0])); + let mut cmd = if words.len() == 1 && canonical_result.is_ok() { + // If the command is a file, execute it directly. + let file = canonical_result.unwrap(); + Command::new(file) + } else { + // Execute the command in `sh -c` to allow pipes. + let mut sh_cmd = Command::new("sh"); + sh_cmd.args(["-c", s]); + sh_cmd + }; + cmd.current_dir(cwd); + Ok(cmd) +} diff --git a/src/dfx/src/util/mod.rs b/src/dfx/src/util/mod.rs index c7543e0ad4..073c4c5e14 100644 --- a/src/dfx/src/util/mod.rs +++ b/src/dfx/src/util/mod.rs @@ -24,6 +24,7 @@ use std::time::Duration; pub mod assets; pub mod clap; +pub mod command; pub mod currency_conversion; pub mod stderr_wrapper; pub mod url;