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
use std::str;
use std::path::Path;
use std::io::{self, Write};
use std::fs::{self, OpenOptions, File};
use strip_ansi_escapes::strip;

pub struct FileWriter {
    file_handle: File,
}

impl FileWriter {
    pub fn new<T: AsRef<str> + ToString>(
        file_path: T,
    ) -> Box<dyn Write> {
        let file_path = file_path.to_string();

        let path = Path::new(&file_path);
        let prefix = path.parent()
            .expect(
                &format!("Cannot get parent folder of [{}]", &file_path)
            );

        let parent_path_string = prefix.to_str().expect(
            &format!("Cannot convert parent path [{:?}] to string.", prefix)
        );

        fs::create_dir_all(&parent_path_string)
            .expect(
                &format!("Cannot create folder at [{}]", &parent_path_string)
            );

        let file_handle = OpenOptions::new()
            .create(true)
            .write(true)
            .append(true)
            .open(&file_path)
            .expect(
                &format!("Cannot open file at [{}].", &file_path),
            );

        return Box::new(FileWriter { file_handle });
    }
}

impl Write for FileWriter
 {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let no_ansi_color_buf = strip(buf)
            .expect("Failed to stip the ANSI escape sequences.");

        // write the contents
        self.file_handle.write(&no_ansi_color_buf)
            .expect("Cannot write to the file.");

        return Ok(no_ansi_color_buf.len());
    }

    fn flush(&mut self) -> io::Result<()> {
        self.file_handle.flush()
            .expect("Failed to flush into the file.");

        return Ok(());
    }
}