use std::{cell::RefCell, collections::HashMap};
use crate::{RepoPath, RepoRoot, Stat};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKind {
Manifest,
Index,
Schema,
Document,
Candidate,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalkedFile {
pub path: RepoPath,
pub root: Option<usize>,
pub kind: FileKind,
pub stat: Stat,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalkedDir {
pub path: RepoPath,
pub root: usize,
}
#[derive(Debug)]
pub struct Tree {
pub root: RepoRoot,
pub roots: Vec<RepoPath>,
pub files: Vec<WalkedFile>,
pub dirs: Vec<WalkedDir>,
pub registered_count: usize,
on_disk: RefCell<HashMap<RepoPath, OnDisk>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OnDisk {
Nothing,
File,
Dir,
}
impl OnDisk {
pub fn at(path: &std::path::Path) -> OnDisk {
match std::fs::metadata(path) {
Ok(m) if m.is_dir() => OnDisk::Dir,
Ok(_) => OnDisk::File,
Err(_) => OnDisk::Nothing,
}
}
pub fn code(self) -> i64 {
match self {
OnDisk::Nothing => 0,
OnDisk::File => 1,
OnDisk::Dir => 2,
}
}
}
impl Tree {
pub fn new(
root: RepoRoot,
roots: Vec<RepoPath>,
mut files: Vec<WalkedFile>,
mut dirs: Vec<WalkedDir>,
) -> Self {
files.sort_by(|a, b| a.path.cmp(&b.path));
dirs.sort_by(|a, b| a.path.cmp(&b.path));
Tree {
root,
roots,
files,
dirs,
registered_count: 0,
on_disk: RefCell::new(HashMap::new()),
}
}
pub fn exists(&self, path: &RepoPath) -> bool {
self.on_disk(path) != OnDisk::Nothing
}
pub fn is_dir(&self, path: &RepoPath) -> bool {
self.on_disk(path) == OnDisk::Dir
}
pub fn on_disk(&self, path: &RepoPath) -> OnDisk {
if let Some(&known) = self.on_disk.borrow().get(path) {
return known;
}
let known = OnDisk::at(&path.to_fs(&self.root));
self.on_disk.borrow_mut().insert(path.clone(), known);
known
}
pub fn file(&self, path: &RepoPath) -> Option<&WalkedFile> {
self.files
.binary_search_by(|f| f.path.cmp(path))
.ok()
.map(|i| &self.files[i])
}
pub fn classify(path: &RepoPath, roots: &[RepoPath]) -> (Option<usize>, FileKind) {
let Some(root_index) = innermost(roots, path) else {
return (None, FileKind::Candidate);
};
let root = &roots[root_index];
let name = path.file_name();
let parent = path.parent();
let kind = if name == "manifest.sokf.yaml" && parent.as_ref() == Some(root) {
FileKind::Manifest
} else if !crate::markdown::is_markdown(path) {
FileKind::Candidate
} else if name == "index.md" {
FileKind::Index
} else if parent == root.join("schemas") {
FileKind::Schema
} else {
FileKind::Document
};
(Some(root_index), kind)
}
}
pub fn innermost<'a>(
roots: impl IntoIterator<Item = &'a RepoPath>,
path: &RepoPath,
) -> Option<usize> {
roots
.into_iter()
.enumerate()
.filter(|(_, r)| path.starts_with(r))
.max_by_key(|(_, r)| r.as_str().len())
.map(|(i, _)| i)
}
#[cfg(test)]
mod tests {
use super::*;
fn p(s: &str) -> RepoPath {
RepoPath::parse(s).unwrap()
}
#[test]
fn the_innermost_root_owns_a_nested_path() {
let roots = vec![p("/knowledge"), p("/knowledge/inner"), p("/docs")];
assert_eq!(innermost(&roots, &p("/knowledge/a.md")), Some(0));
assert_eq!(innermost(&roots, &p("/knowledge/inner/i.md")), Some(1));
assert_eq!(innermost(&roots, &p("/knowledge/inner")), Some(1));
assert_eq!(innermost(&roots, &p("/x.md")), None);
assert_eq!(
Tree::classify(&p("/knowledge/inner/manifest.sokf.yaml"), &roots),
(Some(1), FileKind::Manifest)
);
}
#[test]
fn classifies_per_spec_2() {
let roots = vec![p("/knowledge"), p("/docs")];
let cases = [
("/knowledge/manifest.sokf.yaml", Some(0), FileKind::Manifest),
(
"/knowledge/sub/manifest.sokf.yaml",
Some(0),
FileKind::Candidate,
),
("/knowledge/index.md", Some(0), FileKind::Index),
("/knowledge/schemas/index.md", Some(0), FileKind::Index),
("/knowledge/schemas/issue.md", Some(0), FileKind::Schema),
("/knowledge/schemas/sub/x.md", Some(0), FileKind::Document),
("/knowledge/a.md", Some(0), FileKind::Document),
("/knowledge/a.txt", Some(0), FileKind::Candidate),
("/docs/a.md", Some(1), FileKind::Document),
("/README.md", None, FileKind::Candidate),
("/knowledgebase/a.md", None, FileKind::Candidate),
];
for (path, root, kind) in cases {
assert_eq!(Tree::classify(&p(path), &roots), (root, kind), "{path}");
}
}
#[test]
fn exists_asks_the_filesystem_once() {
let dir = crate::test_support::fresh_dir("tree");
std::fs::write(dir.join("here.md"), "").unwrap();
let tree = Tree::new(
RepoRoot::new(dir.clone()),
vec![],
vec![WalkedFile {
path: p("/b.md"),
root: None,
kind: FileKind::Candidate,
stat: Stat::default(),
}],
vec![],
);
assert!(tree.exists(&p("/here.md")));
assert!(!tree.is_dir(&p("/here.md")));
assert!(tree.is_dir(&p("/")));
assert!(!tree.exists(&p("/gone.md")));
std::fs::write(dir.join("gone.md"), "").unwrap();
assert!(!tree.exists(&p("/gone.md")));
assert_eq!(
tree.files
.iter()
.filter(|f| f.kind == FileKind::Candidate)
.count(),
1
);
std::fs::remove_dir_all(&dir).unwrap();
}
}