aboutsummaryrefslogtreecommitdiffstats
path: root/src/scratch.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/scratch.rs')
-rw-r--r--src/scratch.rs74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/scratch.rs b/src/scratch.rs
new file mode 100644
index 0000000..dddd91b
--- /dev/null
+++ b/src/scratch.rs
@@ -0,0 +1,74 @@
+//! 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?;
+ if entry.file_type()?.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(())
+}