cs_trace/writers/
file_writer.rs

1use std::str;
2use std::path::Path;
3use std::io::{self, Write};
4use std::fs::{self, OpenOptions, File};
5use strip_ansi_escapes::strip;
6
7pub struct FileWriter {
8    file_handle: File,
9}
10
11impl FileWriter {
12    pub fn new<T: AsRef<str> + ToString>(
13        file_path: T,
14        cleanup_file: bool,
15    ) -> Box<dyn Write + Send + Sync> {
16        let file_path = file_path.to_string();
17
18        let path = Path::new(&file_path);
19        let prefix = path.parent()
20            .expect(
21                &format!("Cannot get parent folder of [{}]", &file_path)
22            );
23
24        let parent_path_string = prefix.to_str().expect(
25            &format!("Cannot convert parent path [{:?}] to string.", prefix)
26        );
27
28        fs::create_dir_all(&parent_path_string)
29            .expect(
30                &format!("Cannot create folder at [{}]", &parent_path_string)
31            );
32
33        let file_handle = OpenOptions::new()
34            .create(true)
35            .write(true)
36            .truncate(cleanup_file)
37            .append(!cleanup_file)
38            .open(&file_path)
39            .expect(
40                &format!("Cannot open file at [{}].", &file_path),
41            );
42
43        return Box::new(FileWriter { file_handle });
44    }
45}
46
47impl Write for FileWriter
48 {
49    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
50        let no_ansi_color_buf = strip(buf)
51            .expect("Failed to stip the ANSI escape sequences.");
52
53        // write the contents
54        self.file_handle.write(&no_ansi_color_buf)
55            .expect("Cannot write to the file.");
56
57        return Ok(no_ansi_color_buf.len());
58    }
59
60    fn flush(&mut self) -> io::Result<()> {
61        self.file_handle.flush()
62            .expect("Failed to flush into the file.");
63
64        return Ok(());
65    }
66}