use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::error::{Error, MemoryError};
use super::grammar::validate_document_path;
pub const DOCUMENTS: &str = "documents";
pub const VERSIONS: &str = "versions";
pub const REDACTIONS: &str = "redactions.jsonl";
pub fn scope_dir(root: &Path, scope: &str) -> PathBuf {
scope.split('/').fold(root.to_path_buf(), |dir, segment| {
dir.join(segment.replace(':', "%3A"))
})
}
pub fn doc_file(root: &Path, scope: &str, path: &str) -> Result<PathBuf, Error> {
contained(
root,
scope_dir(root, scope)
.join(DOCUMENTS)
.join(format!("{path}.md")),
path,
)
}
pub fn journal_file(root: &Path, scope: &str, path: &str) -> Result<PathBuf, Error> {
contained(
root,
scope_dir(root, scope)
.join(VERSIONS)
.join(format!("{path}.jsonl")),
path,
)
}
fn contained(root: &Path, candidate: PathBuf, path: &str) -> Result<PathBuf, Error> {
let mut existing = candidate.as_path();
while !existing.exists() {
existing = existing.parent().unwrap_or(root);
}
let below = candidate.strip_prefix(existing).unwrap_or(&candidate);
if existing.canonicalize()?.join(below).starts_with(root) {
Ok(candidate)
} else {
Err(MemoryError::path_invalid(path, "escapes the store root").into())
}
}
pub fn case_collision(root: &Path, scope: &str) -> io::Result<bool> {
let mut parent = root.to_path_buf();
for segment in scope.split('/') {
let component = segment.replace(':', "%3A");
if !parent.join(&component).exists() {
return Ok(false);
}
let mut spelled = false;
for entry in fs::read_dir(&parent)? {
spelled |= entry?.file_name() == component.as_str();
}
if !spelled {
return Ok(true);
}
parent.push(component);
}
Ok(false)
}
pub fn logical_paths(dir: &Path, suffix: &str) -> io::Result<Vec<String>> {
fn walk(dir: &Path, prefix: &str, suffix: &str, found: &mut Vec<String>) -> io::Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let Ok(name) = entry.file_name().into_string() else {
continue;
};
if entry.file_type()?.is_dir() {
walk(&entry.path(), &format!("{prefix}{name}/"), suffix, found)?;
} else if let Some(stem) = name.strip_suffix(suffix) {
let logical = format!("{prefix}{stem}");
if validate_document_path(&logical).is_ok() {
found.push(logical);
}
}
}
Ok(())
}
let mut found = Vec::new();
if dir.is_dir() {
walk(dir, "", suffix, &mut found)?;
}
found.sort();
Ok(found)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_scope_is_one_directory_per_segment() {
assert_eq!(
scope_dir(Path::new("/r"), "user:me/proj:x"),
Path::new("/r").join("user%3Ame").join("proj%3Ax")
);
}
}