1use std::{cell::RefCell, collections::HashMap};
4
5use crate::{RepoPath, RepoRoot, Stat};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum FileKind {
11 Manifest,
13 Index,
15 Schema,
17 Document,
19 Candidate,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct WalkedFile {
26 pub path: RepoPath,
28 pub root: Option<usize>,
30 pub kind: FileKind,
32 pub stat: Stat,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct WalkedDir {
40 pub path: RepoPath,
42 pub root: usize,
44}
45
46#[derive(Debug)]
48pub struct Tree {
49 pub root: RepoRoot,
51 pub roots: Vec<RepoPath>,
53 pub files: Vec<WalkedFile>,
55 pub dirs: Vec<WalkedDir>,
57 pub registered_count: usize,
60 on_disk: RefCell<HashMap<RepoPath, OnDisk>>,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum OnDisk {
66 Nothing,
68 File,
70 Dir,
72}
73
74impl OnDisk {
75 pub fn at(path: &std::path::Path) -> OnDisk {
78 match std::fs::metadata(path) {
79 Ok(m) if m.is_dir() => OnDisk::Dir,
80 Ok(_) => OnDisk::File,
81 Err(_) => OnDisk::Nothing,
82 }
83 }
84
85 pub fn code(self) -> i64 {
88 match self {
89 OnDisk::Nothing => 0,
90 OnDisk::File => 1,
91 OnDisk::Dir => 2,
92 }
93 }
94}
95
96impl Tree {
97 pub fn new(
100 root: RepoRoot,
101 roots: Vec<RepoPath>,
102 mut files: Vec<WalkedFile>,
103 mut dirs: Vec<WalkedDir>,
104 ) -> Self {
105 files.sort_by(|a, b| a.path.cmp(&b.path));
106 dirs.sort_by(|a, b| a.path.cmp(&b.path));
107 Tree {
108 root,
109 roots,
110 files,
111 dirs,
112 registered_count: 0,
113 on_disk: RefCell::new(HashMap::new()),
114 }
115 }
116
117 pub fn exists(&self, path: &RepoPath) -> bool {
123 self.on_disk(path) != OnDisk::Nothing
124 }
125
126 pub fn is_dir(&self, path: &RepoPath) -> bool {
129 self.on_disk(path) == OnDisk::Dir
130 }
131
132 pub fn on_disk(&self, path: &RepoPath) -> OnDisk {
135 if let Some(&known) = self.on_disk.borrow().get(path) {
136 return known;
137 }
138 let known = OnDisk::at(&path.to_fs(&self.root));
139 self.on_disk.borrow_mut().insert(path.clone(), known);
140 known
141 }
142
143 pub fn file(&self, path: &RepoPath) -> Option<&WalkedFile> {
146 self.files
147 .binary_search_by(|f| f.path.cmp(path))
148 .ok()
149 .map(|i| &self.files[i])
150 }
151
152 pub fn classify(path: &RepoPath, roots: &[RepoPath]) -> (Option<usize>, FileKind) {
156 let Some(root_index) = innermost(roots, path) else {
157 return (None, FileKind::Candidate);
158 };
159 let root = &roots[root_index];
160 let name = path.file_name();
161 let parent = path.parent();
162 let kind = if name == "manifest.sokf.yaml" && parent.as_ref() == Some(root) {
163 FileKind::Manifest
164 } else if !crate::markdown::is_markdown(path) {
165 FileKind::Candidate
166 } else if name == "index.md" {
167 FileKind::Index
168 } else if parent == root.join("schemas") {
169 FileKind::Schema
170 } else {
171 FileKind::Document
172 };
173 (Some(root_index), kind)
174 }
175}
176
177pub fn innermost<'a>(
181 roots: impl IntoIterator<Item = &'a RepoPath>,
182 path: &RepoPath,
183) -> Option<usize> {
184 roots
185 .into_iter()
186 .enumerate()
187 .filter(|(_, r)| path.starts_with(r))
188 .max_by_key(|(_, r)| r.as_str().len())
189 .map(|(i, _)| i)
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 fn p(s: &str) -> RepoPath {
197 RepoPath::parse(s).unwrap()
198 }
199
200 #[test]
201 fn the_innermost_root_owns_a_nested_path() {
202 let roots = vec![p("/knowledge"), p("/knowledge/inner"), p("/docs")];
203 assert_eq!(innermost(&roots, &p("/knowledge/a.md")), Some(0));
204 assert_eq!(innermost(&roots, &p("/knowledge/inner/i.md")), Some(1));
205 assert_eq!(innermost(&roots, &p("/knowledge/inner")), Some(1));
206 assert_eq!(innermost(&roots, &p("/x.md")), None);
207 assert_eq!(
208 Tree::classify(&p("/knowledge/inner/manifest.sokf.yaml"), &roots),
209 (Some(1), FileKind::Manifest)
210 );
211 }
212
213 #[test]
214 fn classifies_per_spec_2() {
215 let roots = vec![p("/knowledge"), p("/docs")];
216 let cases = [
217 ("/knowledge/manifest.sokf.yaml", Some(0), FileKind::Manifest),
218 (
219 "/knowledge/sub/manifest.sokf.yaml",
220 Some(0),
221 FileKind::Candidate,
222 ),
223 ("/knowledge/index.md", Some(0), FileKind::Index),
224 ("/knowledge/schemas/index.md", Some(0), FileKind::Index),
225 ("/knowledge/schemas/issue.md", Some(0), FileKind::Schema),
226 ("/knowledge/schemas/sub/x.md", Some(0), FileKind::Document),
227 ("/knowledge/a.md", Some(0), FileKind::Document),
228 ("/knowledge/a.txt", Some(0), FileKind::Candidate),
229 ("/docs/a.md", Some(1), FileKind::Document),
230 ("/README.md", None, FileKind::Candidate),
231 ("/knowledgebase/a.md", None, FileKind::Candidate),
232 ];
233 for (path, root, kind) in cases {
234 assert_eq!(Tree::classify(&p(path), &roots), (root, kind), "{path}");
235 }
236 }
237
238 #[test]
239 fn exists_asks_the_filesystem_once() {
240 let dir = crate::test_support::fresh_dir("tree");
241 std::fs::write(dir.join("here.md"), "").unwrap();
242 let tree = Tree::new(
243 RepoRoot::new(dir.clone()),
244 vec![],
245 vec![WalkedFile {
246 path: p("/b.md"),
247 root: None,
248 kind: FileKind::Candidate,
249 stat: Stat::default(),
250 }],
251 vec![],
252 );
253 assert!(tree.exists(&p("/here.md")));
254 assert!(!tree.is_dir(&p("/here.md")));
255 assert!(tree.is_dir(&p("/")));
256 assert!(!tree.exists(&p("/gone.md")));
257 std::fs::write(dir.join("gone.md"), "").unwrap();
258 assert!(!tree.exists(&p("/gone.md")));
260 assert_eq!(
261 tree.files
262 .iter()
263 .filter(|f| f.kind == FileKind::Candidate)
264 .count(),
265 1
266 );
267 std::fs::remove_dir_all(&dir).unwrap();
268 }
269}