Skip to main content

sokf_core/walk/
tree.rs

1//! This module holds the tree of files and directories that a run reads.
2
3use std::{cell::RefCell, collections::HashMap};
4
5use crate::{RepoPath, RepoRoot, Stat};
6
7/// A `FileKind` is the kind of a walked file, as the store structure of
8/// sokf-format-spec defines it.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum FileKind {
11    /// `manifest.sokf.yaml` at a knowledge root.
12    Manifest,
13    /// An `index.md` inside a knowledge root.
14    Index,
15    /// A `.md` file in `schemas/` at a knowledge root, except `index.md`.
16    Schema,
17    /// Any other `.md` file inside a knowledge root.
18    Document,
19    /// A file that is none of the preceding kinds: a candidate additional file.
20    Candidate,
21}
22
23/// A `WalkedFile` is one file that the walk found.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct WalkedFile {
26    /// The path of the file.
27    pub path: RepoPath,
28    /// The index of the knowledge root that the file lies under, if any.
29    pub root: Option<usize>,
30    /// The kind of the file.
31    pub kind: FileKind,
32    /// The length and modification time of the file, from the walk's stat.
33    pub stat: Stat,
34}
35
36/// A `WalkedDir` is one directory that the walk visits under a knowledge
37/// root. Each such directory must have an index (`SOKF_FORMAT_96`).
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct WalkedDir {
40    /// The path of the directory.
41    pub path: RepoPath,
42    /// The index of the innermost knowledge root that the directory lies under.
43    pub root: usize,
44}
45
46/// A `Tree` is the walked repository.
47#[derive(Debug)]
48pub struct Tree {
49    /// The repository root.
50    pub root: RepoRoot,
51    /// The knowledge roots, in configuration order.
52    pub roots: Vec<RepoPath>,
53    /// Every walked file, ordered by path.
54    pub files: Vec<WalkedFile>,
55    /// Every directory under a root, including the roots, ordered by path.
56    pub dirs: Vec<WalkedDir>,
57    /// The number of registered roots, those of `/.sokf/roots.d/`, at the
58    /// end of `roots`.
59    pub registered_count: usize,
60    on_disk: RefCell<HashMap<RepoPath, OnDisk>>,
61}
62
63/// `OnDisk` is what a path names on disk.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum OnDisk {
66    /// No file or directory exists at the path.
67    Nothing,
68    /// A file, or anything else that is not a directory, exists at the path.
69    File,
70    /// A directory exists at the path.
71    Dir,
72}
73
74impl OnDisk {
75    /// `at` asks the filesystem what `path` names, following a symbolic
76    /// link.
77    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    /// `code` returns the number by which the store keeps the answer: 0 for
86    /// nothing, 1 for a file, and 2 for a directory.
87    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    /// `new` builds a tree from its parts, and sorts the files and the
98    /// directories by path.
99    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    /// `exists` returns whether `path` exists on disk, and caches the
118    /// answer for the rest of the run. It asks the filesystem, not the
119    /// walked files, so that a link into an excluded tree still resolves.
120    // sokf-implements: CONF-3_AC-3
121    // sokf-implements: CONF-3_AC-4
122    pub fn exists(&self, path: &RepoPath) -> bool {
123        self.on_disk(path) != OnDisk::Nothing
124    }
125
126    /// `is_dir` returns whether `path` is a directory on disk, from the
127    /// same cache as `exists`.
128    pub fn is_dir(&self, path: &RepoPath) -> bool {
129        self.on_disk(path) == OnDisk::Dir
130    }
131
132    /// `on_disk` returns what `path` names on disk, and caches the answer
133    /// for the rest of the run.
134    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    /// `file` returns the walked file at `path`, if any, by a binary search
144    /// over the sorted files.
145    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    /// `classify` returns the index of the innermost root that `path` lies
153    /// under, if any, and the kind of the file, as the store structure of
154    /// sokf-format-spec defines it.
155    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
177/// `innermost` returns the index of the innermost root that contains
178/// `path`. It picks the longest such root, so that a root inside another
179/// root owns the files under it.
180pub 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        // `exists` caches its first answer for the rest of the run.
259        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}