cmd_utils/
cmd_to_file.rs

1use std::process::Command;
2use std::fs::File;
3
4use crate::{CmdRun, CmdSpawnError};
5
6/// `spawn`, `wait` and send the stdout of the command to a file
7///
8/// # Errors
9///
10/// command_to_file can result in `CmdSpawnError`:
11/// - `CmdSpawnError::IO(std::io::Error)` when `spawn` or `wait` fail
12/// - `CmdSpawnError::Child(ChildError)` when the child process exit with a failed status
13pub fn command_to_file (
14    command: &mut Command,
15    file: File,
16    stderr_file: Option<File>
17) -> Result<(), CmdSpawnError> {
18    if let Some(f) = stderr_file {
19        command.stderr(f);
20    }
21    command.stdout(file).run()
22}
23
24pub trait CmdToFile {
25    /// `spawn`, `wait` and **stdout** to `file` for the child process,
26    /// optional **stderr** to `stderr_file`
27    ///
28    /// # Errors
29    ///
30    /// command.to_file(file, err_file) can result in `CmdSpawnError`:
31    /// - `CmdSpawnError::IO(std::io::Error)` when `spawn` or `wait` fail
32    /// - `CmdSpawnError::Child(ChildError)` when the child process exit with a failed status
33    fn to_file(&mut self, file: File, stderr_file: Option<File>) -> Result<(), CmdSpawnError>;
34}
35
36impl CmdToFile for Command {
37    fn to_file(&mut self, file: File, stderr_file: Option<File>) -> Result<(), CmdSpawnError> {
38        command_to_file(self, file, stderr_file)
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::CmdToFile;
45    use std::{fs::{File, remove_file}, io::Read};
46    use std::process::Command;
47
48    #[test]
49    fn to_file() {
50        let file_location = ".to_file_test";
51        let file_content = "file-content-test";
52        let file = File::create(&file_location).unwrap();
53        let mut cmd = Command::new("echo");
54        match cmd.arg(&file_content).to_file(file, None) {
55            Ok(_) => (),
56            Err(e) => panic!("{}", e),
57        };
58
59        // read file
60        let mut file = File::open(&file_location).unwrap();
61        let mut res = String::new();
62        match file.read_to_string(&mut res) {
63            Ok(_) => (),
64            Err(e) => panic!("{}", e),
65        };
66
67        assert_eq!(res, file_content.to_owned() + "\n");
68
69        // cleanup file
70        remove_file(&file_location).unwrap();
71    }
72}