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,
)
}
pub fn contained(root: &Path, candidate: PathBuf, path: &str) -> Result<PathBuf, Error> {
if super::fileio::within(root, &candidate)? {
Ok(candidate)
} else {
Err(MemoryError::path_invalid(path, "escapes the store root").into())
}
}
pub fn trail_file(root: &Path, scope: &str) -> Result<PathBuf, Error> {
contained(root, scope_dir(root, scope).join(REDACTIONS), REDACTIONS)
}
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 visit_paths(dir: &Path, suffix: &str, visit: &mut impl FnMut(String)) -> io::Result<()> {
fn walk(
dir: &Path,
prefix: &str,
suffix: &str,
visit: &mut impl FnMut(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, visit)?;
} else if let Some(stem) = name.strip_suffix(suffix) {
let logical = format!("{prefix}{stem}");
if validate_document_path(&logical).is_ok() {
visit(logical);
}
}
}
Ok(())
}
if dir.is_dir() {
walk(dir, "", suffix, visit)?;
}
Ok(())
}
pub fn logical_paths(dir: &Path, suffix: &str) -> io::Result<Vec<String>> {
let mut found = Vec::new();
visit_paths(dir, suffix, &mut |p| found.push(p))?;
found.sort();
Ok(found)
}
pub fn path_page(
dir: &Path,
suffix: &str,
prefix: &str,
after: &str,
limit: usize,
) -> io::Result<Vec<String>> {
let mut selected = std::collections::BTreeSet::new();
visit_paths(dir, suffix, &mut |path| {
if path.as_str() > after && path.starts_with(prefix) {
selected.insert(path);
if selected.len() > limit {
selected.pop_last();
}
}
})?;
Ok(selected.into_iter().collect())
}
#[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")
);
}
}