1use std::process::Command;
2use std::fs::File;
3
4use crate::{CmdRun, CmdSpawnError};
5
6pub 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 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 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 remove_file(&file_location).unwrap();
71 }
72}