//! A project folder: the save format described in docs/STORAGE.md. //! //! A project is a directory with a `blobs/` subdirectory for content-addressed //! files and small RON documents at its root. Text files are written through a //! temporary file and renamed into place, so an interrupted save cannot leave a //! half-written document behind. use std::fs; use std::io; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use crate::blob::BlobStore; /// Subdirectory holding the blobs. const BLOB_DIRECTORY: &str = "blobs"; /// Distinguishes temporary files written by concurrent saves in one process. static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0); /// An existing project directory. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Project { root: PathBuf, } impl Project { /// Creates the directory, its parents and the blob store. pub fn create(root: impl Into) -> io::Result { let root = root.into(); fs::create_dir_all(&root)?; fs::create_dir_all(root.join(BLOB_DIRECTORY))?; Ok(Self { root }) } /// Opens an existing directory; a missing path is [`io::ErrorKind::NotFound`]. pub fn open(root: impl Into) -> io::Result { let root = root.into(); if root.is_dir() { Ok(Self { root }) } else { Err(io::Error::new( io::ErrorKind::NotFound, format!("project directory {} does not exist", root.display()), )) } } /// The project directory. #[must_use] pub fn root(&self) -> &Path { &self.root } /// The blob store under `root/blobs`. #[must_use] pub fn blobs(&self) -> BlobStore { BlobStore::new(self.root.join(BLOB_DIRECTORY)) } /// A file path inside the project; the file need not exist. #[must_use] pub fn path(&self, name: &str) -> PathBuf { self.root.join(name) } /// Writes a text document atomically. pub fn write_text(&self, name: &str, text: &str) -> io::Result<()> { write_atomic(&self.path(name), text) } /// Reads a text document written with [`Self::write_text`]. pub fn read_text(&self, name: &str) -> io::Result { fs::read_to_string(self.path(name)) } } /// Writes through a temporary file in the same directory, then renames. fn write_atomic(path: &Path, text: &str) -> io::Result<()> { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } let temp = temp_path(path); fs::write(&temp, text)?; if let Err(error) = fs::rename(&temp, path) { let _ = fs::remove_file(&temp); return Err(error); } Ok(()) } /// A temporary sibling of `path` that cannot collide with the target name. fn temp_path(path: &Path) -> PathBuf { let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed); let pid = std::process::id(); let name = path .file_name() .and_then(|name| name.to_str()) .unwrap_or("file"); path.with_file_name(format!(".{name}.{pid}-{counter}.tmp")) } #[cfg(test)] mod tests;