summaryrefslogtreecommitdiff
path: root/ofborg/tickborg/src/test_scratch.rs
blob: d63632ecd0cf71a32bb7ab584d1845aaa706b1d9 (plain)
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use tracing::debug;

pub struct TestScratch {
    root: PathBuf,
}

impl TestScratch {
    pub fn new_dir(ident: &str) -> TestScratch {
        let scratch = TestScratch {
            root: Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("test-scratch")
                .join("dirs")
                .join(format!("dir-{ident}")),
        };

        TestScratch::create_dir(&scratch);

        scratch
    }

    pub fn new_file(ident: &str) -> TestScratch {
        let scratch = TestScratch {
            root: Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("test-scratch")
                .join("files")
                .join(format!("file-{ident}")),
        };

        TestScratch::create_dir(&scratch);
        scratch
    }

    fn create_dir(path: &TestScratch) {
        let target = path.root.parent().unwrap();
        debug!("Creating directory {target:?}");
        fs::create_dir_all(target).unwrap();
    }

    pub fn path(&self) -> PathBuf {
        self.root.clone()
    }

    pub fn string(&self) -> String {
        self.path().to_str().unwrap().to_owned()
    }
}

impl Drop for TestScratch {
    fn drop(&mut self) {
        debug!("Deleting root {:?}", self.root);
        Command::new("rm")
            .arg("-rf")
            .arg(self.root.clone())
            .status()
            .expect("cleanup of test-scratch should work");
    }
}