use std::path::{Path, PathBuf};
mod io;
mod test_helpers;
#[derive(Debug, Clone)]
struct MemoryFile {
content: Vec<u8>,
modified: std::time::SystemTime,
}
impl MemoryFile {
fn new(content: Vec<u8>) -> Self {
Self {
content,
modified: std::time::SystemTime::now(),
}
}
const fn with_modified(content: Vec<u8>, modified: std::time::SystemTime) -> Self {
Self { content, modified }
}
}
#[derive(Debug)]
pub struct MemoryWorkspace {
root: PathBuf,
files: std::sync::RwLock<std::collections::HashMap<PathBuf, MemoryFile>>,
directories: std::sync::RwLock<std::collections::HashSet<PathBuf>>,
}
impl MemoryWorkspace {
#[must_use]
pub fn new(root: PathBuf) -> Self {
Self {
root,
files: std::sync::RwLock::new(std::collections::HashMap::new()),
directories: std::sync::RwLock::new(std::collections::HashSet::new()),
}
}
#[must_use]
pub fn new_test() -> Self {
Self::new(PathBuf::from("/test/repo"))
}
fn ensure_parent_dirs(&self, path: &Path) {
if let Some(parent) = path.parent() {
if parent.as_os_str().is_empty() {
return;
}
let dirs_to_create: Vec<PathBuf> = parent
.components()
.scan(PathBuf::new(), |state, component| {
state.push(component);
Some(state.clone())
})
.collect();
self.directories.write()
.expect("RwLock poisoned - indicates panic in another thread holding MemoryWorkspace directories lock")
.extend(dirs_to_create);
}
}
fn ensure_dir_path(&self, path: &Path) {
let dirs_to_create: Vec<PathBuf> = path
.components()
.scan(PathBuf::new(), |state, component| {
state.push(component);
Some(state.clone())
})
.collect();
self.directories.write()
.expect("RwLock poisoned - indicates panic in another thread holding MemoryWorkspace directories lock")
.extend(dirs_to_create);
}
}
impl Clone for MemoryWorkspace {
fn clone(&self) -> Self {
Self {
root: self.root.clone(),
files: std::sync::RwLock::new(self.files.read()
.expect("RwLock poisoned - indicates panic in another thread holding MemoryWorkspace files lock")
.clone()),
directories: std::sync::RwLock::new(self.directories.read()
.expect("RwLock poisoned - indicates panic in another thread holding MemoryWorkspace directories lock")
.clone()),
}
}
}