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

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

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

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