1
//! Removing generated output that a phase is about to recreate.
2
//!
3
//! A leftover tree is worse than a failed removal: it silently joins the next
4
//! report or artifact. So only "not found" is ignored.
5

            
6
use std::io::{self, ErrorKind};
7
use std::path::Path;
8

            
9
use anyhow::{Context, Result};
10

            
11
8
pub fn remove_dir_if_present(path: &Path) -> Result<()> {
12
8
    ignore_not_found(std::fs::remove_dir_all(path))
13
8
        .with_context(|| format!("cannot remove {}", path.display()))
14
8
}
15

            
16
3
pub fn remove_file_if_present(path: &Path) -> Result<()> {
17
3
    ignore_not_found(std::fs::remove_file(path))
18
3
        .with_context(|| format!("cannot remove {}", path.display()))
19
3
}
20

            
21
14
fn ignore_not_found(result: io::Result<()>) -> io::Result<()> {
22
9
    match result {
23
9
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(()),
24
8
        other => other,
25
    }
26
14
}
27

            
28
#[cfg(test)]
29
mod tests;