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