Skip to main content

dots/
analysis.rs

1//! Contains [`Analysis`]
2
3use std::path::PathBuf;
4use std::{fs, io};
5
6use simply_colored::*;
7
8use crate::PathExt as _;
9
10/// Write contents to the path
11#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct WritePath {
13    /// Path to write
14    pub path: PathBuf,
15    /// What to write
16    pub contents: String,
17}
18
19/// Analysis represents finished computation
20#[derive(Debug)]
21pub struct Analysis {
22    /// A list of paths to write
23    pub writes: Vec<WritePath>,
24}
25
26impl Analysis {
27    /// Finish the analysis
28    pub fn finish(self) {
29        for WritePath { path, contents } in self.writes {
30            let contents = contents.to_string();
31
32            if let Err(err) = match fs::remove_file(&path) {
33                Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
34                Err(err) => Err(err),
35                Ok(()) => Ok(()),
36            } {
37                log::error!("failed to remove file {}: {err}", path.show());
38                continue;
39            }
40
41            log::warn!("{RED}removed{RESET} {}", path.show());
42
43            let Some(dir) = path.parent() else {
44                log::error!("failed to obtain parent of {}", path.show());
45                continue;
46            };
47
48            // 2. Create parent directory which will contain the file downloaded from the link
49            if let Err(err) = fs::create_dir_all(dir) {
50                log::error!("failed to create directory for {}: {err}", dir.show());
51            }
52
53            if let Err(err) = fs::write(&path, contents) {
54                log::error!("failed to write to {}: {err}", path.show());
55            }
56
57            log::info!("wrote to {}", path.show());
58        }
59    }
60}