Skip to content

Commit

Permalink
create SafeCommand type to not depend on Debug behavior of stdlib Com…
Browse files Browse the repository at this point in the history
…mand
  • Loading branch information
iostat committed Dec 9, 2019
1 parent 8abf051 commit 3899c2b
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 3 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ rustc_version = "0.2"
semver = "0.9"
toml = "0.5"
which = { version = "3.1.0", default_features = false }
shell-escape = "0.1.4"

[target.'cfg(not(windows))'.dependencies]
nix = "0.15"
Expand Down
6 changes: 3 additions & 3 deletions src/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use error_chain::bail;
use crate::{Target, Toml};
use crate::cargo::Root;
use crate::errors::*;
use crate::extensions::CommandExt;
use crate::extensions::{CommandExt, SafeCommand};
use crate::id;

const DOCKER_IMAGES: &[&str] = &include!(concat!(env!("OUT_DIR"), "/docker-images.rs"));
Expand Down Expand Up @@ -72,9 +72,9 @@ pub fn run(target: &Target,
fs::create_dir(&xargo_dir).ok();

let mut cmd = if uses_xargo {
Command::new("xargo")
SafeCommand::new("xargo")
} else {
Command::new("cargo")
SafeCommand::new("cargo")
};
cmd.args(args);

Expand Down
55 changes: 55 additions & 0 deletions src/extensions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::borrow::Cow;
use std::process::{Command, ExitStatus};
use std::fmt;

use crate::errors::*;

Expand Down Expand Up @@ -50,3 +52,56 @@ impl CommandExt for Command {
.chain_err(|| format!("`{:?}` output was not UTF-8", self))?)
}
}

pub struct SafeCommand {
program: String,
args: Vec<String>,
}

impl SafeCommand {
pub fn new<S: ToString>(program: S) -> Self {
let program = program.to_string();
SafeCommand {
program,
args: Vec::new(),
}
}

pub fn arg<'b, S>(&mut self, arg: &S) -> &mut Self
where
S: ToString,
{
self.args.push(arg.to_string());
self
}

pub fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: ToString,
{
for arg in args {
self.arg(&arg);
}
self
}
}

impl fmt::Debug for SafeCommand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&shell_escape::escape(Cow::from(&self.program)))?;
for arg in &self.args {
f.write_str(" ")?;
f.write_str(&shell_escape::escape(Cow::from(arg)))?;
}
Ok(())
}
}

impl From<SafeCommand> for Command {
fn from(s: SafeCommand) -> Self {
let mut cmd = Command::new(&s.program);
cmd.args(&s.args);
cmd
}
}

0 comments on commit 3899c2b

Please sign in to comment.