aboutsummaryrefslogtreecommitdiffstats
path: root/src/scratch.rs
blob: 8d469c350a5d7e8519a4f502a06bcd22a637a8a3 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//! Scratch directories, removed when dropped.

use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

#[derive(Debug)]
pub struct Scratch {
    path: PathBuf,
    keep: bool,
}

impl Scratch {
    /// A new directory below `parent`, readable by its owner only.
    pub fn new(parent: &Path, prefix: &str) -> Result<Self> {
        use std::os::unix::fs::DirBuilderExt;
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
        let path = parent.join(format!("{prefix}{}", crate::new_id()?));
        std::fs::DirBuilder::new()
            .mode(0o700)
            .create(&path)
            .with_context(|| format!("creating {}", path.display()))?;
        Ok(Self { path, keep: false })
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Its path, no longer removed when dropped: it has been moved, or is kept.
    pub fn keep(mut self) -> PathBuf {
        self.keep = true;
        self.path.clone()
    }

    /// Gives the files below it `mode`, and the directories (it too) the mode to reach
    /// them: `0o400` makes it read-only, `0o644` readable by all.
    pub fn set_modes(&self, mode: u32) -> Result<()> {
        set_modes(&self.path, mode)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        if !self.keep {
            // A read-only directory's entries can't be removed: writable first.
            let _ = set_modes(&self.path, 0o600);
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }
}

/// Files below `dir` get `mode`, directories (`dir` too) the mode to reach them, set
/// on the way down so each can still be entered.
pub fn set_modes(dir: &Path, mode: u32) -> Result<()> {
    let directory = crate::content::directory_mode(mode) | 0o100;
    let reach = std::fs::Permissions::from_mode(directory | 0o700);
    std::fs::set_permissions(dir, reach).with_context(|| format!("chmod {}", dir.display()))?;
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let kind = entry.file_type()?;
        if kind.is_symlink() {
            // A link's own mode means nothing, and following it would change its target.
            continue;
        } else if kind.is_dir() {
            set_modes(&entry.path(), mode)?;
        } else {
            std::fs::set_permissions(entry.path(), std::fs::Permissions::from_mode(mode))?;
        }
    }
    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(directory))?;
    Ok(())
}