use std::ffi::{OsStr, OsString};
use crate::args::ToArgs;
#[derive(Debug)]
pub struct Command {
pub command: OsString,
pub args: Vec<OsString>,
}
impl Command {
pub fn new<S: AsRef<OsStr>>(command: S) -> Command {
Command {
command: command.as_ref().to_owned(),
args: vec![],
}
}
pub fn from_ordered_vec(list: Vec<String>) -> Option<Command> {
list.split_first().map(|(executable, args)| Command {
command: OsString::from(executable),
args: args.iter().map(|arg| arg.into()).collect(),
})
}
pub fn with_args<A>(mut self, args: A) -> Command
where
A: IntoIterator,
A::Item: Into<OsString>,
{
self.args = args.into_iter().map(|arg| arg.into()).collect();
self
}
}
impl ToArgs for Command {
fn to_args(&self) -> Vec<OsString> {
let mut result: Vec<OsString> = vec![self.command.clone()];
result.extend(self.args.iter().cloned());
result
}
}
#[test]
fn command_to_args_converts_to_arguments() {
assert_eq!(Command::new("foo").to_args(), vec![OsStr::new("foo")]);
assert_eq!(
Command::new("foo").with_args(&["--opt"]).to_args(),
vec![OsStr::new("foo"), OsStr::new("--opt")]
);
}