1extern crate toml;
6
7use error::{YabsError, YabsErrorKind};
8use std::env;
9use std::fs::File;
10use std::io::Read;
11use std::path::{Path, PathBuf};
12use std::process::{Child, Command};
13
14pub struct Job {
15 process: Child,
16 command: String,
17}
18
19impl Job {
20 pub fn new(raw: (String, Child)) -> Job {
21 Job {
22 command: raw.0,
23 process: raw.1,
24 }
25 }
26
27 pub fn command(&self) -> String {
28 self.command.clone()
29 }
30
31 pub fn yield_self(&mut self) -> Result<(), YabsError> {
32 let status = self.process.wait()?;
33 if !status.success() {
34 if let Some(ref mut stderr) = self.process.stderr {
35 let mut buffer = String::new();
36 stderr.read_to_string(&mut buffer)?;
37 info!("{}", buffer);
38 }
39 bail!(YabsErrorKind::Command(self.command(), status.code().unwrap_or(1)));
40 }
41 Ok(())
42 }
43}
44
45pub fn parse_toml_file<T: AsRef<Path> + Clone>(file: T) -> Result<String, YabsError> {
46 let mut buff = String::new();
47 let mut file = File::open(&file)?;
48 file.read_to_string(&mut buff)?;
49 Ok(buff)
50}
51
52pub fn get_assumed_filename() -> Option<String> {
53 if let Ok(current_dir) = env::current_dir() {
54 if let Some(file_stem) = current_dir.file_stem() {
55 let mut file_name = file_stem.to_string_lossy().into_owned();
56 file_name.push_str(".toml");
57 return Some(file_name);
58 }
59 }
60 None
61}
62
63pub fn get_assumed_filename_for_dir(dir: &PathBuf) -> Option<PathBuf> {
64 if let Some(file_stem) = dir.file_stem() {
65 return Some(PathBuf::from(file_stem.to_string_lossy().into_owned() + ".toml"));
66 }
67 None
68}
69
70pub fn run_cmd(cmd: &str) -> Result<(), YabsError> {
71 let command = Command::new("sh").arg("-c").arg(&cmd).spawn()?.wait_with_output()?;
72 println!("{}", &cmd);
73 if !command.status.success() {
74 print!("{}", String::from_utf8(command.stderr)?);
75 bail!(YabsErrorKind::Command(cmd.to_owned(), command.status.code().unwrap_or(1)));
76 }
77 print!("{}", String::from_utf8(command.stdout)?);
78 Ok(())
79}
80
81pub fn spawn_cmd(cmd: &str) -> Result<Child, YabsError> {
82 Ok(Command::new("sh").arg("-c").arg(&cmd).spawn()?)
83}
84
85pub trait PrependEach<T> {
86 fn prepend_each(&self, pre: &str) -> Vec<String>;
87}
88
89impl PrependEach<String> for Vec<String> {
91 fn prepend_each(&self, pre: &str) -> Vec<String> {
92 let mut clone = self.clone();
93 for each in &mut clone {
94 *each = pre.to_owned() + each;
95 }
96 clone
97 }
98}