Skip to content

Commit

Permalink
refactor: direct_or_shell_command (#3924)
Browse files Browse the repository at this point in the history
  • Loading branch information
ericswanson-dfinity authored Sep 24, 2024
1 parent 69940b2 commit d15c4f2
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 15 deletions.
18 changes: 3 additions & 15 deletions src/dfx/src/lib/builders/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)]
Expand Down Expand Up @@ -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())
Expand Down
21 changes: 21 additions & 0 deletions src/dfx/src/util/command.rs
Original file line number Diff line number Diff line change
@@ -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<Command> {
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)
}
1 change: 1 addition & 0 deletions src/dfx/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit d15c4f2

Please sign in to comment.